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