svn merge ^/trunk/blender -r46380:46390
[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         int i;
63
64         for (i = 0; i < MOD_UVPROJECT_MAXPROJECTORS; ++i)
65                 umd->projectors[i] = NULL;
66         umd->image = NULL;
67         umd->flags = 0;
68         umd->num_projectors = 1;
69         umd->aspectx = umd->aspecty = 1.0f;
70         umd->scalex = umd->scaley = 1.0f;
71 }
72
73 static void copyData(ModifierData *md, ModifierData *target)
74 {
75         UVProjectModifierData *umd = (UVProjectModifierData *) md;
76         UVProjectModifierData *tumd = (UVProjectModifierData *) target;
77         int i;
78
79         for (i = 0; i < MOD_UVPROJECT_MAXPROJECTORS; ++i)
80                 tumd->projectors[i] = umd->projectors[i];
81         tumd->image = umd->image;
82         tumd->flags = umd->flags;
83         tumd->num_projectors = umd->num_projectors;
84         tumd->aspectx = umd->aspectx;
85         tumd->aspecty = umd->aspecty;
86         tumd->scalex = umd->scalex;
87         tumd->scaley = umd->scaley;
88         BLI_strncpy(tumd->uvlayer_name, umd->uvlayer_name, sizeof(umd->uvlayer_name));
89 }
90
91 static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *UNUSED(md))
92 {
93         CustomDataMask dataMask = 0;
94
95         /* ask for UV coordinates */
96         dataMask |= CD_MASK_MTFACE;
97
98         return dataMask;
99 }
100
101 static void foreachObjectLink(ModifierData *md, Object *ob,
102                               ObjectWalkFunc walk, void *userData)
103 {
104         UVProjectModifierData *umd = (UVProjectModifierData *) md;
105         int i;
106
107         for (i = 0; i < MOD_UVPROJECT_MAXPROJECTORS; ++i)
108                 walk(userData, ob, &umd->projectors[i]);
109 }
110
111 static void foreachIDLink(ModifierData *md, Object *ob,
112                           IDWalkFunc walk, void *userData)
113 {
114         UVProjectModifierData *umd = (UVProjectModifierData *) md;
115
116         walk(userData, ob, (ID **)&umd->image);
117
118         foreachObjectLink(md, ob, (ObjectWalkFunc)walk,
119                           userData);
120 }
121
122 static void updateDepgraph(ModifierData *md, DagForest *forest,
123                            struct Scene *UNUSED(scene),
124                            Object *UNUSED(ob),
125                            DagNode *obNode)
126 {
127         UVProjectModifierData *umd = (UVProjectModifierData *) md;
128         int i;
129
130         for (i = 0; i < umd->num_projectors; ++i) {
131                 if (umd->projectors[i]) {
132                         DagNode *curNode = dag_get_node(forest, umd->projectors[i]);
133
134                         dag_add_relation(forest, curNode, obNode,
135                                          DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "UV Project Modifier");
136                 }
137         }
138 }
139
140 typedef struct Projector {
141         Object *ob;             /* object this projector is derived from */
142         float projmat[4][4];    /* projection matrix */
143         float normal[3];        /* projector normal in world space */
144         void *uci;              /* optional uv-project info (panorama projection) */
145 } Projector;
146
147 static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
148                                          Object *ob, DerivedMesh *dm)
149 {
150         float (*coords)[3], (*co)[3];
151         MLoopUV *mloop_uv;
152         MTexPoly *mtexpoly, *mt = NULL;
153         int i, numVerts, numPolys, numLoops;
154         Image *image = umd->image;
155         MPoly *mpoly, *mp;
156         MLoop *mloop;
157         int override_image = ((umd->flags & MOD_UVPROJECT_OVERRIDEIMAGE) != 0);
158         Projector projectors[MOD_UVPROJECT_MAXPROJECTORS];
159         int num_projectors = 0;
160         float aspect;
161         char uvname[MAX_CUSTOMDATA_LAYER_NAME];
162         float aspx = umd->aspectx ? umd->aspectx : 1.0f;
163         float aspy = umd->aspecty ? umd->aspecty : 1.0f;
164         float scax = umd->scalex ? umd->scalex : 1.0f;
165         float scay = umd->scaley ? umd->scaley : 1.0f;
166         int free_uci = 0;
167
168         aspect = aspx / aspy;
169
170         for (i = 0; i < umd->num_projectors; ++i)
171                 if (umd->projectors[i])
172                         projectors[num_projectors++].ob = umd->projectors[i];
173
174         if (num_projectors == 0) return dm;
175
176         /* make sure there are UV Maps available */
177
178         if (!CustomData_has_layer(&dm->loopData, CD_MLOOPUV)) return dm;
179
180         /* make sure we're using an existing layer */
181         CustomData_validate_layer_name(&dm->loopData, CD_MLOOPUV, umd->uvlayer_name, uvname);
182
183         /* calculate a projection matrix and normal for each projector */
184         for (i = 0; i < num_projectors; ++i) {
185                 float tmpmat[4][4];
186                 float offsetmat[4][4];
187                 Camera *cam = NULL;
188                 /* calculate projection matrix */
189                 invert_m4_m4(projectors[i].projmat, projectors[i].ob->obmat);
190
191                 projectors[i].uci = NULL;
192
193                 if (projectors[i].ob->type == OB_CAMERA) {
194                         
195                         cam = (Camera *)projectors[i].ob->data;
196                         if (cam->flag & CAM_PANORAMA) {
197                                 projectors[i].uci = BLI_uvproject_camera_info(projectors[i].ob, NULL, aspx, aspy);
198                                 BLI_uvproject_camera_info_scale(projectors[i].uci, scax, scay);
199                                 free_uci = 1;
200                         }
201                         else {
202                                 float sensor = BKE_camera_sensor_size(cam->sensor_fit, cam->sensor_x, cam->sensor_y);
203                                 int sensor_fit = BKE_camera_sensor_fit(cam->sensor_fit, aspx, aspy);
204                                 float scale = (cam->type == CAM_PERSP) ? cam->clipsta * sensor / cam->lens : cam->ortho_scale;
205                                 float xmax, xmin, ymax, ymin;
206
207                                 if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
208                                         xmax = 0.5f * scale;
209                                         ymax = xmax / aspect;
210                                 }
211                                 else {
212                                         ymax = 0.5f * scale;
213                                         xmax = ymax * aspect;
214                                 }
215
216                                 xmin = -xmax;
217                                 ymin = -ymax;
218
219                                 /* scale the matrix */
220                                 xmin *= scax;
221                                 xmax *= scax;
222                                 ymin *= scay;
223                                 ymax *= scay;
224
225                                 if (cam->type == CAM_PERSP) {
226                                         float perspmat[4][4];
227                                         perspective_m4(perspmat, xmin, xmax, ymin, ymax, cam->clipsta, cam->clipend);
228                                         mult_m4_m4m4(tmpmat, perspmat, projectors[i].projmat);
229                                 }
230                                 else { /* if (cam->type == CAM_ORTHO) */
231                                         float orthomat[4][4];
232                                         orthographic_m4(orthomat, xmin, xmax, ymin, ymax, cam->clipsta, cam->clipend);
233                                         mult_m4_m4m4(tmpmat, orthomat, projectors[i].projmat);
234                                 }
235                         }
236                 }
237                 else {
238                         copy_m4_m4(tmpmat, projectors[i].projmat);
239                 }
240
241                 unit_m4(offsetmat);
242                 mul_mat3_m4_fl(offsetmat, 0.5);
243                 offsetmat[3][0] = offsetmat[3][1] = offsetmat[3][2] = 0.5;
244                 
245                 if (cam) {
246                         if (aspx == aspy) { 
247                                 offsetmat[3][0] -= cam->shiftx;
248                                 offsetmat[3][1] -= cam->shifty;
249                         }
250                         else if (aspx < aspy) {
251                                 offsetmat[3][0] -= (cam->shiftx * aspy / aspx);
252                                 offsetmat[3][1] -= cam->shifty;
253                         }
254                         else {
255                                 offsetmat[3][0] -= cam->shiftx;
256                                 offsetmat[3][1] -= (cam->shifty * aspx / aspy);
257                         }
258                 }
259                 
260                 mult_m4_m4m4(projectors[i].projmat, offsetmat, tmpmat);
261
262                 /* calculate worldspace projector normal (for best projector test) */
263                 projectors[i].normal[0] = 0;
264                 projectors[i].normal[1] = 0;
265                 projectors[i].normal[2] = 1;
266                 mul_mat3_m4_v3(projectors[i].ob->obmat, projectors[i].normal);
267         }
268
269         numPolys = dm->getNumPolys(dm);
270         numLoops = dm->getNumLoops(dm);
271
272         /* make sure we are not modifying the original UV map */
273         mloop_uv = CustomData_duplicate_referenced_layer_named(&dm->loopData,
274                                                                CD_MLOOPUV, uvname, numLoops);
275
276         /* can be NULL */
277         mt = mtexpoly = CustomData_duplicate_referenced_layer_named(&dm->polyData,
278                                                                     CD_MTEXPOLY, uvname, numPolys);
279
280         numVerts = dm->getNumVerts(dm);
281
282         coords = MEM_callocN(sizeof(*coords) * numVerts,
283                              "uvprojectModifier_do coords");
284         dm->getVertCos(dm, coords);
285
286         /* convert coords to world space */
287         for (i = 0, co = coords; i < numVerts; ++i, ++co)
288                 mul_m4_v3(ob->obmat, *co);
289         
290         /* if only one projector, project coords to UVs */
291         if (num_projectors == 1 && projectors[0].uci == NULL)
292                 for (i = 0, co = coords; i < numVerts; ++i, ++co)
293                         mul_project_m4_v3(projectors[0].projmat, *co);
294
295         mpoly = dm->getPolyArray(dm);
296         mloop = dm->getLoopArray(dm);
297
298         /* apply coords as UVs, and apply image if tfaces are new */
299         for (i = 0, mp = mpoly; i < numPolys; ++i, ++mp, ++mt) {
300                 if (override_image || !image || (mtexpoly == NULL || mt->tpage == image)) {
301                         if (num_projectors == 1) {
302                                 if (projectors[0].uci) {
303                                         unsigned int fidx = mp->totloop - 1;
304                                         do {
305                                                 unsigned int lidx = mp->loopstart + fidx;
306                                                 unsigned int vidx = mloop[lidx].v;
307                                                 BLI_uvproject_from_camera(mloop_uv[lidx].uv, coords[vidx], projectors[0].uci);
308                                         } while (fidx--);
309                                 }
310                                 else {
311                                         /* apply transformed coords as UVs */
312                                         unsigned int fidx = mp->totloop - 1;
313                                         do {
314                                                 unsigned int lidx = mp->loopstart + fidx;
315                                                 unsigned int vidx = mloop[lidx].v;
316                                                 copy_v2_v2(mloop_uv[lidx].uv, coords[vidx]);
317                                         } while (fidx--);
318                                 }
319                         }
320                         else {
321                                 /* multiple projectors, select the closest to face normal direction */
322                                 float face_no[3];
323                                 int j;
324                                 Projector *best_projector;
325                                 float best_dot;
326
327                                 /* get the untransformed face normal */
328                                 BKE_mesh_calc_poly_normal_coords(mp, mloop + mp->loopstart, (const float (*)[3])coords, face_no);
329
330                                 /* find the projector which the face points at most directly
331                                  * (projector normal with largest dot product is best)
332                                  */
333                                 best_dot = dot_v3v3(projectors[0].normal, face_no);
334                                 best_projector = &projectors[0];
335
336                                 for (j = 1; j < num_projectors; ++j) {
337                                         float tmp_dot = dot_v3v3(projectors[j].normal,
338                                                                  face_no);
339                                         if (tmp_dot > best_dot) {
340                                                 best_dot = tmp_dot;
341                                                 best_projector = &projectors[j];
342                                         }
343                                 }
344
345                                 if (best_projector->uci) {
346                                         unsigned int fidx = mp->totloop - 1;
347                                         do {
348                                                 unsigned int lidx = mp->loopstart + fidx;
349                                                 unsigned int vidx = mloop[lidx].v;
350                                                 BLI_uvproject_from_camera(mloop_uv[lidx].uv, coords[vidx], best_projector->uci);
351                                         } while (fidx--);
352                                 }
353                                 else {
354                                         unsigned int fidx = mp->totloop - 1;
355                                         do {
356                                                 unsigned int lidx = mp->loopstart + fidx;
357                                                 unsigned int vidx = mloop[lidx].v;
358                                                 float tco[3];
359
360                                                 copy_v3_v3(tco, coords[vidx]);
361                                                 mul_project_m4_v3(best_projector->projmat, tco);
362                                                 copy_v2_v2(mloop_uv[lidx].uv, tco);
363
364                                         } while (fidx--);
365                                 }
366                         }
367                 }
368
369                 if (override_image && mtexpoly) {
370                         mt->tpage = image;
371                 }
372         }
373
374         MEM_freeN(coords);
375         
376         if (free_uci) {
377                 int j;
378                 for (j = 0; j < num_projectors; ++j) {
379                         if (projectors[j].uci) {
380                                 MEM_freeN(projectors[j].uci);
381                         }
382                 }
383         }
384
385         /* Mark tessellated CD layers as dirty. */
386         dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
387
388         return dm;
389 }
390
391 static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
392                                   DerivedMesh *derivedData,
393                                   int UNUSED(useRenderParams),
394                                   int UNUSED(isFinalCalc))
395 {
396         DerivedMesh *result;
397         UVProjectModifierData *umd = (UVProjectModifierData *) md;
398
399         result = uvprojectModifier_do(umd, ob, derivedData);
400
401         return result;
402 }
403
404 static DerivedMesh *applyModifierEM(ModifierData *md, Object *ob,
405                                     struct BMEditMesh *UNUSED(editData),
406                                     DerivedMesh *derivedData)
407 {
408         return applyModifier(md, ob, derivedData, 0, 1);
409 }
410
411
412 ModifierTypeInfo modifierType_UVProject = {
413         /* name */              "UVProject",
414         /* structName */        "UVProjectModifierData",
415         /* structSize */        sizeof(UVProjectModifierData),
416         /* type */              eModifierTypeType_NonGeometrical,
417         /* flags */             eModifierTypeFlag_AcceptsMesh |
418                                 eModifierTypeFlag_SupportsMapping |
419                                 eModifierTypeFlag_SupportsEditmode |
420                                 eModifierTypeFlag_EnableInEditmode,
421
422         /* copyData */          copyData,
423         /* deformVerts */       NULL,
424         /* deformMatrices */    NULL,
425         /* deformVertsEM */     NULL,
426         /* deformMatricesEM */  NULL,
427         /* applyModifier */     applyModifier,
428         /* applyModifierEM */   applyModifierEM,
429         /* initData */          initData,
430         /* requiredDataMask */  requiredDataMask,
431         /* freeData */          NULL,
432         /* isDisabled */        NULL,
433         /* updateDepgraph */    updateDepgraph,
434         /* dependsOnTime */     NULL,
435         /* dependsOnNormals */  NULL,
436         /* foreachObjectLink */ foreachObjectLink,
437         /* foreachIDLink */     foreachIDLink,
438         /* foreachTexLink */    NULL,
439 };