add matrix multiply for projection that outputs 2d values.
[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         char uvname[MAX_CUSTOMDATA_LAYER_NAME];
161         float aspx = umd->aspectx ? umd->aspectx : 1.0f;
162         float aspy = umd->aspecty ? umd->aspecty : 1.0f;
163         float scax = umd->scalex ? umd->scalex : 1.0f;
164         float scay = umd->scaley ? umd->scaley : 1.0f;
165         int free_uci = 0;
166
167         for (i = 0; i < umd->num_projectors; ++i)
168                 if (umd->projectors[i])
169                         projectors[num_projectors++].ob = umd->projectors[i];
170
171         if (num_projectors == 0) return dm;
172
173         /* make sure there are UV Maps available */
174
175         if (!CustomData_has_layer(&dm->loopData, CD_MLOOPUV)) return dm;
176
177         /* make sure we're using an existing layer */
178         CustomData_validate_layer_name(&dm->loopData, CD_MLOOPUV, umd->uvlayer_name, uvname);
179
180         /* calculate a projection matrix and normal for each projector */
181         for (i = 0; i < num_projectors; ++i) {
182                 float tmpmat[4][4];
183                 float offsetmat[4][4];
184                 Camera *cam = NULL;
185                 /* calculate projection matrix */
186                 invert_m4_m4(projectors[i].projmat, projectors[i].ob->obmat);
187
188                 projectors[i].uci = NULL;
189
190                 if (projectors[i].ob->type == OB_CAMERA) {
191                         
192                         cam = (Camera *)projectors[i].ob->data;
193                         if (cam->type == CAM_PANO) {
194                                 projectors[i].uci = BLI_uvproject_camera_info(projectors[i].ob, NULL, aspx, aspy);
195                                 BLI_uvproject_camera_info_scale(projectors[i].uci, scax, scay);
196                                 free_uci = 1;
197                         }
198                         else {
199                                 CameraParams params;
200
201                                 /* setup parameters */
202                                 BKE_camera_params_init(&params);
203                                 BKE_camera_params_from_object(&params, projectors[i].ob);
204
205                                 /* compute matrix, viewplane, .. */
206                                 BKE_camera_params_compute_viewplane(&params, 1, 1, aspx, aspy);
207
208                                 /* scale the view-plane */
209                                 params.viewplane.xmin *= scax;
210                                 params.viewplane.xmax *= scax;
211                                 params.viewplane.ymin *= scay;
212                                 params.viewplane.ymax *= scay;
213
214                                 BKE_camera_params_compute_matrix(&params);
215                                 mult_m4_m4m4(tmpmat, params.winmat, projectors[i].projmat);
216                         }
217                 }
218                 else {
219                         copy_m4_m4(tmpmat, projectors[i].projmat);
220                 }
221
222                 unit_m4(offsetmat);
223                 mul_mat3_m4_fl(offsetmat, 0.5);
224                 offsetmat[3][0] = offsetmat[3][1] = offsetmat[3][2] = 0.5;
225
226                 mult_m4_m4m4(projectors[i].projmat, offsetmat, tmpmat);
227
228                 /* calculate worldspace projector normal (for best projector test) */
229                 projectors[i].normal[0] = 0;
230                 projectors[i].normal[1] = 0;
231                 projectors[i].normal[2] = 1;
232                 mul_mat3_m4_v3(projectors[i].ob->obmat, projectors[i].normal);
233         }
234
235         numPolys = dm->getNumPolys(dm);
236         numLoops = dm->getNumLoops(dm);
237
238         /* make sure we are not modifying the original UV map */
239         mloop_uv = CustomData_duplicate_referenced_layer_named(&dm->loopData,
240                                                                CD_MLOOPUV, uvname, numLoops);
241
242         /* can be NULL */
243         mt = mtexpoly = CustomData_duplicate_referenced_layer_named(&dm->polyData,
244                                                                     CD_MTEXPOLY, uvname, numPolys);
245
246         numVerts = dm->getNumVerts(dm);
247
248         coords = MEM_callocN(sizeof(*coords) * numVerts,
249                              "uvprojectModifier_do coords");
250         dm->getVertCos(dm, coords);
251
252         /* convert coords to world space */
253         for (i = 0, co = coords; i < numVerts; ++i, ++co)
254                 mul_m4_v3(ob->obmat, *co);
255         
256         /* if only one projector, project coords to UVs */
257         if (num_projectors == 1 && projectors[0].uci == NULL)
258                 for (i = 0, co = coords; i < numVerts; ++i, ++co)
259                         mul_project_m4_v3(projectors[0].projmat, *co);
260
261         mpoly = dm->getPolyArray(dm);
262         mloop = dm->getLoopArray(dm);
263
264         /* apply coords as UVs, and apply image if tfaces are new */
265         for (i = 0, mp = mpoly; i < numPolys; ++i, ++mp, ++mt) {
266                 if (override_image || !image || (mtexpoly == NULL || mt->tpage == image)) {
267                         if (num_projectors == 1) {
268                                 if (projectors[0].uci) {
269                                         unsigned int fidx = mp->totloop - 1;
270                                         do {
271                                                 unsigned int lidx = mp->loopstart + fidx;
272                                                 unsigned int vidx = mloop[lidx].v;
273                                                 BLI_uvproject_from_camera(mloop_uv[lidx].uv, coords[vidx], projectors[0].uci);
274                                         } while (fidx--);
275                                 }
276                                 else {
277                                         /* apply transformed coords as UVs */
278                                         unsigned int fidx = mp->totloop - 1;
279                                         do {
280                                                 unsigned int lidx = mp->loopstart + fidx;
281                                                 unsigned int vidx = mloop[lidx].v;
282                                                 copy_v2_v2(mloop_uv[lidx].uv, coords[vidx]);
283                                         } while (fidx--);
284                                 }
285                         }
286                         else {
287                                 /* multiple projectors, select the closest to face normal direction */
288                                 float face_no[3];
289                                 int j;
290                                 Projector *best_projector;
291                                 float best_dot;
292
293                                 /* get the untransformed face normal */
294                                 BKE_mesh_calc_poly_normal_coords(mp, mloop + mp->loopstart, (const float (*)[3])coords, face_no);
295
296                                 /* find the projector which the face points at most directly
297                                  * (projector normal with largest dot product is best)
298                                  */
299                                 best_dot = dot_v3v3(projectors[0].normal, face_no);
300                                 best_projector = &projectors[0];
301
302                                 for (j = 1; j < num_projectors; ++j) {
303                                         float tmp_dot = dot_v3v3(projectors[j].normal,
304                                                                  face_no);
305                                         if (tmp_dot > best_dot) {
306                                                 best_dot = tmp_dot;
307                                                 best_projector = &projectors[j];
308                                         }
309                                 }
310
311                                 if (best_projector->uci) {
312                                         unsigned int fidx = mp->totloop - 1;
313                                         do {
314                                                 unsigned int lidx = mp->loopstart + fidx;
315                                                 unsigned int vidx = mloop[lidx].v;
316                                                 BLI_uvproject_from_camera(mloop_uv[lidx].uv, coords[vidx], best_projector->uci);
317                                         } while (fidx--);
318                                 }
319                                 else {
320                                         unsigned int fidx = mp->totloop - 1;
321                                         do {
322                                                 unsigned int lidx = mp->loopstart + fidx;
323                                                 unsigned int vidx = mloop[lidx].v;
324                                                 mul_v2_project_m4_v3(mloop_uv[lidx].uv, best_projector->projmat, coords[vidx]);
325                                         } while (fidx--);
326                                 }
327                         }
328                 }
329
330                 if (override_image && mtexpoly) {
331                         mt->tpage = image;
332                 }
333         }
334
335         MEM_freeN(coords);
336         
337         if (free_uci) {
338                 int j;
339                 for (j = 0; j < num_projectors; ++j) {
340                         if (projectors[j].uci) {
341                                 MEM_freeN(projectors[j].uci);
342                         }
343                 }
344         }
345
346         /* Mark tessellated CD layers as dirty. */
347         dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
348
349         return dm;
350 }
351
352 static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
353                                   DerivedMesh *derivedData,
354                                   ModifierApplyFlag UNUSED(flag))
355 {
356         DerivedMesh *result;
357         UVProjectModifierData *umd = (UVProjectModifierData *) md;
358
359         result = uvprojectModifier_do(umd, ob, derivedData);
360
361         return result;
362 }
363
364
365 ModifierTypeInfo modifierType_UVProject = {
366         /* name */              "UVProject",
367         /* structName */        "UVProjectModifierData",
368         /* structSize */        sizeof(UVProjectModifierData),
369         /* type */              eModifierTypeType_NonGeometrical,
370         /* flags */             eModifierTypeFlag_AcceptsMesh |
371                                 eModifierTypeFlag_SupportsMapping |
372                                 eModifierTypeFlag_SupportsEditmode |
373                                 eModifierTypeFlag_EnableInEditmode,
374
375         /* copyData */          copyData,
376         /* deformVerts */       NULL,
377         /* deformMatrices */    NULL,
378         /* deformVertsEM */     NULL,
379         /* deformMatricesEM */  NULL,
380         /* applyModifier */     applyModifier,
381         /* applyModifierEM */   NULL,
382         /* initData */          initData,
383         /* requiredDataMask */  requiredDataMask,
384         /* freeData */          NULL,
385         /* isDisabled */        NULL,
386         /* updateDepgraph */    updateDepgraph,
387         /* dependsOnTime */     NULL,
388         /* dependsOnNormals */  NULL,
389         /* foreachObjectLink */ foreachObjectLink,
390         /* foreachIDLink */     foreachIDLink,
391         /* foreachTexLink */    NULL,
392 };