Merge remote-tracking branch 'origin/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_object_types.h"
39 #include "DNA_scene_types.h"
40 #include "DNA_group_types.h"
41 #include "DNA_lattice_types.h"
42 #include "DNA_lamp_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         CTX_DATA_END;
484         
485         if (!changed)
486                 return OPERATOR_CANCELLED;
487
488         changed = false;
489
490         /* now execute */
491         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
492         {
493
494                 /* calculate rotation/scale matrix */
495                 if (apply_scale && apply_rot)
496                         BKE_object_to_mat3(ob, rsmat);
497                 else if (apply_scale)
498                         BKE_object_scale_to_mat3(ob, rsmat);
499                 else if (apply_rot) {
500                         float tmat[3][3], timat[3][3];
501
502                         /* simple rotation matrix */
503                         BKE_object_rot_to_mat3(ob, rsmat, true);
504
505                         /* correct for scale, note mul_m3_m3m3 has swapped args! */
506                         BKE_object_scale_to_mat3(ob, tmat);
507                         invert_m3_m3(timat, tmat);
508                         mul_m3_m3m3(rsmat, timat, rsmat);
509                         mul_m3_m3m3(rsmat, rsmat, tmat);
510                 }
511                 else
512                         unit_m3(rsmat);
513
514                 copy_m4_m3(mat, rsmat);
515
516                 /* calculate translation */
517                 if (apply_loc) {
518                         copy_v3_v3(mat[3], ob->loc);
519
520                         if (!(apply_scale && apply_rot)) {
521                                 float tmat[3][3];
522                                 /* correct for scale and rotation that is still applied */
523                                 BKE_object_to_mat3(ob, obmat);
524                                 invert_m3_m3(iobmat, obmat);
525                                 mul_m3_m3m3(tmat, rsmat, iobmat);
526                                 mul_m3_v3(tmat, mat[3]);
527                         }
528                 }
529
530                 /* apply to object data */
531                 if (ob->type == OB_MESH) {
532                         Mesh *me = ob->data;
533
534                         if (apply_scale)
535                                 multiresModifier_scale_disp(depsgraph, scene, ob);
536                         
537                         /* adjust data */
538                         BKE_mesh_transform(me, mat, true);
539                         
540                         /* update normals */
541                         BKE_mesh_calc_normals(me);
542                 }
543                 else if (ob->type == OB_ARMATURE) {
544                         ED_armature_transform_apply(ob, mat, do_props);
545                 }
546                 else if (ob->type == OB_LATTICE) {
547                         Lattice *lt = ob->data;
548
549                         BKE_lattice_transform(lt, mat, true);
550                 }
551                 else if (ob->type == OB_MBALL) {
552                         MetaBall *mb = ob->data;
553                         BKE_mball_transform(mb, mat, do_props);
554                 }
555                 else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
556                         Curve *cu = ob->data;
557                         scale = mat3_to_scale(rsmat);
558                         BKE_curve_transform_ex(cu, mat, true, do_props, scale);
559                 }
560                 else if (ob->type == OB_FONT) {
561                         Curve *cu = ob->data;
562                         int i;
563
564                         scale = mat3_to_scale(rsmat);
565
566                         for (i = 0; i < cu->totbox; i++) {
567                                 TextBox *tb = &cu->tb[i];
568                                 tb->x *= scale;
569                                 tb->y *= scale;
570                                 tb->w *= scale;
571                                 tb->h *= scale;
572                         }
573
574                         if (do_props) {
575                                 cu->fsize *= scale;
576                         }
577                 }
578                 else if (ob->type == OB_CAMERA) {
579                         MovieClip *clip = BKE_object_movieclip_get(scene, ob, false);
580
581                         /* applying scale on camera actually scales clip's reconstruction.
582                          * of there's clip assigned to camera nothing to do actually.
583                          */
584                         if (!clip)
585                                 continue;
586
587                         if (apply_scale)
588                                 BKE_tracking_reconstruction_scale(&clip->tracking, ob->size);
589                 }
590                 else if (ob->type == OB_EMPTY) {
591                         /* It's possible for empties too, even though they don't 
592                          * really have obdata, since we can simply apply the maximum
593                          * scaling to the empty's drawsize.
594                          *
595                          * Core Assumptions:
596                          * 1) Most scaled empties have uniform scaling 
597                          *    (i.e. for visibility reasons), AND/OR
598                          * 2) Preserving non-uniform scaling is not that important,
599                          *    and is something that many users would be willing to
600                          *    sacrifice for having an easy way to do this.
601                          */
602
603                         if ((apply_loc == false) &&
604                             (apply_rot == false) &&
605                             (apply_scale == true))
606                         {
607                                 float max_scale = max_fff(fabsf(ob->size[0]), fabsf(ob->size[1]), fabsf(ob->size[2]));
608                                 ob->empty_drawsize *= max_scale;
609                         }
610                 }
611                 else {
612                         continue;
613                 }
614
615                 if (apply_loc)
616                         zero_v3(ob->loc);
617                 if (apply_scale)
618                         ob->size[0] = ob->size[1] = ob->size[2] = 1.0f;
619                 if (apply_rot) {
620                         zero_v3(ob->rot);
621                         unit_qt(ob->quat);
622                         unit_axis_angle(ob->rotAxis, &ob->rotAngle);
623                 }
624
625                 BKE_object_where_is_calc(depsgraph, scene, ob);
626                 if (ob->type == OB_ARMATURE) {
627                         BKE_pose_where_is(depsgraph, scene, ob); /* needed for bone parents */
628                 }
629
630                 ignore_parent_tx(C, bmain, scene, ob);
631
632                 DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA);
633
634                 changed = true;
635         }
636         CTX_DATA_END;
637
638         if (!changed) {
639                 BKE_report(reports, RPT_WARNING, "Objects have no data to transform");
640                 return OPERATOR_CANCELLED;
641         }
642
643         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
644         return OPERATOR_FINISHED;
645 }
646
647 static int visual_transform_apply_exec(bContext *C, wmOperator *UNUSED(op))
648 {
649         Scene *scene = CTX_data_scene(C);
650         Depsgraph *depsgraph = CTX_data_depsgraph(C);
651         bool changed = false;
652
653         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
654         {
655                 BKE_object_where_is_calc(depsgraph, scene, ob);
656                 BKE_object_apply_mat4(ob, ob->obmat, true, true);
657                 BKE_object_where_is_calc(depsgraph, scene, ob);
658
659                 /* update for any children that may get moved */
660                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
661         
662                 changed = true;
663         }
664         CTX_DATA_END;
665
666         if (!changed)
667                 return OPERATOR_CANCELLED;
668
669         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
670         return OPERATOR_FINISHED;
671 }
672
673 void OBJECT_OT_visual_transform_apply(wmOperatorType *ot)
674 {
675         /* identifiers */
676         ot->name = "Apply Visual Transform";
677         ot->description = "Apply the object's visual transformation to its data";
678         ot->idname = "OBJECT_OT_visual_transform_apply";
679         
680         /* api callbacks */
681         ot->exec = visual_transform_apply_exec;
682         ot->poll = ED_operator_scene_editable;
683         
684         /* flags */
685         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
686 }
687
688 static int object_transform_apply_exec(bContext *C, wmOperator *op)
689 {
690         const bool loc = RNA_boolean_get(op->ptr, "location");
691         const bool rot = RNA_boolean_get(op->ptr, "rotation");
692         const bool sca = RNA_boolean_get(op->ptr, "scale");
693         const bool do_props = RNA_boolean_get(op->ptr, "properties");
694
695         if (loc || rot || sca) {
696                 return apply_objects_internal(C, op->reports, loc, rot, sca, do_props);
697         }
698         else {
699                 /* allow for redo */
700                 return OPERATOR_FINISHED;
701         }
702 }
703
704 void OBJECT_OT_transform_apply(wmOperatorType *ot)
705 {
706         /* identifiers */
707         ot->name = "Apply Object Transform";
708         ot->description = "Apply the object's transformation to its data";
709         ot->idname = "OBJECT_OT_transform_apply";
710
711         /* api callbacks */
712         ot->exec = object_transform_apply_exec;
713         ot->poll = ED_operator_objectmode;
714
715         /* flags */
716         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
717
718         RNA_def_boolean(ot->srna, "location", 0, "Location", "");
719         RNA_def_boolean(ot->srna, "rotation", 0, "Rotation", "");
720         RNA_def_boolean(ot->srna, "scale", 0, "Scale", "");
721         RNA_def_boolean(ot->srna, "properties", true, "Apply Properties",
722                         "Modify properties such as curve vertex radius, font size and bone envelope");
723 }
724
725 /********************* Set Object Center ************************/
726
727 enum {
728         GEOMETRY_TO_ORIGIN = 0,
729         ORIGIN_TO_GEOMETRY,
730         ORIGIN_TO_CURSOR,
731         ORIGIN_TO_CENTER_OF_MASS_SURFACE,
732         ORIGIN_TO_CENTER_OF_MASS_VOLUME,
733 };
734
735 static int object_origin_set_exec(bContext *C, wmOperator *op)
736 {
737         Main *bmain = CTX_data_main(C);
738         Scene *scene = CTX_data_scene(C);
739         Object *obact = CTX_data_active_object(C);
740         Object *obedit = CTX_data_edit_object(C);
741         Depsgraph *depsgraph = CTX_data_depsgraph(C);
742         Object *tob;
743         float cursor[3], cent[3], cent_neg[3], centn[3];
744         int centermode = RNA_enum_get(op->ptr, "type");
745         int around = RNA_enum_get(op->ptr, "center"); /* initialized from v3d->around */
746
747         ListBase ctx_data_list;
748         CollectionPointerLink *ctx_ob;
749         CollectionPointerLink *ctx_ob_act = NULL;
750
751         /* keep track of what is changed */
752         int tot_change = 0, tot_lib_error = 0, tot_multiuser_arm_error = 0;
753
754         if (obedit && centermode != GEOMETRY_TO_ORIGIN) {
755                 BKE_report(op->reports, RPT_ERROR, "Operation cannot be performed in edit mode");
756                 return OPERATOR_CANCELLED;
757         }
758         else {
759                 /* get the view settings if 'around' isn't set and the view is available */
760                 View3D *v3d = CTX_wm_view3d(C);
761                 copy_v3_v3(cursor, ED_view3d_cursor3d_get(scene, v3d));
762                 if (v3d && !RNA_struct_property_is_set(op->ptr, "center"))
763                         around = v3d->around;
764         }
765
766         zero_v3(cent);
767
768         if (obedit) {
769                 if (obedit->type == OB_MESH) {
770                         Mesh *me = obedit->data;
771                         BMEditMesh *em = me->edit_btmesh;
772                         BMVert *eve;
773                         BMIter iter;
774                         
775                         if (centermode == ORIGIN_TO_CURSOR) {
776                                 copy_v3_v3(cent, cursor);
777                                 invert_m4_m4(obedit->imat, obedit->obmat);
778                                 mul_m4_v3(obedit->imat, cent);
779                         }
780                         else {
781                                 if (around == V3D_AROUND_CENTER_MEAN) {
782                                         if (em->bm->totvert) {
783                                                 const float total_div = 1.0f / (float)em->bm->totvert;
784                                                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
785                                                         madd_v3_v3fl(cent, eve->co, total_div);
786                                                 }
787                                         }
788                                 }
789                                 else {
790                                         float min[3], max[3];
791                                         INIT_MINMAX(min, max);
792                                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
793                                                 minmax_v3v3_v3(min, max, eve->co);
794                                         }
795                                         mid_v3_v3v3(cent, min, max);
796                                 }
797                         }
798                         
799                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
800                                 sub_v3_v3(eve->co, cent);
801                         }
802
803                         EDBM_mesh_normals_update(em);
804                         tot_change++;
805                         DEG_id_tag_update(&obedit->id, OB_RECALC_DATA);
806                 }
807         }
808
809         CTX_data_selected_editable_objects(C, &ctx_data_list);
810
811         /* reset flags */
812         for (ctx_ob = ctx_data_list.first;
813              ctx_ob;
814              ctx_ob = ctx_ob->next)
815         {
816                 Object *ob = ctx_ob->ptr.data;
817                 ob->flag &= ~OB_DONE;
818
819                 /* move active first */
820                 if (ob == obact) {
821                         ctx_ob_act = ctx_ob;
822                 }
823         }
824
825         if (ctx_ob_act) {
826                 BLI_listbase_rotate_first(&ctx_data_list, (LinkData *)ctx_ob_act);
827         }
828
829         for (tob = bmain->object.first; tob; tob = tob->id.next) {
830                 if (tob->data)
831                         ((ID *)tob->data)->tag &= ~LIB_TAG_DOIT;
832                 if (tob->dup_group)
833                         ((ID *)tob->dup_group)->tag &= ~LIB_TAG_DOIT;
834         }
835
836         for (ctx_ob = ctx_data_list.first;
837              ctx_ob;
838              ctx_ob = ctx_ob->next)
839         {
840                 Object *ob = ctx_ob->ptr.data;
841
842                 if ((ob->flag & OB_DONE) == 0) {
843                         bool do_inverse_offset = false;
844                         ob->flag |= OB_DONE;
845
846                         if (centermode == ORIGIN_TO_CURSOR) {
847                                 copy_v3_v3(cent, cursor);
848                                 invert_m4_m4(ob->imat, ob->obmat);
849                                 mul_m4_v3(ob->imat, cent);
850                         }
851                         
852                         if (ob->data == NULL) {
853                                 /* special support for dupligroups */
854                                 if ((ob->transflag & OB_DUPLIGROUP) && ob->dup_group && (ob->dup_group->id.tag & LIB_TAG_DOIT) == 0) {
855                                         if (ID_IS_LINKED(ob->dup_group)) {
856                                                 tot_lib_error++;
857                                         }
858                                         else {
859                                                 if (centermode == ORIGIN_TO_CURSOR) {
860                                                         /* done */
861                                                 }
862                                                 else {
863                                                         float min[3], max[3];
864                                                         /* only bounds support */
865                                                         INIT_MINMAX(min, max);
866                                                         BKE_object_minmax_dupli(depsgraph, scene, ob, min, max, true);
867                                                         mid_v3_v3v3(cent, min, max);
868                                                         invert_m4_m4(ob->imat, ob->obmat);
869                                                         mul_m4_v3(ob->imat, cent);
870                                                 }
871                                                 
872                                                 add_v3_v3(ob->dup_group->dupli_ofs, cent);
873
874                                                 tot_change++;
875                                                 ob->dup_group->id.tag |= LIB_TAG_DOIT;
876                                                 do_inverse_offset = true;
877                                         }
878                                 }
879                         }
880                         else if (ID_IS_LINKED(ob->data)) {
881                                 tot_lib_error++;
882                         }
883
884                         if (obedit == NULL && ob->type == OB_MESH) {
885                                 Mesh *me = ob->data;
886
887                                 if (centermode == ORIGIN_TO_CURSOR) {
888                                         /* done */
889                                 }
890                                 else if (centermode == ORIGIN_TO_CENTER_OF_MASS_SURFACE) {
891                                         BKE_mesh_center_of_surface(me, cent);
892                                 }
893                                 else if (centermode == ORIGIN_TO_CENTER_OF_MASS_VOLUME) {
894                                         BKE_mesh_center_of_volume(me, cent);
895                                 }
896                                 else if (around == V3D_AROUND_CENTER_MEAN) {
897                                         BKE_mesh_center_median(me, cent);
898                                 }
899                                 else {
900                                         BKE_mesh_center_bounds(me, cent);
901                                 }
902
903                                 negate_v3_v3(cent_neg, cent);
904                                 BKE_mesh_translate(me, cent_neg, 1);
905
906                                 tot_change++;
907                                 me->id.tag |= LIB_TAG_DOIT;
908                                 do_inverse_offset = true;
909                         }
910                         else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
911                                 Curve *cu = ob->data;
912
913                                 if      (centermode == ORIGIN_TO_CURSOR)    { /* done */ }
914                                 else if (around == V3D_AROUND_CENTER_MEAN)  { BKE_curve_center_median(cu, cent); }
915                                 else                                        { BKE_curve_center_bounds(cu, cent); }
916
917                                 /* don't allow Z change if curve is 2D */
918                                 if ((ob->type == OB_CURVE) && !(cu->flag & CU_3D))
919                                         cent[2] = 0.0;
920
921                                 negate_v3_v3(cent_neg, cent);
922                                 BKE_curve_translate(cu, cent_neg, 1);
923
924                                 tot_change++;
925                                 cu->id.tag |= LIB_TAG_DOIT;
926                                 do_inverse_offset = true;
927
928                                 if (obedit) {
929                                         if (centermode == GEOMETRY_TO_ORIGIN) {
930                                                 DEG_id_tag_update(&obedit->id, OB_RECALC_DATA);
931                                         }
932                                         break;
933                                 }
934                         }
935                         else if (ob->type == OB_FONT) {
936                                 /* get from bb */
937
938                                 Curve *cu = ob->data;
939
940                                 if (ob->bb == NULL && (centermode != ORIGIN_TO_CURSOR)) {
941                                         /* do nothing*/
942                                 }
943                                 else {
944                                         if (centermode == ORIGIN_TO_CURSOR) {
945                                                 /* done */
946                                         }
947                                         else {
948                                                 /* extra 0.5 is the height o above line */
949                                                 cent[0] = 0.5f * (ob->bb->vec[4][0] + ob->bb->vec[0][0]);
950                                                 cent[1] = 0.5f * (ob->bb->vec[0][1] + ob->bb->vec[2][1]);
951                                         }
952
953                                         cent[2] = 0.0f;
954
955                                         cu->xof = cu->xof - cent[0];
956                                         cu->yof = cu->yof - cent[1];
957
958                                         tot_change++;
959                                         cu->id.tag |= LIB_TAG_DOIT;
960                                         do_inverse_offset = true;
961                                 }
962                         }
963                         else if (ob->type == OB_ARMATURE) {
964                                 bArmature *arm = ob->data;
965
966                                 if (ID_REAL_USERS(arm) > 1) {
967 #if 0
968                                         BKE_report(op->reports, RPT_ERROR, "Cannot apply to a multi user armature");
969                                         return;
970 #endif
971                                         tot_multiuser_arm_error++;
972                                 }
973                                 else {
974                                         /* Function to recenter armatures in editarmature.c
975                                          * Bone + object locations are handled there.
976                                          */
977                                         ED_armature_origin_set(ob, cursor, centermode, around);
978
979                                         tot_change++;
980                                         arm->id.tag |= LIB_TAG_DOIT;
981                                         /* do_inverse_offset = true; */ /* docenter_armature() handles this */
982
983                                         BKE_object_where_is_calc(depsgraph, scene, ob);
984                                         BKE_pose_where_is(depsgraph, scene, ob); /* needed for bone parents */
985
986                                         ignore_parent_tx(C, bmain, scene, ob);
987
988                                         if (obedit)
989                                                 break;
990                                 }
991                         }
992                         else if (ob->type == OB_MBALL) {
993                                 MetaBall *mb = ob->data;
994
995                                 if      (centermode == ORIGIN_TO_CURSOR)    { /* done */ }
996                                 else if (around == V3D_AROUND_CENTER_MEAN)  { BKE_mball_center_median(mb, cent); }
997                                 else                                        { BKE_mball_center_bounds(mb, cent); }
998
999                                 negate_v3_v3(cent_neg, cent);
1000                                 BKE_mball_translate(mb, cent_neg);
1001
1002                                 tot_change++;
1003                                 mb->id.tag |= LIB_TAG_DOIT;
1004                                 do_inverse_offset = true;
1005
1006                                 if (obedit) {
1007                                         if (centermode == GEOMETRY_TO_ORIGIN) {
1008                                                 DEG_id_tag_update(&obedit->id, OB_RECALC_DATA);
1009                                         }
1010                                         break;
1011                                 }
1012                         }
1013                         else if (ob->type == OB_LATTICE) {
1014                                 Lattice *lt = ob->data;
1015
1016                                 if      (centermode == ORIGIN_TO_CURSOR)    { /* done */ }
1017                                 else if (around == V3D_AROUND_CENTER_MEAN)  { BKE_lattice_center_median(lt, cent); }
1018                                 else                                        { BKE_lattice_center_bounds(lt, cent); }
1019
1020                                 negate_v3_v3(cent_neg, cent);
1021                                 BKE_lattice_translate(lt, cent_neg, 1);
1022
1023                                 tot_change++;
1024                                 lt->id.tag |= LIB_TAG_DOIT;
1025                                 do_inverse_offset = true;
1026                         }
1027
1028                         /* offset other selected objects */
1029                         if (do_inverse_offset && (centermode != GEOMETRY_TO_ORIGIN)) {
1030                                 CollectionPointerLink *ctx_link_other;
1031                                 float obmat[4][4];
1032
1033                                 /* was the object data modified
1034                                  * note: the functions above must set 'cent' */
1035
1036                                 /* convert the offset to parent space */
1037                                 BKE_object_to_mat4(ob, obmat);
1038                                 mul_v3_mat3_m4v3(centn, obmat, cent); /* omit translation part */
1039
1040                                 add_v3_v3(ob->loc, centn);
1041
1042                                 BKE_object_where_is_calc(depsgraph, scene, ob);
1043                                 if (ob->type == OB_ARMATURE) {
1044                                         BKE_pose_where_is(depsgraph, scene, ob); /* needed for bone parents */
1045                                 }
1046
1047                                 ignore_parent_tx(C, bmain, scene, ob);
1048                                 
1049                                 /* other users? */
1050                                 //CTX_DATA_BEGIN (C, Object *, ob_other, selected_editable_objects)
1051                                 //{
1052
1053                                 /* use existing context looper */
1054                                 for (ctx_link_other = ctx_data_list.first;
1055                                      ctx_link_other;
1056                                      ctx_link_other = ctx_link_other->next)
1057                                 {
1058                                         Object *ob_other = ctx_link_other->ptr.data;
1059
1060                                         if ((ob_other->flag & OB_DONE) == 0 &&
1061                                             ((ob->data && (ob->data == ob_other->data)) ||
1062                                              (ob->dup_group == ob_other->dup_group &&
1063                                               (ob->transflag | ob_other->transflag) & OB_DUPLIGROUP)))
1064                                         {
1065                                                 ob_other->flag |= OB_DONE;
1066                                                 DEG_id_tag_update(&ob_other->id, OB_RECALC_OB | OB_RECALC_DATA);
1067
1068                                                 mul_v3_mat3_m4v3(centn, ob_other->obmat, cent); /* omit translation part */
1069                                                 add_v3_v3(ob_other->loc, centn);
1070
1071                                                 BKE_object_where_is_calc(depsgraph, scene, ob_other);
1072                                                 if (ob_other->type == OB_ARMATURE) {
1073                                                         BKE_pose_where_is(depsgraph, scene, ob_other); /* needed for bone parents */
1074                                                 }
1075                                                 ignore_parent_tx(C, bmain, scene, ob_other);
1076                                         }
1077                                 }
1078                                 //CTX_DATA_END;
1079                         }
1080                 }
1081         }
1082         BLI_freelistN(&ctx_data_list);
1083
1084         for (tob = bmain->object.first; tob; tob = tob->id.next) {
1085                 if (tob->data && (((ID *)tob->data)->tag & LIB_TAG_DOIT)) {
1086                         BKE_mesh_batch_cache_dirty(tob->data, BKE_MESH_BATCH_DIRTY_ALL);
1087                         DEG_id_tag_update(&tob->id, OB_RECALC_OB | OB_RECALC_DATA);
1088                 }
1089         }
1090
1091         if (tot_change) {
1092                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1093         }
1094
1095         /* Warn if any errors occurred */
1096         if (tot_lib_error + tot_multiuser_arm_error) {
1097                 BKE_reportf(op->reports, RPT_WARNING, "%i object(s) not centered, %i changed:", tot_lib_error + tot_multiuser_arm_error, tot_change);
1098                 if (tot_lib_error)
1099                         BKE_reportf(op->reports, RPT_WARNING, "|%i linked library object(s)", tot_lib_error);
1100                 if (tot_multiuser_arm_error)
1101                         BKE_reportf(op->reports, RPT_WARNING, "|%i multiuser armature object(s)", tot_multiuser_arm_error);
1102         }
1103
1104         return OPERATOR_FINISHED;
1105 }
1106
1107 void OBJECT_OT_origin_set(wmOperatorType *ot)
1108 {
1109         static const EnumPropertyItem prop_set_center_types[] = {
1110                 {GEOMETRY_TO_ORIGIN, "GEOMETRY_ORIGIN", 0, "Geometry to Origin", "Move object geometry to object origin"},
1111                 {ORIGIN_TO_GEOMETRY, "ORIGIN_GEOMETRY", 0, "Origin to Geometry",
1112                  "Calculate the center of geometry based on the current pivot point (median, otherwise bounding-box)"},
1113                 {ORIGIN_TO_CURSOR, "ORIGIN_CURSOR", 0, "Origin to 3D Cursor",
1114                  "Move object origin to position of the 3D cursor"},
1115                 /* Intentional naming mismatch since some scripts refer to this. */
1116                 {ORIGIN_TO_CENTER_OF_MASS_SURFACE, "ORIGIN_CENTER_OF_MASS", 0, "Origin to Center of Mass (Surface)",
1117                  "Calculate the center of mass from the surface area"},
1118                 {ORIGIN_TO_CENTER_OF_MASS_VOLUME, "ORIGIN_CENTER_OF_VOLUME", 0, "Origin to Center of Mass (Volume)",
1119                  "Calculate the center of mass from the volume (must be manifold geometry with consistent normals)"},
1120                 {0, NULL, 0, NULL, NULL}
1121         };
1122         
1123         static const EnumPropertyItem prop_set_bounds_types[] = {
1124                 {V3D_AROUND_CENTER_MEAN, "MEDIAN", 0, "Median Center", ""},
1125                 {V3D_AROUND_CENTER_BOUNDS, "BOUNDS", 0, "Bounds Center", ""},
1126                 {0, NULL, 0, NULL, NULL}
1127         };
1128         
1129         /* identifiers */
1130         ot->name = "Set Origin";
1131         ot->description = "Set the object's origin, by either moving the data, or set to center of data, or use 3D cursor";
1132         ot->idname = "OBJECT_OT_origin_set";
1133         
1134         /* api callbacks */
1135         ot->invoke = WM_menu_invoke;
1136         ot->exec = object_origin_set_exec;
1137         
1138         ot->poll = ED_operator_scene_editable;
1139         
1140         /* flags */
1141         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1142         
1143         ot->prop = RNA_def_enum(ot->srna, "type", prop_set_center_types, 0, "Type", "");
1144         RNA_def_enum(ot->srna, "center", prop_set_bounds_types, V3D_AROUND_CENTER_MEAN, "Center", "");
1145 }
1146
1147 /* -------------------------------------------------------------------- */
1148
1149 /** \name Transform Axis Target
1150  *
1151  * Note this is an experemental operator to point lamps/cameras at objects.
1152  * We may re-work how this behaves based on user feedback.
1153  * - campbell.
1154  * \{ */
1155
1156 /* When using multiple objects, apply their relative rotational offset to the active object. */
1157 #define USE_RELATIVE_ROTATION
1158
1159 struct XFormAxisItem {
1160         Object *ob;
1161         float rot_mat[3][3];
1162         void *obtfm;
1163         float xform_dist;
1164
1165 #ifdef USE_RELATIVE_ROTATION
1166         /* use when translating multiple */
1167         float xform_rot_offset[3][3];
1168 #endif
1169 };
1170
1171 struct XFormAxisData {
1172         ViewContext vc;
1173         struct {
1174                 float depth;
1175                 float normal[3];
1176                 bool is_depth_valid;
1177                 bool is_normal_valid;
1178         } prev;
1179
1180         struct XFormAxisItem *object_data;
1181         uint object_data_len;
1182         bool is_translate;
1183
1184         int init_event;
1185 };
1186
1187 static bool object_is_target_compat(const Object *ob)
1188 {
1189         if (ob->type == OB_LAMP) {
1190                 const Lamp *la = ob->data;
1191                 if (ELEM(la->type, LA_SUN, LA_SPOT, LA_HEMI, LA_AREA)) {
1192                         return true;
1193                 }
1194         }
1195         /* We might want to enable this later, for now just lamps */
1196 #if 0
1197         else if (ob->type == OB_CAMERA) {
1198                 return true;
1199         }
1200 #endif
1201         return false;
1202 }
1203
1204 static void object_transform_axis_target_free_data(wmOperator *op)
1205 {
1206         struct XFormAxisData *xfd = op->customdata;
1207         struct XFormAxisItem *item = xfd->object_data;
1208         for (int i = 0; i < xfd->object_data_len; i++, item++) {
1209                 MEM_freeN(item->obtfm);
1210         }
1211         MEM_freeN(xfd->object_data);
1212         MEM_freeN(xfd);
1213         op->customdata = NULL;
1214 }
1215
1216 /* We may want to expose as alternative to: BKE_object_apply_rotation */
1217 static void object_apply_rotation(Object *ob, const float rmat[3][3])
1218 {
1219         float size[3];
1220         float loc[3];
1221         float rmat4[4][4];
1222         copy_m4_m3(rmat4, rmat);
1223
1224         copy_v3_v3(size, ob->size);
1225         copy_v3_v3(loc, ob->loc);
1226         BKE_object_apply_mat4(ob, rmat4, true, true);
1227         copy_v3_v3(ob->size, size);
1228         copy_v3_v3(ob->loc, loc);
1229 }
1230 /* We may want to extract this to: BKE_object_apply_location */
1231 static void object_apply_location(Object *ob, const float loc[3])
1232 {
1233         /* quick but weak */
1234         Object ob_prev = *ob;
1235         float mat[4][4];
1236         copy_m4_m4(mat, ob->obmat);
1237         copy_v3_v3(mat[3], loc);
1238         BKE_object_apply_mat4(ob, mat, true, true);
1239         copy_v3_v3(mat[3], ob->loc);
1240         *ob = ob_prev;
1241         copy_v3_v3(ob->loc, mat[3]);
1242 }
1243
1244 static void object_orient_to_location(
1245         Object *ob, float rot_orig[3][3], const float axis[3], const float location[3])
1246 {
1247         float delta[3];
1248         sub_v3_v3v3(delta, ob->obmat[3], location);
1249         if (normalize_v3(delta) != 0.0f) {
1250                 if (len_squared_v3v3(delta, axis) > FLT_EPSILON) {
1251                         float delta_rot[3][3];
1252                         float final_rot[3][3];
1253                         rotation_between_vecs_to_mat3(delta_rot, axis, delta);
1254
1255                         mul_m3_m3m3(final_rot, delta_rot, rot_orig);
1256
1257                         object_apply_rotation(ob, final_rot);
1258
1259                         DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1260                 }
1261         }
1262 }
1263
1264 static void object_transform_axis_target_cancel(bContext *C, wmOperator *op)
1265 {
1266         struct XFormAxisData *xfd = op->customdata;
1267         struct XFormAxisItem *item = xfd->object_data;
1268         for (int i = 0; i < xfd->object_data_len; i++, item++) {
1269                 BKE_object_tfm_restore(item->ob, item->obtfm);
1270                 DEG_id_tag_update(&item->ob->id, OB_RECALC_OB);
1271                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, item->ob);
1272         }
1273
1274         object_transform_axis_target_free_data(op);
1275 }
1276
1277 static int object_transform_axis_target_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1278 {
1279         ViewContext vc;
1280         ED_view3d_viewcontext_init(C, &vc);
1281
1282         if (!object_is_target_compat(vc.obact)) {
1283                 /* Falls back to texture space transform. */
1284                 return OPERATOR_PASS_THROUGH;
1285         }
1286
1287         ED_view3d_autodist_init(vc.depsgraph, vc.ar, vc.v3d, 0);
1288
1289         if (vc.rv3d->depths != NULL) {
1290                 vc.rv3d->depths->damaged = true;
1291         }
1292         ED_view3d_depth_update(vc.ar);
1293
1294         if (vc.rv3d->depths == NULL) {
1295                 BKE_report(op->reports, RPT_WARNING, "Unable to access depth buffer, using view plane");
1296                 return OPERATOR_CANCELLED;
1297         }
1298
1299         ED_region_tag_redraw(vc.ar);
1300
1301         struct XFormAxisData *xfd;
1302         xfd = op->customdata = MEM_callocN(sizeof(struct XFormAxisData), __func__);
1303
1304         /* Don't change this at runtime. */
1305         xfd->vc = vc;
1306         xfd->vc.mval[0] = event->mval[0];
1307         xfd->vc.mval[1] = event->mval[1];
1308
1309         xfd->prev.depth = 1.0f;
1310         xfd->prev.is_depth_valid = false;
1311         xfd->prev.is_normal_valid = false;
1312         xfd->is_translate = false;
1313
1314         xfd->init_event = WM_userdef_event_type_from_keymap_type(event->type);
1315
1316         {
1317                 struct XFormAxisItem *object_data = NULL;
1318                 BLI_array_declare(object_data);
1319
1320                 struct XFormAxisItem *item = BLI_array_append_ret(object_data);
1321                 item->ob = xfd->vc.obact;
1322
1323                 CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1324                 {
1325                         if ((ob != xfd->vc.obact) && object_is_target_compat(ob)) {
1326                                 item = BLI_array_append_ret(object_data);
1327                                 item->ob = ob;
1328                         }
1329                 }
1330                 CTX_DATA_END;
1331
1332                 xfd->object_data = object_data;
1333                 xfd->object_data_len = BLI_array_len(object_data);
1334
1335                 if (xfd->object_data_len != BLI_array_len(object_data)) {
1336                         xfd->object_data = MEM_reallocN(xfd->object_data, xfd->object_data_len * sizeof(*xfd->object_data));
1337                 }
1338         }
1339
1340         {
1341                 struct XFormAxisItem *item = xfd->object_data;
1342                 for (int i = 0; i < xfd->object_data_len; i++, item++) {
1343                         item->obtfm = BKE_object_tfm_backup(item->ob);
1344                         BKE_object_rot_to_mat3(item->ob, item->rot_mat, true);
1345                 }
1346         }
1347
1348         WM_event_add_modal_handler(C, op);
1349
1350         return OPERATOR_RUNNING_MODAL;
1351 }
1352
1353 static int object_transform_axis_target_modal(bContext *C, wmOperator *op, const wmEvent *event)
1354 {
1355         struct XFormAxisData *xfd = op->customdata;
1356         ARegion *ar = xfd->vc.ar;
1357
1358         view3d_operator_needs_opengl(C);
1359
1360         const bool is_translate = (event->ctrl != 0);
1361         const bool is_translate_init = is_translate && (xfd->is_translate != is_translate);
1362
1363         if (event->type == MOUSEMOVE || is_translate_init) {
1364                 const ViewDepths *depths = xfd->vc.rv3d->depths;
1365                 if (depths &&
1366                     ((unsigned int)event->mval[0] < depths->w) &&
1367                     ((unsigned int)event->mval[1] < depths->h))
1368                 {
1369                         double depth = (double)ED_view3d_depth_read_cached(&xfd->vc, event->mval);
1370                         float location_world[3];
1371                         if (depth == 1.0f) {
1372                                 if (xfd->prev.is_depth_valid) {
1373                                         depth = (double)xfd->prev.depth;
1374                                 }
1375                         }
1376                         if ((depth > depths->depth_range[0]) && (depth < depths->depth_range[1])) {
1377                                 xfd->prev.depth = depth;
1378                                 xfd->prev.is_depth_valid = true;
1379                                 if (ED_view3d_depth_unproject(ar, event->mval, depth, location_world)) {
1380                                         if (is_translate) {
1381
1382                                                 float normal[3];
1383                                                 bool normal_found = false;
1384                                                 if (ED_view3d_depth_read_cached_normal(&xfd->vc, event->mval, normal)) {
1385                                                         normal_found = true;
1386
1387                                                         /* cheap attempt to smooth normals out a bit! */
1388                                                         const uint ofs = 2;
1389                                                         for (uint x = -ofs; x <= ofs; x += ofs / 2) {
1390                                                                 for (uint y = -ofs; y <= ofs; y += ofs / 2) {
1391                                                                         if (x != 0 && y != 0) {
1392                                                                                 int mval_ofs[2] = {event->mval[0] + x, event->mval[1] + y};
1393                                                                                 float n[3];
1394                                                                                 if (ED_view3d_depth_read_cached_normal(
1395                                                                                         &xfd->vc, mval_ofs, n))
1396                                                                                 {
1397                                                                                         add_v3_v3(normal, n);
1398                                                                                 }
1399                                                                         }
1400                                                                 }
1401                                                         }
1402                                                         normalize_v3(normal);
1403                                                 }
1404                                                 else if (xfd->prev.is_normal_valid) {
1405                                                         copy_v3_v3(normal, xfd->prev.normal);
1406                                                         normal_found = true;
1407                                                 }
1408
1409                                                 if (normal_found) {
1410 #ifdef USE_RELATIVE_ROTATION
1411                                                         if (is_translate_init && xfd->object_data_len > 1) {
1412                                                                 float xform_rot_offset_inv_first[3][3];
1413                                                                 struct XFormAxisItem *item = xfd->object_data;
1414                                                                 for (int i = 0; i < xfd->object_data_len; i++, item++) {
1415                                                                         copy_m3_m4(item->xform_rot_offset, item->ob->obmat);
1416                                                                         normalize_m3(item->xform_rot_offset);
1417
1418                                                                         if (i == 0) {
1419                                                                                 invert_m3_m3(xform_rot_offset_inv_first, xfd->object_data[0].xform_rot_offset);
1420                                                                         }
1421                                                                         else {
1422                                                                                 mul_m3_m3m3(item->xform_rot_offset,
1423                                                                                             item->xform_rot_offset,
1424                                                                                             xform_rot_offset_inv_first);
1425                                                                         }
1426                                                                 }
1427                                                         }
1428
1429 #endif
1430
1431                                                         struct XFormAxisItem *item = xfd->object_data;
1432                                                         for (int i = 0; i < xfd->object_data_len; i++, item++) {
1433                                                                 if (is_translate_init) {
1434                                                                         float ob_axis[3];
1435                                                                         item->xform_dist = len_v3v3(item->ob->obmat[3], location_world);
1436                                                                         normalize_v3_v3(ob_axis, item->ob->obmat[2]);
1437                                                                         /* Scale to avoid adding distance when moving between surfaces. */
1438                                                                         float scale = fabsf(dot_v3v3(ob_axis, normal));
1439                                                                         item->xform_dist *= scale;
1440                                                                 }
1441
1442                                                                 float target_normal[3];
1443                                                                 copy_v3_v3(target_normal, normal);
1444
1445 #ifdef USE_RELATIVE_ROTATION
1446                                                                 if (i != 0) {
1447                                                                         mul_m3_v3(item->xform_rot_offset, target_normal);
1448                                                                 }
1449 #endif
1450                                                                 {
1451                                                                         float loc[3];
1452
1453                                                                         copy_v3_v3(loc, location_world);
1454                                                                         madd_v3_v3fl(loc, target_normal, item->xform_dist);
1455                                                                         object_apply_location(item->ob, loc);
1456                                                                         copy_v3_v3(item->ob->obmat[3], loc);  /* so orient behaves as expected */
1457                                                                 }
1458
1459                                                                 object_orient_to_location(item->ob, item->rot_mat, item->rot_mat[2], location_world);
1460                                                                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, item->ob);
1461                                                         }
1462                                                         copy_v3_v3(xfd->prev.normal, normal);
1463                                                         xfd->prev.is_normal_valid = true;
1464                                                 }
1465                                         }
1466                                         else {
1467                                                 struct XFormAxisItem *item = xfd->object_data;
1468                                                 for (int i = 0; i < xfd->object_data_len; i++, item++) {
1469                                                         object_orient_to_location(item->ob, item->rot_mat, item->rot_mat[2], location_world);
1470                                                         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, item->ob);
1471                                                 }
1472                                                 xfd->prev.is_normal_valid = false;
1473                                         }
1474                                 }
1475                         }
1476                 }
1477                 xfd->is_translate = is_translate;
1478
1479                 ED_region_tag_redraw(xfd->vc.ar);
1480         }
1481
1482         bool is_finished = false;
1483
1484         if (ISMOUSE(xfd->init_event)) {
1485                 if ((event->type == xfd->init_event) && (event->val == KM_RELEASE)) {
1486                         is_finished = true;
1487                 }
1488         }
1489         else {
1490                 if (ELEM(event->type, LEFTMOUSE, RETKEY, PADENTER)) {
1491                         is_finished = true;
1492                 }
1493         }
1494
1495         if (is_finished) {
1496                 object_transform_axis_target_free_data(op);
1497                 return OPERATOR_FINISHED;
1498         }
1499         else if (ELEM(event->type, ESCKEY, RIGHTMOUSE)) {
1500                 object_transform_axis_target_cancel(C, op);
1501                 return OPERATOR_CANCELLED;
1502         }
1503
1504
1505         return OPERATOR_RUNNING_MODAL;
1506 }
1507
1508 void OBJECT_OT_transform_axis_target(wmOperatorType *ot)
1509 {
1510         /* identifiers */
1511         ot->name = "Interactive Lamp Track to Cursor";
1512         ot->description = "Interactively point cameras and lamps to a location (Ctrl translates)";
1513         ot->idname = "OBJECT_OT_transform_axis_target";
1514
1515         /* api callbacks */
1516         ot->invoke = object_transform_axis_target_invoke;
1517         ot->cancel = object_transform_axis_target_cancel;
1518         ot->modal = object_transform_axis_target_modal;
1519         ot->poll = ED_operator_region_view3d_active;
1520
1521         /* flags */
1522         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
1523 }
1524
1525 #undef USE_RELATIVE_ROTATION
1526
1527 /** \} */