Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / object / object_transform.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2002-2008 full recode
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/object/object_transform.c
27  *  \ingroup edobj
28  */
29
30
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include "DNA_anim_types.h"
35 #include "DNA_armature_types.h"
36 #include "DNA_mesh_types.h"
37 #include "DNA_meta_types.h"
38 #include "DNA_lamp_types.h"
39 #include "DNA_object_types.h"
40 #include "DNA_scene_types.h"
41 #include "DNA_group_types.h"
42 #include "DNA_lattice_types.h"
43
44 #include "BLI_math.h"
45 #include "BLI_listbase.h"
46 #include "BLI_utildefines.h"
47 #include "BLI_array.h"
48
49 #include "BKE_context.h"
50 #include "BKE_curve.h"
51 #include "BKE_main.h"
52 #include "BKE_idcode.h"
53 #include "BKE_mball.h"
54 #include "BKE_mesh.h"
55 #include "BKE_object.h"
56 #include "BKE_report.h"
57 #include "BKE_editmesh.h"
58 #include "BKE_multires.h"
59 #include "BKE_armature.h"
60 #include "BKE_lattice.h"
61 #include "BKE_tracking.h"
62
63 #include "DEG_depsgraph.h"
64
65 #include "RNA_define.h"
66 #include "RNA_access.h"
67
68 #include "WM_api.h"
69 #include "WM_types.h"
70
71 #include "ED_armature.h"
72 #include "ED_keyframing.h"
73 #include "ED_mesh.h"
74 #include "ED_screen.h"
75 #include "ED_view3d.h"
76
77 #include "MEM_guardedalloc.h"
78
79 #include "object_intern.h"
80
81 /*************************** Clear Transformation ****************************/
82
83 /* clear location of object */
84 static void object_clear_loc(Object *ob, const bool clear_delta)
85 {
86         /* clear location if not locked */
87         if ((ob->protectflag & OB_LOCK_LOCX) == 0) {
88                 ob->loc[0] = 0.0f;
89                 if (clear_delta) ob->dloc[0] = 0.0f;
90         }
91         if ((ob->protectflag & OB_LOCK_LOCY) == 0) {
92                 ob->loc[1] = 0.0f;
93                 if (clear_delta) ob->dloc[1] = 0.0f;
94         }
95         if ((ob->protectflag & OB_LOCK_LOCZ) == 0) {
96                 ob->loc[2] = 0.0f;
97                 if (clear_delta) ob->dloc[2] = 0.0f;
98         }
99 }
100
101 /* clear rotation of object */
102 static void object_clear_rot(Object *ob, const bool clear_delta)
103 {
104         /* clear rotations that aren't locked */
105         if (ob->protectflag & (OB_LOCK_ROTX | OB_LOCK_ROTY | OB_LOCK_ROTZ | OB_LOCK_ROTW)) {
106                 if (ob->protectflag & OB_LOCK_ROT4D) {
107                         /* perform clamping on a component by component basis */
108                         if (ob->rotmode == ROT_MODE_AXISANGLE) {
109                                 if ((ob->protectflag & OB_LOCK_ROTW) == 0) {
110                                         ob->rotAngle = 0.0f;
111                                         if (clear_delta) ob->drotAngle = 0.0f;
112                                 }
113                                 if ((ob->protectflag & OB_LOCK_ROTX) == 0) {
114                                         ob->rotAxis[0] = 0.0f;
115                                         if (clear_delta) ob->drotAxis[0] = 0.0f;
116                                 }
117                                 if ((ob->protectflag & OB_LOCK_ROTY) == 0) {
118                                         ob->rotAxis[1] = 0.0f;
119                                         if (clear_delta) ob->drotAxis[1] = 0.0f;
120                                 }
121                                 if ((ob->protectflag & OB_LOCK_ROTZ) == 0) {
122                                         ob->rotAxis[2] = 0.0f;
123                                         if (clear_delta) ob->drotAxis[2] = 0.0f;
124                                 }
125
126                                 /* check validity of axis - axis should never be 0,0,0 (if so, then we make it rotate about y) */
127                                 if (IS_EQF(ob->rotAxis[0], ob->rotAxis[1]) && IS_EQF(ob->rotAxis[1], ob->rotAxis[2]))
128                                         ob->rotAxis[1] = 1.0f;
129                                 if (IS_EQF(ob->drotAxis[0], ob->drotAxis[1]) && IS_EQF(ob->drotAxis[1], ob->drotAxis[2]) && clear_delta)
130                                         ob->drotAxis[1] = 1.0f;
131                         }
132                         else if (ob->rotmode == ROT_MODE_QUAT) {
133                                 if ((ob->protectflag & OB_LOCK_ROTW) == 0) {
134                                         ob->quat[0] = 1.0f;
135                                         if (clear_delta) ob->dquat[0] = 1.0f;
136                                 }
137                                 if ((ob->protectflag & OB_LOCK_ROTX) == 0) {
138                                         ob->quat[1] = 0.0f;
139                                         if (clear_delta) ob->dquat[1] = 0.0f;
140                                 }
141                                 if ((ob->protectflag & OB_LOCK_ROTY) == 0) {
142                                         ob->quat[2] = 0.0f;
143                                         if (clear_delta) ob->dquat[2] = 0.0f;
144                                 }
145                                 if ((ob->protectflag & OB_LOCK_ROTZ) == 0) {
146                                         ob->quat[3] = 0.0f;
147                                         if (clear_delta) ob->dquat[3] = 0.0f;
148                                 }
149                                 /* TODO: does this quat need normalizing now? */
150                         }
151                         else {
152                                 /* the flag may have been set for the other modes, so just ignore the extra flag... */
153                                 if ((ob->protectflag & OB_LOCK_ROTX) == 0) {
154                                         ob->rot[0] = 0.0f;
155                                         if (clear_delta) ob->drot[0] = 0.0f;
156                                 }
157                                 if ((ob->protectflag & OB_LOCK_ROTY) == 0) {
158                                         ob->rot[1] = 0.0f;
159                                         if (clear_delta) ob->drot[1] = 0.0f;
160                                 }
161                                 if ((ob->protectflag & OB_LOCK_ROTZ) == 0) {
162                                         ob->rot[2] = 0.0f;
163                                         if (clear_delta) ob->drot[2] = 0.0f;
164                                 }
165                         }
166                 }
167                 else {
168                         /* perform clamping using euler form (3-components) */
169                         /* FIXME: deltas are not handled for these cases yet... */
170                         float eul[3], oldeul[3], quat1[4] = {0};
171
172                         if (ob->rotmode == ROT_MODE_QUAT) {
173                                 copy_qt_qt(quat1, ob->quat);
174                                 quat_to_eul(oldeul, ob->quat);
175                         }
176                         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
177                                 axis_angle_to_eulO(oldeul, EULER_ORDER_DEFAULT, ob->rotAxis, ob->rotAngle);
178                         }
179                         else {
180                                 copy_v3_v3(oldeul, ob->rot);
181                         }
182
183                         eul[0] = eul[1] = eul[2] = 0.0f;
184
185                         if (ob->protectflag & OB_LOCK_ROTX)
186                                 eul[0] = oldeul[0];
187                         if (ob->protectflag & OB_LOCK_ROTY)
188                                 eul[1] = oldeul[1];
189                         if (ob->protectflag & OB_LOCK_ROTZ)
190                                 eul[2] = oldeul[2];
191
192                         if (ob->rotmode == ROT_MODE_QUAT) {
193                                 eul_to_quat(ob->quat, eul);
194                                 /* quaternions flip w sign to accumulate rotations correctly */
195                                 if ((quat1[0] < 0.0f && ob->quat[0] > 0.0f) || (quat1[0] > 0.0f && ob->quat[0] < 0.0f)) {
196                                         mul_qt_fl(ob->quat, -1.0f);
197                                 }
198                         }
199                         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
200                                 eulO_to_axis_angle(ob->rotAxis, &ob->rotAngle, eul, EULER_ORDER_DEFAULT);
201                         }
202                         else {
203                                 copy_v3_v3(ob->rot, eul);
204                         }
205                 }
206         }                        // Duplicated in source/blender/editors/armature/editarmature.c
207         else {
208                 if (ob->rotmode == ROT_MODE_QUAT) {
209                         unit_qt(ob->quat);
210                         if (clear_delta) unit_qt(ob->dquat);
211                 }
212                 else if (ob->rotmode == ROT_MODE_AXISANGLE) {
213                         unit_axis_angle(ob->rotAxis, &ob->rotAngle);
214                         if (clear_delta) unit_axis_angle(ob->drotAxis, &ob->drotAngle);
215                 }
216                 else {
217                         zero_v3(ob->rot);
218                         if (clear_delta) zero_v3(ob->drot);
219                 }
220         }
221 }
222
223 /* clear scale of object */
224 static void object_clear_scale(Object *ob, const bool clear_delta)
225 {
226         /* clear scale factors which are not locked */
227         if ((ob->protectflag & OB_LOCK_SCALEX) == 0) {
228                 ob->size[0] = 1.0f;
229                 if (clear_delta) ob->dscale[0] = 1.0f;
230         }
231         if ((ob->protectflag & OB_LOCK_SCALEY) == 0) {
232                 ob->size[1] = 1.0f;
233                 if (clear_delta) ob->dscale[1] = 1.0f;
234         }
235         if ((ob->protectflag & OB_LOCK_SCALEZ) == 0) {
236                 ob->size[2] = 1.0f;
237                 if (clear_delta) ob->dscale[2] = 1.0f;
238         }
239 }
240
241 /* --------------- */
242
243 /* generic exec for clear-transform operators */
244 static int object_clear_transform_generic_exec(bContext *C, wmOperator *op,
245                                                void (*clear_func)(Object *, const bool),
246                                                const char default_ksName[])
247 {
248         Scene *scene = CTX_data_scene(C);
249         KeyingSet *ks;
250         const bool clear_delta = RNA_boolean_get(op->ptr, "clear_delta");
251
252         /* sanity checks */
253         if (ELEM(NULL, clear_func, default_ksName)) {
254                 BKE_report(op->reports, RPT_ERROR, "Programming error: missing clear transform function or keying set name");
255                 return OPERATOR_CANCELLED;
256         }
257
258         /* get KeyingSet to use */
259         ks = ANIM_get_keyingset_for_autokeying(scene, default_ksName);
260
261         /* operate on selected objects only if they aren't in weight-paint mode
262          * (so that object-transform clearing won't be applied at same time as bone-clearing)
263          */
264         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
265         {
266                 if (!(ob->mode & OB_MODE_WEIGHT_PAINT)) {
267                         /* run provided clearing function */
268                         clear_func(ob, clear_delta);
269
270                         ED_autokeyframe_object(C, scene, ob, ks);
271
272                         /* tag for updates */
273                         DEG_id_tag_update(&ob->id, OB_RECALC_OB);
274                 }
275         }
276         CTX_DATA_END;
277
278         /* this is needed so children are also updated */
279         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
280
281         return OPERATOR_FINISHED;
282 }
283
284 /* --------------- */
285
286
287 static int object_location_clear_exec(bContext *C, wmOperator *op)
288 {
289         return object_clear_transform_generic_exec(C, op, object_clear_loc, ANIM_KS_LOCATION_ID);
290 }
291
292 void OBJECT_OT_location_clear(wmOperatorType *ot)
293 {
294         /* identifiers */
295         ot->name = "Clear Location";
296         ot->description = "Clear the object's location";
297         ot->idname = "OBJECT_OT_location_clear";
298
299         /* api callbacks */
300         ot->exec = object_location_clear_exec;
301         ot->poll = ED_operator_scene_editable;
302
303         /* flags */
304         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
305
306
307         /* properties */
308         ot->prop = RNA_def_boolean(ot->srna, "clear_delta", false, "Clear Delta",
309                                    "Clear delta location in addition to clearing the normal location transform");
310 }
311
312 static int object_rotation_clear_exec(bContext *C, wmOperator *op)
313 {
314         return object_clear_transform_generic_exec(C, op, object_clear_rot, ANIM_KS_ROTATION_ID);
315 }
316
317 void OBJECT_OT_rotation_clear(wmOperatorType *ot)
318 {
319         /* identifiers */
320         ot->name = "Clear Rotation";
321         ot->description = "Clear the object's rotation";
322         ot->idname = "OBJECT_OT_rotation_clear";
323
324         /* api callbacks */
325         ot->exec = object_rotation_clear_exec;
326         ot->poll = ED_operator_scene_editable;
327
328         /* flags */
329         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
330
331         /* properties */
332         ot->prop = RNA_def_boolean(ot->srna, "clear_delta", false, "Clear Delta",
333                                    "Clear delta rotation in addition to clearing the normal rotation transform");
334 }
335
336 static int object_scale_clear_exec(bContext *C, wmOperator *op)
337 {
338         return object_clear_transform_generic_exec(C, op, object_clear_scale, ANIM_KS_SCALING_ID);
339 }
340
341 void OBJECT_OT_scale_clear(wmOperatorType *ot)
342 {
343         /* identifiers */
344         ot->name = "Clear Scale";
345         ot->description = "Clear the object's scale";
346         ot->idname = "OBJECT_OT_scale_clear";
347
348         /* api callbacks */
349         ot->exec = object_scale_clear_exec;
350         ot->poll = ED_operator_scene_editable;
351
352         /* flags */
353         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
354
355         /* properties */
356         ot->prop = RNA_def_boolean(ot->srna, "clear_delta", false, "Clear Delta",
357                                    "Clear delta scale in addition to clearing the normal scale transform");
358 }
359
360 /* --------------- */
361
362 static int object_origin_clear_exec(bContext *C, wmOperator *UNUSED(op))
363 {
364         float *v1, *v3;
365         float mat[3][3];
366
367         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
368         {
369                 if (ob->parent) {
370                         /* vectors pointed to by v1 and v3 will get modified */
371                         v1 = ob->loc;
372                         v3 = ob->parentinv[3];
373
374                         copy_m3_m4(mat, ob->parentinv);
375                         negate_v3_v3(v3, v1);
376                         mul_m3_v3(mat, v3);
377                 }
378
379                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
380         }
381         CTX_DATA_END;
382
383         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
384
385         return OPERATOR_FINISHED;
386 }
387
388 void OBJECT_OT_origin_clear(wmOperatorType *ot)
389 {
390         /* identifiers */
391         ot->name = "Clear Origin";
392         ot->description = "Clear the object's origin";
393         ot->idname = "OBJECT_OT_origin_clear";
394
395         /* api callbacks */
396         ot->exec = object_origin_clear_exec;
397         ot->poll = ED_operator_scene_editable;
398
399         /* flags */
400         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
401 }
402
403 /*************************** Apply Transformation ****************************/
404
405 /* use this when the loc/size/rot of the parent has changed but the children
406  * should stay in the same place, e.g. for apply-size-rot or object center */
407 static void ignore_parent_tx(const bContext *C, Main *bmain, Scene *scene, Object *ob)
408 {
409         Object workob;
410         Object *ob_child;
411         Depsgraph *depsgraph = CTX_data_depsgraph(C);
412
413         /* a change was made, adjust the children to compensate */
414         for (ob_child = bmain->object.first; ob_child; ob_child = ob_child->id.next) {
415                 if (ob_child->parent == ob) {
416                         BKE_object_apply_mat4(ob_child, ob_child->obmat, true, false);
417                         BKE_object_workob_calc_parent(depsgraph, scene, ob_child, &workob);
418                         invert_m4_m4(ob_child->parentinv, workob.obmat);
419                 }
420         }
421 }
422
423 static int apply_objects_internal(
424         bContext *C, ReportList *reports,
425         bool apply_loc, bool apply_rot, bool apply_scale,
426         bool do_props)
427 {
428         Main *bmain = CTX_data_main(C);
429         Scene *scene = CTX_data_scene(C);
430         Depsgraph *depsgraph = CTX_data_depsgraph(C);
431         float rsmat[3][3], obmat[3][3], iobmat[3][3], mat[4][4], scale;
432         bool changed = true;
433
434         /* first check if we can execute */
435         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
436         {
437                 if (ELEM(ob->type, OB_MESH, OB_ARMATURE, OB_LATTICE, OB_MBALL, OB_CURVE, OB_SURF, OB_FONT)) {
438                         ID *obdata = ob->data;
439                         if (ID_REAL_USERS(obdata) > 1) {
440                                 BKE_reportf(reports, RPT_ERROR,
441                                             "Cannot apply to a multi user: Object \"%s\", %s \"%s\", aborting",
442                                             ob->id.name + 2, BKE_idcode_to_name(GS(obdata->name)), obdata->name + 2);
443                                 changed = false;
444                         }
445
446                         if (ID_IS_LINKED(obdata)) {
447                                 BKE_reportf(reports, RPT_ERROR,
448                                             "Cannot apply to library data: Object \"%s\", %s \"%s\", aborting",
449                                             ob->id.name + 2, BKE_idcode_to_name(GS(obdata->name)), obdata->name + 2);
450                                 changed = false;
451                         }
452                 }
453
454                 if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
455                         ID *obdata = ob->data;
456                         Curve *cu;
457
458                         cu = ob->data;
459
460                         if (((ob->type == OB_CURVE) && !(cu->flag & CU_3D)) && (apply_rot || apply_loc)) {
461                                 BKE_reportf(reports, RPT_ERROR,
462                                             "Rotation/Location can't apply to a 2D curve: Object \"%s\", %s \"%s\", aborting",
463                                             ob->id.name + 2, BKE_idcode_to_name(GS(obdata->name)), obdata->name + 2);
464                                 changed = false;
465                         }
466                         if (cu->key) {
467                                 BKE_reportf(reports, RPT_ERROR,
468                                             "Can't apply to a curve with shape-keys: Object \"%s\", %s \"%s\", aborting",
469                                             ob->id.name + 2, BKE_idcode_to_name(GS(obdata->name)), obdata->name + 2);
470                                 changed = false;
471                         }
472                 }
473
474                 if (ob->type == OB_FONT) {
475                         if (apply_rot || apply_loc) {
476                                 BKE_reportf(reports, RPT_ERROR,
477                                             "Font's can only have scale applied: \"%s\"",
478                                             ob->id.name + 2);
479                                 changed = false;
480                         }
481                 }
482
483                 if (ob->type == OB_LAMP) {
484                         Lamp *la = ob->data;
485                         if (la->type == LA_AREA) {
486                                 if (apply_rot || apply_loc) {
487                                         BKE_reportf(reports, RPT_ERROR,
488                                                     "Area Lamps can only have scale applied: \"%s\"",
489                                                     ob->id.name + 2);
490                                         changed = false;
491                                 }
492                         }
493                 }
494         }
495         CTX_DATA_END;
496
497         if (!changed)
498                 return OPERATOR_CANCELLED;
499
500         changed = false;
501
502         /* now execute */
503         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
504         {
505
506                 /* calculate rotation/scale matrix */
507                 if (apply_scale && apply_rot)
508                         BKE_object_to_mat3(ob, rsmat);
509                 else if (apply_scale)
510                         BKE_object_scale_to_mat3(ob, rsmat);
511                 else if (apply_rot) {
512                         float tmat[3][3], timat[3][3];
513
514                         /* simple rotation matrix */
515                         BKE_object_rot_to_mat3(ob, rsmat, true);
516
517                         /* correct for scale, note mul_m3_m3m3 has swapped args! */
518                         BKE_object_scale_to_mat3(ob, tmat);
519                         invert_m3_m3(timat, tmat);
520                         mul_m3_m3m3(rsmat, timat, rsmat);
521                         mul_m3_m3m3(rsmat, rsmat, tmat);
522                 }
523                 else
524                         unit_m3(rsmat);
525
526                 copy_m4_m3(mat, rsmat);
527
528                 /* calculate translation */
529                 if (apply_loc) {
530                         copy_v3_v3(mat[3], ob->loc);
531
532                         if (!(apply_scale && apply_rot)) {
533                                 float tmat[3][3];
534                                 /* correct for scale and rotation that is still applied */
535                                 BKE_object_to_mat3(ob, obmat);
536                                 invert_m3_m3(iobmat, obmat);
537                                 mul_m3_m3m3(tmat, rsmat, iobmat);
538                                 mul_m3_v3(tmat, mat[3]);
539                         }
540                 }
541
542                 /* apply to object data */
543                 if (ob->type == OB_MESH) {
544                         Mesh *me = ob->data;
545
546                         if (apply_scale)
547                                 multiresModifier_scale_disp(depsgraph, scene, ob);
548
549                         /* adjust data */
550                         BKE_mesh_transform(me, mat, true);
551
552                         /* update normals */
553                         BKE_mesh_calc_normals(me);
554                 }
555                 else if (ob->type == OB_ARMATURE) {
556                         ED_armature_transform_apply(ob, mat, do_props);
557                 }
558                 else if (ob->type == OB_LATTICE) {
559                         Lattice *lt = ob->data;
560
561                         BKE_lattice_transform(lt, mat, true);
562                 }
563                 else if (ob->type == OB_MBALL) {
564                         MetaBall *mb = ob->data;
565                         BKE_mball_transform(mb, mat, do_props);
566                 }
567                 else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
568                         Curve *cu = ob->data;
569                         scale = mat3_to_scale(rsmat);
570                         BKE_curve_transform_ex(cu, mat, true, do_props, scale);
571                 }
572                 else if (ob->type == OB_FONT) {
573                         Curve *cu = ob->data;
574                         int i;
575
576                         scale = mat3_to_scale(rsmat);
577
578                         for (i = 0; i < cu->totbox; i++) {
579                                 TextBox *tb = &cu->tb[i];
580                                 tb->x *= scale;
581                                 tb->y *= scale;
582                                 tb->w *= scale;
583                                 tb->h *= scale;
584                         }
585
586                         if (do_props) {
587                                 cu->fsize *= scale;
588                         }
589                 }
590                 else if (ob->type == OB_CAMERA) {
591                         MovieClip *clip = BKE_object_movieclip_get(scene, ob, false);
592
593                         /* applying scale on camera actually scales clip's reconstruction.
594                          * of there's clip assigned to camera nothing to do actually.
595                          */
596                         if (!clip)
597                                 continue;
598
599                         if (apply_scale)
600                                 BKE_tracking_reconstruction_scale(&clip->tracking, ob->size);
601                 }
602                 else if (ob->type == OB_EMPTY) {
603                         /* It's possible for empties too, even though they don't
604                          * really have obdata, since we can simply apply the maximum
605                          * scaling to the empty's drawsize.
606                          *
607                          * Core Assumptions:
608                          * 1) Most scaled empties have uniform scaling
609                          *    (i.e. for visibility reasons), AND/OR
610                          * 2) Preserving non-uniform scaling is not that important,
611                          *    and is something that many users would be willing to
612                          *    sacrifice for having an easy way to do this.
613                          */
614
615                         if ((apply_loc == false) &&
616                             (apply_rot == false) &&
617                             (apply_scale == true))
618                         {
619                                 float max_scale = max_fff(fabsf(ob->size[0]), fabsf(ob->size[1]), fabsf(ob->size[2]));
620                                 ob->empty_drawsize *= max_scale;
621                         }
622                 }
623                 else if (ob->type == OB_LAMP) {
624                         Lamp *la = ob->data;
625                         if (la->type != LA_AREA) {
626                                 continue;
627                         }
628
629                         bool keeps_aspect_ratio = compare_ff_relative(rsmat[0][0], rsmat[1][1], FLT_EPSILON, 64);
630                         if ((la->area_shape == LA_AREA_SQUARE) && !keeps_aspect_ratio) {
631                                 la->area_shape = LA_AREA_RECT;
632                                 la->area_sizey = la->area_size;
633                         }
634                         else if ((la->area_shape == LA_AREA_DISK) && !keeps_aspect_ratio) {
635                                 la->area_shape = LA_AREA_ELLIPSE;
636                                 la->area_sizey = la->area_size;
637                         }
638
639                         la->area_size *= rsmat[0][0];
640                         la->area_sizey *= rsmat[1][1];
641                         la->area_sizez *= rsmat[2][2];
642                 }
643                 else {
644                         continue;
645                 }
646
647                 if (apply_loc)
648                         zero_v3(ob->loc);
649                 if (apply_scale)
650                         ob->size[0] = ob->size[1] = ob->size[2] = 1.0f;
651                 if (apply_rot) {
652                         zero_v3(ob->rot);
653                         unit_qt(ob->quat);
654                         unit_axis_angle(ob->rotAxis, &ob->rotAngle);
655                 }
656
657                 BKE_object_where_is_calc(depsgraph, scene, ob);
658                 if (ob->type == OB_ARMATURE) {
659                         BKE_pose_where_is(depsgraph, scene, ob); /* needed for bone parents */
660                 }
661
662                 ignore_parent_tx(C, bmain, scene, ob);
663
664                 DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA);
665
666                 changed = true;
667         }
668         CTX_DATA_END;
669
670         if (!changed) {
671                 BKE_report(reports, RPT_WARNING, "Objects have no data to transform");
672                 return OPERATOR_CANCELLED;
673         }
674
675         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
676         return OPERATOR_FINISHED;
677 }
678
679 static int visual_transform_apply_exec(bContext *C, wmOperator *UNUSED(op))
680 {
681         Scene *scene = CTX_data_scene(C);
682         Depsgraph *depsgraph = CTX_data_depsgraph(C);
683         bool changed = false;
684
685         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
686         {
687                 BKE_object_where_is_calc(depsgraph, scene, ob);
688                 BKE_object_apply_mat4(ob, ob->obmat, true, true);
689                 BKE_object_where_is_calc(depsgraph, scene, ob);
690
691                 /* update for any children that may get moved */
692                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
693
694                 changed = true;
695         }
696         CTX_DATA_END;
697
698         if (!changed)
699                 return OPERATOR_CANCELLED;
700
701         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
702         return OPERATOR_FINISHED;
703 }
704
705 void OBJECT_OT_visual_transform_apply(wmOperatorType *ot)
706 {
707         /* identifiers */
708         ot->name = "Apply Visual Transform";
709         ot->description = "Apply the object's visual transformation to its data";
710         ot->idname = "OBJECT_OT_visual_transform_apply";
711
712         /* api callbacks */
713         ot->exec = visual_transform_apply_exec;
714         ot->poll = ED_operator_scene_editable;
715
716         /* flags */
717         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
718 }
719
720 static int object_transform_apply_exec(bContext *C, wmOperator *op)
721 {
722         const bool loc = RNA_boolean_get(op->ptr, "location");
723         const bool rot = RNA_boolean_get(op->ptr, "rotation");
724         const bool sca = RNA_boolean_get(op->ptr, "scale");
725         const bool do_props = RNA_boolean_get(op->ptr, "properties");
726
727         if (loc || rot || sca) {
728                 return apply_objects_internal(C, op->reports, loc, rot, sca, do_props);
729         }
730         else {
731                 /* allow for redo */
732                 return OPERATOR_FINISHED;
733         }
734 }
735
736 void OBJECT_OT_transform_apply(wmOperatorType *ot)
737 {
738         /* identifiers */
739         ot->name = "Apply Object Transform";
740         ot->description = "Apply the object's transformation to its data";
741         ot->idname = "OBJECT_OT_transform_apply";
742
743         /* api callbacks */
744         ot->exec = object_transform_apply_exec;
745         ot->poll = ED_operator_objectmode;
746
747         /* flags */
748         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
749
750         RNA_def_boolean(ot->srna, "location", 0, "Location", "");
751         RNA_def_boolean(ot->srna, "rotation", 0, "Rotation", "");
752         RNA_def_boolean(ot->srna, "scale", 0, "Scale", "");
753         RNA_def_boolean(ot->srna, "properties", true, "Apply Properties",
754                         "Modify properties such as curve vertex radius, font size and bone envelope");
755 }
756
757 /********************* Set Object Center ************************/
758
759 enum {
760         GEOMETRY_TO_ORIGIN = 0,
761         ORIGIN_TO_GEOMETRY,
762         ORIGIN_TO_CURSOR,
763         ORIGIN_TO_CENTER_OF_MASS_SURFACE,
764         ORIGIN_TO_CENTER_OF_MASS_VOLUME,
765 };
766
767 static int object_origin_set_exec(bContext *C, wmOperator *op)
768 {
769         Main *bmain = CTX_data_main(C);
770         Scene *scene = CTX_data_scene(C);
771         Object *obact = CTX_data_active_object(C);
772         Object *obedit = CTX_data_edit_object(C);
773         Depsgraph *depsgraph = CTX_data_depsgraph(C);
774         Object *tob;
775         float cursor[3], cent[3], cent_neg[3], centn[3];
776         int centermode = RNA_enum_get(op->ptr, "type");
777         int around = RNA_enum_get(op->ptr, "center"); /* initialized from v3d->around */
778
779         ListBase ctx_data_list;
780         CollectionPointerLink *ctx_ob;
781         CollectionPointerLink *ctx_ob_act = NULL;
782
783         /* keep track of what is changed */
784         int tot_change = 0, tot_lib_error = 0, tot_multiuser_arm_error = 0;
785
786         if (obedit && centermode != GEOMETRY_TO_ORIGIN) {
787                 BKE_report(op->reports, RPT_ERROR, "Operation cannot be performed in edit mode");
788                 return OPERATOR_CANCELLED;
789         }
790         else {
791                 /* get the view settings if 'around' isn't set and the view is available */
792                 View3D *v3d = CTX_wm_view3d(C);
793                 copy_v3_v3(cursor, ED_view3d_cursor3d_get(scene, v3d)->location);
794                 if (v3d && !RNA_struct_property_is_set(op->ptr, "center"))
795                         around = scene->toolsettings->transform_pivot_point;
796         }
797
798         zero_v3(cent);
799
800         if (obedit) {
801                 if (obedit->type == OB_MESH) {
802                         Mesh *me = obedit->data;
803                         BMEditMesh *em = me->edit_btmesh;
804                         BMVert *eve;
805                         BMIter iter;
806
807                         if (centermode == ORIGIN_TO_CURSOR) {
808                                 copy_v3_v3(cent, cursor);
809                                 invert_m4_m4(obedit->imat, obedit->obmat);
810                                 mul_m4_v3(obedit->imat, cent);
811                         }
812                         else {
813                                 if (around == V3D_AROUND_CENTER_MEAN) {
814                                         if (em->bm->totvert) {
815                                                 const float total_div = 1.0f / (float)em->bm->totvert;
816                                                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
817                                                         madd_v3_v3fl(cent, eve->co, total_div);
818                                                 }
819                                         }
820                                 }
821                                 else {
822                                         float min[3], max[3];
823                                         INIT_MINMAX(min, max);
824                                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
825                                                 minmax_v3v3_v3(min, max, eve->co);
826                                         }
827                                         mid_v3_v3v3(cent, min, max);
828                                 }
829                         }
830
831                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
832                                 sub_v3_v3(eve->co, cent);
833                         }
834
835                         EDBM_mesh_normals_update(em);
836                         tot_change++;
837                         DEG_id_tag_update(&obedit->id, OB_RECALC_DATA);
838                 }
839         }
840
841         CTX_data_selected_editable_objects(C, &ctx_data_list);
842
843         /* reset flags */
844         for (ctx_ob = ctx_data_list.first;
845              ctx_ob;
846              ctx_ob = ctx_ob->next)
847         {
848                 Object *ob = ctx_ob->ptr.data;
849                 ob->flag &= ~OB_DONE;
850
851                 /* move active first */
852                 if (ob == obact) {
853                         ctx_ob_act = ctx_ob;
854                 }
855         }
856
857         if (ctx_ob_act) {
858                 BLI_listbase_rotate_first(&ctx_data_list, (LinkData *)ctx_ob_act);
859         }
860
861         for (tob = bmain->object.first; tob; tob = tob->id.next) {
862                 if (tob->data)
863                         ((ID *)tob->data)->tag &= ~LIB_TAG_DOIT;
864                 if (tob->dup_group)
865                         ((ID *)tob->dup_group)->tag &= ~LIB_TAG_DOIT;
866         }
867
868         for (ctx_ob = ctx_data_list.first;
869              ctx_ob;
870              ctx_ob = ctx_ob->next)
871         {
872                 Object *ob = ctx_ob->ptr.data;
873
874                 if ((ob->flag & OB_DONE) == 0) {
875                         bool do_inverse_offset = false;
876                         ob->flag |= OB_DONE;
877
878                         if (centermode == ORIGIN_TO_CURSOR) {
879                                 copy_v3_v3(cent, cursor);
880                                 invert_m4_m4(ob->imat, ob->obmat);
881                                 mul_m4_v3(ob->imat, cent);
882                         }
883
884                         if (ob->data == NULL) {
885                                 /* special support for dupligroups */
886                                 if ((ob->transflag & OB_DUPLICOLLECTION) && ob->dup_group && (ob->dup_group->id.tag & LIB_TAG_DOIT) == 0) {
887                                         if (ID_IS_LINKED(ob->dup_group)) {
888                                                 tot_lib_error++;
889                                         }
890                                         else {
891                                                 if (centermode == ORIGIN_TO_CURSOR) {
892                                                         /* done */
893                                                 }
894                                                 else {
895                                                         float min[3], max[3];
896                                                         /* only bounds support */
897                                                         INIT_MINMAX(min, max);
898                                                         BKE_object_minmax_dupli(depsgraph, scene, ob, min, max, true);
899                                                         mid_v3_v3v3(cent, min, max);
900                                                         invert_m4_m4(ob->imat, ob->obmat);
901                                                         mul_m4_v3(ob->imat, cent);
902                                                 }
903
904                                                 add_v3_v3(ob->dup_group->dupli_ofs, cent);
905
906                                                 tot_change++;
907                                                 ob->dup_group->id.tag |= LIB_TAG_DOIT;
908                                                 do_inverse_offset = true;
909                                         }
910                                 }
911                         }
912                         else if (ID_IS_LINKED(ob->data)) {
913                                 tot_lib_error++;
914                         }
915
916                         if (obedit == NULL && ob->type == OB_MESH) {
917                                 Mesh *me = ob->data;
918
919                                 if (centermode == ORIGIN_TO_CURSOR) {
920                                         /* done */
921                                 }
922                                 else if (centermode == ORIGIN_TO_CENTER_OF_MASS_SURFACE) {
923                                         BKE_mesh_center_of_surface(me, cent);
924                                 }
925                                 else if (centermode == ORIGIN_TO_CENTER_OF_MASS_VOLUME) {
926                                         BKE_mesh_center_of_volume(me, cent);
927                                 }
928                                 else if (around == V3D_AROUND_CENTER_MEAN) {
929                                         BKE_mesh_center_median(me, cent);
930                                 }
931                                 else {
932                                         BKE_mesh_center_bounds(me, cent);
933                                 }
934
935                                 negate_v3_v3(cent_neg, cent);
936                                 BKE_mesh_translate(me, cent_neg, 1);
937
938                                 tot_change++;
939                                 me->id.tag |= LIB_TAG_DOIT;
940                                 do_inverse_offset = true;
941                         }
942                         else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
943                                 Curve *cu = ob->data;
944
945                                 if      (centermode == ORIGIN_TO_CURSOR)    { /* done */ }
946                                 else if (around == V3D_AROUND_CENTER_MEAN)  { BKE_curve_center_median(cu, cent); }
947                                 else                                        { BKE_curve_center_bounds(cu, cent); }
948
949                                 /* don't allow Z change if curve is 2D */
950                                 if ((ob->type == OB_CURVE) && !(cu->flag & CU_3D))
951                                         cent[2] = 0.0;
952
953                                 negate_v3_v3(cent_neg, cent);
954                                 BKE_curve_translate(cu, cent_neg, 1);
955
956                                 tot_change++;
957                                 cu->id.tag |= LIB_TAG_DOIT;
958                                 do_inverse_offset = true;
959
960                                 if (obedit) {
961                                         if (centermode == GEOMETRY_TO_ORIGIN) {
962                                                 DEG_id_tag_update(&obedit->id, OB_RECALC_DATA);
963                                         }
964                                         break;
965                                 }
966                         }
967                         else if (ob->type == OB_FONT) {
968                                 /* get from bb */
969
970                                 Curve *cu = ob->data;
971
972                                 if (ob->bb == NULL && (centermode != ORIGIN_TO_CURSOR)) {
973                                         /* do nothing*/
974                                 }
975                                 else {
976                                         if (centermode == ORIGIN_TO_CURSOR) {
977                                                 /* done */
978                                         }
979                                         else {
980                                                 /* extra 0.5 is the height o above line */
981                                                 cent[0] = 0.5f * (ob->bb->vec[4][0] + ob->bb->vec[0][0]);
982                                                 cent[1] = 0.5f * (ob->bb->vec[0][1] + ob->bb->vec[2][1]);
983                                         }
984
985                                         cent[2] = 0.0f;
986
987                                         cu->xof = cu->xof - cent[0];
988                                         cu->yof = cu->yof - cent[1];
989
990                                         tot_change++;
991                                         cu->id.tag |= LIB_TAG_DOIT;
992                                         do_inverse_offset = true;
993                                 }
994                         }
995                         else if (ob->type == OB_ARMATURE) {
996                                 bArmature *arm = ob->data;
997
998                                 if (ID_REAL_USERS(arm) > 1) {
999 #if 0
1000                                         BKE_report(op->reports, RPT_ERROR, "Cannot apply to a multi user armature");
1001                                         return;
1002 #endif
1003                                         tot_multiuser_arm_error++;
1004                                 }
1005                                 else {
1006                                         /* Function to recenter armatures in editarmature.c
1007                                          * Bone + object locations are handled there.
1008                                          */
1009                                         ED_armature_origin_set(ob, cursor, centermode, around);
1010
1011                                         tot_change++;
1012                                         arm->id.tag |= LIB_TAG_DOIT;
1013                                         /* do_inverse_offset = true; */ /* docenter_armature() handles this */
1014
1015                                         BKE_object_where_is_calc(depsgraph, scene, ob);
1016                                         BKE_pose_where_is(depsgraph, scene, ob); /* needed for bone parents */
1017
1018                                         ignore_parent_tx(C, bmain, scene, ob);
1019
1020                                         if (obedit)
1021                                                 break;
1022                                 }
1023                         }
1024                         else if (ob->type == OB_MBALL) {
1025                                 MetaBall *mb = ob->data;
1026
1027                                 if      (centermode == ORIGIN_TO_CURSOR)    { /* done */ }
1028                                 else if (around == V3D_AROUND_CENTER_MEAN)  { BKE_mball_center_median(mb, cent); }
1029                                 else                                        { BKE_mball_center_bounds(mb, cent); }
1030
1031                                 negate_v3_v3(cent_neg, cent);
1032                                 BKE_mball_translate(mb, cent_neg);
1033
1034                                 tot_change++;
1035                                 mb->id.tag |= LIB_TAG_DOIT;
1036                                 do_inverse_offset = true;
1037
1038                                 if (obedit) {
1039                                         if (centermode == GEOMETRY_TO_ORIGIN) {
1040                                                 DEG_id_tag_update(&obedit->id, OB_RECALC_DATA);
1041                                         }
1042                                         break;
1043                                 }
1044                         }
1045                         else if (ob->type == OB_LATTICE) {
1046                                 Lattice *lt = ob->data;
1047
1048                                 if      (centermode == ORIGIN_TO_CURSOR)    { /* done */ }
1049                                 else if (around == V3D_AROUND_CENTER_MEAN)  { BKE_lattice_center_median(lt, cent); }
1050                                 else                                        { BKE_lattice_center_bounds(lt, cent); }
1051
1052                                 negate_v3_v3(cent_neg, cent);
1053                                 BKE_lattice_translate(lt, cent_neg, 1);
1054
1055                                 tot_change++;
1056                                 lt->id.tag |= LIB_TAG_DOIT;
1057                                 do_inverse_offset = true;
1058                         }
1059
1060                         /* offset other selected objects */
1061                         if (do_inverse_offset && (centermode != GEOMETRY_TO_ORIGIN)) {
1062                                 CollectionPointerLink *ctx_link_other;
1063                                 float obmat[4][4];
1064
1065                                 /* was the object data modified
1066                                  * note: the functions above must set 'cent' */
1067
1068                                 /* convert the offset to parent space */
1069                                 BKE_object_to_mat4(ob, obmat);
1070                                 mul_v3_mat3_m4v3(centn, obmat, cent); /* omit translation part */
1071
1072                                 add_v3_v3(ob->loc, centn);
1073
1074                                 BKE_object_where_is_calc(depsgraph, scene, ob);
1075                                 if (ob->type == OB_ARMATURE) {
1076                                         BKE_pose_where_is(depsgraph, scene, ob); /* needed for bone parents */
1077                                 }
1078
1079                                 ignore_parent_tx(C, bmain, scene, ob);
1080
1081                                 /* other users? */
1082                                 //CTX_DATA_BEGIN (C, Object *, ob_other, selected_editable_objects)
1083                                 //{
1084
1085                                 /* use existing context looper */
1086                                 for (ctx_link_other = ctx_data_list.first;
1087                                      ctx_link_other;
1088                                      ctx_link_other = ctx_link_other->next)
1089                                 {
1090                                         Object *ob_other = ctx_link_other->ptr.data;
1091
1092                                         if ((ob_other->flag & OB_DONE) == 0 &&
1093                                             ((ob->data && (ob->data == ob_other->data)) ||
1094                                              (ob->dup_group == ob_other->dup_group &&
1095                                               (ob->transflag | ob_other->transflag) & OB_DUPLICOLLECTION)))
1096                                         {
1097                                                 ob_other->flag |= OB_DONE;
1098                                                 DEG_id_tag_update(&ob_other->id, OB_RECALC_OB | OB_RECALC_DATA);
1099
1100                                                 mul_v3_mat3_m4v3(centn, ob_other->obmat, cent); /* omit translation part */
1101                                                 add_v3_v3(ob_other->loc, centn);
1102
1103                                                 BKE_object_where_is_calc(depsgraph, scene, ob_other);
1104                                                 if (ob_other->type == OB_ARMATURE) {
1105                                                         BKE_pose_where_is(depsgraph, scene, ob_other); /* needed for bone parents */
1106                                                 }
1107                                                 ignore_parent_tx(C, bmain, scene, ob_other);
1108                                         }
1109                                 }
1110                                 //CTX_DATA_END;
1111                         }
1112                 }
1113         }
1114         BLI_freelistN(&ctx_data_list);
1115
1116         for (tob = bmain->object.first; tob; tob = tob->id.next) {
1117                 if (tob->data && (((ID *)tob->data)->tag & LIB_TAG_DOIT)) {
1118                         BKE_mesh_batch_cache_dirty(tob->data, BKE_MESH_BATCH_DIRTY_ALL);
1119                         DEG_id_tag_update(&tob->id, OB_RECALC_OB | OB_RECALC_DATA);
1120                 }
1121         }
1122
1123         if (tot_change) {
1124                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1125         }
1126
1127         /* Warn if any errors occurred */
1128         if (tot_lib_error + tot_multiuser_arm_error) {
1129                 BKE_reportf(op->reports, RPT_WARNING, "%i object(s) not centered, %i changed:", tot_lib_error + tot_multiuser_arm_error, tot_change);
1130                 if (tot_lib_error)
1131                         BKE_reportf(op->reports, RPT_WARNING, "|%i linked library object(s)", tot_lib_error);
1132                 if (tot_multiuser_arm_error)
1133                         BKE_reportf(op->reports, RPT_WARNING, "|%i multiuser armature object(s)", tot_multiuser_arm_error);
1134         }
1135
1136         return OPERATOR_FINISHED;
1137 }
1138
1139 void OBJECT_OT_origin_set(wmOperatorType *ot)
1140 {
1141         static const EnumPropertyItem prop_set_center_types[] = {
1142                 {GEOMETRY_TO_ORIGIN, "GEOMETRY_ORIGIN", 0, "Geometry to Origin", "Move object geometry to object origin"},
1143                 {ORIGIN_TO_GEOMETRY, "ORIGIN_GEOMETRY", 0, "Origin to Geometry",
1144                  "Calculate the center of geometry based on the current pivot point (median, otherwise bounding-box)"},
1145                 {ORIGIN_TO_CURSOR, "ORIGIN_CURSOR", 0, "Origin to 3D Cursor",
1146                  "Move object origin to position of the 3D cursor"},
1147                 /* Intentional naming mismatch since some scripts refer to this. */
1148                 {ORIGIN_TO_CENTER_OF_MASS_SURFACE, "ORIGIN_CENTER_OF_MASS", 0, "Origin to Center of Mass (Surface)",
1149                  "Calculate the center of mass from the surface area"},
1150                 {ORIGIN_TO_CENTER_OF_MASS_VOLUME, "ORIGIN_CENTER_OF_VOLUME", 0, "Origin to Center of Mass (Volume)",
1151                  "Calculate the center of mass from the volume (must be manifold geometry with consistent normals)"},
1152                 {0, NULL, 0, NULL, NULL}
1153         };
1154
1155         static const EnumPropertyItem prop_set_bounds_types[] = {
1156                 {V3D_AROUND_CENTER_MEAN, "MEDIAN", 0, "Median Center", ""},
1157                 {V3D_AROUND_CENTER_BOUNDS, "BOUNDS", 0, "Bounds Center", ""},
1158                 {0, NULL, 0, NULL, NULL}
1159         };
1160
1161         /* identifiers */
1162         ot->name = "Set Origin";
1163         ot->description = "Set the object's origin, by either moving the data, or set to center of data, or use 3D cursor";
1164         ot->idname = "OBJECT_OT_origin_set";
1165
1166         /* api callbacks */
1167         ot->invoke = WM_menu_invoke;
1168         ot->exec = object_origin_set_exec;
1169
1170         ot->poll = ED_operator_scene_editable;
1171
1172         /* flags */
1173         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1174
1175         ot->prop = RNA_def_enum(ot->srna, "type", prop_set_center_types, 0, "Type", "");
1176         RNA_def_enum(ot->srna, "center", prop_set_bounds_types, V3D_AROUND_CENTER_MEAN, "Center", "");
1177 }
1178
1179 /* -------------------------------------------------------------------- */
1180
1181 /** \name Transform Axis Target
1182  *
1183  * Note this is an experemental operator to point lamps/cameras at objects.
1184  * We may re-work how this behaves based on user feedback.
1185  * - campbell.
1186  * \{ */
1187
1188 /* When using multiple objects, apply their relative rotational offset to the active object. */
1189 #define USE_RELATIVE_ROTATION
1190
1191 struct XFormAxisItem {
1192         Object *ob;
1193         float rot_mat[3][3];
1194         void *obtfm;
1195         float xform_dist;
1196
1197 #ifdef USE_RELATIVE_ROTATION
1198         /* use when translating multiple */
1199         float xform_rot_offset[3][3];
1200 #endif
1201 };
1202
1203 struct XFormAxisData {
1204         ViewContext vc;
1205         struct {
1206                 float depth;
1207                 float normal[3];
1208                 bool is_depth_valid;
1209                 bool is_normal_valid;
1210         } prev;
1211
1212         struct XFormAxisItem *object_data;
1213         uint object_data_len;
1214         bool is_translate;
1215
1216         int init_event;
1217 };
1218
1219 static bool object_is_target_compat(const Object *ob)
1220 {
1221         if (ob->type == OB_LAMP) {
1222                 const Lamp *la = ob->data;
1223                 if (ELEM(la->type, LA_SUN, LA_SPOT, LA_HEMI, LA_AREA)) {
1224                         return true;
1225                 }
1226         }
1227         /* We might want to enable this later, for now just lamps */
1228 #if 0
1229         else if (ob->type == OB_CAMERA) {
1230                 return true;
1231         }
1232 #endif
1233         return false;
1234 }
1235
1236 static void object_transform_axis_target_free_data(wmOperator *op)
1237 {
1238         struct XFormAxisData *xfd = op->customdata;
1239         struct XFormAxisItem *item = xfd->object_data;
1240         for (int i = 0; i < xfd->object_data_len; i++, item++) {
1241                 MEM_freeN(item->obtfm);
1242         }
1243         MEM_freeN(xfd->object_data);
1244         MEM_freeN(xfd);
1245         op->customdata = NULL;
1246 }
1247
1248 /* We may want to expose as alternative to: BKE_object_apply_rotation */
1249 static void object_apply_rotation(Object *ob, const float rmat[3][3])
1250 {
1251         float size[3];
1252         float loc[3];
1253         float rmat4[4][4];
1254         copy_m4_m3(rmat4, rmat);
1255
1256         copy_v3_v3(size, ob->size);
1257         copy_v3_v3(loc, ob->loc);
1258         BKE_object_apply_mat4(ob, rmat4, true, true);
1259         copy_v3_v3(ob->size, size);
1260         copy_v3_v3(ob->loc, loc);
1261 }
1262 /* We may want to extract this to: BKE_object_apply_location */
1263 static void object_apply_location(Object *ob, const float loc[3])
1264 {
1265         /* quick but weak */
1266         Object ob_prev = *ob;
1267         float mat[4][4];
1268         copy_m4_m4(mat, ob->obmat);
1269         copy_v3_v3(mat[3], loc);
1270         BKE_object_apply_mat4(ob, mat, true, true);
1271         copy_v3_v3(mat[3], ob->loc);
1272         *ob = ob_prev;
1273         copy_v3_v3(ob->loc, mat[3]);
1274 }
1275
1276 static void object_orient_to_location(
1277         Object *ob, float rot_orig[3][3], const float axis[3], const float location[3])
1278 {
1279         float delta[3];
1280         sub_v3_v3v3(delta, ob->obmat[3], location);
1281         if (normalize_v3(delta) != 0.0f) {
1282                 if (len_squared_v3v3(delta, axis) > FLT_EPSILON) {
1283                         float delta_rot[3][3];
1284                         float final_rot[3][3];
1285                         rotation_between_vecs_to_mat3(delta_rot, axis, delta);
1286
1287                         mul_m3_m3m3(final_rot, delta_rot, rot_orig);
1288
1289                         object_apply_rotation(ob, final_rot);
1290
1291                         DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1292                 }
1293         }
1294 }
1295
1296 static void object_transform_axis_target_cancel(bContext *C, wmOperator *op)
1297 {
1298         struct XFormAxisData *xfd = op->customdata;
1299         struct XFormAxisItem *item = xfd->object_data;
1300         for (int i = 0; i < xfd->object_data_len; i++, item++) {
1301                 BKE_object_tfm_restore(item->ob, item->obtfm);
1302                 DEG_id_tag_update(&item->ob->id, OB_RECALC_OB);
1303                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, item->ob);
1304         }
1305
1306         object_transform_axis_target_free_data(op);
1307 }
1308
1309 static int object_transform_axis_target_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1310 {
1311         ViewContext vc;
1312         ED_view3d_viewcontext_init(C, &vc);
1313
1314         if (!object_is_target_compat(vc.obact)) {
1315                 /* Falls back to texture space transform. */
1316                 return OPERATOR_PASS_THROUGH;
1317         }
1318
1319         ED_view3d_autodist_init(vc.depsgraph, vc.ar, vc.v3d, 0);
1320
1321         if (vc.rv3d->depths != NULL) {
1322                 vc.rv3d->depths->damaged = true;
1323         }
1324         ED_view3d_depth_update(vc.ar);
1325
1326         if (vc.rv3d->depths == NULL) {
1327                 BKE_report(op->reports, RPT_WARNING, "Unable to access depth buffer, using view plane");
1328                 return OPERATOR_CANCELLED;
1329         }
1330
1331         ED_region_tag_redraw(vc.ar);
1332
1333         struct XFormAxisData *xfd;
1334         xfd = op->customdata = MEM_callocN(sizeof(struct XFormAxisData), __func__);
1335
1336         /* Don't change this at runtime. */
1337         xfd->vc = vc;
1338         xfd->vc.mval[0] = event->mval[0];
1339         xfd->vc.mval[1] = event->mval[1];
1340
1341         xfd->prev.depth = 1.0f;
1342         xfd->prev.is_depth_valid = false;
1343         xfd->prev.is_normal_valid = false;
1344         xfd->is_translate = false;
1345
1346         xfd->init_event = WM_userdef_event_type_from_keymap_type(event->type);
1347
1348         {
1349                 struct XFormAxisItem *object_data = NULL;
1350                 BLI_array_declare(object_data);
1351
1352                 struct XFormAxisItem *item = BLI_array_append_ret(object_data);
1353                 item->ob = xfd->vc.obact;
1354
1355                 CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1356                 {
1357                         if ((ob != xfd->vc.obact) && object_is_target_compat(ob)) {
1358                                 item = BLI_array_append_ret(object_data);
1359                                 item->ob = ob;
1360                         }
1361                 }
1362                 CTX_DATA_END;
1363
1364                 xfd->object_data = object_data;
1365                 xfd->object_data_len = BLI_array_len(object_data);
1366
1367                 if (xfd->object_data_len != BLI_array_len(object_data)) {
1368                         xfd->object_data = MEM_reallocN(xfd->object_data, xfd->object_data_len * sizeof(*xfd->object_data));
1369                 }
1370         }
1371
1372         {
1373                 struct XFormAxisItem *item = xfd->object_data;
1374                 for (int i = 0; i < xfd->object_data_len; i++, item++) {
1375                         item->obtfm = BKE_object_tfm_backup(item->ob);
1376                         BKE_object_rot_to_mat3(item->ob, item->rot_mat, true);
1377                 }
1378         }
1379
1380         WM_event_add_modal_handler(C, op);
1381
1382         return OPERATOR_RUNNING_MODAL;
1383 }
1384
1385 static int object_transform_axis_target_modal(bContext *C, wmOperator *op, const wmEvent *event)
1386 {
1387         struct XFormAxisData *xfd = op->customdata;
1388         ARegion *ar = xfd->vc.ar;
1389
1390         view3d_operator_needs_opengl(C);
1391
1392         const bool is_translate = (event->ctrl != 0);
1393         const bool is_translate_init = is_translate && (xfd->is_translate != is_translate);
1394
1395         if (event->type == MOUSEMOVE || is_translate_init) {
1396                 const ViewDepths *depths = xfd->vc.rv3d->depths;
1397                 if (depths &&
1398                     ((unsigned int)event->mval[0] < depths->w) &&
1399                     ((unsigned int)event->mval[1] < depths->h))
1400                 {
1401                         double depth = (double)ED_view3d_depth_read_cached(&xfd->vc, event->mval);
1402                         float location_world[3];
1403                         if (depth == 1.0f) {
1404                                 if (xfd->prev.is_depth_valid) {
1405                                         depth = (double)xfd->prev.depth;
1406                                 }
1407                         }
1408                         if ((depth > depths->depth_range[0]) && (depth < depths->depth_range[1])) {
1409                                 xfd->prev.depth = depth;
1410                                 xfd->prev.is_depth_valid = true;
1411                                 if (ED_view3d_depth_unproject(ar, event->mval, depth, location_world)) {
1412                                         if (is_translate) {
1413
1414                                                 float normal[3];
1415                                                 bool normal_found = false;
1416                                                 if (ED_view3d_depth_read_cached_normal(&xfd->vc, event->mval, normal)) {
1417                                                         normal_found = true;
1418
1419                                                         /* cheap attempt to smooth normals out a bit! */
1420                                                         const uint ofs = 2;
1421                                                         for (uint x = -ofs; x <= ofs; x += ofs / 2) {
1422                                                                 for (uint y = -ofs; y <= ofs; y += ofs / 2) {
1423                                                                         if (x != 0 && y != 0) {
1424                                                                                 int mval_ofs[2] = {event->mval[0] + x, event->mval[1] + y};
1425                                                                                 float n[3];
1426                                                                                 if (ED_view3d_depth_read_cached_normal(
1427                                                                                         &xfd->vc, mval_ofs, n))
1428                                                                                 {
1429                                                                                         add_v3_v3(normal, n);
1430                                                                                 }
1431                                                                         }
1432                                                                 }
1433                                                         }
1434                                                         normalize_v3(normal);
1435                                                 }
1436                                                 else if (xfd->prev.is_normal_valid) {
1437                                                         copy_v3_v3(normal, xfd->prev.normal);
1438                                                         normal_found = true;
1439                                                 }
1440
1441                                                 if (normal_found) {
1442 #ifdef USE_RELATIVE_ROTATION
1443                                                         if (is_translate_init && xfd->object_data_len > 1) {
1444                                                                 float xform_rot_offset_inv_first[3][3];
1445                                                                 struct XFormAxisItem *item = xfd->object_data;
1446                                                                 for (int i = 0; i < xfd->object_data_len; i++, item++) {
1447                                                                         copy_m3_m4(item->xform_rot_offset, item->ob->obmat);
1448                                                                         normalize_m3(item->xform_rot_offset);
1449
1450                                                                         if (i == 0) {
1451                                                                                 invert_m3_m3(xform_rot_offset_inv_first, xfd->object_data[0].xform_rot_offset);
1452                                                                         }
1453                                                                         else {
1454                                                                                 mul_m3_m3m3(item->xform_rot_offset,
1455                                                                                             item->xform_rot_offset,
1456                                                                                             xform_rot_offset_inv_first);
1457                                                                         }
1458                                                                 }
1459                                                         }
1460
1461 #endif
1462
1463                                                         struct XFormAxisItem *item = xfd->object_data;
1464                                                         for (int i = 0; i < xfd->object_data_len; i++, item++) {
1465                                                                 if (is_translate_init) {
1466                                                                         float ob_axis[3];
1467                                                                         item->xform_dist = len_v3v3(item->ob->obmat[3], location_world);
1468                                                                         normalize_v3_v3(ob_axis, item->ob->obmat[2]);
1469                                                                         /* Scale to avoid adding distance when moving between surfaces. */
1470                                                                         float scale = fabsf(dot_v3v3(ob_axis, normal));
1471                                                                         item->xform_dist *= scale;
1472                                                                 }
1473
1474                                                                 float target_normal[3];
1475                                                                 copy_v3_v3(target_normal, normal);
1476
1477 #ifdef USE_RELATIVE_ROTATION
1478                                                                 if (i != 0) {
1479                                                                         mul_m3_v3(item->xform_rot_offset, target_normal);
1480                                                                 }
1481 #endif
1482                                                                 {
1483                                                                         float loc[3];
1484
1485                                                                         copy_v3_v3(loc, location_world);
1486                                                                         madd_v3_v3fl(loc, target_normal, item->xform_dist);
1487                                                                         object_apply_location(item->ob, loc);
1488                                                                         copy_v3_v3(item->ob->obmat[3], loc);  /* so orient behaves as expected */
1489                                                                 }
1490
1491                                                                 object_orient_to_location(item->ob, item->rot_mat, item->rot_mat[2], location_world);
1492                                                                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, item->ob);
1493                                                         }
1494                                                         copy_v3_v3(xfd->prev.normal, normal);
1495                                                         xfd->prev.is_normal_valid = true;
1496                                                 }
1497                                         }
1498                                         else {
1499                                                 struct XFormAxisItem *item = xfd->object_data;
1500                                                 for (int i = 0; i < xfd->object_data_len; i++, item++) {
1501                                                         object_orient_to_location(item->ob, item->rot_mat, item->rot_mat[2], location_world);
1502                                                         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, item->ob);
1503                                                 }
1504                                                 xfd->prev.is_normal_valid = false;
1505                                         }
1506                                 }
1507                         }
1508                 }
1509                 xfd->is_translate = is_translate;
1510
1511                 ED_region_tag_redraw(xfd->vc.ar);
1512         }
1513
1514         bool is_finished = false;
1515
1516         if (ISMOUSE(xfd->init_event)) {
1517                 if ((event->type == xfd->init_event) && (event->val == KM_RELEASE)) {
1518                         is_finished = true;
1519                 }
1520         }
1521         else {
1522                 if (ELEM(event->type, LEFTMOUSE, RETKEY, PADENTER)) {
1523                         is_finished = true;
1524                 }
1525         }
1526
1527         if (is_finished) {
1528                 object_transform_axis_target_free_data(op);
1529                 return OPERATOR_FINISHED;
1530         }
1531         else if (ELEM(event->type, ESCKEY, RIGHTMOUSE)) {
1532                 object_transform_axis_target_cancel(C, op);
1533                 return OPERATOR_CANCELLED;
1534         }
1535
1536
1537         return OPERATOR_RUNNING_MODAL;
1538 }
1539
1540 void OBJECT_OT_transform_axis_target(wmOperatorType *ot)
1541 {
1542         /* identifiers */
1543         ot->name = "Interactive Lamp Track to Cursor";
1544         ot->description = "Interactively point cameras and lamps to a location (Ctrl translates)";
1545         ot->idname = "OBJECT_OT_transform_axis_target";
1546
1547         /* api callbacks */
1548         ot->invoke = object_transform_axis_target_invoke;
1549         ot->cancel = object_transform_axis_target_cancel;
1550         ot->modal = object_transform_axis_target_modal;
1551         ot->poll = ED_operator_region_view3d_active;
1552
1553         /* flags */
1554         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
1555 }
1556
1557 #undef USE_RELATIVE_ROTATION
1558
1559 /** \} */