svn merge ^/trunk/blender -r44235:44250
[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= project_camera_info(projectors[i].ob, NULL, aspx, aspy);
198                                 project_camera_info_scale(projectors[i].uci, scax, scay);
199                                 free_uci= 1;
200                         }
201                         else {
202                                 float sensor= camera_sensor_size(cam->sensor_fit, cam->sensor_x, cam->sensor_y);
203                                 int sensor_fit= 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                                 } else { /* if(cam->type == CAM_ORTHO) */
230                                         float orthomat[4][4];
231                                         orthographic_m4( orthomat,xmin, xmax, ymin, ymax, cam->clipsta, cam->clipend);
232                                         mult_m4_m4m4(tmpmat, orthomat, projectors[i].projmat);
233                                 }
234                         }
235                 } else {
236                         copy_m4_m4(tmpmat, projectors[i].projmat);
237                 }
238
239                 unit_m4(offsetmat);
240                 mul_mat3_m4_fl(offsetmat, 0.5);
241                 offsetmat[3][0] = offsetmat[3][1] = offsetmat[3][2] = 0.5;
242                 
243                 if (cam) {
244                         if (aspx == aspy) { 
245                                 offsetmat[3][0] -= cam->shiftx;
246                                 offsetmat[3][1] -= cam->shifty;
247                         } else if (aspx < aspy)  {
248                                 offsetmat[3][0] -=(cam->shiftx * aspy/aspx);
249                                 offsetmat[3][1] -= cam->shifty;
250                         } else {
251                                 offsetmat[3][0] -= cam->shiftx;
252                                 offsetmat[3][1] -=(cam->shifty * aspx/aspy);
253                         }
254                 }
255                 
256                 mult_m4_m4m4(projectors[i].projmat, offsetmat, tmpmat);
257
258                 /* calculate worldspace projector normal (for best projector test) */
259                 projectors[i].normal[0] = 0;
260                 projectors[i].normal[1] = 0;
261                 projectors[i].normal[2] = 1;
262                 mul_mat3_m4_v3(projectors[i].ob->obmat, projectors[i].normal);
263         }
264
265         numPolys = dm->getNumPolys(dm);
266         numLoops = dm->getNumLoops(dm);
267
268         /* make sure we are not modifying the original UV map */
269         mloop_uv = CustomData_duplicate_referenced_layer_named(&dm->loopData,
270                         CD_MLOOPUV, uvname, numLoops);
271
272         /* can be NULL */
273         mtexpoly = CustomData_duplicate_referenced_layer_named(&dm->polyData,
274                         CD_MTEXPOLY, uvname, numPolys);
275
276         numVerts = dm->getNumVerts(dm);
277
278         coords = MEM_callocN(sizeof(*coords) * numVerts,
279                                  "uvprojectModifier_do coords");
280         dm->getVertCos(dm, coords);
281
282         /* convert coords to world space */
283         for(i = 0, co = coords; i < numVerts; ++i, ++co)
284                 mul_m4_v3(ob->obmat, *co);
285         
286         /* if only one projector, project coords to UVs */
287         if(num_projectors == 1 && projectors[0].uci==NULL)
288                 for(i = 0, co = coords; i < numVerts; ++i, ++co)
289                         mul_project_m4_v3(projectors[0].projmat, *co);
290
291         mpoly = dm->getPolyArray(dm);
292         mloop = dm->getLoopArray(dm);
293
294         /* apply coords as UVs, and apply image if tfaces are new */
295         for(i = 0, mp = mpoly; i < numPolys; ++i, ++mp, ++mt) {
296                 if(override_image || !image || (mtexpoly == NULL || mt->tpage == image)) {
297                         if(num_projectors == 1) {
298                                 if(projectors[0].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                                                 project_from_camera(mloop_uv[lidx].uv, coords[vidx], projectors[0].uci);
304                                         } while (fidx--);
305                                 }
306                                 else {
307                                         /* apply transformed coords as UVs */
308                                         unsigned int fidx= mp->totloop - 1;
309                                         do {
310                                                 unsigned int lidx= mp->loopstart + fidx;
311                                                 unsigned int vidx= mloop[lidx].v;
312                                                 copy_v2_v2(mloop_uv[lidx].uv, coords[vidx]);
313                                         } while (fidx--);
314                                 }
315                         } else {
316                                 /* multiple projectors, select the closest to face normal
317                                 * direction
318                                 */
319                                 float face_no[3];
320                                 int j;
321                                 Projector *best_projector;
322                                 float best_dot;
323
324                                 /* get the untransformed face normal */
325                                 mesh_calc_poly_normal_coords(mp, mloop + mp->loopstart, (const float (*)[3])coords, face_no);
326
327                                 /* find the projector which the face points at most directly
328                                 * (projector normal with largest dot product is best)
329                                 */
330                                 best_dot = dot_v3v3(projectors[0].normal, face_no);
331                                 best_projector = &projectors[0];
332
333                                 for(j = 1; j < num_projectors; ++j) {
334                                         float tmp_dot = dot_v3v3(projectors[j].normal,
335                                                         face_no);
336                                         if(tmp_dot > best_dot) {
337                                                 best_dot = tmp_dot;
338                                                 best_projector = &projectors[j];
339                                         }
340                                 }
341
342                                 if(best_projector->uci) {
343                                         unsigned int fidx= mp->totloop - 1;
344                                         do {
345                                                 unsigned int lidx= mp->loopstart + fidx;
346                                                 unsigned int vidx= mloop[lidx].v;
347                                                 project_from_camera(mloop_uv[lidx].uv, coords[vidx], best_projector->uci);
348                                         } while (fidx--);
349                                 }
350                                 else {
351                                         unsigned int fidx= mp->totloop - 1;
352                                         do {
353                                                 unsigned int lidx= mp->loopstart + fidx;
354                                                 unsigned int vidx= mloop[lidx].v;
355                                                 float tco[3];
356
357                                                 copy_v3_v3(tco, coords[vidx]);
358                                                 mul_project_m4_v3(best_projector->projmat, tco);
359                                                 copy_v2_v2(mloop_uv[lidx].uv, tco);
360
361                                         } while (fidx--);
362                                 }
363                         }
364                 }
365
366                 if(override_image && mtexpoly) {
367                         mt->tpage = image;
368                 }
369         }
370
371         MEM_freeN(coords);
372         
373         if(free_uci) {
374                 int j;
375                 for(j = 0; j < num_projectors; ++j) {
376                         if(projectors[j].uci) {
377                                 MEM_freeN(projectors[j].uci);
378                         }
379                 }
380         }
381         return dm;
382 }
383
384 static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
385                                                 DerivedMesh *derivedData,
386                                                 int UNUSED(useRenderParams),
387                                                 int UNUSED(isFinalCalc))
388 {
389         DerivedMesh *result;
390         UVProjectModifierData *umd = (UVProjectModifierData*) md;
391
392         result = uvprojectModifier_do(umd, ob, derivedData);
393
394         return result;
395 }
396
397 static DerivedMesh *applyModifierEM(ModifierData *md, Object *ob,
398                                                 struct BMEditMesh *UNUSED(editData),
399                                                 DerivedMesh *derivedData)
400 {
401         return applyModifier(md, ob, derivedData, 0, 1);
402 }
403
404
405 ModifierTypeInfo modifierType_UVProject = {
406         /* name */              "UVProject",
407         /* structName */        "UVProjectModifierData",
408         /* structSize */        sizeof(UVProjectModifierData),
409         /* type */              eModifierTypeType_NonGeometrical,
410         /* flags */             eModifierTypeFlag_AcceptsMesh
411                                                         | eModifierTypeFlag_SupportsMapping
412                                                         | eModifierTypeFlag_SupportsEditmode
413                                                         | eModifierTypeFlag_EnableInEditmode,
414
415         /* copyData */          copyData,
416         /* deformVerts */       NULL,
417         /* deformMatrices */    NULL,
418         /* deformVertsEM */     NULL,
419         /* deformMatricesEM */  NULL,
420         /* applyModifier */     applyModifier,
421         /* applyModifierEM */   applyModifierEM,
422         /* initData */          initData,
423         /* requiredDataMask */  requiredDataMask,
424         /* freeData */          NULL,
425         /* isDisabled */        NULL,
426         /* updateDepgraph */    updateDepgraph,
427         /* dependsOnTime */     NULL,
428         /* dependsOnNormals */  NULL,
429         /* foreachObjectLink */ foreachObjectLink,
430         /* foreachIDLink */     foreachIDLink,
431         /* foreachTexLink */    NULL,
432 };