svn merge -r 15800:15973 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[blender-staging.git] / source / blender / blenkernel / intern / modifier.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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 *
20 * The Original Code is Copyright (C) 2005 by the Blender Foundation.
21 * All rights reserved.
22 *
23 * The Original Code is: all of this file.
24 *
25 * Contributor(s): Daniel Dunbar
26 *                 Ton Roosendaal,
27 *                 Ben Batt,
28 *                 Brecht Van Lommel,
29 *                 Campbell Barton
30 *
31 * ***** END GPL LICENSE BLOCK *****
32 *
33 * Modifier stack implementation.
34 *
35 * BKE_modifier.h contains the function prototypes for this file.
36 *
37 */
38
39 #include "string.h"
40 #include "stdarg.h"
41 #include "math.h"
42 #include "float.h"
43 #include "ctype.h"
44
45 #include "BLI_arithb.h"
46 #include "BLI_blenlib.h"
47 #include "BLI_kdopbvh.h"
48 #include "BLI_kdtree.h"
49 #include "BLI_linklist.h"
50 #include "BLI_rand.h"
51 #include "BLI_edgehash.h"
52 #include "BLI_ghash.h"
53 #include "BLI_memarena.h"
54
55 #include "MEM_guardedalloc.h"
56
57 #include "DNA_armature_types.h"
58 #include "DNA_camera_types.h"
59 #include "DNA_cloth_types.h"
60 #include "DNA_curve_types.h"
61 #include "DNA_effect_types.h"
62 #include "DNA_material_types.h"
63 #include "DNA_mesh_types.h"
64 #include "DNA_meshdata_types.h"
65 #include "DNA_modifier_types.h"
66 #include "DNA_object_types.h"
67 #include "DNA_object_force.h"
68 #include "DNA_particle_types.h"
69 #include "DNA_scene_types.h"
70 #include "DNA_texture_types.h"
71
72 #include "BLI_editVert.h"
73
74 #include "MTC_matrixops.h"
75 #include "MTC_vectorops.h"
76
77 #include "BKE_main.h"
78 #include "BKE_anim.h"
79 #include "BKE_bad_level_calls.h"
80 #include "BKE_bmesh.h"
81 #include "BKE_booleanops.h"
82 #include "BKE_cloth.h"
83 #include "BKE_collision.h"
84 #include "BKE_cdderivedmesh.h"
85 #include "BKE_curve.h"
86 #include "BKE_customdata.h"
87 #include "BKE_DerivedMesh.h"
88 #include "BKE_displist.h"
89 #include "BKE_fluidsim.h"
90 #include "BKE_global.h"
91 #include "BKE_lattice.h"
92 #include "BKE_library.h"
93 #include "BKE_material.h"
94 #include "BKE_mesh.h"
95 #include "BKE_modifier.h"
96 #include "BKE_object.h"
97 #include "BKE_particle.h"
98 #include "BKE_pointcache.h"
99 #include "BKE_softbody.h"
100 #include "BKE_subsurf.h"
101 #include "BKE_utildefines.h"
102
103 #include "depsgraph_private.h"
104
105 #include "LOD_DependKludge.h"
106 #include "LOD_decimation.h"
107
108 #include "CCGSubSurf.h"
109
110 #include "RE_shader_ext.h"
111
112 /***/
113
114 static int noneModifier_isDisabled(ModifierData *md)
115 {
116         return 1;
117 }
118
119 /* Curve */
120
121 static void curveModifier_initData(ModifierData *md)
122 {
123         CurveModifierData *cmd = (CurveModifierData*) md;
124
125         cmd->defaxis = MOD_CURVE_POSX;
126 }
127
128 static void curveModifier_copyData(ModifierData *md, ModifierData *target)
129 {
130         CurveModifierData *cmd = (CurveModifierData*) md;
131         CurveModifierData *tcmd = (CurveModifierData*) target;
132
133         tcmd->defaxis = cmd->defaxis;
134         tcmd->object = cmd->object;
135         strncpy(tcmd->name, cmd->name, 32);
136 }
137
138 CustomDataMask curveModifier_requiredDataMask(ModifierData *md)
139 {
140         CurveModifierData *cmd = (CurveModifierData *)md;
141         CustomDataMask dataMask = 0;
142
143         /* ask for vertexgroups if we need them */
144         if(cmd->name[0]) dataMask |= (1 << CD_MDEFORMVERT);
145
146         return dataMask;
147 }
148
149 static int curveModifier_isDisabled(ModifierData *md)
150 {
151         CurveModifierData *cmd = (CurveModifierData*) md;
152
153         return !cmd->object;
154 }
155
156 static void curveModifier_foreachObjectLink(
157                                             ModifierData *md, Object *ob,
158          void (*walk)(void *userData, Object *ob, Object **obpoin),
159                 void *userData)
160 {
161         CurveModifierData *cmd = (CurveModifierData*) md;
162
163         walk(userData, ob, &cmd->object);
164 }
165
166 static void curveModifier_updateDepgraph(
167                                          ModifierData *md, DagForest *forest,
168       Object *ob, DagNode *obNode)
169 {
170         CurveModifierData *cmd = (CurveModifierData*) md;
171
172         if (cmd->object) {
173                 DagNode *curNode = dag_get_node(forest, cmd->object);
174
175                 dag_add_relation(forest, curNode, obNode,
176                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Curve Modifier");
177         }
178 }
179
180 static void curveModifier_deformVerts(
181                                       ModifierData *md, Object *ob, DerivedMesh *derivedData,
182           float (*vertexCos)[3], int numVerts)
183 {
184         CurveModifierData *cmd = (CurveModifierData*) md;
185
186         curve_deform_verts(cmd->object, ob, derivedData, vertexCos, numVerts,
187                            cmd->name, cmd->defaxis);
188 }
189
190 static void curveModifier_deformVertsEM(
191                                         ModifierData *md, Object *ob, EditMesh *editData,
192      DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
193 {
194         DerivedMesh *dm = derivedData;
195
196         if(!derivedData) dm = CDDM_from_editmesh(editData, ob->data);
197
198         curveModifier_deformVerts(md, ob, dm, vertexCos, numVerts);
199
200         if(!derivedData) dm->release(dm);
201 }
202
203 /* Lattice */
204
205 static void latticeModifier_copyData(ModifierData *md, ModifierData *target)
206 {
207         LatticeModifierData *lmd = (LatticeModifierData*) md;
208         LatticeModifierData *tlmd = (LatticeModifierData*) target;
209
210         tlmd->object = lmd->object;
211         strncpy(tlmd->name, lmd->name, 32);
212 }
213
214 CustomDataMask latticeModifier_requiredDataMask(ModifierData *md)
215 {
216         LatticeModifierData *lmd = (LatticeModifierData *)md;
217         CustomDataMask dataMask = 0;
218
219         /* ask for vertexgroups if we need them */
220         if(lmd->name[0]) dataMask |= (1 << CD_MDEFORMVERT);
221
222         return dataMask;
223 }
224
225 static int latticeModifier_isDisabled(ModifierData *md)
226 {
227         LatticeModifierData *lmd = (LatticeModifierData*) md;
228
229         return !lmd->object;
230 }
231
232 static void latticeModifier_foreachObjectLink(
233                                               ModifierData *md, Object *ob,
234            void (*walk)(void *userData, Object *ob, Object **obpoin),
235                   void *userData)
236 {
237         LatticeModifierData *lmd = (LatticeModifierData*) md;
238
239         walk(userData, ob, &lmd->object);
240 }
241
242 static void latticeModifier_updateDepgraph(ModifierData *md, DagForest *forest,
243                                            Object *ob, DagNode *obNode)
244 {
245         LatticeModifierData *lmd = (LatticeModifierData*) md;
246
247         if(lmd->object) {
248                 DagNode *latNode = dag_get_node(forest, lmd->object);
249
250                 dag_add_relation(forest, latNode, obNode,
251                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Lattice Modifier");
252         }
253 }
254
255 static void modifier_vgroup_cache(ModifierData *md, float (*vertexCos)[3])
256 {
257         md= md->next;
258         if(md) {
259                 if(md->type==eModifierType_Armature) {
260                         ArmatureModifierData *amd = (ArmatureModifierData*) md;
261                         if(amd->multi)
262                                 amd->prevCos= MEM_dupallocN(vertexCos);
263                 }
264                 /* lattice/mesh modifier too */
265         }
266 }
267
268
269 static void latticeModifier_deformVerts(
270                                         ModifierData *md, Object *ob, DerivedMesh *derivedData,
271      float (*vertexCos)[3], int numVerts)
272 {
273         LatticeModifierData *lmd = (LatticeModifierData*) md;
274
275
276         modifier_vgroup_cache(md, vertexCos); /* if next modifier needs original vertices */
277         
278         lattice_deform_verts(lmd->object, ob, derivedData,
279                              vertexCos, numVerts, lmd->name);
280 }
281
282 static void latticeModifier_deformVertsEM(
283                                           ModifierData *md, Object *ob, EditMesh *editData,
284        DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
285 {
286         DerivedMesh *dm = derivedData;
287
288         if(!derivedData) dm = CDDM_from_editmesh(editData, ob->data);
289
290         latticeModifier_deformVerts(md, ob, dm, vertexCos, numVerts);
291
292         if(!derivedData) dm->release(dm);
293 }
294
295 /* Subsurf */
296
297 static void subsurfModifier_initData(ModifierData *md)
298 {
299         SubsurfModifierData *smd = (SubsurfModifierData*) md;
300
301         smd->levels = 1;
302         smd->renderLevels = 2;
303         smd->flags |= eSubsurfModifierFlag_SubsurfUv;
304 }
305
306 static void subsurfModifier_copyData(ModifierData *md, ModifierData *target)
307 {
308         SubsurfModifierData *smd = (SubsurfModifierData*) md;
309         SubsurfModifierData *tsmd = (SubsurfModifierData*) target;
310
311         tsmd->flags = smd->flags;
312         tsmd->levels = smd->levels;
313         tsmd->renderLevels = smd->renderLevels;
314         tsmd->subdivType = smd->subdivType;
315 }
316
317 static void subsurfModifier_freeData(ModifierData *md)
318 {
319         SubsurfModifierData *smd = (SubsurfModifierData*) md;
320
321         if(smd->mCache) {
322                 ccgSubSurf_free(smd->mCache);
323         }
324         if(smd->emCache) {
325                 ccgSubSurf_free(smd->emCache);
326         }
327 }
328
329 static DerivedMesh *subsurfModifier_applyModifier(
330                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
331   int useRenderParams, int isFinalCalc)
332 {
333         SubsurfModifierData *smd = (SubsurfModifierData*) md;
334         DerivedMesh *result;
335
336         result = subsurf_make_derived_from_derived(derivedData, smd,
337                         useRenderParams, NULL,
338    isFinalCalc, 0);
339
340         return result;
341 }
342
343 static DerivedMesh *subsurfModifier_applyModifierEM(
344                 ModifierData *md, Object *ob, EditMesh *editData,
345   DerivedMesh *derivedData)
346 {
347         SubsurfModifierData *smd = (SubsurfModifierData*) md;
348         DerivedMesh *result;
349
350         result = subsurf_make_derived_from_derived(derivedData, smd, 0,
351                         NULL, 0, 1);
352
353         return result;
354 }
355
356 /* Build */
357
358 static void buildModifier_initData(ModifierData *md)
359 {
360         BuildModifierData *bmd = (BuildModifierData*) md;
361
362         bmd->start = 1.0;
363         bmd->length = 100.0;
364 }
365
366 static void buildModifier_copyData(ModifierData *md, ModifierData *target)
367 {
368         BuildModifierData *bmd = (BuildModifierData*) md;
369         BuildModifierData *tbmd = (BuildModifierData*) target;
370
371         tbmd->start = bmd->start;
372         tbmd->length = bmd->length;
373         tbmd->randomize = bmd->randomize;
374         tbmd->seed = bmd->seed;
375 }
376
377 static int buildModifier_dependsOnTime(ModifierData *md)
378 {
379         return 1;
380 }
381
382 static DerivedMesh *buildModifier_applyModifier(ModifierData *md, Object *ob,
383                 DerivedMesh *derivedData,
384   int useRenderParams, int isFinalCalc)
385 {
386         DerivedMesh *dm = derivedData;
387         DerivedMesh *result;
388         BuildModifierData *bmd = (BuildModifierData*) md;
389         int i;
390         int numFaces, numEdges;
391         int maxVerts, maxEdges, maxFaces;
392         int *vertMap, *edgeMap, *faceMap;
393         float frac;
394         GHashIterator *hashIter;
395         /* maps vert indices in old mesh to indices in new mesh */
396         GHash *vertHash = BLI_ghash_new(BLI_ghashutil_inthash,
397                                         BLI_ghashutil_intcmp);
398         /* maps edge indices in new mesh to indices in old mesh */
399         GHash *edgeHash = BLI_ghash_new(BLI_ghashutil_inthash,
400                                         BLI_ghashutil_intcmp);
401
402         maxVerts = dm->getNumVerts(dm);
403         vertMap = MEM_callocN(sizeof(*vertMap) * maxVerts,
404                               "build modifier vertMap");
405         for(i = 0; i < maxVerts; ++i) vertMap[i] = i;
406
407         maxEdges = dm->getNumEdges(dm);
408         edgeMap = MEM_callocN(sizeof(*edgeMap) * maxEdges,
409                               "build modifier edgeMap");
410         for(i = 0; i < maxEdges; ++i) edgeMap[i] = i;
411
412         maxFaces = dm->getNumFaces(dm);
413         faceMap = MEM_callocN(sizeof(*faceMap) * maxFaces,
414                               "build modifier faceMap");
415         for(i = 0; i < maxFaces; ++i) faceMap[i] = i;
416
417         if (ob) {
418                 frac = bsystem_time(ob, (float)G.scene->r.cfra,
419                                     bmd->start - 1.0f) / bmd->length;
420         } else {
421                 frac = G.scene->r.cfra - bmd->start / bmd->length;
422         }
423         CLAMP(frac, 0.0, 1.0);
424
425         numFaces = dm->getNumFaces(dm) * frac;
426         numEdges = dm->getNumEdges(dm) * frac;
427
428         /* if there's at least one face, build based on faces */
429         if(numFaces) {
430                 int maxEdges;
431
432                 if(bmd->randomize)
433                         BLI_array_randomize(faceMap, sizeof(*faceMap),
434                                             maxFaces, bmd->seed);
435
436                 /* get the set of all vert indices that will be in the final mesh,
437                 * mapped to the new indices
438                 */
439                 for(i = 0; i < numFaces; ++i) {
440                         MFace mf;
441                         dm->getFace(dm, faceMap[i], &mf);
442
443                         if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v1)))
444                                 BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v1),
445                                         SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
446                         if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v2)))
447                                 BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v2),
448                                         SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
449                         if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v3)))
450                                 BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v3),
451                                         SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
452                         if(mf.v4 && !BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v4)))
453                                 BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v4),
454                                         SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
455                 }
456
457                 /* get the set of edges that will be in the new mesh (i.e. all edges
458                 * that have both verts in the new mesh)
459                 */
460                 maxEdges = dm->getNumEdges(dm);
461                 for(i = 0; i < maxEdges; ++i) {
462                         MEdge me;
463                         dm->getEdge(dm, i, &me);
464
465                         if(BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1))
466                                                 && BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)))
467                                 BLI_ghash_insert(edgeHash,
468                                         SET_INT_IN_POINTER(BLI_ghash_size(edgeHash)), SET_INT_IN_POINTER(i));
469                 }
470         } else if(numEdges) {
471                 if(bmd->randomize)
472                         BLI_array_randomize(edgeMap, sizeof(*edgeMap),
473                                             maxEdges, bmd->seed);
474
475                 /* get the set of all vert indices that will be in the final mesh,
476                 * mapped to the new indices
477                 */
478                 for(i = 0; i < numEdges; ++i) {
479                         MEdge me;
480                         dm->getEdge(dm, edgeMap[i], &me);
481
482                         if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1)))
483                                 BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(me.v1),
484                                         SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
485                         if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)))
486                                 BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(me.v2),
487                                         SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
488                 }
489
490                 /* get the set of edges that will be in the new mesh
491                 */
492                 for(i = 0; i < numEdges; ++i) {
493                         MEdge me;
494                         dm->getEdge(dm, edgeMap[i], &me);
495
496                         BLI_ghash_insert(edgeHash, SET_INT_IN_POINTER(BLI_ghash_size(edgeHash)),
497                                          SET_INT_IN_POINTER(edgeMap[i]));
498                 }
499         } else {
500                 int numVerts = dm->getNumVerts(dm) * frac;
501
502                 if(bmd->randomize)
503                         BLI_array_randomize(vertMap, sizeof(*vertMap),
504                                             maxVerts, bmd->seed);
505
506                 /* get the set of all vert indices that will be in the final mesh,
507                 * mapped to the new indices
508                 */
509                 for(i = 0; i < numVerts; ++i)
510                         BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(vertMap[i]), SET_INT_IN_POINTER(i));
511         }
512
513         /* now we know the number of verts, edges and faces, we can create
514         * the mesh
515         */
516         result = CDDM_from_template(dm, BLI_ghash_size(vertHash),
517                                     BLI_ghash_size(edgeHash), numFaces);
518
519         /* copy the vertices across */
520         for(hashIter = BLI_ghashIterator_new(vertHash);
521                    !BLI_ghashIterator_isDone(hashIter);
522                    BLI_ghashIterator_step(hashIter)) {
523                            MVert source;
524                            MVert *dest;
525                            int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
526                            int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
527
528                            dm->getVert(dm, oldIndex, &source);
529                            dest = CDDM_get_vert(result, newIndex);
530
531                            DM_copy_vert_data(dm, result, oldIndex, newIndex, 1);
532                            *dest = source;
533                    }
534                    BLI_ghashIterator_free(hashIter);
535
536                    /* copy the edges across, remapping indices */
537                    for(i = 0; i < BLI_ghash_size(edgeHash); ++i) {
538                            MEdge source;
539                            MEdge *dest;
540                            int oldIndex = GET_INT_FROM_POINTER(BLI_ghash_lookup(edgeHash, SET_INT_IN_POINTER(i)));
541
542                            dm->getEdge(dm, oldIndex, &source);
543                            dest = CDDM_get_edge(result, i);
544
545                            source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
546                            source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
547
548                            DM_copy_edge_data(dm, result, oldIndex, i, 1);
549                            *dest = source;
550                    }
551
552                    /* copy the faces across, remapping indices */
553                    for(i = 0; i < numFaces; ++i) {
554                            MFace source;
555                            MFace *dest;
556                            int orig_v4;
557
558                            dm->getFace(dm, faceMap[i], &source);
559                            dest = CDDM_get_face(result, i);
560
561                            orig_v4 = source.v4;
562
563                            source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
564                            source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
565                            source.v3 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v3)));
566                            if(source.v4)
567                                    source.v4 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v4)));
568
569                            DM_copy_face_data(dm, result, faceMap[i], i, 1);
570                            *dest = source;
571
572                            test_index_face(dest, &result->faceData, i, (orig_v4 ? 4 : 3));
573                    }
574
575                    CDDM_calc_normals(result);
576
577                    BLI_ghash_free(vertHash, NULL, NULL);
578                    BLI_ghash_free(edgeHash, NULL, NULL);
579
580                    MEM_freeN(vertMap);
581                    MEM_freeN(edgeMap);
582                    MEM_freeN(faceMap);
583
584                    return result;
585 }
586
587 /* Array */
588 /* Array modifier: duplicates the object multiple times along an axis
589 */
590
591 static void arrayModifier_initData(ModifierData *md)
592 {
593         ArrayModifierData *amd = (ArrayModifierData*) md;
594
595         /* default to 2 duplicates distributed along the x-axis by an
596         offset of 1 object-width
597         */
598         amd->start_cap = amd->end_cap = amd->curve_ob = amd->offset_ob = NULL;
599         amd->count = 2;
600         amd->offset[0] = amd->offset[1] = amd->offset[2] = 0;
601         amd->scale[0] = 1;
602         amd->scale[1] = amd->scale[2] = 0;
603         amd->length = 0;
604         amd->merge_dist = 0.01;
605         amd->fit_type = MOD_ARR_FIXEDCOUNT;
606         amd->offset_type = MOD_ARR_OFF_RELATIVE;
607         amd->flags = 0;
608 }
609
610 static void arrayModifier_copyData(ModifierData *md, ModifierData *target)
611 {
612         ArrayModifierData *amd = (ArrayModifierData*) md;
613         ArrayModifierData *tamd = (ArrayModifierData*) target;
614
615         tamd->start_cap = amd->start_cap;
616         tamd->end_cap = amd->end_cap;
617         tamd->curve_ob = amd->curve_ob;
618         tamd->offset_ob = amd->offset_ob;
619         tamd->count = amd->count;
620         VECCOPY(tamd->offset, amd->offset);
621         VECCOPY(tamd->scale, amd->scale);
622         tamd->length = amd->length;
623         tamd->merge_dist = amd->merge_dist;
624         tamd->fit_type = amd->fit_type;
625         tamd->offset_type = amd->offset_type;
626         tamd->flags = amd->flags;
627 }
628
629 static void arrayModifier_foreachObjectLink(
630                                             ModifierData *md, Object *ob,
631          void (*walk)(void *userData, Object *ob, Object **obpoin),
632                 void *userData)
633 {
634         ArrayModifierData *amd = (ArrayModifierData*) md;
635
636         walk(userData, ob, &amd->start_cap);
637         walk(userData, ob, &amd->end_cap);
638         walk(userData, ob, &amd->curve_ob);
639         walk(userData, ob, &amd->offset_ob);
640 }
641
642 static void arrayModifier_updateDepgraph(ModifierData *md, DagForest *forest,
643                                          Object *ob, DagNode *obNode)
644 {
645         ArrayModifierData *amd = (ArrayModifierData*) md;
646
647         if (amd->start_cap) {
648                 DagNode *curNode = dag_get_node(forest, amd->start_cap);
649
650                 dag_add_relation(forest, curNode, obNode,
651                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
652         }
653         if (amd->end_cap) {
654                 DagNode *curNode = dag_get_node(forest, amd->end_cap);
655
656                 dag_add_relation(forest, curNode, obNode,
657                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
658         }
659         if (amd->curve_ob) {
660                 DagNode *curNode = dag_get_node(forest, amd->curve_ob);
661
662                 dag_add_relation(forest, curNode, obNode,
663                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
664         }
665         if (amd->offset_ob) {
666                 DagNode *curNode = dag_get_node(forest, amd->offset_ob);
667
668                 dag_add_relation(forest, curNode, obNode,
669                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
670         }
671 }
672
673 float vertarray_size(MVert *mvert, int numVerts, int axis)
674 {
675         int i;
676         float min_co, max_co;
677
678         /* if there are no vertices, width is 0 */
679         if(numVerts == 0) return 0;
680
681         /* find the minimum and maximum coordinates on the desired axis */
682         min_co = max_co = mvert->co[axis];
683         ++mvert;
684         for(i = 1; i < numVerts; ++i, ++mvert) {
685                 if(mvert->co[axis] < min_co) min_co = mvert->co[axis];
686                 if(mvert->co[axis] > max_co) max_co = mvert->co[axis];
687         }
688
689         return max_co - min_co;
690 }
691
692 typedef struct IndexMapEntry {
693         /* the new vert index that this old vert index maps to */
694         int new;
695         /* -1 if this vert isn't merged, otherwise the old vert index it
696         * should be replaced with
697         */
698         int merge;
699         /* 1 if this vert's first copy is merged with the last copy of its
700         * merge target, otherwise 0
701         */
702         short merge_final;
703 } IndexMapEntry;
704
705 /* indexMap - an array of IndexMap entries
706  * oldIndex - the old index to map
707  * copyNum - the copy number to map to (original = 0, first copy = 1, etc.)
708  */
709 static int calc_mapping(IndexMapEntry *indexMap, int oldIndex, int copyNum)
710 {
711         if(indexMap[oldIndex].merge < 0) {
712                 /* vert wasn't merged, so use copy of this vert */
713                 return indexMap[oldIndex].new + copyNum;
714         } else if(indexMap[oldIndex].merge == oldIndex) {
715                 /* vert was merged with itself */
716                 return indexMap[oldIndex].new;
717         } else {
718                 /* vert was merged with another vert */
719                 /* follow the chain of merges to the end, or until we've passed
720                 * a number of vertices equal to the copy number
721                 */
722                 if(copyNum <= 0)
723                         return indexMap[oldIndex].new;
724                 else
725                         return calc_mapping(indexMap, indexMap[oldIndex].merge,
726                                             copyNum - 1);
727         }
728 }
729
730 static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
731                                           Object *ob, DerivedMesh *dm,
732        int initFlags)
733 {
734         int i, j;
735         /* offset matrix */
736         float offset[4][4];
737         float final_offset[4][4];
738         float tmp_mat[4][4];
739         float length = amd->length;
740         int count = amd->count;
741         int numVerts, numEdges, numFaces;
742         int maxVerts, maxEdges, maxFaces;
743         int finalVerts, finalEdges, finalFaces;
744         DerivedMesh *result, *start_cap = NULL, *end_cap = NULL;
745         MVert *mvert, *src_mvert;
746         MEdge *medge;
747         MFace *mface;
748
749         IndexMapEntry *indexMap;
750
751         EdgeHash *edges;
752
753         /* need to avoid infinite recursion here */
754         if(amd->start_cap && amd->start_cap != ob)
755                 start_cap = mesh_get_derived_final(amd->start_cap, CD_MASK_MESH);
756         if(amd->end_cap && amd->end_cap != ob)
757                 end_cap = mesh_get_derived_final(amd->end_cap, CD_MASK_MESH);
758
759         MTC_Mat4One(offset);
760
761         indexMap = MEM_callocN(sizeof(*indexMap) * dm->getNumVerts(dm),
762                                "indexmap");
763
764         src_mvert = dm->getVertArray(dm);
765
766         maxVerts = dm->getNumVerts(dm);
767
768         if(amd->offset_type & MOD_ARR_OFF_CONST)
769                 VecAddf(offset[3], offset[3], amd->offset);
770         if(amd->offset_type & MOD_ARR_OFF_RELATIVE) {
771                 for(j = 0; j < 3; j++)
772                         offset[3][j] += amd->scale[j] * vertarray_size(src_mvert,
773                                         maxVerts, j);
774         }
775
776         if((amd->offset_type & MOD_ARR_OFF_OBJ) && (amd->offset_ob)) {
777                 float obinv[4][4];
778                 float result_mat[4][4];
779
780                 if(ob)
781                         MTC_Mat4Invert(obinv, ob->obmat);
782                 else
783                         MTC_Mat4One(obinv);
784
785                 MTC_Mat4MulSerie(result_mat, offset,
786                                  obinv, amd->offset_ob->obmat,
787      NULL, NULL, NULL, NULL, NULL);
788                 MTC_Mat4CpyMat4(offset, result_mat);
789         }
790
791         if(amd->fit_type == MOD_ARR_FITCURVE && amd->curve_ob) {
792                 Curve *cu = amd->curve_ob->data;
793                 if(cu) {
794                         if(!cu->path) {
795                                 cu->flag |= CU_PATH; // needed for path & bevlist
796                                 makeDispListCurveTypes(amd->curve_ob, 0);
797                         }
798                         if(cu->path)
799                                 length = cu->path->totdist;
800                 }
801         }
802
803         /* calculate the maximum number of copies which will fit within the
804         prescribed length */
805         if(amd->fit_type == MOD_ARR_FITLENGTH
806                   || amd->fit_type == MOD_ARR_FITCURVE) {
807                 float dist = sqrt(MTC_dot3Float(offset[3], offset[3]));
808
809                 if(dist > 1e-6f)
810                         /* this gives length = first copy start to last copy end
811                         add a tiny offset for floating point rounding errors */
812                         count = (length + 1e-6f) / dist;
813                 else
814                         /* if the offset has no translation, just make one copy */
815                         count = 1;
816                   }
817
818                   if(count < 1)
819                           count = 1;
820
821         /* allocate memory for count duplicates (including original) plus
822                   * start and end caps
823         */
824                   finalVerts = dm->getNumVerts(dm) * count;
825                   finalEdges = dm->getNumEdges(dm) * count;
826                   finalFaces = dm->getNumFaces(dm) * count;
827                   if(start_cap) {
828                           finalVerts += start_cap->getNumVerts(start_cap);
829                           finalEdges += start_cap->getNumEdges(start_cap);
830                           finalFaces += start_cap->getNumFaces(start_cap);
831                   }
832                   if(end_cap) {
833                           finalVerts += end_cap->getNumVerts(end_cap);
834                           finalEdges += end_cap->getNumEdges(end_cap);
835                           finalFaces += end_cap->getNumFaces(end_cap);
836                   }
837                   result = CDDM_from_template(dm, finalVerts, finalEdges, finalFaces);
838
839                   /* calculate the offset matrix of the final copy (for merging) */ 
840                   MTC_Mat4One(final_offset);
841
842                   for(j=0; j < count - 1; j++) {
843                           MTC_Mat4MulMat4(tmp_mat, final_offset, offset);
844                           MTC_Mat4CpyMat4(final_offset, tmp_mat);
845                   }
846
847                   numVerts = numEdges = numFaces = 0;
848                   mvert = CDDM_get_verts(result);
849
850                   for (i = 0; i < maxVerts; i++) {
851                           indexMap[i].merge = -1; /* default to no merge */
852                           indexMap[i].merge_final = 0; /* default to no merge */
853                   }
854
855                   for (i = 0; i < maxVerts; i++) {
856                           MVert *inMV;
857                           MVert *mv = &mvert[numVerts];
858                           MVert *mv2;
859                           float co[3];
860
861                           inMV = &src_mvert[i];
862
863                           DM_copy_vert_data(dm, result, i, numVerts, 1);
864                           *mv = *inMV;
865                           numVerts++;
866
867                           indexMap[i].new = numVerts - 1;
868
869                           VECCOPY(co, mv->co);
870                 
871                 /* Attempts to merge verts from one duplicate with verts from the
872                           * next duplicate which are closer than amd->merge_dist.
873                           * Only the first such vert pair is merged.
874                           * If verts are merged in the first duplicate pair, they are merged
875                           * in all pairs.
876                 */
877                           if((count > 1) && (amd->flags & MOD_ARR_MERGE)) {
878                                   float tmp_co[3];
879                                   VECCOPY(tmp_co, mv->co);
880                                   MTC_Mat4MulVecfl(offset, tmp_co);
881
882                                   for(j = 0; j < maxVerts; j++) {
883                                           /* if vertex already merged, don't use it */
884                                           if( indexMap[j].merge != -1 ) continue;
885
886                                           inMV = &src_mvert[j];
887                                           /* if this vert is within merge limit, merge */
888                                           if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist)) {
889                                                   indexMap[i].merge = j;
890
891                                                   /* test for merging with final copy of merge target */
892                                                   if(amd->flags & MOD_ARR_MERGEFINAL) {
893                                                           VECCOPY(tmp_co, inMV->co);
894                                                           inMV = &src_mvert[i];
895                                                           MTC_Mat4MulVecfl(final_offset, tmp_co);
896                                                           if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist))
897                                                                   indexMap[i].merge_final = 1;
898                                                   }
899                                                   break;
900                                           }
901                                   }
902                           }
903
904                           /* if no merging, generate copies of this vert */
905                           if(indexMap[i].merge < 0) {
906                                   for(j=0; j < count - 1; j++) {
907                                           mv2 = &mvert[numVerts];
908
909                                           DM_copy_vert_data(result, result, numVerts - 1, numVerts, 1);
910                                           *mv2 = *mv;
911                                           numVerts++;
912
913                                           MTC_Mat4MulVecfl(offset, co);
914                                           VECCOPY(mv2->co, co);
915                                   }
916                           } else if(indexMap[i].merge != i && indexMap[i].merge_final) {
917                         /* if this vert is not merging with itself, and it is merging
918                                   * with the final copy of its merge target, remove the first copy
919                         */
920                                   numVerts--;
921                                   DM_free_vert_data(result, numVerts, 1);
922                           }
923                   }
924
925                   /* make a hashtable so we can avoid duplicate edges from merging */
926                   edges = BLI_edgehash_new();
927
928                   maxEdges = dm->getNumEdges(dm);
929                   medge = CDDM_get_edges(result);
930                   for(i = 0; i < maxEdges; i++) {
931                           MEdge inMED;
932                           MEdge med;
933                           MEdge *med2;
934                           int vert1, vert2;
935
936                           dm->getEdge(dm, i, &inMED);
937
938                           med = inMED;
939                           med.v1 = indexMap[inMED.v1].new;
940                           med.v2 = indexMap[inMED.v2].new;
941
942                 /* if vertices are to be merged with the final copies of their
943                           * merge targets, calculate that final copy
944                 */
945                           if(indexMap[inMED.v1].merge_final) {
946                                   med.v1 = calc_mapping(indexMap, indexMap[inMED.v1].merge,
947                                                   count - 1);
948                           }
949                           if(indexMap[inMED.v2].merge_final) {
950                                   med.v2 = calc_mapping(indexMap, indexMap[inMED.v2].merge,
951                                                   count - 1);
952                           }
953
954                           if(med.v1 == med.v2) continue;
955
956                           if (initFlags) {
957                                   med.flag |= ME_EDGEDRAW | ME_EDGERENDER;
958                           }
959
960                           if(!BLI_edgehash_haskey(edges, med.v1, med.v2)) {
961                                   DM_copy_edge_data(dm, result, i, numEdges, 1);
962                                   medge[numEdges] = med;
963                                   numEdges++;
964
965                                   BLI_edgehash_insert(edges, med.v1, med.v2, NULL);
966                           }
967
968                           for(j = 1; j < count; j++)
969                           {
970                                   vert1 = calc_mapping(indexMap, inMED.v1, j);
971                                   vert2 = calc_mapping(indexMap, inMED.v2, j);
972                                   /* avoid duplicate edges */
973                                   if(!BLI_edgehash_haskey(edges, vert1, vert2)) {
974                                           med2 = &medge[numEdges];
975
976                                           DM_copy_edge_data(dm, result, i, numEdges, 1);
977                                           *med2 = med;
978                                           numEdges++;
979
980                                           med2->v1 = vert1;
981                                           med2->v2 = vert2;
982
983                                           BLI_edgehash_insert(edges, med2->v1, med2->v2, NULL);
984                                   }
985                           }
986                   }
987
988                   maxFaces = dm->getNumFaces(dm);
989                   mface = CDDM_get_faces(result);
990                   for (i=0; i < maxFaces; i++) {
991                           MFace inMF;
992                           MFace *mf = &mface[numFaces];
993
994                           dm->getFace(dm, i, &inMF);
995
996                           DM_copy_face_data(dm, result, i, numFaces, 1);
997                           *mf = inMF;
998
999                           mf->v1 = indexMap[inMF.v1].new;
1000                           mf->v2 = indexMap[inMF.v2].new;
1001                           mf->v3 = indexMap[inMF.v3].new;
1002                           if(inMF.v4)
1003                                   mf->v4 = indexMap[inMF.v4].new;
1004
1005                 /* if vertices are to be merged with the final copies of their
1006                           * merge targets, calculate that final copy
1007                 */
1008                           if(indexMap[inMF.v1].merge_final)
1009                                   mf->v1 = calc_mapping(indexMap, indexMap[inMF.v1].merge, count-1);
1010                           if(indexMap[inMF.v2].merge_final)
1011                                   mf->v2 = calc_mapping(indexMap, indexMap[inMF.v2].merge, count-1);
1012                           if(indexMap[inMF.v3].merge_final)
1013                                   mf->v3 = calc_mapping(indexMap, indexMap[inMF.v3].merge, count-1);
1014                           if(inMF.v4 && indexMap[inMF.v4].merge_final)
1015                                   mf->v4 = calc_mapping(indexMap, indexMap[inMF.v4].merge, count-1);
1016
1017                           if(test_index_face(mf, &result->faceData, numFaces, inMF.v4?4:3) < 3)
1018                                   continue;
1019
1020                           numFaces++;
1021
1022                           /* if the face has fewer than 3 vertices, don't create it */
1023                           if(mf->v3 == 0 || (mf->v1 && (mf->v1 == mf->v3 || mf->v1 == mf->v4))) {
1024                                   numFaces--;
1025                                   DM_free_face_data(result, numFaces, 1);
1026                           }
1027
1028                           for(j = 1; j < count; j++)
1029                           {
1030                                   MFace *mf2 = &mface[numFaces];
1031
1032                                   DM_copy_face_data(dm, result, i, numFaces, 1);
1033                                   *mf2 = *mf;
1034
1035                                   mf2->v1 = calc_mapping(indexMap, inMF.v1, j);
1036                                   mf2->v2 = calc_mapping(indexMap, inMF.v2, j);
1037                                   mf2->v3 = calc_mapping(indexMap, inMF.v3, j);
1038                                   if (inMF.v4)
1039                                           mf2->v4 = calc_mapping(indexMap, inMF.v4, j);
1040
1041                                   test_index_face(mf2, &result->faceData, numFaces, inMF.v4?4:3);
1042                                   numFaces++;
1043
1044                                   /* if the face has fewer than 3 vertices, don't create it */
1045                                   if(mf2->v3 == 0 || (mf2->v1 && (mf2->v1 == mf2->v3 || mf2->v1 ==
1046                                                                  mf2->v4))) {
1047                                           numFaces--;
1048                                           DM_free_face_data(result, numFaces, 1);
1049                                                                  }
1050                           }
1051                   }
1052
1053                   /* add start and end caps */
1054                   if(start_cap) {
1055                           float startoffset[4][4];
1056                           MVert *cap_mvert;
1057                           MEdge *cap_medge;
1058                           MFace *cap_mface;
1059                           int *origindex;
1060                           int *vert_map;
1061                           int capVerts, capEdges, capFaces;
1062
1063                           capVerts = start_cap->getNumVerts(start_cap);
1064                           capEdges = start_cap->getNumEdges(start_cap);
1065                           capFaces = start_cap->getNumFaces(start_cap);
1066                           cap_mvert = start_cap->getVertArray(start_cap);
1067                           cap_medge = start_cap->getEdgeArray(start_cap);
1068                           cap_mface = start_cap->getFaceArray(start_cap);
1069
1070                           Mat4Invert(startoffset, offset);
1071
1072                           vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
1073                                           "arrayModifier_doArray vert_map");
1074
1075                           origindex = result->getVertDataArray(result, CD_ORIGINDEX);
1076                           for(i = 0; i < capVerts; i++) {
1077                                   MVert *mv = &cap_mvert[i];
1078                                   short merged = 0;
1079
1080                                   if(amd->flags & MOD_ARR_MERGE) {
1081                                           float tmp_co[3];
1082                                           MVert *in_mv;
1083                                           int j;
1084
1085                                           VECCOPY(tmp_co, mv->co);
1086                                           Mat4MulVecfl(startoffset, tmp_co);
1087
1088                                           for(j = 0; j < maxVerts; j++) {
1089                                                   in_mv = &src_mvert[j];
1090                                                   /* if this vert is within merge limit, merge */
1091                                                   if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
1092                                                           vert_map[i] = calc_mapping(indexMap, j, 0);
1093                                                           merged = 1;
1094                                                           break;
1095                                                   }
1096                                           }
1097                                   }
1098
1099                                   if(!merged) {
1100                                           DM_copy_vert_data(start_cap, result, i, numVerts, 1);
1101                                           mvert[numVerts] = *mv;
1102                                           Mat4MulVecfl(startoffset, mvert[numVerts].co);
1103                                           origindex[numVerts] = ORIGINDEX_NONE;
1104
1105                                           vert_map[i] = numVerts;
1106
1107                                           numVerts++;
1108                                   }
1109                           }
1110                           origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
1111                           for(i = 0; i < capEdges; i++) {
1112                                   int v1, v2;
1113
1114                                   v1 = vert_map[cap_medge[i].v1];
1115                                   v2 = vert_map[cap_medge[i].v2];
1116
1117                                   if(!BLI_edgehash_haskey(edges, v1, v2)) {
1118                                           DM_copy_edge_data(start_cap, result, i, numEdges, 1);
1119                                           medge[numEdges] = cap_medge[i];
1120                                           medge[numEdges].v1 = v1;
1121                                           medge[numEdges].v2 = v2;
1122                                           origindex[numEdges] = ORIGINDEX_NONE;
1123
1124                                           numEdges++;
1125                                   }
1126                           }
1127                           origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
1128                           for(i = 0; i < capFaces; i++) {
1129                                   DM_copy_face_data(start_cap, result, i, numFaces, 1);
1130                                   mface[numFaces] = cap_mface[i];
1131                                   mface[numFaces].v1 = vert_map[mface[numFaces].v1];
1132                                   mface[numFaces].v2 = vert_map[mface[numFaces].v2];
1133                                   mface[numFaces].v3 = vert_map[mface[numFaces].v3];
1134                                   if(mface[numFaces].v4) {
1135                                           mface[numFaces].v4 = vert_map[mface[numFaces].v4];
1136
1137                                           test_index_face(&mface[numFaces], &result->faceData,
1138                                                           numFaces, 4);
1139                                   }
1140                                   else
1141                                   {
1142                                           test_index_face(&mface[numFaces], &result->faceData,
1143                                                           numFaces, 3);
1144                                   }
1145
1146                                   origindex[numFaces] = ORIGINDEX_NONE;
1147
1148                                   numFaces++;
1149                           }
1150
1151                           MEM_freeN(vert_map);
1152                           start_cap->release(start_cap);
1153                   }
1154
1155                   if(end_cap) {
1156                           float endoffset[4][4];
1157                           MVert *cap_mvert;
1158                           MEdge *cap_medge;
1159                           MFace *cap_mface;
1160                           int *origindex;
1161                           int *vert_map;
1162                           int capVerts, capEdges, capFaces;
1163
1164                           capVerts = end_cap->getNumVerts(end_cap);
1165                           capEdges = end_cap->getNumEdges(end_cap);
1166                           capFaces = end_cap->getNumFaces(end_cap);
1167                           cap_mvert = end_cap->getVertArray(end_cap);
1168                           cap_medge = end_cap->getEdgeArray(end_cap);
1169                           cap_mface = end_cap->getFaceArray(end_cap);
1170
1171                           Mat4MulMat4(endoffset, final_offset, offset);
1172
1173                           vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
1174                                           "arrayModifier_doArray vert_map");
1175
1176                           origindex = result->getVertDataArray(result, CD_ORIGINDEX);
1177                           for(i = 0; i < capVerts; i++) {
1178                                   MVert *mv = &cap_mvert[i];
1179                                   short merged = 0;
1180
1181                                   if(amd->flags & MOD_ARR_MERGE) {
1182                                           float tmp_co[3];
1183                                           MVert *in_mv;
1184                                           int j;
1185
1186                                           VECCOPY(tmp_co, mv->co);
1187                                           Mat4MulVecfl(offset, tmp_co);
1188
1189                                           for(j = 0; j < maxVerts; j++) {
1190                                                   in_mv = &src_mvert[j];
1191                                                   /* if this vert is within merge limit, merge */
1192                                                   if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
1193                                                           vert_map[i] = calc_mapping(indexMap, j, count - 1);
1194                                                           merged = 1;
1195                                                           break;
1196                                                   }
1197                                           }
1198                                   }
1199
1200                                   if(!merged) {
1201                                           DM_copy_vert_data(end_cap, result, i, numVerts, 1);
1202                                           mvert[numVerts] = *mv;
1203                                           Mat4MulVecfl(endoffset, mvert[numVerts].co);
1204                                           origindex[numVerts] = ORIGINDEX_NONE;
1205
1206                                           vert_map[i] = numVerts;
1207
1208                                           numVerts++;
1209                                   }
1210                           }
1211                           origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
1212                           for(i = 0; i < capEdges; i++) {
1213                                   int v1, v2;
1214
1215                                   v1 = vert_map[cap_medge[i].v1];
1216                                   v2 = vert_map[cap_medge[i].v2];
1217
1218                                   if(!BLI_edgehash_haskey(edges, v1, v2)) {
1219                                           DM_copy_edge_data(end_cap, result, i, numEdges, 1);
1220                                           medge[numEdges] = cap_medge[i];
1221                                           medge[numEdges].v1 = v1;
1222                                           medge[numEdges].v2 = v2;
1223                                           origindex[numEdges] = ORIGINDEX_NONE;
1224
1225                                           numEdges++;
1226                                   }
1227                           }
1228                           origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
1229                           for(i = 0; i < capFaces; i++) {
1230                                   DM_copy_face_data(end_cap, result, i, numFaces, 1);
1231                                   mface[numFaces] = cap_mface[i];
1232                                   mface[numFaces].v1 = vert_map[mface[numFaces].v1];
1233                                   mface[numFaces].v2 = vert_map[mface[numFaces].v2];
1234                                   mface[numFaces].v3 = vert_map[mface[numFaces].v3];
1235                                   if(mface[numFaces].v4) {
1236                                           mface[numFaces].v4 = vert_map[mface[numFaces].v4];
1237
1238                                           test_index_face(&mface[numFaces], &result->faceData,
1239                                                           numFaces, 4);
1240                                   }
1241                                   else
1242                                   {
1243                                           test_index_face(&mface[numFaces], &result->faceData,
1244                                                           numFaces, 3);
1245                                   }
1246                                   origindex[numFaces] = ORIGINDEX_NONE;
1247
1248                                   numFaces++;
1249                           }
1250
1251                           MEM_freeN(vert_map);
1252                           end_cap->release(end_cap);
1253                   }
1254
1255                   BLI_edgehash_free(edges, NULL);
1256                   MEM_freeN(indexMap);
1257
1258                   CDDM_lower_num_verts(result, numVerts);
1259                   CDDM_lower_num_edges(result, numEdges);
1260                   CDDM_lower_num_faces(result, numFaces);
1261
1262                   return result;
1263 }
1264
1265 static DerivedMesh *arrayModifier_applyModifier(
1266                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
1267   int useRenderParams, int isFinalCalc)
1268 {
1269         DerivedMesh *result;
1270         ArrayModifierData *amd = (ArrayModifierData*) md;
1271
1272         result = arrayModifier_doArray(amd, ob, derivedData, 0);
1273
1274         if(result != derivedData)
1275                 CDDM_calc_normals(result);
1276
1277         return result;
1278 }
1279
1280 static DerivedMesh *arrayModifier_applyModifierEM(
1281                 ModifierData *md, Object *ob, EditMesh *editData,
1282   DerivedMesh *derivedData)
1283 {
1284         return arrayModifier_applyModifier(md, ob, derivedData, 0, 1);
1285 }
1286
1287 /* Mirror */
1288
1289 static void mirrorModifier_initData(ModifierData *md)
1290 {
1291         MirrorModifierData *mmd = (MirrorModifierData*) md;
1292
1293         mmd->flag |= (MOD_MIR_AXIS_X | MOD_MIR_VGROUP);
1294         mmd->tolerance = 0.001;
1295         mmd->mirror_ob = NULL;
1296 }
1297
1298 static void mirrorModifier_copyData(ModifierData *md, ModifierData *target)
1299 {
1300         MirrorModifierData *mmd = (MirrorModifierData*) md;
1301         MirrorModifierData *tmmd = (MirrorModifierData*) target;
1302
1303         tmmd->axis = mmd->axis;
1304         tmmd->flag = mmd->flag;
1305         tmmd->tolerance = mmd->tolerance;
1306         tmmd->mirror_ob = mmd->mirror_ob;;
1307 }
1308
1309 static void mirrorModifier_foreachObjectLink(
1310                                              ModifierData *md, Object *ob,
1311           void (*walk)(void *userData, Object *ob, Object **obpoin),
1312                  void *userData)
1313 {
1314         MirrorModifierData *mmd = (MirrorModifierData*) md;
1315
1316         walk(userData, ob, &mmd->mirror_ob);
1317 }
1318
1319 static void mirrorModifier_updateDepgraph(ModifierData *md, DagForest *forest,
1320                                           Object *ob, DagNode *obNode)
1321 {
1322         MirrorModifierData *mmd = (MirrorModifierData*) md;
1323
1324         if(mmd->mirror_ob) {
1325                 DagNode *latNode = dag_get_node(forest, mmd->mirror_ob);
1326
1327                 dag_add_relation(forest, latNode, obNode,
1328                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Mirror Modifier");
1329         }
1330 }
1331
1332 /* finds the best possible flipped name. For renaming; check for unique names afterwards */
1333 /* if strip_number: removes number extensions */
1334 void vertgroup_flip_name (char *name, int strip_number)
1335 {
1336         int     len;
1337         char    prefix[128]={""};   /* The part before the facing */
1338         char    suffix[128]={""};   /* The part after the facing */
1339         char    replace[128]={""};  /* The replacement string */
1340         char    number[128]={""};   /* The number extension string */
1341         char    *index=NULL;
1342
1343         len= strlen(name);
1344         if(len<3) return; // we don't do names like .R or .L
1345
1346         /* We first check the case with a .### extension, let's find the last period */
1347         if(isdigit(name[len-1])) {
1348                 index= strrchr(name, '.'); // last occurrance
1349                 if (index && isdigit(index[1]) ) { // doesnt handle case bone.1abc2 correct..., whatever!
1350                         if(strip_number==0) 
1351                                 strcpy(number, index);
1352                         *index= 0;
1353                         len= strlen(name);
1354                 }
1355         }
1356
1357         strcpy (prefix, name);
1358
1359 #define IS_SEPARATOR(a) ((a)=='.' || (a)==' ' || (a)=='-' || (a)=='_')
1360
1361         /* first case; separator . - _ with extensions r R l L  */
1362         if( IS_SEPARATOR(name[len-2]) ) {
1363                 switch(name[len-1]) {
1364                         case 'l':
1365                                 prefix[len-1]= 0;
1366                                 strcpy(replace, "r");
1367                                 break;
1368                         case 'r':
1369                                 prefix[len-1]= 0;
1370                                 strcpy(replace, "l");
1371                                 break;
1372                         case 'L':
1373                                 prefix[len-1]= 0;
1374                                 strcpy(replace, "R");
1375                                 break;
1376                         case 'R':
1377                                 prefix[len-1]= 0;
1378                                 strcpy(replace, "L");
1379                                 break;
1380                 }
1381         }
1382         /* case; beginning with r R l L , with separator after it */
1383         else if( IS_SEPARATOR(name[1]) ) {
1384                 switch(name[0]) {
1385                         case 'l':
1386                                 strcpy(replace, "r");
1387                                 strcpy(suffix, name+1);
1388                                 prefix[0]= 0;
1389                                 break;
1390                         case 'r':
1391                                 strcpy(replace, "l");
1392                                 strcpy(suffix, name+1);
1393                                 prefix[0]= 0;
1394                                 break;
1395                         case 'L':
1396                                 strcpy(replace, "R");
1397                                 strcpy(suffix, name+1);
1398                                 prefix[0]= 0;
1399                                 break;
1400                         case 'R':
1401                                 strcpy(replace, "L");
1402                                 strcpy(suffix, name+1);
1403                                 prefix[0]= 0;
1404                                 break;
1405                 }
1406         }
1407         else if(len > 5) {
1408                 /* hrms, why test for a separator? lets do the rule 'ultimate left or right' */
1409                 index = BLI_strcasestr(prefix, "right");
1410                 if (index==prefix || index==prefix+len-5) {
1411                         if(index[0]=='r') 
1412                                 strcpy (replace, "left");
1413                         else {
1414                                 if(index[1]=='I') 
1415                                         strcpy (replace, "LEFT");
1416                                 else
1417                                         strcpy (replace, "Left");
1418                         }
1419                         *index= 0;
1420                         strcpy (suffix, index+5);
1421                 }
1422                 else {
1423                         index = BLI_strcasestr(prefix, "left");
1424                         if (index==prefix || index==prefix+len-4) {
1425                                 if(index[0]=='l') 
1426                                         strcpy (replace, "right");
1427                                 else {
1428                                         if(index[1]=='E') 
1429                                                 strcpy (replace, "RIGHT");
1430                                         else
1431                                                 strcpy (replace, "Right");
1432                                 }
1433                                 *index= 0;
1434                                 strcpy (suffix, index+4);
1435                         }
1436                 }
1437         }
1438
1439 #undef IS_SEPARATOR
1440
1441         sprintf (name, "%s%s%s%s", prefix, replace, suffix, number);
1442 }
1443
1444 static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
1445                 Object *ob,
1446                 DerivedMesh *dm,
1447                 int initFlags,
1448                 int axis)
1449 {
1450         int i;
1451         float tolerance = mmd->tolerance;
1452         DerivedMesh *result;
1453         int numVerts, numEdges, numFaces;
1454         int maxVerts = dm->getNumVerts(dm);
1455         int maxEdges = dm->getNumEdges(dm);
1456         int maxFaces = dm->getNumFaces(dm);
1457         int vector_size=0, j, a, b;
1458         bDeformGroup *def, *defb;
1459         bDeformGroup **vector_def = NULL;
1460         int (*indexMap)[2];
1461         float mtx[4][4], imtx[4][4];
1462
1463         numVerts = numEdges = numFaces = 0;
1464
1465         indexMap = MEM_mallocN(sizeof(*indexMap) * maxVerts, "indexmap");
1466
1467         result = CDDM_from_template(dm, maxVerts * 2, maxEdges * 2, maxFaces * 2);
1468
1469
1470         if (mmd->flag & MOD_MIR_VGROUP) {
1471                 /* calculate the number of deformedGroups */
1472                 for(vector_size = 0, def = ob->defbase.first; def;
1473                     def = def->next, vector_size++);
1474
1475                 /* load the deformedGroups for fast access */
1476                 vector_def =
1477                     (bDeformGroup **)MEM_mallocN(sizeof(bDeformGroup*) * vector_size,
1478                                                  "group_index");
1479                 for(a = 0, def = ob->defbase.first; def; def = def->next, a++) {
1480                         vector_def[a] = def;
1481                 }
1482         }
1483
1484         if (mmd->mirror_ob) {
1485                 float obinv[4][4];
1486                 
1487                 Mat4Invert(obinv, mmd->mirror_ob->obmat);
1488                 Mat4MulMat4(mtx, ob->obmat, obinv);
1489                 Mat4Invert(imtx, mtx);
1490         }
1491
1492         for(i = 0; i < maxVerts; i++) {
1493                 MVert inMV;
1494                 MVert *mv = CDDM_get_vert(result, numVerts);
1495                 int isShared;
1496                 float co[3];
1497                 
1498                 dm->getVert(dm, i, &inMV);
1499                 
1500                 VecCopyf(co, inMV.co);
1501                 
1502                 if (mmd->mirror_ob) {
1503                         VecMat4MulVecfl(co, mtx, co);
1504                 }
1505                 isShared = ABS(co[axis])<=tolerance;
1506                 
1507                 /* Because the topology result (# of vertices) must be the same if
1508                 * the mesh data is overridden by vertex cos, have to calc sharedness
1509                 * based on original coordinates. This is why we test before copy.
1510                 */
1511                 DM_copy_vert_data(dm, result, i, numVerts, 1);
1512                 *mv = inMV;
1513                 numVerts++;
1514                 
1515                 indexMap[i][0] = numVerts - 1;
1516                 indexMap[i][1] = !isShared;
1517                 
1518                 if(isShared) {
1519                         co[axis] = 0;
1520                         if (mmd->mirror_ob) {
1521                                 VecMat4MulVecfl(co, imtx, co);
1522                         }
1523                         VecCopyf(mv->co, co);
1524                         
1525                         mv->flag |= ME_VERT_MERGED;
1526                 } else {
1527                         MVert *mv2 = CDDM_get_vert(result, numVerts);
1528                         MDeformVert *dvert = NULL;
1529                         
1530                         DM_copy_vert_data(dm, result, i, numVerts, 1);
1531                         *mv2 = *mv;
1532                         
1533                         co[axis] = -co[axis];
1534                         if (mmd->mirror_ob) {
1535                                 VecMat4MulVecfl(co, imtx, co);
1536                         }
1537                         VecCopyf(mv2->co, co);
1538                         
1539                         if (mmd->flag & MOD_MIR_VGROUP){
1540                                 dvert = DM_get_vert_data(result, numVerts, CD_MDEFORMVERT);
1541                                 
1542                                 if (dvert)
1543                                 {
1544                                         for(j = 0; j < dvert[0].totweight; ++j)
1545                                         {
1546                                                 char tmpname[32];
1547                                                 
1548                                                 if(dvert->dw[j].def_nr < 0 ||
1549                                                    dvert->dw[j].def_nr >= vector_size)
1550                                                         continue;
1551                                                 
1552                                                 def = vector_def[dvert->dw[j].def_nr];
1553                                                 strcpy(tmpname, def->name);
1554                                                 vertgroup_flip_name(tmpname,0);
1555                                                 
1556                                                 for(b = 0, defb = ob->defbase.first; defb;
1557                                                     defb = defb->next, b++)
1558                                                 {
1559                                                         if(!strcmp(defb->name, tmpname))
1560                                                         {
1561                                                                 dvert->dw[j].def_nr = b;
1562                                                                 break;
1563                                                         }
1564                                                 }
1565                                         }
1566                                 }
1567                         }
1568                         
1569                         numVerts++;
1570                 }
1571         }
1572
1573         for(i = 0; i < maxEdges; i++) {
1574                 MEdge inMED;
1575                 MEdge *med = CDDM_get_edge(result, numEdges);
1576                 
1577                 dm->getEdge(dm, i, &inMED);
1578                 
1579                 DM_copy_edge_data(dm, result, i, numEdges, 1);
1580                 *med = inMED;
1581                 numEdges++;
1582                 
1583                 med->v1 = indexMap[inMED.v1][0];
1584                 med->v2 = indexMap[inMED.v2][0];
1585                 if(initFlags)
1586                         med->flag |= ME_EDGEDRAW | ME_EDGERENDER;
1587                 
1588                 if(indexMap[inMED.v1][1] || indexMap[inMED.v2][1]) {
1589                         MEdge *med2 = CDDM_get_edge(result, numEdges);
1590                         
1591                         DM_copy_edge_data(dm, result, i, numEdges, 1);
1592                         *med2 = *med;
1593                         numEdges++;
1594                         
1595                         med2->v1 += indexMap[inMED.v1][1];
1596                         med2->v2 += indexMap[inMED.v2][1];
1597                 }
1598         }
1599
1600         for(i = 0; i < maxFaces; i++) {
1601                 MFace inMF;
1602                 MFace *mf = CDDM_get_face(result, numFaces);
1603                 
1604                 dm->getFace(dm, i, &inMF);
1605                 
1606                 DM_copy_face_data(dm, result, i, numFaces, 1);
1607                 *mf = inMF;
1608                 numFaces++;
1609                 
1610                 mf->v1 = indexMap[inMF.v1][0];
1611                 mf->v2 = indexMap[inMF.v2][0];
1612                 mf->v3 = indexMap[inMF.v3][0];
1613                 mf->v4 = indexMap[inMF.v4][0];
1614                 
1615                 if(indexMap[inMF.v1][1]
1616                                  || indexMap[inMF.v2][1]
1617                                  || indexMap[inMF.v3][1]
1618                                  || (mf->v4 && indexMap[inMF.v4][1])) {
1619                         MFace *mf2 = CDDM_get_face(result, numFaces);
1620                         static int corner_indices[4] = {2, 1, 0, 3};
1621                         
1622                         DM_copy_face_data(dm, result, i, numFaces, 1);
1623                         *mf2 = *mf;
1624                         
1625                         mf2->v1 += indexMap[inMF.v1][1];
1626                         mf2->v2 += indexMap[inMF.v2][1];
1627                         mf2->v3 += indexMap[inMF.v3][1];
1628                         if(inMF.v4) mf2->v4 += indexMap[inMF.v4][1];
1629                         
1630                         /* mirror UVs if enabled */
1631                         if(mmd->flag & (MOD_MIR_MIRROR_U | MOD_MIR_MIRROR_V)) {
1632                                 MTFace *tf = result->getFaceData(result, numFaces, CD_MTFACE);
1633                                 if(tf) {
1634                                         int j;
1635                                         for(j = 0; j < 4; ++j) {
1636                                                 if(mmd->flag & MOD_MIR_MIRROR_U)
1637                                                         tf->uv[j][0] = 1.0f - tf->uv[j][0];
1638                                                 if(mmd->flag & MOD_MIR_MIRROR_V)
1639                                                         tf->uv[j][1] = 1.0f - tf->uv[j][1];
1640                                         }
1641                                 }
1642                         }
1643                         
1644                         /* Flip face normal */
1645                         SWAP(int, mf2->v1, mf2->v3);
1646                         DM_swap_face_data(result, numFaces, corner_indices);
1647                         
1648                         test_index_face(mf2, &result->faceData, numFaces, inMF.v4?4:3);
1649                         numFaces++;
1650                 }
1651         }
1652
1653         if (vector_def) MEM_freeN(vector_def);
1654
1655         MEM_freeN(indexMap);
1656
1657         CDDM_lower_num_verts(result, numVerts);
1658         CDDM_lower_num_edges(result, numEdges);
1659         CDDM_lower_num_faces(result, numFaces);
1660
1661         return result;
1662 }
1663
1664 static DerivedMesh *mirrorModifier__doMirror(MirrorModifierData *mmd,
1665                                             Object *ob, DerivedMesh *dm,
1666                                                 int initFlags)
1667 {
1668         DerivedMesh *result = dm;
1669
1670         /* check which axes have been toggled and mirror accordingly */
1671         if(mmd->flag & MOD_MIR_AXIS_X) {
1672                 result = doMirrorOnAxis(mmd, ob, result, initFlags, 0);
1673         }
1674         if(mmd->flag & MOD_MIR_AXIS_Y) {
1675                 DerivedMesh *tmp = result;
1676                 result = doMirrorOnAxis(mmd, ob, result, initFlags, 1);
1677                 if(tmp != dm) tmp->release(tmp); /* free intermediate results */
1678         }
1679         if(mmd->flag & MOD_MIR_AXIS_Z) {
1680                 DerivedMesh *tmp = result;
1681                 result = doMirrorOnAxis(mmd, ob, result, initFlags, 2);
1682                 if(tmp != dm) tmp->release(tmp); /* free intermediate results */
1683         }
1684
1685         return result;
1686 }
1687
1688 static DerivedMesh *mirrorModifier_applyModifier(
1689                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
1690   int useRenderParams, int isFinalCalc)
1691 {
1692         DerivedMesh *result;
1693         MirrorModifierData *mmd = (MirrorModifierData*) md;
1694
1695         result = mirrorModifier__doMirror(mmd, ob, derivedData, 0);
1696
1697         if(result != derivedData)
1698                 CDDM_calc_normals(result);
1699         
1700         return result;
1701 }
1702
1703 static DerivedMesh *mirrorModifier_applyModifierEM(
1704                 ModifierData *md, Object *ob, EditMesh *editData,
1705   DerivedMesh *derivedData)
1706 {
1707         return mirrorModifier_applyModifier(md, ob, derivedData, 0, 1);
1708 }
1709
1710 /* EdgeSplit */
1711 /* EdgeSplit modifier: Splits edges in the mesh according to sharpness flag
1712  * or edge angle (can be used to achieve autosmoothing)
1713 */
1714 #if 0
1715 #define EDGESPLIT_DEBUG_3
1716 #define EDGESPLIT_DEBUG_2
1717 #define EDGESPLIT_DEBUG_1
1718 #define EDGESPLIT_DEBUG_0
1719 #endif
1720
1721 static void edgesplitModifier_initData(ModifierData *md)
1722 {
1723         EdgeSplitModifierData *emd = (EdgeSplitModifierData*) md;
1724
1725         /* default to 30-degree split angle, sharpness from both angle & flag
1726         */
1727         emd->split_angle = 30;
1728         emd->flags = MOD_EDGESPLIT_FROMANGLE | MOD_EDGESPLIT_FROMFLAG;
1729 }
1730
1731 static void edgesplitModifier_copyData(ModifierData *md, ModifierData *target)
1732 {
1733         EdgeSplitModifierData *emd = (EdgeSplitModifierData*) md;
1734         EdgeSplitModifierData *temd = (EdgeSplitModifierData*) target;
1735
1736         temd->split_angle = emd->split_angle;
1737         temd->flags = emd->flags;
1738 }
1739
1740 /* Mesh data for edgesplit operation */
1741 typedef struct SmoothVert {
1742         LinkNode *faces;     /* all faces which use this vert */
1743         int oldIndex; /* the index of the original DerivedMesh vert */
1744         int newIndex; /* the index of the new DerivedMesh vert */
1745 } SmoothVert;
1746
1747 #define SMOOTHEDGE_NUM_VERTS 2
1748
1749 typedef struct SmoothEdge {
1750         SmoothVert *verts[SMOOTHEDGE_NUM_VERTS]; /* the verts used by this edge */
1751         LinkNode *faces;     /* all faces which use this edge */
1752         int oldIndex; /* the index of the original DerivedMesh edge */
1753         int newIndex; /* the index of the new DerivedMesh edge */
1754         short flag; /* the flags from the original DerivedMesh edge */
1755 } SmoothEdge;
1756
1757 #define SMOOTHFACE_MAX_EDGES 4
1758
1759 typedef struct SmoothFace {
1760         SmoothEdge *edges[SMOOTHFACE_MAX_EDGES]; /* nonexistent edges == NULL */
1761         int flip[SMOOTHFACE_MAX_EDGES]; /* 1 = flip edge dir, 0 = don't flip */
1762         float normal[3]; /* the normal of this face */
1763         int oldIndex; /* the index of the original DerivedMesh face */
1764         int newIndex; /* the index of the new DerivedMesh face */
1765 } SmoothFace;
1766
1767 typedef struct SmoothMesh {
1768         SmoothVert *verts;
1769         SmoothEdge *edges;
1770         SmoothFace *faces;
1771         int num_verts, num_edges, num_faces;
1772         int max_verts, max_edges, max_faces;
1773         DerivedMesh *dm;
1774         float threshold; /* the cosine of the smoothing angle */
1775         int flags;
1776 } SmoothMesh;
1777
1778 static SmoothVert *smoothvert_copy(SmoothVert *vert, SmoothMesh *mesh)
1779 {
1780         SmoothVert *copy = &mesh->verts[mesh->num_verts];
1781
1782         if(mesh->num_verts >= mesh->max_verts) {
1783                 printf("Attempted to add a SmoothMesh vert beyond end of array\n");
1784                 return NULL;
1785         }
1786
1787         *copy = *vert;
1788         copy->faces = NULL;
1789         copy->newIndex = mesh->num_verts;
1790         ++mesh->num_verts;
1791
1792 #ifdef EDGESPLIT_DEBUG_2
1793         printf("copied vert %4d to vert %4d\n", vert->newIndex, copy->newIndex);
1794 #endif
1795         return copy;
1796 }
1797
1798 static SmoothEdge *smoothedge_copy(SmoothEdge *edge, SmoothMesh *mesh)
1799 {
1800         SmoothEdge *copy = &mesh->edges[mesh->num_edges];
1801
1802         if(mesh->num_edges >= mesh->max_edges) {
1803                 printf("Attempted to add a SmoothMesh edge beyond end of array\n");
1804                 return NULL;
1805         }
1806
1807         *copy = *edge;
1808         copy->faces = NULL;
1809         copy->newIndex = mesh->num_edges;
1810         ++mesh->num_edges;
1811
1812 #ifdef EDGESPLIT_DEBUG_2
1813         printf("copied edge %4d to edge %4d\n", edge->newIndex, copy->newIndex);
1814 #endif
1815         return copy;
1816 }
1817
1818 static int smoothedge_has_vert(SmoothEdge *edge, SmoothVert *vert)
1819 {
1820         int i;
1821         for(i = 0; i < SMOOTHEDGE_NUM_VERTS; i++)
1822                 if(edge->verts[i] == vert) return 1;
1823
1824         return 0;
1825 }
1826
1827 static SmoothMesh *smoothmesh_new(int num_verts, int num_edges, int num_faces,
1828                                   int max_verts, int max_edges, int max_faces)
1829 {
1830         SmoothMesh *mesh = MEM_callocN(sizeof(*mesh), "smoothmesh");
1831         mesh->verts = MEM_callocN(sizeof(*mesh->verts) * max_verts,
1832                                   "SmoothMesh.verts");
1833         mesh->edges = MEM_callocN(sizeof(*mesh->edges) * max_edges,
1834                                   "SmoothMesh.edges");
1835         mesh->faces = MEM_callocN(sizeof(*mesh->faces) * max_faces,
1836                                   "SmoothMesh.faces");
1837
1838         mesh->num_verts = num_verts;
1839         mesh->num_edges = num_edges;
1840         mesh->num_faces = num_faces;
1841
1842         mesh->max_verts = max_verts;
1843         mesh->max_edges = max_edges;
1844         mesh->max_faces = max_faces;
1845
1846         return mesh;
1847 }
1848
1849 static void smoothmesh_free(SmoothMesh *mesh)
1850 {
1851         int i;
1852
1853         for(i = 0; i < mesh->num_verts; ++i)
1854                 BLI_linklist_free(mesh->verts[i].faces, NULL);
1855
1856         for(i = 0; i < mesh->num_edges; ++i)
1857                 BLI_linklist_free(mesh->edges[i].faces, NULL);
1858
1859         MEM_freeN(mesh->verts);
1860         MEM_freeN(mesh->edges);
1861         MEM_freeN(mesh->faces);
1862         MEM_freeN(mesh);
1863 }
1864
1865 static void smoothmesh_resize_verts(SmoothMesh *mesh, int max_verts)
1866 {
1867         int i;
1868         SmoothVert *tmp;
1869
1870         if(max_verts <= mesh->max_verts) return;
1871
1872         tmp = MEM_callocN(sizeof(*tmp) * max_verts, "SmoothMesh.verts");
1873
1874         memcpy(tmp, mesh->verts, sizeof(*tmp) * mesh->num_verts);
1875
1876         /* remap vert pointers in edges */
1877         for(i = 0; i < mesh->num_edges; ++i) {
1878                 int j;
1879                 SmoothEdge *edge = &mesh->edges[i];
1880
1881                 for(j = 0; j < SMOOTHEDGE_NUM_VERTS; ++j)
1882                         /* pointer arithmetic to get vert array index */
1883                         edge->verts[j] = &tmp[edge->verts[j] - mesh->verts];
1884         }
1885
1886         MEM_freeN(mesh->verts);
1887         mesh->verts = tmp;
1888         mesh->max_verts = max_verts;
1889 }
1890
1891 static void smoothmesh_resize_edges(SmoothMesh *mesh, int max_edges)
1892 {
1893         int i;
1894         SmoothEdge *tmp;
1895
1896         if(max_edges <= mesh->max_edges) return;
1897
1898         tmp = MEM_callocN(sizeof(*tmp) * max_edges, "SmoothMesh.edges");
1899
1900         memcpy(tmp, mesh->edges, sizeof(*tmp) * mesh->num_edges);
1901
1902         /* remap edge pointers in faces */
1903         for(i = 0; i < mesh->num_faces; ++i) {
1904                 int j;
1905                 SmoothFace *face = &mesh->faces[i];
1906
1907                 for(j = 0; j < SMOOTHFACE_MAX_EDGES; ++j)
1908                         if(face->edges[j])
1909                                 /* pointer arithmetic to get edge array index */
1910                                 face->edges[j] = &tmp[face->edges[j] - mesh->edges];
1911         }
1912
1913         MEM_freeN(mesh->edges);
1914         mesh->edges = tmp;
1915         mesh->max_edges = max_edges;
1916 }
1917
1918 #ifdef EDGESPLIT_DEBUG_0
1919 static void smoothmesh_print(SmoothMesh *mesh)
1920 {
1921         int i, j;
1922         DerivedMesh *dm = mesh->dm;
1923
1924         printf("--- SmoothMesh ---\n");
1925         printf("--- Vertices ---\n");
1926         for(i = 0; i < mesh->num_verts; i++) {
1927                 SmoothVert *vert = &mesh->verts[i];
1928                 LinkNode *node;
1929                 MVert mv;
1930
1931                 dm->getVert(dm, vert->oldIndex, &mv);
1932
1933                 printf("%3d: ind={%3d, %3d}, pos={% 5.1f, % 5.1f, % 5.1f}",
1934                        i, vert->oldIndex, vert->newIndex,
1935          mv.co[0], mv.co[1], mv.co[2]);
1936                 printf(", faces={");
1937                 for(node = vert->faces; node != NULL; node = node->next) {
1938                         printf(" %d", ((SmoothFace *)node->link)->newIndex);
1939                 }
1940                 printf("}\n");
1941         }
1942
1943         printf("\n--- Edges ---\n");
1944         for(i = 0; i < mesh->num_edges; i++) {
1945                 SmoothEdge *edge = &mesh->edges[i];
1946                 LinkNode *node;
1947
1948                 printf("%4d: indices={%4d, %4d}, verts={%4d, %4d}",
1949                        i,
1950          edge->oldIndex, edge->newIndex,
1951   edge->verts[0]->newIndex, edge->verts[1]->newIndex);
1952                 if(edge->verts[0] == edge->verts[1]) printf(" <- DUPLICATE VERTEX");
1953                 printf(", faces={");
1954                 for(node = edge->faces; node != NULL; node = node->next) {
1955                         printf(" %d", ((SmoothFace *)node->link)->newIndex);
1956                 }
1957                 printf("}\n");
1958         }
1959
1960         printf("\n--- Faces ---\n");
1961         for(i = 0; i < mesh->num_faces; i++) {
1962                 SmoothFace *face = &mesh->faces[i];
1963
1964                 printf("%4d: indices={%4d, %4d}, edges={", i,
1965                        face->oldIndex, face->newIndex);
1966                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
1967                         if(face->flip[j])
1968                                 printf(" -%-2d", face->edges[j]->newIndex);
1969                         else
1970                                 printf("  %-2d", face->edges[j]->newIndex);
1971                 }
1972                 printf("}, verts={");
1973                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
1974                         printf(" %d", face->edges[j]->verts[face->flip[j]]->newIndex);
1975                 }
1976                 printf("}\n");
1977         }
1978 }
1979 #endif
1980
1981 static SmoothMesh *smoothmesh_from_derivedmesh(DerivedMesh *dm)
1982 {
1983         SmoothMesh *mesh;
1984         EdgeHash *edges = BLI_edgehash_new();
1985         int i;
1986         int totvert, totedge, totface;
1987
1988         totvert = dm->getNumVerts(dm);
1989         totedge = dm->getNumEdges(dm);
1990         totface = dm->getNumFaces(dm);
1991
1992         mesh = smoothmesh_new(totvert, totedge, totface,
1993                               totvert, totedge, totface);
1994
1995         mesh->dm = dm;
1996
1997         for(i = 0; i < totvert; i++) {
1998                 SmoothVert *vert = &mesh->verts[i];
1999
2000                 vert->oldIndex = vert->newIndex = i;
2001         }
2002
2003         for(i = 0; i < totedge; i++) {
2004                 SmoothEdge *edge = &mesh->edges[i];
2005                 MEdge med;
2006
2007                 dm->getEdge(dm, i, &med);
2008                 edge->verts[0] = &mesh->verts[med.v1];
2009                 edge->verts[1] = &mesh->verts[med.v2];
2010                 edge->oldIndex = edge->newIndex = i;
2011                 edge->flag = med.flag;
2012
2013                 BLI_edgehash_insert(edges, med.v1, med.v2, edge);
2014         }
2015
2016         for(i = 0; i < totface; i++) {
2017                 SmoothFace *face = &mesh->faces[i];
2018                 MFace mf;
2019                 MVert v1, v2, v3;
2020                 int j;
2021
2022                 dm->getFace(dm, i, &mf);
2023
2024                 dm->getVert(dm, mf.v1, &v1);
2025                 dm->getVert(dm, mf.v2, &v2);
2026                 dm->getVert(dm, mf.v3, &v3);
2027                 face->edges[0] = BLI_edgehash_lookup(edges, mf.v1, mf.v2);
2028                 if(face->edges[0]->verts[1]->oldIndex == mf.v1) face->flip[0] = 1;
2029                 face->edges[1] = BLI_edgehash_lookup(edges, mf.v2, mf.v3);
2030                 if(face->edges[1]->verts[1]->oldIndex == mf.v2) face->flip[1] = 1;
2031                 if(mf.v4) {
2032                         MVert v4;
2033                         dm->getVert(dm, mf.v4, &v4);
2034                         face->edges[2] = BLI_edgehash_lookup(edges, mf.v3, mf.v4);
2035                         if(face->edges[2]->verts[1]->oldIndex == mf.v3) face->flip[2] = 1;
2036                         face->edges[3] = BLI_edgehash_lookup(edges, mf.v4, mf.v1);
2037                         if(face->edges[3]->verts[1]->oldIndex == mf.v4) face->flip[3] = 1;
2038                         CalcNormFloat4(v1.co, v2.co, v3.co, v4.co, face->normal);
2039                 } else {
2040                         face->edges[2] = BLI_edgehash_lookup(edges, mf.v3, mf.v1);
2041                         if(face->edges[2]->verts[1]->oldIndex == mf.v3) face->flip[2] = 1;
2042                         face->edges[3] = NULL;
2043                         CalcNormFloat(v1.co, v2.co, v3.co, face->normal);
2044                 }
2045
2046                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
2047                         SmoothEdge *edge = face->edges[j];
2048                         BLI_linklist_prepend(&edge->faces, face);
2049                         BLI_linklist_prepend(&edge->verts[face->flip[j]]->faces, face);
2050                 }
2051
2052                 face->oldIndex = face->newIndex = i;
2053         }
2054
2055         BLI_edgehash_free(edges, NULL);
2056
2057         return mesh;
2058 }
2059
2060 static DerivedMesh *CDDM_from_smoothmesh(SmoothMesh *mesh)
2061 {
2062         DerivedMesh *result = CDDM_from_template(mesh->dm,
2063                         mesh->num_verts,
2064    mesh->num_edges,
2065    mesh->num_faces);
2066         MVert *new_verts = CDDM_get_verts(result);
2067         MEdge *new_edges = CDDM_get_edges(result);
2068         MFace *new_faces = CDDM_get_faces(result);
2069         int i;
2070
2071         for(i = 0; i < mesh->num_verts; ++i) {
2072                 SmoothVert *vert = &mesh->verts[i];
2073                 MVert *newMV = &new_verts[vert->newIndex];
2074
2075                 DM_copy_vert_data(mesh->dm, result,
2076                                   vert->oldIndex, vert->newIndex, 1);
2077                 mesh->dm->getVert(mesh->dm, vert->oldIndex, newMV);
2078         }
2079
2080         for(i = 0; i < mesh->num_edges; ++i) {
2081                 SmoothEdge *edge = &mesh->edges[i];
2082                 MEdge *newME = &new_edges[edge->newIndex];
2083
2084                 DM_copy_edge_data(mesh->dm, result,
2085                                   edge->oldIndex, edge->newIndex, 1);
2086                 mesh->dm->getEdge(mesh->dm, edge->oldIndex, newME);
2087                 newME->v1 = edge->verts[0]->newIndex;
2088                 newME->v2 = edge->verts[1]->newIndex;
2089         }
2090
2091         for(i = 0; i < mesh->num_faces; ++i) {
2092                 SmoothFace *face = &mesh->faces[i];
2093                 MFace *newMF = &new_faces[face->newIndex];
2094
2095                 DM_copy_face_data(mesh->dm, result,
2096                                   face->oldIndex, face->newIndex, 1);
2097                 mesh->dm->getFace(mesh->dm, face->oldIndex, newMF);
2098
2099                 newMF->v1 = face->edges[0]->verts[face->flip[0]]->newIndex;
2100                 newMF->v2 = face->edges[1]->verts[face->flip[1]]->newIndex;
2101                 newMF->v3 = face->edges[2]->verts[face->flip[2]]->newIndex;
2102
2103                 if(face->edges[3]) {
2104                         newMF->v4 = face->edges[3]->verts[face->flip[3]]->newIndex;
2105                 } else {
2106                         newMF->v4 = 0;
2107                 }
2108         }
2109
2110         return result;
2111 }
2112
2113 /* returns the other vert in the given edge
2114  */
2115 static SmoothVert *other_vert(SmoothEdge *edge, SmoothVert *vert)
2116 {
2117         if(edge->verts[0] == vert) return edge->verts[1];
2118         else return edge->verts[0];
2119 }
2120
2121 /* returns the other edge in the given face that uses the given vert
2122  * returns NULL if no other edge in the given face uses the given vert
2123  * (this should never happen)
2124  */
2125 static SmoothEdge *other_edge(SmoothFace *face, SmoothVert *vert,
2126                               SmoothEdge *edge)
2127 {
2128         int i,j;
2129         for(i = 0; i < SMOOTHFACE_MAX_EDGES && face->edges[i]; i++) {
2130                 SmoothEdge *tmp_edge = face->edges[i];
2131                 if(tmp_edge == edge) continue;
2132
2133                 for(j = 0; j < SMOOTHEDGE_NUM_VERTS; j++)
2134                         if(tmp_edge->verts[j] == vert) return tmp_edge;
2135         }
2136
2137         /* if we get to here, something's wrong (there should always be 2 edges
2138         * which use the same vert in a face)
2139         */
2140         return NULL;
2141 }
2142
2143 /* returns a face attached to the given edge which is not the given face.
2144  * returns NULL if no other faces use this edge.
2145  */
2146 static SmoothFace *other_face(SmoothEdge *edge, SmoothFace *face)
2147 {
2148         LinkNode *node;
2149
2150         for(node = edge->faces; node != NULL; node = node->next)
2151                 if(node->link != face) return node->link;
2152
2153         return NULL;
2154 }
2155
2156 #if 0
2157 /* copies source list to target, overwriting target (target is not freed)
2158  * nodes in the copy will be in the same order as in source
2159  */
2160 static void linklist_copy(LinkNode **target, LinkNode *source)
2161 {
2162         LinkNode *node = NULL;
2163         *target = NULL;
2164
2165         for(; source; source = source->next) {
2166                 if(node) {
2167                         node->next = MEM_mallocN(sizeof(*node->next), "nlink_copy");
2168                                                                                 node = node->next;
2169 } else {
2170                                                                                 node = *target = MEM_mallocN(sizeof(**target), "nlink_copy");
2171 }
2172                                                                                 node->link = source->link;
2173                                                                                 node->next = NULL;
2174 }
2175 }
2176 #endif
2177
2178                                                                                 /* appends source to target if it's not already in target */
2179                                                                                 static void linklist_append_unique(LinkNode **target, void *source) 
2180 {
2181         LinkNode *node;
2182         LinkNode *prev = NULL;
2183
2184         /* check if source value is already in the list */
2185         for(node = *target; node; prev = node, node = node->next)
2186                 if(node->link == source) return;
2187
2188         node = MEM_mallocN(sizeof(*node), "nlink");
2189         node->next = NULL;
2190         node->link = source;
2191
2192         if(prev) prev->next = node;
2193         else *target = node;
2194 }
2195
2196 /* appends elements of source which aren't already in target to target */
2197 static void linklist_append_list_unique(LinkNode **target, LinkNode *source)
2198 {
2199         for(; source; source = source->next)
2200                 linklist_append_unique(target, source->link);
2201 }
2202
2203 #if 0 /* this is no longer used, it should possibly be removed */
2204 /* prepends prepend to list - doesn't copy nodes, just joins the lists */
2205 static void linklist_prepend_linklist(LinkNode **list, LinkNode *prepend)
2206 {
2207         if(prepend) {
2208                 LinkNode *node = prepend;
2209                 while(node->next) node = node->next;
2210
2211                 node->next = *list;
2212                 *list = prepend;
2213 }
2214 }
2215 #endif
2216
2217 /* returns 1 if the linked list contains the given pointer, 0 otherwise
2218  */
2219 static int linklist_contains(LinkNode *list, void *ptr)
2220 {
2221         LinkNode *node;
2222
2223         for(node = list; node; node = node->next)
2224                 if(node->link == ptr) return 1;
2225
2226         return 0;
2227 }
2228
2229 /* returns 1 if the first linked list is a subset of the second (comparing
2230  * pointer values), 0 if not
2231  */
2232 static int linklist_subset(LinkNode *list1, LinkNode *list2)
2233 {
2234         for(; list1; list1 = list1->next)
2235                 if(!linklist_contains(list2, list1->link))
2236                         return 0;
2237
2238         return 1;
2239 }
2240
2241 #if 0
2242 /* empties the linked list
2243  * frees pointers with freefunc if freefunc is not NULL
2244  */
2245 static void linklist_empty(LinkNode **list, LinkNodeFreeFP freefunc)
2246 {
2247         BLI_linklist_free(*list, freefunc);
2248         *list = NULL;
2249 }
2250 #endif
2251
2252 /* removes the first instance of value from the linked list
2253  * frees the pointer with freefunc if freefunc is not NULL
2254  */
2255 static void linklist_remove_first(LinkNode **list, void *value,
2256                                   LinkNodeFreeFP freefunc)
2257 {
2258         LinkNode *node = *list;
2259         LinkNode *prev = NULL;
2260
2261         while(node && node->link != value) {
2262                 prev = node;
2263                 node = node->next;
2264         }
2265
2266         if(node) {
2267                 if(prev)
2268                         prev->next = node->next;
2269                 else
2270                         *list = node->next;
2271
2272                 if(freefunc)
2273                         freefunc(node->link);
2274
2275                 MEM_freeN(node);
2276         }
2277 }
2278
2279 /* removes all elements in source from target */
2280 static void linklist_remove_list(LinkNode **target, LinkNode *source,
2281                                  LinkNodeFreeFP freefunc)
2282 {
2283         for(; source; source = source->next)
2284                 linklist_remove_first(target, source->link, freefunc);
2285 }
2286
2287 #ifdef EDGESPLIT_DEBUG_0
2288 static void print_ptr(void *ptr)
2289 {
2290         printf("%p\n", ptr);
2291 }
2292
2293 static void print_edge(void *ptr)
2294 {
2295         SmoothEdge *edge = ptr;
2296         printf(" %4d", edge->newIndex);
2297 }
2298
2299 static void print_face(void *ptr)
2300 {
2301         SmoothFace *face = ptr;
2302         printf(" %4d", face->newIndex);
2303 }
2304 #endif
2305
2306 typedef struct ReplaceData {
2307         void *find;
2308         void *replace;
2309 } ReplaceData;
2310
2311 static void edge_replace_vert(void *ptr, void *userdata)
2312 {
2313         SmoothEdge *edge = ptr;
2314         SmoothVert *find = ((ReplaceData *)userdata)->find;
2315         SmoothVert *replace = ((ReplaceData *)userdata)->replace;
2316         int i;
2317
2318 #ifdef EDGESPLIT_DEBUG_3
2319         printf("replacing vert %4d with %4d in edge %4d",
2320                find->newIndex, replace->newIndex, edge->newIndex);
2321         printf(": {%4d, %4d}", edge->verts[0]->newIndex, edge->verts[1]->newIndex);
2322 #endif
2323
2324         for(i = 0; i < SMOOTHEDGE_NUM_VERTS; i++) {
2325                 if(edge->verts[i] == find) {
2326                         linklist_append_list_unique(&replace->faces, edge->faces);
2327                         linklist_remove_list(&find->faces, edge->faces, NULL);
2328
2329                         edge->verts[i] = replace;
2330                 }
2331         }
2332
2333 #ifdef EDGESPLIT_DEBUG_3
2334         printf(" -> {%4d, %4d}\n", edge->verts[0]->newIndex, edge->verts[1]->newIndex);
2335 #endif
2336 }
2337
2338 static void face_replace_vert(void *ptr, void *userdata)
2339 {
2340         SmoothFace *face = ptr;
2341         int i;
2342
2343         for(i = 0; i < SMOOTHFACE_MAX_EDGES && face->edges[i]; i++)
2344                 edge_replace_vert(face->edges[i], userdata);
2345 }
2346
2347 static void face_replace_edge(void *ptr, void *userdata)
2348 {
2349         SmoothFace *face = ptr;
2350         SmoothEdge *find = ((ReplaceData *)userdata)->find;
2351         SmoothEdge *replace = ((ReplaceData *)userdata)->replace;
2352         int i;
2353
2354 #ifdef EDGESPLIT_DEBUG_3
2355         printf("replacing edge %4d with %4d in face %4d",
2356                find->newIndex, replace->newIndex, face->newIndex);
2357         if(face->edges[3])
2358                 printf(": {%2d %2d %2d %2d}",
2359                        face->edges[0]->newIndex, face->edges[1]->newIndex,
2360          face->edges[2]->newIndex, face->edges[3]->newIndex);
2361         else
2362                 printf(": {%2d %2d %2d}",
2363                        face->edges[0]->newIndex, face->edges[1]->newIndex,
2364          face->edges[2]->newIndex);
2365 #endif
2366
2367         for(i = 0; i < SMOOTHFACE_MAX_EDGES && face->edges[i]; i++) {
2368                 if(face->edges[i] == find) {
2369                         linklist_remove_first(&face->edges[i]->faces, face, NULL);
2370                         BLI_linklist_prepend(&replace->faces, face);
2371                         face->edges[i] = replace;
2372                 }
2373         }
2374
2375 #ifdef EDGESPLIT_DEBUG_3
2376         if(face->edges[3])
2377                 printf(" -> {%2d %2d %2d %2d}\n",
2378                        face->edges[0]->newIndex, face->edges[1]->newIndex,
2379          face->edges[2]->newIndex, face->edges[3]->newIndex);
2380         else
2381                 printf(" -> {%2d %2d %2d}\n",
2382                        face->edges[0]->newIndex, face->edges[1]->newIndex,
2383          face->edges[2]->newIndex);
2384 #endif
2385 }
2386
2387 static int edge_is_loose(SmoothEdge *edge)
2388 {
2389         return !(edge->faces && edge->faces->next);
2390 }
2391
2392 static int edge_is_sharp(SmoothEdge *edge, int flags,
2393                          float threshold)
2394 {
2395 #ifdef EDGESPLIT_DEBUG_1
2396         printf("edge %d: ", edge->newIndex);
2397 #endif
2398         if(edge->flag & ME_SHARP) {
2399                 /* edge can only be sharp if it has at least 2 faces */
2400                 if(!edge_is_loose(edge)) {
2401 #ifdef EDGESPLIT_DEBUG_1
2402                         printf("sharp\n");
2403 #endif
2404                         return 1;
2405                 } else {
2406                         /* edge is loose, so it can't be sharp */
2407                         edge->flag &= ~ME_SHARP;
2408                 }
2409         }
2410
2411 #ifdef EDGESPLIT_DEBUG_1
2412         printf("not sharp\n");
2413 #endif
2414         return 0;
2415 }
2416
2417 /* finds another sharp edge which uses vert, by traversing faces around the
2418  * vert until it does one of the following:
2419  * - hits a loose edge (the edge is returned)
2420  * - hits a sharp edge (the edge is returned)
2421  * - returns to the start edge (NULL is returned)
2422  */
2423 static SmoothEdge *find_other_sharp_edge(SmoothVert *vert, SmoothEdge *edge,
2424                                          LinkNode **visited_faces, float threshold, int flags)
2425 {
2426         SmoothFace *face = NULL;
2427         SmoothEdge *edge2 = NULL;
2428         /* holds the edges we've seen so we can avoid looping indefinitely */
2429         LinkNode *visited_edges = NULL;
2430 #ifdef EDGESPLIT_DEBUG_1
2431         printf("=== START === find_other_sharp_edge(edge = %4d, vert = %4d)\n",
2432                edge->newIndex, vert->newIndex);
2433 #endif
2434
2435         /* get a face on which to start */
2436         if(edge->faces) face = edge->faces->link;
2437         else return NULL;
2438
2439         /* record this edge as visited */
2440         BLI_linklist_prepend(&visited_edges, edge);
2441
2442         /* get the next edge */
2443         edge2 = other_edge(face, vert, edge);
2444
2445         /* record this face as visited */
2446         if(visited_faces)
2447                 BLI_linklist_prepend(visited_faces, face);
2448
2449         /* search until we hit a loose edge or a sharp edge or an edge we've
2450         * seen before
2451         */
2452         while(face && !edge_is_sharp(edge2, flags, threshold)
2453                      && !linklist_contains(visited_edges, edge2)) {
2454 #ifdef EDGESPLIT_DEBUG_3
2455                 printf("current face %4d; current edge %4d\n", face->newIndex,
2456                        edge2->newIndex);
2457 #endif
2458                 /* get the next face */
2459                 face = other_face(edge2, face);
2460
2461                 /* if face == NULL, edge2 is a loose edge */
2462                 if(face) {
2463                         /* record this face as visited */
2464                         if(visited_faces)
2465                                 BLI_linklist_prepend(visited_faces, face);
2466
2467                         /* record this edge as visited */
2468                         BLI_linklist_prepend(&visited_edges, edge2);
2469
2470                         /* get the next edge */
2471                         edge2 = other_edge(face, vert, edge2);
2472 #ifdef EDGESPLIT_DEBUG_3
2473                         printf("next face %4d; next edge %4d\n",
2474                                face->newIndex, edge2->newIndex);
2475                 } else {
2476                         printf("loose edge: %4d\n", edge2->newIndex);
2477 #endif
2478                 }
2479                      }
2480
2481                      /* either we came back to the start edge or we found a sharp/loose edge */
2482                      if(linklist_contains(visited_edges, edge2))
2483                              /* we came back to the start edge */
2484                              edge2 = NULL;
2485
2486                      BLI_linklist_free(visited_edges, NULL);
2487
2488 #ifdef EDGESPLIT_DEBUG_1
2489                      printf("=== END === find_other_sharp_edge(edge = %4d, vert = %4d), "
2490                                      "returning edge %d\n",
2491          edge->newIndex, vert->newIndex, edge2 ? edge2->newIndex : -1);
2492 #endif
2493                      return edge2;
2494 }
2495
2496 static void split_single_vert(SmoothVert *vert, SmoothFace *face,
2497                               SmoothMesh *mesh)
2498 {
2499         SmoothVert *copy_vert;
2500         ReplaceData repdata;
2501
2502         copy_vert = smoothvert_copy(vert, mesh);
2503
2504         repdata.find = vert;
2505         repdata.replace = copy_vert;
2506         face_replace_vert(face, &repdata);
2507 }
2508
2509 static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh);
2510
2511 static void propagate_split(SmoothEdge *edge, SmoothVert *vert,
2512                             SmoothMesh *mesh)
2513 {
2514         SmoothEdge *edge2;
2515         LinkNode *visited_faces = NULL;
2516 #ifdef EDGESPLIT_DEBUG_1
2517         printf("=== START === propagate_split(edge = %4d, vert = %4d)\n",
2518                edge->newIndex, vert->newIndex);
2519 #endif
2520
2521         edge2 = find_other_sharp_edge(vert, edge, &visited_faces,
2522                                       mesh->threshold, mesh->flags);
2523
2524         if(!edge2) {
2525                 /* didn't find a sharp or loose edge, so we've hit a dead end */
2526         } else if(!edge_is_loose(edge2)) {
2527                 /* edge2 is not loose, so it must be sharp */
2528                 if(edge_is_loose(edge)) {
2529                         /* edge is loose, so we can split edge2 at this vert */
2530                         split_edge(edge2, vert, mesh);
2531                 } else if(edge_is_sharp(edge, mesh->flags, mesh->threshold)) {
2532                         /* both edges are sharp, so we can split the pair at vert */
2533                         split_edge(edge, vert, mesh);
2534                 } else {
2535                         /* edge is not sharp, so try to split edge2 at its other vert */
2536                         split_edge(edge2, other_vert(edge2, vert), mesh);
2537                 }
2538         } else { /* edge2 is loose */
2539                 if(edge_is_loose(edge)) {
2540                         SmoothVert *vert2;
2541                         ReplaceData repdata;
2542
2543                         /* can't split edge, what should we do with vert? */
2544                         if(linklist_subset(vert->faces, visited_faces)) {
2545                                 /* vert has only one fan of faces attached; don't split it */
2546                         } else {
2547                                 /* vert has more than one fan of faces attached; split it */
2548                                 vert2 = smoothvert_copy(vert, mesh);
2549
2550                                 /* replace vert with its copy in visited_faces */
2551                                 repdata.find = vert;
2552                                 repdata.replace = vert2;
2553                                 BLI_linklist_apply(visited_faces, face_replace_vert, &repdata);
2554                         }
2555                 } else {
2556                         /* edge is not loose, so it must be sharp; split it */
2557                         split_edge(edge, vert, mesh);
2558                 }
2559         }
2560
2561         BLI_linklist_free(visited_faces, NULL);
2562 #ifdef EDGESPLIT_DEBUG_1
2563         printf("=== END === propagate_split(edge = %4d, vert = %4d)\n",
2564                edge->newIndex, vert->newIndex);
2565 #endif
2566 }
2567
2568 static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh)
2569 {
2570         SmoothEdge *edge2;
2571         SmoothVert *vert2;
2572         ReplaceData repdata;
2573         /* the list of faces traversed while looking for a sharp edge */
2574         LinkNode *visited_faces = NULL;
2575 #ifdef EDGESPLIT_DEBUG_1
2576         printf("=== START === split_edge(edge = %4d, vert = %4d)\n",
2577                edge->newIndex, vert->newIndex);
2578 #endif
2579
2580         edge2 = find_other_sharp_edge(vert, edge, &visited_faces,
2581                                       mesh->threshold, mesh->flags);
2582
2583         if(!edge2) {
2584                 /* didn't find a sharp or loose edge, so try the other vert */
2585                 vert2 = other_vert(edge, vert);
2586                 propagate_split(edge, vert2, mesh);
2587         } else if(!edge_is_loose(edge2)) {
2588                 /* edge2 is not loose, so it must be sharp */
2589                 SmoothEdge *copy_edge = smoothedge_copy(edge, mesh);
2590                 SmoothEdge *copy_edge2 = smoothedge_copy(edge2, mesh);
2591                 SmoothVert *vert2;
2592
2593                 /* replace edge with its copy in visited_faces */
2594                 repdata.find = edge;
2595                 repdata.replace = copy_edge;
2596                 BLI_linklist_apply(visited_faces, face_replace_edge, &repdata);
2597
2598                 /* replace edge2 with its copy in visited_faces */
2599                 repdata.find = edge2;
2600                 repdata.replace = copy_edge2;
2601                 BLI_linklist_apply(visited_faces, face_replace_edge, &repdata);
2602
2603                 vert2 = smoothvert_copy(vert, mesh);
2604
2605                 /* replace vert with its copy in visited_faces (must be done after
2606                 * edge replacement so edges have correct vertices)
2607                 */
2608                 repdata.find = vert;
2609                 repdata.replace = vert2;
2610                 BLI_linklist_apply(visited_faces, face_replace_vert, &repdata);
2611
2612                 /* all copying and replacing is done; the mesh should be consistent.
2613                 * now propagate the split to the vertices at either end
2614                 */
2615                 propagate_split(copy_edge, other_vert(copy_edge, vert2), mesh);
2616                 propagate_split(copy_edge2, other_vert(copy_edge2, vert2), mesh);
2617
2618                 if(smoothedge_has_vert(edge, vert))
2619                         propagate_split(edge, vert, mesh);
2620         } else {
2621                 /* edge2 is loose */
2622                 SmoothEdge *copy_edge = smoothedge_copy(edge, mesh);
2623                 SmoothVert *vert2;
2624
2625                 /* replace edge with its copy in visited_faces */
2626                 repdata.find = edge;
2627                 repdata.replace = copy_edge;
2628                 BLI_linklist_apply(visited_faces, face_replace_edge, &repdata);
2629
2630                 vert2 = smoothvert_copy(vert, mesh);
2631
2632                 /* replace vert with its copy in visited_faces (must be done after
2633                 * edge replacement so edges have correct vertices)
2634                 */
2635                 repdata.find = vert;
2636                 repdata.replace = vert2;
2637                 BLI_linklist_apply(visited_faces, face_replace_vert, &repdata);
2638
2639                 /* copying and replacing is done; the mesh should be consistent.
2640                 * now propagate the split to the vertex at the other end
2641                 */
2642                 propagate_split(copy_edge, other_vert(copy_edge, vert2), mesh);
2643
2644                 if(smoothedge_has_vert(edge, vert))
2645                         propagate_split(edge, vert, mesh);
2646         }
2647
2648         BLI_linklist_free(visited_faces, NULL);
2649 #ifdef EDGESPLIT_DEBUG_1
2650         printf("=== END === split_edge(edge = %4d, vert = %4d)\n",
2651                edge->newIndex, vert->newIndex);
2652 #endif
2653 }
2654
2655 static void tag_and_count_extra_edges(SmoothMesh *mesh, float split_angle,
2656                                       int flags, int *extra_edges)
2657 {
2658         /* if normal1 dot normal2 < threshold, angle is greater, so split */
2659         /* FIXME not sure if this always works */
2660         /* 0.00001 added for floating-point rounding */
2661         float threshold = cos((split_angle + 0.00001) * M_PI / 180.0);
2662         int i;
2663
2664         *extra_edges = 0;
2665
2666         /* loop through edges, counting potential new ones */
2667         for(i = 0; i < mesh->num_edges; i++) {
2668                 SmoothEdge *edge = &mesh->edges[i];
2669                 int sharp = 0;
2670
2671                 /* treat all non-manifold edges (3 or more faces) as sharp */
2672                 if(edge->faces && edge->faces->next && edge->faces->next->next) {
2673                         LinkNode *node;
2674
2675                         /* this edge is sharp */
2676                         sharp = 1;
2677
2678                         /* add an extra edge for every face beyond the first */
2679                         *extra_edges += 2;
2680                         for(node = edge->faces->next->next->next; node; node = node->next)
2681                                 (*extra_edges)++;
2682                 } else if((flags & (MOD_EDGESPLIT_FROMANGLE | MOD_EDGESPLIT_FROMFLAG))
2683                                          && !edge_is_loose(edge)) {
2684                         /* (the edge can only be sharp if we're checking angle or flag,
2685                         * and it has at least 2 faces) */
2686
2687                                                  /* if we're checking the sharp flag and it's set, good */
2688                                                  if((flags & MOD_EDGESPLIT_FROMFLAG) && (edge->flag & ME_SHARP)) {
2689                                                          /* this edge is sharp */
2690                                                          sharp = 1;
2691
2692                                                          (*extra_edges)++;
2693                                                  } else if(flags & MOD_EDGESPLIT_FROMANGLE) {
2694                                                          /* we know the edge has 2 faces, so check the angle */
2695                                                          SmoothFace *face1 = edge->faces->link;
2696                                                          SmoothFace *face2 = edge->faces->next->link;
2697                                                          float edge_angle_cos = MTC_dot3Float(face1->normal,
2698                                                                          face2->normal);
2699
2700                                                          if(edge_angle_cos < threshold) {
2701                                                                  /* this edge is sharp */
2702                                                                  sharp = 1;
2703
2704                                                                  (*extra_edges)++;
2705                                                          }
2706                                                  }
2707                                          }
2708
2709                                          /* set/clear sharp flag appropriately */
2710                                          if(sharp) edge->flag |= ME_SHARP;
2711                                          else edge->flag &= ~ME_SHARP;
2712         }
2713 }
2714
2715 static void split_sharp_edges(SmoothMesh *mesh, float split_angle, int flags)
2716 {
2717         int i;
2718         /* if normal1 dot normal2 < threshold, angle is greater, so split */
2719         /* FIXME not sure if this always works */
2720         /* 0.00001 added for floating-point rounding */
2721         mesh->threshold = cos((split_angle + 0.00001) * M_PI / 180.0);
2722         mesh->flags = flags;
2723
2724         /* loop through edges, splitting sharp ones */
2725         /* can't use an iterator here, because we'll be adding edges */
2726         for(i = 0; i < mesh->num_edges; i++) {
2727                 SmoothEdge *edge = &mesh->edges[i];
2728
2729                 if(edge_is_sharp(edge, flags, mesh->threshold))
2730                         split_edge(edge, edge->verts[0], mesh);
2731         }
2732
2733 }
2734
2735 static int count_bridge_verts(SmoothMesh *mesh)
2736 {
2737         int i, j, count = 0;
2738
2739         for(i = 0; i < mesh->num_faces; i++) {
2740                 SmoothFace *face = &mesh->faces[i];
2741
2742                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
2743                         SmoothEdge *edge = face->edges[j];
2744                         SmoothEdge *next_edge;
2745                         SmoothVert *vert = edge->verts[1 - face->flip[j]];
2746                         int next = (j + 1) % SMOOTHFACE_MAX_EDGES;
2747
2748                         /* wrap next around if at last edge */
2749                         if(!face->edges[next]) next = 0;
2750
2751                         next_edge = face->edges[next];
2752
2753                         /* if there are other faces sharing this vertex but not
2754                         * these edges, the vertex will be split, so count it
2755                         */
2756                         /* vert has to have at least one face (this one), so faces != 0 */
2757                         if(!edge->faces->next && !next_edge->faces->next
2758                                                  && vert->faces->next) {
2759                                 count++;
2760                                                  }
2761                 }
2762         }
2763
2764         /* each bridge vert will be counted once per face that uses it,
2765         * so count is too high, but it's ok for now
2766         */
2767         return count;
2768 }
2769
2770 static void split_bridge_verts(SmoothMesh *mesh)
2771 {
2772         int i,j;
2773
2774         for(i = 0; i < mesh->num_faces; i++) {
2775                 SmoothFace *face = &mesh->faces[i];
2776
2777                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
2778                         SmoothEdge *edge = face->edges[j];
2779                         SmoothEdge *next_edge;
2780                         SmoothVert *vert = edge->verts[1 - face->flip[j]];
2781                         int next = (j + 1) % SMOOTHFACE_MAX_EDGES;
2782
2783                         /* wrap next around if at last edge */
2784                         if(!face->edges[next]) next = 0;
2785
2786                         next_edge = face->edges[next];
2787
2788                         /* if there are other faces sharing this vertex but not
2789                         * these edges, split the vertex
2790                         */
2791                         /* vert has to have at least one face (this one), so faces != 0 */
2792                         if(!edge->faces->next && !next_edge->faces->next
2793                                                  && vert->faces->next)
2794                                 /* FIXME this needs to find all faces that share edges with
2795                                 * this one and split off together
2796                                 */
2797                                 split_single_vert(vert, face, mesh);
2798                 }
2799         }
2800 }
2801
2802 static DerivedMesh *edgesplitModifier_do(EdgeSplitModifierData *emd,
2803                                          Object *ob, DerivedMesh *dm)
2804 {
2805         SmoothMesh *mesh;
2806         DerivedMesh *result;
2807         int max_verts, max_edges;
2808
2809         if(!(emd->flags & (MOD_EDGESPLIT_FROMANGLE | MOD_EDGESPLIT_FROMFLAG)))
2810                 return dm;
2811
2812         /* 1. make smoothmesh with initial number of elements */
2813         mesh = smoothmesh_from_derivedmesh(dm);
2814
2815         /* 2. count max number of elements to add */
2816         tag_and_count_extra_edges(mesh, emd->split_angle, emd->flags, &max_edges);
2817         max_verts = max_edges * 2 + mesh->max_verts;
2818         max_verts += count_bridge_verts(mesh);
2819         max_edges += mesh->max_edges;
2820
2821         /* 3. reallocate smoothmesh arrays & copy elements across */
2822         /* 4. remap copied elements' pointers to point into the new arrays */
2823         smoothmesh_resize_verts(mesh, max_verts);
2824         smoothmesh_resize_edges(mesh, max_edges);
2825
2826 #ifdef EDGESPLIT_DEBUG_1
2827         printf("********** Pre-split **********\n");
2828         smoothmesh_print(mesh);
2829 #endif
2830
2831         split_sharp_edges(mesh, emd->split_angle, emd->flags);
2832 #ifdef EDGESPLIT_DEBUG_1
2833         printf("********** Post-edge-split **********\n");
2834         smoothmesh_print(mesh);
2835 #endif
2836
2837         split_bridge_verts(mesh);
2838
2839 #ifdef EDGESPLIT_DEBUG_1
2840         printf("********** Post-vert-split **********\n");
2841         smoothmesh_print(mesh);
2842 #endif
2843
2844 #ifdef EDGESPLIT_DEBUG_0
2845         printf("Edgesplit: Estimated %d verts & %d edges, "
2846                         "found %d verts & %d edges\n", max_verts, max_edges,
2847    mesh->num_verts, mesh->num_edges);
2848 #endif
2849
2850         result = CDDM_from_smoothmesh(mesh);
2851         smoothmesh_free(mesh);
2852
2853         return result;
2854 }
2855
2856 static DerivedMesh *edgesplitModifier_applyModifier(
2857                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
2858   int useRenderParams, int isFinalCalc)
2859 {
2860         DerivedMesh *result;
2861         EdgeSplitModifierData *emd = (EdgeSplitModifierData*) md;
2862
2863         result = edgesplitModifier_do(emd, ob, derivedData);
2864
2865         if(result != derivedData)
2866                 CDDM_calc_normals(result);
2867
2868         return result;
2869 }
2870
2871 static DerivedMesh *edgesplitModifier_applyModifierEM(
2872                 ModifierData *md, Object *ob, EditMesh *editData,
2873   DerivedMesh *derivedData)
2874 {
2875         return edgesplitModifier_applyModifier(md, ob, derivedData, 0, 1);
2876 }
2877
2878 /* Bevel */
2879
2880 static void bevelModifier_initData(ModifierData *md)
2881 {
2882         BevelModifierData *bmd = (BevelModifierData*) md;
2883
2884         bmd->value = 0.1f;
2885         bmd->res = 1;
2886         bmd->flags = 0;
2887         bmd->val_flags = 0;
2888         bmd->lim_flags = 0;
2889         bmd->e_flags = 0;
2890         bmd->bevel_angle = 30;
2891         bmd->defgrp_name[0] = '\0';
2892 }
2893
2894 static void bevelModifier_copyData(ModifierData *md, ModifierData *target)
2895 {
2896         BevelModifierData *bmd = (BevelModifierData*) md;
2897         BevelModifierData *tbmd = (BevelModifierData*) target;
2898
2899         tbmd->value = bmd->value;
2900         tbmd->res = bmd->res;
2901         tbmd->flags = bmd->flags;
2902         tbmd->val_flags = bmd->val_flags;
2903         tbmd->lim_flags = bmd->lim_flags;
2904         tbmd->e_flags = bmd->e_flags;
2905         tbmd->bevel_angle = bmd->bevel_angle;
2906         strncpy(tbmd->defgrp_name, bmd->defgrp_name, 32);
2907 }
2908
2909 CustomDataMask bevelModifier_requiredDataMask(ModifierData *md)
2910 {
2911         BevelModifierData *bmd = (BevelModifierData *)md;
2912         CustomDataMask dataMask = 0;
2913
2914         /* ask for vertexgroups if we need them */
2915         if(bmd->defgrp_name[0]) dataMask |= (1 << CD_MDEFORMVERT);
2916
2917         return dataMask;
2918 }
2919
2920 static DerivedMesh *bevelModifier_applyModifier(
2921                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
2922   int useRenderParams, int isFinalCalc)
2923 {
2924         DerivedMesh *result;
2925         BME_Mesh *bm;
2926
2927         /*bDeformGroup *def;*/
2928         int /*i,*/ options, defgrp_index = -1;
2929         BevelModifierData *bmd = (BevelModifierData*) md;
2930
2931         options = bmd->flags|bmd->val_flags|bmd->lim_flags|bmd->e_flags;
2932
2933         //~ if ((options & BME_BEVEL_VWEIGHT) && bmd->defgrp_name[0]) {
2934                 //~ for (i = 0, def = ob->defbase.first; def; def = def->next, i++) {
2935                         //~ if (!strcmp(def->name, bmd->defgrp_name)) {
2936                                 //~ defgrp_index = i;
2937                                 //~ break;
2938                         //~ }
2939                 //~ }
2940                 //~ if (defgrp_index < 0) {
2941                         //~ options &= ~BME_BEVEL_VWEIGHT;
2942                 //~ }
2943         //~ }
2944
2945         bm = BME_derivedmesh_to_bmesh(derivedData);
2946         BME_bevel(bm,bmd->value,bmd->res,options,defgrp_index,bmd->bevel_angle,NULL);
2947         result = BME_bmesh_to_derivedmesh(bm,derivedData);
2948         BME_free_mesh(bm);
2949
2950         CDDM_calc_normals(result);
2951
2952         return result;
2953 }
2954
2955 static DerivedMesh *bevelModifier_applyModifierEM(
2956                 ModifierData *md, Object *ob, EditMesh *editData,
2957   DerivedMesh *derivedData)
2958 {
2959         return bevelModifier_applyModifier(md, ob, derivedData, 0, 1);
2960 }
2961
2962 /* Displace */
2963
2964 static void displaceModifier_initData(ModifierData *md)
2965 {
2966         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2967
2968         dmd->texture = NULL;
2969         dmd->strength = 1;
2970         dmd->direction = MOD_DISP_DIR_NOR;
2971         dmd->midlevel = 0.5;
2972 }
2973
2974 static void displaceModifier_copyData(ModifierData *md, ModifierData *target)
2975 {
2976         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2977         DisplaceModifierData *tdmd = (DisplaceModifierData*) target;
2978
2979         tdmd->texture = dmd->texture;
2980         tdmd->strength = dmd->strength;
2981         tdmd->direction = dmd->direction;
2982         strncpy(tdmd->defgrp_name, dmd->defgrp_name, 32);
2983         tdmd->midlevel = dmd->midlevel;
2984         tdmd->texmapping = dmd->texmapping;
2985         tdmd->map_object = dmd->map_object;
2986         strncpy(tdmd->uvlayer_name, dmd->uvlayer_name, 32);
2987 }
2988
2989 CustomDataMask displaceModifier_requiredDataMask(ModifierData *md)
2990 {
2991         DisplaceModifierData *dmd = (DisplaceModifierData *)md;
2992         CustomDataMask dataMask = 0;
2993
2994         /* ask for vertexgroups if we need them */
2995         if(dmd->defgrp_name[0]) dataMask |= (1 << CD_MDEFORMVERT);
2996
2997         /* ask for UV coordinates if we need them */
2998         if(dmd->texmapping == MOD_DISP_MAP_UV) dataMask |= (1 << CD_MTFACE);
2999
3000         return dataMask;
3001 }
3002
3003 static int displaceModifier_dependsOnTime(ModifierData *md)
3004 {
3005         DisplaceModifierData *dmd = (DisplaceModifierData *)md;
3006
3007         if(dmd->texture)
3008         {
3009                 return BKE_texture_dependsOnTime(dmd->texture);
3010         }
3011         else
3012         {
3013                 return 0;
3014         }
3015 }
3016
3017 static void displaceModifier_foreachObjectLink(ModifierData *md, Object *ob,
3018                                                ObjectWalkFunc walk, void *userData)
3019 {
3020         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
3021
3022         walk(userData, ob, &dmd->map_object);
3023 }
3024
3025 static void displaceModifier_foreachIDLink(ModifierData *md, Object *ob,
3026                                            IDWalkFunc walk, void *userData)
3027 {
3028         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
3029
3030         walk(userData, ob, (ID **)&dmd->texture);
3031
3032         displaceModifier_foreachObjectLink(md, ob, (ObjectWalkFunc)walk, userData);
3033 }
3034
3035 static int displaceModifier_isDisabled(ModifierData *md)
3036 {
3037         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
3038
3039         return !dmd->texture;
3040 }
3041
3042 static void displaceModifier_updateDepgraph(
3043                                             ModifierData *md, DagForest *forest,
3044          Object *ob, DagNode *obNode)
3045 {
3046         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
3047