Code cleanup: no need to use calloc when memory is initialized after
[blender-staging.git] / source / blender / modifiers / intern / MOD_uvproject.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software  Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2005 by the Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Daniel Dunbar
22  *                 Ton Roosendaal,
23  *                 Ben Batt,
24  *                 Brecht Van Lommel,
25  *                 Campbell Barton
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  *
29  */
30
31 /** \file blender/modifiers/intern/MOD_uvproject.c
32  *  \ingroup modifiers
33  */
34
35
36 /* UV Project modifier: Generates UVs projected from an object */
37
38 #include "DNA_meshdata_types.h"
39 #include "DNA_camera_types.h"
40 #include "DNA_object_types.h"
41 #include "DNA_scene_types.h"
42
43 #include "BLI_math.h"
44 #include "BLI_string.h"
45 #include "BLI_uvproject.h"
46 #include "BLI_utildefines.h"
47
48
49 #include "BKE_camera.h"
50 #include "BKE_mesh.h"
51 #include "BKE_DerivedMesh.h"
52
53 #include "MOD_modifiertypes.h"
54 #include "MOD_util.h"
55
56 #include "MEM_guardedalloc.h"
57 #include "depsgraph_private.h"
58
59 static void initData(ModifierData *md)
60 {
61         UVProjectModifierData *umd = (UVProjectModifierData *) md;
62
63         umd->flags = 0;
64         umd->num_projectors = 1;
65         umd->aspectx = umd->aspecty = 1.0f;
66         umd->scalex = umd->scaley = 1.0f;
67 }
68
69 static void copyData(ModifierData *md, ModifierData *target)
70 {
71 #if 0
72         UVProjectModifierData *umd = (UVProjectModifierData *) md;
73         UVProjectModifierData *tumd = (UVProjectModifierData *) target;
74 #endif
75         modifier_copyData_generic(md, target);
76 }
77
78 static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *UNUSED(md))
79 {
80         CustomDataMask dataMask = 0;
81
82         /* ask for UV coordinates */
83         dataMask |= CD_MLOOPUV | CD_MTEXPOLY;
84
85         return dataMask;
86 }
87
88 static void foreachObjectLink(ModifierData *md, Object *ob,
89                               ObjectWalkFunc walk, void *userData)
90 {
91         UVProjectModifierData *umd = (UVProjectModifierData *) md;
92         int i;
93
94         for (i = 0; i < MOD_UVPROJECT_MAXPROJECTORS; ++i)
95                 walk(userData, ob, &umd->projectors[i]);
96 }
97
98 static void foreachIDLink(ModifierData *md, Object *ob,
99                           IDWalkFunc walk, void *userData)
100 {
101         UVProjectModifierData *umd = (UVProjectModifierData *) md;
102
103         walk(userData, ob, (ID **)&umd->image);
104
105         foreachObjectLink(md, ob, (ObjectWalkFunc)walk,
106                           userData);
107 }
108
109 static void updateDepgraph(ModifierData *md, DagForest *forest,
110                            struct Scene *UNUSED(scene),
111                            Object *UNUSED(ob),
112                            DagNode *obNode)
113 {
114         UVProjectModifierData *umd = (UVProjectModifierData *) md;
115         int i;
116
117         for (i = 0; i < umd->num_projectors; ++i) {
118                 if (umd->projectors[i]) {
119                         DagNode *curNode = dag_get_node(forest, umd->projectors[i]);
120
121                         dag_add_relation(forest, curNode, obNode,
122                                          DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "UV Project Modifier");
123                 }
124         }
125 }
126
127 typedef struct Projector {
128         Object *ob;             /* object this projector is derived from */
129         float projmat[4][4];    /* projection matrix */
130         float normal[3];        /* projector normal in world space */
131         void *uci;              /* optional uv-project info (panorama projection) */
132 } Projector;
133
134 static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
135                                          Object *ob, DerivedMesh *dm)
136 {
137         float (*coords)[3], (*co)[3];
138         MLoopUV *mloop_uv;
139         MTexPoly *mtexpoly, *mt = NULL;
140         int i, numVerts, numPolys, numLoops;
141         Image *image = umd->image;
142         MPoly *mpoly, *mp;
143         MLoop *mloop;
144         int override_image = ((umd->flags & MOD_UVPROJECT_OVERRIDEIMAGE) != 0);
145         Projector projectors[MOD_UVPROJECT_MAXPROJECTORS];
146         int num_projectors = 0;
147         char uvname[MAX_CUSTOMDATA_LAYER_NAME];
148         float aspx = umd->aspectx ? umd->aspectx : 1.0f;
149         float aspy = umd->aspecty ? umd->aspecty : 1.0f;
150         float scax = umd->scalex ? umd->scalex : 1.0f;
151         float scay = umd->scaley ? umd->scaley : 1.0f;
152         int free_uci = 0;
153
154         for (i = 0; i < umd->num_projectors; ++i)
155                 if (umd->projectors[i])
156                         projectors[num_projectors++].ob = umd->projectors[i];
157
158         if (num_projectors == 0) return dm;
159
160         /* make sure there are UV Maps available */
161
162         if (!CustomData_has_layer(&dm->loopData, CD_MLOOPUV)) return dm;
163
164         /* make sure we're using an existing layer */
165         CustomData_validate_layer_name(&dm->loopData, CD_MLOOPUV, umd->uvlayer_name, uvname);
166
167         /* calculate a projection matrix and normal for each projector */
168         for (i = 0; i < num_projectors; ++i) {
169                 float tmpmat[4][4];
170                 float offsetmat[4][4];
171                 Camera *cam = NULL;
172                 /* calculate projection matrix */
173                 invert_m4_m4(projectors[i].projmat, projectors[i].ob->obmat);
174
175                 projectors[i].uci = NULL;
176
177                 if (projectors[i].ob->type == OB_CAMERA) {
178                         
179                         cam = (Camera *)projectors[i].ob->data;
180                         if (cam->type == CAM_PANO) {
181                                 projectors[i].uci = BLI_uvproject_camera_info(projectors[i].ob, NULL, aspx, aspy);
182                                 BLI_uvproject_camera_info_scale(projectors[i].uci, scax, scay);
183                                 free_uci = 1;
184                         }
185                         else {
186                                 CameraParams params;
187
188                                 /* setup parameters */
189                                 BKE_camera_params_init(&params);
190                                 BKE_camera_params_from_object(&params, projectors[i].ob);
191
192                                 /* compute matrix, viewplane, .. */
193                                 BKE_camera_params_compute_viewplane(&params, 1, 1, aspx, aspy);
194
195                                 /* scale the view-plane */
196                                 params.viewplane.xmin *= scax;
197                                 params.viewplane.xmax *= scax;
198                                 params.viewplane.ymin *= scay;
199                                 params.viewplane.ymax *= scay;
200
201                                 BKE_camera_params_compute_matrix(&params);
202                                 mul_m4_m4m4(tmpmat, params.winmat, projectors[i].projmat);
203                         }
204                 }
205                 else {
206                         copy_m4_m4(tmpmat, projectors[i].projmat);
207                 }
208
209                 unit_m4(offsetmat);
210                 mul_mat3_m4_fl(offsetmat, 0.5);
211                 offsetmat[3][0] = offsetmat[3][1] = offsetmat[3][2] = 0.5;
212
213                 mul_m4_m4m4(projectors[i].projmat, offsetmat, tmpmat);
214
215                 /* calculate worldspace projector normal (for best projector test) */
216                 projectors[i].normal[0] = 0;
217                 projectors[i].normal[1] = 0;
218                 projectors[i].normal[2] = 1;
219                 mul_mat3_m4_v3(projectors[i].ob->obmat, projectors[i].normal);
220         }
221
222         numPolys = dm->getNumPolys(dm);
223         numLoops = dm->getNumLoops(dm);
224
225         /* make sure we are not modifying the original UV map */
226         mloop_uv = CustomData_duplicate_referenced_layer_named(&dm->loopData,
227                                                                CD_MLOOPUV, uvname, numLoops);
228
229         /* can be NULL */
230         mt = mtexpoly = CustomData_duplicate_referenced_layer_named(&dm->polyData,
231                                                                     CD_MTEXPOLY, uvname, numPolys);
232
233         numVerts = dm->getNumVerts(dm);
234
235         coords = MEM_mallocN(sizeof(*coords) * numVerts,
236                              "uvprojectModifier_do coords");
237         dm->getVertCos(dm, coords);
238
239         /* convert coords to world space */
240         for (i = 0, co = coords; i < numVerts; ++i, ++co)
241                 mul_m4_v3(ob->obmat, *co);
242         
243         /* if only one projector, project coords to UVs */
244         if (num_projectors == 1 && projectors[0].uci == NULL)
245                 for (i = 0, co = coords; i < numVerts; ++i, ++co)
246                         mul_project_m4_v3(projectors[0].projmat, *co);
247
248         mpoly = dm->getPolyArray(dm);
249         mloop = dm->getLoopArray(dm);
250
251         /* apply coords as UVs, and apply image if tfaces are new */
252         for (i = 0, mp = mpoly; i < numPolys; ++i, ++mp, ++mt) {
253                 if (override_image || !image || (mtexpoly == NULL || mt->tpage == image)) {
254                         if (num_projectors == 1) {
255                                 if (projectors[0].uci) {
256                                         unsigned int fidx = mp->totloop - 1;
257                                         do {
258                                                 unsigned int lidx = mp->loopstart + fidx;
259                                                 unsigned int vidx = mloop[lidx].v;
260                                                 BLI_uvproject_from_camera(mloop_uv[lidx].uv, coords[vidx], projectors[0].uci);
261                                         } while (fidx--);
262                                 }
263                                 else {
264                                         /* apply transformed coords as UVs */
265                                         unsigned int fidx = mp->totloop - 1;
266                                         do {
267                                                 unsigned int lidx = mp->loopstart + fidx;
268                                                 unsigned int vidx = mloop[lidx].v;
269                                                 copy_v2_v2(mloop_uv[lidx].uv, coords[vidx]);
270                                         } while (fidx--);
271                                 }
272                         }
273                         else {
274                                 /* multiple projectors, select the closest to face normal direction */
275                                 float face_no[3];
276                                 int j;
277                                 Projector *best_projector;
278                                 float best_dot;
279
280                                 /* get the untransformed face normal */
281                                 BKE_mesh_calc_poly_normal_coords(mp, mloop + mp->loopstart, (const float (*)[3])coords, face_no);
282
283                                 /* find the projector which the face points at most directly
284                                  * (projector normal with largest dot product is best)
285                                  */
286                                 best_dot = dot_v3v3(projectors[0].normal, face_no);
287                                 best_projector = &projectors[0];
288
289                                 for (j = 1; j < num_projectors; ++j) {
290                                         float tmp_dot = dot_v3v3(projectors[j].normal,
291                                                                  face_no);
292                                         if (tmp_dot > best_dot) {
293                                                 best_dot = tmp_dot;
294                                                 best_projector = &projectors[j];
295                                         }
296                                 }
297
298                                 if (best_projector->uci) {
299                                         unsigned int fidx = mp->totloop - 1;
300                                         do {
301                                                 unsigned int lidx = mp->loopstart + fidx;
302                                                 unsigned int vidx = mloop[lidx].v;
303                                                 BLI_uvproject_from_camera(mloop_uv[lidx].uv, coords[vidx], best_projector->uci);
304                                         } while (fidx--);
305                                 }
306                                 else {
307                                         unsigned int fidx = mp->totloop - 1;
308                                         do {
309                                                 unsigned int lidx = mp->loopstart + fidx;
310                                                 unsigned int vidx = mloop[lidx].v;
311                                                 mul_v2_project_m4_v3(mloop_uv[lidx].uv, best_projector->projmat, coords[vidx]);
312                                         } while (fidx--);
313                                 }
314                         }
315                 }
316
317                 if (override_image && mtexpoly) {
318                         mt->tpage = image;
319                 }
320         }
321
322         MEM_freeN(coords);
323         
324         if (free_uci) {
325                 int j;
326                 for (j = 0; j < num_projectors; ++j) {
327                         if (projectors[j].uci) {
328                                 MEM_freeN(projectors[j].uci);
329                         }
330                 }
331         }
332
333         /* Mark tessellated CD layers as dirty. */
334         dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
335
336         return dm;
337 }
338
339 static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
340                                   DerivedMesh *derivedData,
341                                   ModifierApplyFlag UNUSED(flag))
342 {
343         DerivedMesh *result;
344         UVProjectModifierData *umd = (UVProjectModifierData *) md;
345
346         result = uvprojectModifier_do(umd, ob, derivedData);
347
348         return result;
349 }
350
351
352 ModifierTypeInfo modifierType_UVProject = {
353         /* name */              "UVProject",
354         /* structName */        "UVProjectModifierData",
355         /* structSize */        sizeof(UVProjectModifierData),
356         /* type */              eModifierTypeType_NonGeometrical,
357         /* flags */             eModifierTypeFlag_AcceptsMesh |
358                                 eModifierTypeFlag_SupportsMapping |
359                                 eModifierTypeFlag_SupportsEditmode |
360                                 eModifierTypeFlag_EnableInEditmode,
361
362         /* copyData */          copyData,
363         /* deformVerts */       NULL,
364         /* deformMatrices */    NULL,
365         /* deformVertsEM */     NULL,
366         /* deformMatricesEM */  NULL,
367         /* applyModifier */     applyModifier,
368         /* applyModifierEM */   NULL,
369         /* initData */          initData,
370         /* requiredDataMask */  requiredDataMask,
371         /* freeData */          NULL,
372         /* isDisabled */        NULL,
373         /* updateDepgraph */    updateDepgraph,
374         /* dependsOnTime */     NULL,
375         /* dependsOnNormals */  NULL,
376         /* foreachObjectLink */ foreachObjectLink,
377         /* foreachIDLink */     foreachIDLink,
378         /* foreachTexLink */    NULL,
379 };