Merging r42648 through r42722 from trunk into soc-2011-tomato
[blender.git] / source / blender / editors / object / object_constraint.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  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Joshua Leung, Blender Foundation
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/object/object_constraint.c
29  *  \ingroup edobj
30  */
31
32
33 #include <stdio.h>
34 #include <string.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_blenlib.h"
39 #include "BLI_math.h"
40 #include "BLI_dynstr.h"
41 #include "BLI_utildefines.h"
42
43 #include "DNA_constraint_types.h"
44 #include "DNA_curve_types.h"
45 #include "DNA_scene_types.h"
46 #include "DNA_text_types.h"
47 #include "DNA_object_types.h"
48
49 #include "BKE_action.h"
50 #include "BKE_armature.h"
51 #include "BKE_constraint.h"
52 #include "BKE_context.h"
53 #include "BKE_depsgraph.h"
54 #include "BKE_global.h"
55 #include "BKE_main.h"
56 #include "BKE_object.h"
57 #include "BKE_report.h"
58 #include "BKE_tracking.h"
59 #include "BIK_api.h"
60
61 #ifdef WITH_PYTHON
62 #include "BPY_extern.h"
63 #endif
64
65 #include "WM_api.h"
66 #include "WM_types.h"
67
68 #include "RNA_access.h"
69 #include "RNA_define.h"
70 #include "RNA_enum_types.h"
71
72 #include "ED_object.h"
73 #include "ED_armature.h"
74 #include "ED_screen.h"
75
76 #include "UI_interface.h"
77 #include "UI_resources.h"
78
79 #include "object_intern.h"
80
81 /* -------------- Get Active Constraint Data ---------------------- */
82
83 /* if object in posemode, active bone constraints, else object constraints */
84 ListBase *get_active_constraints (Object *ob)
85 {
86         if (ob == NULL)
87                 return NULL;
88         
89         if (ob->mode & OB_MODE_POSE) {
90                 bPoseChannel *pchan;
91                 
92                 pchan = get_active_posechannel(ob);
93                 if (pchan)
94                         return &pchan->constraints;
95         }
96         else 
97                 return &ob->constraints;
98         
99         return NULL;
100 }
101
102 /* Find the list that a given constraint belongs to, and/or also get the posechannel this is from (if applicable) */
103 ListBase *get_constraint_lb (Object *ob, bConstraint *con, bPoseChannel **pchan_r)
104 {
105         if (pchan_r)
106                 *pchan_r= NULL;
107         
108         if (ELEM(NULL, ob, con))
109                 return NULL;
110         
111         /* try object constraints first */
112         if ((BLI_findindex(&ob->constraints, con) != -1)) {
113                 return &ob->constraints;
114         }
115         
116         /* if armature, try pose bones too */
117         if (ob->pose) {
118                 bPoseChannel *pchan;
119                 
120                 /* try each bone in order 
121                  * NOTE: it's not possible to directly look up the active bone yet, so this will have to do
122                  */
123                 for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
124                         if ((BLI_findindex(&pchan->constraints, con) != -1)) {
125                                 
126                                 if (pchan_r)
127                                         *pchan_r= pchan;
128                                 
129                                 return &pchan->constraints;
130                         }
131                 }
132         }
133         
134         /* done */
135         return NULL;
136 }
137
138 /* single constraint */
139 bConstraint *get_active_constraint (Object *ob)
140 {
141         return constraints_get_active(get_active_constraints(ob));
142 }
143
144 /* -------------- Constraint Management (Add New, Remove, Rename) -------------------- */
145 /* ------------- PyConstraints ------------------ */
146
147 /* this callback sets the text-file to be used for selected menu item */
148 static void validate_pyconstraint_cb (void *arg1, void *arg2)
149 {
150         bPythonConstraint *data = arg1;
151         Text *text= NULL;
152         int index = *((int *)arg2);
153         int i;
154         
155         /* exception for no script */
156         if (index) {
157                 /* innovative use of a for...loop to search */
158                 for (text=G.main->text.first, i=1; text && index!=i; i++, text=text->id.next);
159         }
160         data->text = text;
161 }
162
163 #ifdef WITH_PYTHON
164 /* this returns a string for the list of usable pyconstraint script names */
165 static char *buildmenu_pyconstraints (Text *con_text, int *pyconindex)
166 {
167         DynStr *pupds= BLI_dynstr_new();
168         Text *text;
169         char *str;
170         char buf[64];
171         int i;
172         
173         /* add title first */
174         sprintf(buf, "Scripts: %%t|[None]%%x0|");
175         BLI_dynstr_append(pupds, buf);
176         
177         /* init active-index first */
178         if (con_text == NULL)
179                 *pyconindex= 0;
180         
181         /* loop through markers, adding them */
182         for (text=G.main->text.first, i=1; text; i++, text=text->id.next) {
183                 /* this is important to ensure that right script is shown as active */
184                 if (text == con_text) *pyconindex = i;
185                 
186                 /* only include valid pyconstraint scripts */
187                 if (BPY_is_pyconstraint(text)) {
188                         BLI_dynstr_append(pupds, text->id.name+2);
189                         
190                         sprintf(buf, "%%x%d", i);
191                         BLI_dynstr_append(pupds, buf);
192                         
193                         if (text->id.next)
194                                 BLI_dynstr_append(pupds, "|");
195                 }
196         }
197         
198         /* convert to normal MEM_malloc'd string */
199         str= BLI_dynstr_get_cstring(pupds);
200         BLI_dynstr_free(pupds);
201         
202         return str;
203 }
204 #endif /* WITH_PYTHON */
205
206 #if 0 // UNUSED, until pyconstraints are added back.
207 /* this callback gets called when the 'refresh' button of a pyconstraint gets pressed */
208 static void update_pyconstraint_cb (void *arg1, void *arg2)
209 {
210 #ifndef WITH_PYTHON
211         (void)arg1; /* unused */
212         (void)arg2; /* unused */
213 #else
214         Object *owner= (Object *)arg1;
215         bConstraint *con= (bConstraint *)arg2;
216         if (owner && con)
217                 BPY_pyconstraint_update(owner, con);
218 #endif
219 }
220 #endif // UNUSED
221
222 /* helper function for add_constriant - sets the last target for the active constraint */
223 static void set_constraint_nth_target (bConstraint *con, Object *target, const char subtarget[], int index)
224 {
225         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
226         ListBase targets = {NULL, NULL};
227         bConstraintTarget *ct;
228         int num_targets, i;
229         
230         if (cti && cti->get_constraint_targets) {
231                 cti->get_constraint_targets(con, &targets);
232                 num_targets= BLI_countlist(&targets);
233                 
234                 if (index < 0) {
235                         if (abs(index) < num_targets)
236                                 index= num_targets - abs(index);
237                         else
238                                 index= num_targets - 1;
239                 }
240                 else if (index >= num_targets) {
241                         index= num_targets - 1;
242                 }
243                 
244                 for (ct=targets.first, i=0; ct; ct= ct->next, i++) {
245                         if (i == index) {
246                                 ct->tar= target;
247                                 BLI_strncpy(ct->subtarget, subtarget, sizeof(ct->subtarget));
248                                 break;
249                         }
250                 }
251                 
252                 if (cti->flush_constraint_targets)
253                         cti->flush_constraint_targets(con, &targets, 0);
254         }
255 }
256
257 /* ------------- Constraint Sanity Testing ------------------- */
258
259 /* checks validity of object pointers, and NULLs,
260  * if Bone doesnt exist it sets the CONSTRAINT_DISABLE flag.
261  */
262 static void test_constraints (Object *owner, bPoseChannel *pchan)
263 {
264         bConstraint *curcon;
265         ListBase *conlist= NULL;
266         int type;
267         
268         if (owner==NULL) return;
269         
270         /* Check parents */
271         if (pchan) {
272                 switch (owner->type) {
273                         case OB_ARMATURE:
274                                 type = CONSTRAINT_OBTYPE_BONE;
275                                 break;
276                         default:
277                                 type = CONSTRAINT_OBTYPE_OBJECT;
278                                 break;
279                 }
280         }
281         else
282                 type = CONSTRAINT_OBTYPE_OBJECT;
283         
284         /* Get the constraint list for this object */
285         switch (type) {
286                 case CONSTRAINT_OBTYPE_OBJECT:
287                         conlist = &owner->constraints;
288                         break;
289                 case CONSTRAINT_OBTYPE_BONE:
290                         conlist = &pchan->constraints;
291                         break;
292         }
293         
294         /* Check all constraints - is constraint valid? */
295         if (conlist) {
296                 for (curcon = conlist->first; curcon; curcon=curcon->next) {
297                         bConstraintTypeInfo *cti= constraint_get_typeinfo(curcon);
298                         ListBase targets = {NULL, NULL};
299                         bConstraintTarget *ct;
300                         
301                         /* clear disabled-flag first */
302                         curcon->flag &= ~CONSTRAINT_DISABLE;
303                         
304                         if (curcon->type == CONSTRAINT_TYPE_KINEMATIC) {
305                                 bKinematicConstraint *data = curcon->data;
306                                 
307                                 /* bad: we need a separate set of checks here as poletarget is 
308                                  *              optional... otherwise poletarget must exist too or else
309                                  *              the constraint is deemed invalid
310                                  */
311                                 /* default IK check ... */
312                                 if (exist_object(data->tar) == 0) {
313                                         data->tar = NULL;
314                                         curcon->flag |= CONSTRAINT_DISABLE;
315                                 }
316                                 else if (data->tar == owner) {
317                                         if (!get_named_bone(get_armature(owner), data->subtarget)) {
318                                                 curcon->flag |= CONSTRAINT_DISABLE;
319                                         }
320                                 }
321                                 
322                                 if (data->poletar) {
323                                         if (exist_object(data->poletar) == 0) {
324                                                 data->poletar = NULL;
325                                                 curcon->flag |= CONSTRAINT_DISABLE;
326                                         }
327                                         else if (data->poletar == owner) {
328                                                 if (!get_named_bone(get_armature(owner), data->polesubtarget)) {
329                                                         curcon->flag |= CONSTRAINT_DISABLE;
330                                                 }
331                                         }
332                                 }
333                                 /* ... can be overwritten here */
334                                 BIK_test_constraint(owner, curcon);
335                                 /* targets have already been checked for this */
336                                 continue;
337                         }
338                         else if (curcon->type == CONSTRAINT_TYPE_PIVOT) {
339                                 bPivotConstraint *data = curcon->data;
340                                 
341                                 /* target doesn't have to exist, but if it is non-null, it must exist! */
342                                 if (data->tar && exist_object(data->tar)==0) {
343                                         data->tar = NULL;
344                                         curcon->flag |= CONSTRAINT_DISABLE;
345                                 }
346                                 else if (data->tar == owner) {
347                                         if (!get_named_bone(get_armature(owner), data->subtarget)) {
348                                                 curcon->flag |= CONSTRAINT_DISABLE;
349                                         }
350                                 }
351                                 
352                                 /* targets have already been checked for this */
353                                 continue;
354                         }
355                         else if (curcon->type == CONSTRAINT_TYPE_ACTION) {
356                                 bActionConstraint *data = curcon->data;
357                                 
358                                 /* validate action */
359                                 if (data->act == NULL) 
360                                         curcon->flag |= CONSTRAINT_DISABLE;
361                         }
362                         else if (curcon->type == CONSTRAINT_TYPE_FOLLOWPATH) {
363                                 bFollowPathConstraint *data = curcon->data;
364                                 
365                                 /* don't allow track/up axes to be the same */
366                                 if (data->upflag==data->trackflag)
367                                         curcon->flag |= CONSTRAINT_DISABLE;
368                                 if (data->upflag+3==data->trackflag)
369                                         curcon->flag |= CONSTRAINT_DISABLE;
370                         }
371                         else if (curcon->type == CONSTRAINT_TYPE_TRACKTO) {
372                                 bTrackToConstraint *data = curcon->data;
373                                 
374                                 /* don't allow track/up axes to be the same */
375                                 if (data->reserved2==data->reserved1)
376                                         curcon->flag |= CONSTRAINT_DISABLE;
377                                 if (data->reserved2+3==data->reserved1)
378                                         curcon->flag |= CONSTRAINT_DISABLE;
379                         }
380                         else if (curcon->type == CONSTRAINT_TYPE_LOCKTRACK) {
381                                 bLockTrackConstraint *data = curcon->data;
382                                 
383                                 if (data->lockflag==data->trackflag)
384                                         curcon->flag |= CONSTRAINT_DISABLE;
385                                 if (data->lockflag+3==data->trackflag)
386                                         curcon->flag |= CONSTRAINT_DISABLE;
387                         }
388                         else if (curcon->type == CONSTRAINT_TYPE_SPLINEIK) {
389                                 bSplineIKConstraint *data = curcon->data;
390                                 
391                                 /* if the number of points does not match the amount required by the chain length,
392                                  * free the points array and request a rebind...
393                                  */
394                                 if ((data->points == NULL) || (data->numpoints != data->chainlen+1))
395                                 {
396                                         /* free the points array */
397                                         if (data->points) {
398                                                 MEM_freeN(data->points);
399                                                 data->points = NULL;
400                                         }
401                                         
402                                         /* clear the bound flag, forcing a rebind next time this is evaluated */
403                                         data->flag &= ~CONSTRAINT_SPLINEIK_BOUND;
404                                 }
405                         }
406                         else if (curcon->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
407                                 bFollowTrackConstraint *data = curcon->data;
408
409                                 if((data->flag&CAMERASOLVER_ACTIVECLIP)==0) {
410                                         if(data->clip != NULL && data->track[0]) {
411                                                 MovieTracking *tracking= &data->clip->tracking;
412                                                 MovieTrackingObject *tracking_object;
413
414                                                 if(data->object[0])
415                                                         tracking_object= BKE_tracking_named_object(tracking, data->object);
416                                                 else
417                                                         tracking_object= BKE_tracking_get_camera_object(tracking);
418
419                                                 if(!tracking_object) {
420                                                         curcon->flag |= CONSTRAINT_DISABLE;
421                                                 }
422                                                 else {
423                                                         if (!BKE_tracking_named_track(tracking, tracking_object, data->track))
424                                                                 curcon->flag |= CONSTRAINT_DISABLE;
425                                                 }
426                                         }
427                                         else curcon->flag |= CONSTRAINT_DISABLE;
428                                 }
429                         }
430                         else if (curcon->type == CONSTRAINT_TYPE_CAMERASOLVER) {
431                                 bCameraSolverConstraint *data = curcon->data;
432
433                                 if((data->flag&CAMERASOLVER_ACTIVECLIP)==0 && data->clip == NULL)
434                                         curcon->flag |= CONSTRAINT_DISABLE;
435                         }
436                         else if (curcon->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
437                                 bObjectSolverConstraint *data = curcon->data;
438
439                                 if((data->flag&CAMERASOLVER_ACTIVECLIP)==0 && data->clip == NULL)
440                                         curcon->flag |= CONSTRAINT_DISABLE;
441                         }
442                         
443                         /* Check targets for constraints */
444                         if (cti && cti->get_constraint_targets) {
445                                 cti->get_constraint_targets(curcon, &targets);
446                                 
447                                 /* disable and clear constraints targets that are incorrect */
448                                 for (ct= targets.first; ct; ct= ct->next) {
449                                         /* general validity checks (for those constraints that need this) */
450                                         if (exist_object(ct->tar) == 0) {
451                                                 /* object doesn't exist, but constraint requires target */
452                                                 ct->tar = NULL;
453                                                 curcon->flag |= CONSTRAINT_DISABLE;
454                                         }
455                                         else if (ct->tar == owner) {
456                                                 if (type == CONSTRAINT_OBTYPE_BONE) {
457                                                         if (!get_named_bone(get_armature(owner), ct->subtarget)) {
458                                                                 /* bone must exist in armature... */
459                                                                 // TODO: clear subtarget?
460                                                                 curcon->flag |= CONSTRAINT_DISABLE;
461                                                         }
462                                                         else if (strcmp(pchan->name, ct->subtarget) == 0) {
463                                                                 /* cannot target self */
464                                                                 ct->subtarget[0] = '\0';
465                                                                 curcon->flag |= CONSTRAINT_DISABLE;
466                                                         }
467                                                 }
468                                                 else {
469                                                         /* cannot use self as target */
470                                                         ct->tar = NULL;
471                                                         curcon->flag |= CONSTRAINT_DISABLE;
472                                                 }
473                                         }
474                                         
475                                         /* target checks for specific constraints */
476                                         if (ELEM3(curcon->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_SPLINEIK)) {
477                                                 if (ct->tar) {
478                                                         if (ct->tar->type != OB_CURVE) {
479                                                                 ct->tar= NULL;
480                                                                 curcon->flag |= CONSTRAINT_DISABLE;
481                                                         }
482                                                         else {
483                                                                 Curve *cu= ct->tar->data;
484                                                                 
485                                                                 /* auto-set 'Path' setting on curve so this works  */
486                                                                 cu->flag |= CU_PATH;
487                                                         }
488                                                 }                                               
489                                         }
490                                 }       
491                                 
492                                 /* free any temporary targets */
493                                 if (cti->flush_constraint_targets)
494                                         cti->flush_constraint_targets(curcon, &targets, 0);
495                         }
496                 }
497         }
498 }
499
500 void object_test_constraints (Object *owner)
501 {
502         if (owner->constraints.first)
503                 test_constraints(owner, NULL);
504         
505         if (owner->type==OB_ARMATURE && owner->pose) {
506                 bPoseChannel *pchan;
507                 
508                 for (pchan= owner->pose->chanbase.first; pchan; pchan= pchan->next) {
509                         if (pchan->constraints.first)
510                                 test_constraints(owner, pchan);
511                 }
512         }
513 }
514
515
516 /************************ generic functions for operators using constraint names and data context *********************/
517
518 #define EDIT_CONSTRAINT_OWNER_OBJECT    0
519 #define EDIT_CONSTRAINT_OWNER_BONE              1
520
521 static EnumPropertyItem constraint_owner_items[] = {
522         {EDIT_CONSTRAINT_OWNER_OBJECT, "OBJECT", 0, "Object", "Edit a constraint on the active object"},
523         {EDIT_CONSTRAINT_OWNER_BONE, "BONE", 0, "Bone", "Edit a constraint on the active bone"},
524         {0, NULL, 0, NULL, NULL}};
525
526
527 static int edit_constraint_poll_generic(bContext *C, StructRNA *rna_type)
528 {
529         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", rna_type);
530         Object *ob= (ptr.id.data) ? ptr.id.data : ED_object_active_context(C);
531
532         if (!ob || ob->id.lib) return 0;
533         if (ptr.id.data && ((ID*)ptr.id.data)->lib) return 0;
534
535         return 1;
536 }
537
538 static int edit_constraint_poll(bContext *C)
539 {
540         return edit_constraint_poll_generic(C, &RNA_Constraint);
541 }
542
543 static void edit_constraint_properties(wmOperatorType *ot)
544 {
545         RNA_def_string(ot->srna, "constraint", "", 32, "Constraint", "Name of the constraint to edit");
546         RNA_def_enum(ot->srna, "owner", constraint_owner_items, 0, "Owner", "The owner of this constraint");
547 }
548
549 static int edit_constraint_invoke_properties(bContext *C, wmOperator *op)
550 {
551         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
552         Object *ob= (ptr.id.data)?ptr.id.data:ED_object_active_context(C);
553         bConstraint *con;
554         ListBase *list;
555         
556         if (RNA_property_is_set(op->ptr, "constraint") && RNA_property_is_set(op->ptr, "owner"))
557                 return 1;
558         
559         if (ptr.data) {
560                 con = ptr.data;
561                 RNA_string_set(op->ptr, "constraint", con->name);
562                 
563                 list = get_constraint_lb(ob, con, NULL);
564                 
565                 if (&ob->constraints == list)
566                         RNA_enum_set(op->ptr, "owner", EDIT_CONSTRAINT_OWNER_OBJECT);
567                 else
568                         RNA_enum_set(op->ptr, "owner", EDIT_CONSTRAINT_OWNER_BONE);
569                 
570                 return 1;
571         }
572         
573         return 0;
574 }
575
576 static bConstraint *edit_constraint_property_get(wmOperator *op, Object *ob, int type)
577 {
578         char constraint_name[32];
579         int owner = RNA_enum_get(op->ptr, "owner");
580         bConstraint *con;
581         ListBase *list=NULL;
582         
583         RNA_string_get(op->ptr, "constraint", constraint_name);
584         
585         if (owner == EDIT_CONSTRAINT_OWNER_OBJECT) {
586                 list = &ob->constraints;
587         } 
588         else if (owner == EDIT_CONSTRAINT_OWNER_BONE) {
589                 bPoseChannel *pchan= get_active_posechannel(ob);
590                 if (pchan)
591                         list = &pchan->constraints;
592                 else {
593                         //if (G.f & G_DEBUG)
594                         //printf("edit_constraint_property_get: No active bone for object '%s'\n", (ob)? ob->id.name+2 : "<None>");
595                         return NULL;
596                 }
597         }
598         else {
599                 //if (G.f & G_DEBUG)
600                 //printf("edit_constraint_property_get: defaulting to getting list in the standard way\n");
601                 list = get_active_constraints(ob);
602         }
603         
604         con = constraints_findByName(list, constraint_name);
605         //if (G.f & G_DEBUG)
606         //printf("constraint found = %p, %s\n", (void *)con, (con)?con->name:"<Not found>");
607
608         if (con && (type != 0) && (con->type != type))
609                 con = NULL;
610         
611         return con;
612 }
613
614 /* ********************** CONSTRAINT-SPECIFIC STUFF ********************* */
615
616 /* ---------- Distance-Dependent Constraints ---------- */
617 /* StretchTo, Limit Distance */
618
619 static int stretchto_reset_exec (bContext *C, wmOperator *op)
620 {
621         Object *ob = ED_object_active_context(C);
622         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_STRETCHTO);
623         bStretchToConstraint *data= (con) ? (bStretchToConstraint *)con->data : NULL;
624         
625         /* despite 3 layers of checks, we may still not be able to find a constraint */
626         if (data == NULL)
627                 return OPERATOR_CANCELLED;
628         
629         /* just set original length to 0.0, which will cause a reset on next recalc */
630         data->orglength = 0.0f;
631         ED_object_constraint_update(ob);
632         
633         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, NULL);
634         return OPERATOR_FINISHED;
635 }
636
637 static int stretchto_reset_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
638 {
639         if (edit_constraint_invoke_properties(C, op))
640                 return stretchto_reset_exec(C, op);
641         else
642                 return OPERATOR_CANCELLED;
643 }
644
645 void CONSTRAINT_OT_stretchto_reset (wmOperatorType *ot)
646 {
647         /* identifiers */
648         ot->name= "Reset Original Length";
649         ot->idname= "CONSTRAINT_OT_stretchto_reset";
650         ot->description= "Reset original length of bone for Stretch To Constraint";
651         
652         ot->exec= stretchto_reset_exec;
653         ot->invoke= stretchto_reset_invoke;
654         ot->poll= edit_constraint_poll;
655         
656         /* flags */
657         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
658         edit_constraint_properties(ot);
659 }
660
661
662 static int limitdistance_reset_exec (bContext *C, wmOperator *op)
663 {
664         Object *ob = ED_object_active_context(C);
665         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_DISTLIMIT);
666         bDistLimitConstraint *data= (con) ? (bDistLimitConstraint *)con->data : NULL;
667         
668         /* despite 3 layers of checks, we may still not be able to find a constraint */
669         if (data == NULL)
670                 return OPERATOR_CANCELLED;
671         
672         /* just set original length to 0.0, which will cause a reset on next recalc */
673         data->dist = 0.0f;
674         ED_object_constraint_update(ob);
675         
676         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, NULL);
677         return OPERATOR_FINISHED;
678 }
679
680 static int limitdistance_reset_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
681 {
682         if (edit_constraint_invoke_properties(C, op))
683                 return limitdistance_reset_exec(C, op);
684         else
685                 return OPERATOR_CANCELLED;
686 }
687
688 void CONSTRAINT_OT_limitdistance_reset (wmOperatorType *ot)
689 {
690         /* identifiers */
691         ot->name= "Reset Distance";
692         ot->idname= "CONSTRAINT_OT_limitdistance_reset";
693         ot->description= "Reset limiting distance for Limit Distance Constraint";
694         
695         ot->exec= limitdistance_reset_exec;
696         ot->invoke= limitdistance_reset_invoke;
697         ot->poll= edit_constraint_poll;
698         
699         /* flags */
700         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
701         edit_constraint_properties(ot);
702 }
703
704 /* ------------- Child-Of Constraint ------------------ */
705
706 static void child_get_inverse_matrix (Scene *scene, Object *ob, bConstraint *con, float invmat[4][4])
707 {
708         bConstraint *lastcon = NULL;
709         bPoseChannel *pchan= NULL;
710         
711         /* nullify inverse matrix first */
712         unit_m4(invmat);
713         
714         /* try to find a pose channel - assume that this is the constraint owner */
715         // TODO: get from context instead?
716         if (ob && ob->pose)
717                 pchan= get_active_posechannel(ob);
718         
719         /* calculate/set inverse matrix:
720          *      We just calculate all transform-stack eval up to but not including this constraint.
721          *      This is because inverse should just inverse correct for just the constraint's influence
722          *      when it gets applied; that is, at the time of application, we don't know anything about
723          *      what follows.
724          */
725         if (pchan) {
726                 float imat[4][4], tmat[4][4];
727                 float pmat[4][4];
728                 
729                 /* 1. calculate posemat where inverse doesn't exist yet (inverse was cleared above), 
730                  * to use as baseline ("pmat") to derive delta from. This extra calc saves users 
731                  * from having pressing "Clear Inverse" first
732                  */
733                 where_is_pose(scene, ob);
734                 copy_m4_m4(pmat, pchan->pose_mat);
735                 
736                 /* 2. knock out constraints starting from this one */
737                 lastcon = pchan->constraints.last;
738                 pchan->constraints.last = con->prev;
739                 
740                 if (con->prev) {
741                         /* new end must not point to this one, else this chain cutting is useless */
742                         con->prev->next = NULL;
743                 }
744                 else {
745                         /* constraint was first */
746                         pchan->constraints.first = NULL;
747                 }
748                 
749                 /* 3. solve pose without disabled constraints */
750                 where_is_pose(scene, ob);
751                 
752                 /* 4. determine effect of constraint by removing the newly calculated 
753                  * pchan->pose_mat from the original pchan->pose_mat, thus determining 
754                  * the effect of the constraint
755                  */
756                 invert_m4_m4(imat, pchan->pose_mat);
757                 mult_m4_m4m4(tmat, pmat, imat);
758                 invert_m4_m4(invmat, tmat);
759                 
760                 /* 5. restore constraints */
761                 pchan->constraints.last = lastcon;
762                 
763                 if (con->prev) {
764                         /* hook up prev to this one again */
765                         con->prev->next = con;
766                 }
767                 else {
768                         /* set as first again */
769                         pchan->constraints.first = con;
770                 }
771                 
772                 /* 6. recalculate pose with new inv-mat applied */
773                 where_is_pose(scene, ob);
774         }
775         else if (ob) {
776                 Object workob;
777                 
778                 /* use what_does_parent to find inverse - just like for normal parenting */
779                 what_does_parent(scene, ob, &workob);
780                 invert_m4_m4(invmat, workob.obmat);
781         }
782 }
783
784 /* ChildOf Constraint - set inverse callback */
785 static int childof_set_inverse_exec (bContext *C, wmOperator *op)
786 {
787         Scene *scene= CTX_data_scene(C);
788         Object *ob = ED_object_active_context(C);
789         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_CHILDOF);
790         bChildOfConstraint *data= (con) ? (bChildOfConstraint *)con->data : NULL;
791
792         /* despite 3 layers of checks, we may still not be able to find a constraint */
793         if (data == NULL) {
794                 printf("DEBUG: Child-Of Set Inverse - object = '%s'\n", (ob)? ob->id.name+2 : "<None>");
795                 BKE_report(op->reports, RPT_ERROR, "Couldn't find constraint data for Child-Of Set Inverse");
796                 return OPERATOR_CANCELLED;
797         }
798         
799         child_get_inverse_matrix(scene, ob, con, data->invmat);
800
801         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
802         
803         return OPERATOR_FINISHED;
804 }
805
806 static int childof_set_inverse_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
807 {
808         if (edit_constraint_invoke_properties(C, op))
809                 return childof_set_inverse_exec(C, op);
810         else
811                 return OPERATOR_CANCELLED;
812 }
813
814 void CONSTRAINT_OT_childof_set_inverse (wmOperatorType *ot)
815 {
816         /* identifiers */
817         ot->name= "Set Inverse";
818         ot->idname= "CONSTRAINT_OT_childof_set_inverse";
819         ot->description= "Set inverse correction for ChildOf constraint";
820         
821         ot->exec= childof_set_inverse_exec;
822         ot->invoke= childof_set_inverse_invoke;
823         ot->poll= edit_constraint_poll;
824         
825         /* flags */
826         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
827         edit_constraint_properties(ot);
828 }
829
830 /* ChildOf Constraint - clear inverse callback */
831 static int childof_clear_inverse_exec (bContext *C, wmOperator *op)
832 {
833         Object *ob = ED_object_active_context(C);
834         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_CHILDOF);
835         bChildOfConstraint *data= (con) ? (bChildOfConstraint *)con->data : NULL;
836         
837         if(data==NULL) {
838                 BKE_report(op->reports, RPT_ERROR, "Childof constraint not found");
839                 return OPERATOR_CANCELLED;
840         }
841         
842         /* simply clear the matrix */
843         unit_m4(data->invmat);
844         
845         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
846         
847         return OPERATOR_FINISHED;
848 }
849
850 static int childof_clear_inverse_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
851 {
852         if (edit_constraint_invoke_properties(C, op))
853                 return childof_clear_inverse_exec(C, op);
854         else
855                 return OPERATOR_CANCELLED;
856 }
857
858 void CONSTRAINT_OT_childof_clear_inverse (wmOperatorType *ot)
859 {
860         /* identifiers */
861         ot->name= "Clear Inverse";
862         ot->idname= "CONSTRAINT_OT_childof_clear_inverse";
863         ot->description= "Clear inverse correction for ChildOf constraint";
864         
865         ot->exec= childof_clear_inverse_exec;
866         ot->invoke= childof_clear_inverse_invoke;
867         ot->poll= edit_constraint_poll;
868         
869         /* flags */
870         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
871         edit_constraint_properties(ot);
872 }
873
874 /* ------------- Object Solver Constraint ------------------ */
875
876 static int objectsolver_set_inverse_exec (bContext *C, wmOperator *op)
877 {
878         Scene *scene= CTX_data_scene(C);
879         Object *ob = ED_object_active_context(C);
880         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_OBJECTSOLVER);
881         bObjectSolverConstraint *data= (con) ? (bObjectSolverConstraint *)con->data : NULL;
882
883         /* despite 3 layers of checks, we may still not be able to find a constraint */
884         if (data == NULL) {
885                 printf("DEBUG: Child-Of Set Inverse - object = '%s'\n", (ob)? ob->id.name+2 : "<None>");
886                 BKE_report(op->reports, RPT_ERROR, "Couldn't find constraint data for Child-Of Set Inverse");
887                 return OPERATOR_CANCELLED;
888         }
889
890         child_get_inverse_matrix(scene, ob, con, data->invmat);
891
892         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
893
894         return OPERATOR_FINISHED;
895 }
896
897 static int objectsolver_set_inverse_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
898 {
899         if (edit_constraint_invoke_properties(C, op))
900                 return objectsolver_set_inverse_exec(C, op);
901         else
902                 return OPERATOR_CANCELLED;
903 }
904
905 void CONSTRAINT_OT_objectsolver_set_inverse (wmOperatorType *ot)
906 {
907         /* identifiers */
908         ot->name= "Set Inverse";
909         ot->idname= "CONSTRAINT_OT_objectsolver_set_inverse";
910         ot->description= "Set inverse correction for ObjectSolver constraint";
911
912         ot->exec= objectsolver_set_inverse_exec;
913         ot->invoke= objectsolver_set_inverse_invoke;
914         ot->poll= edit_constraint_poll;
915
916         /* flags */
917         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
918         edit_constraint_properties(ot);
919 }
920
921 static int objectsolver_clear_inverse_exec (bContext *C, wmOperator *op)
922 {
923         Object *ob = ED_object_active_context(C);
924         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_OBJECTSOLVER);
925         bObjectSolverConstraint *data= (con) ? (bObjectSolverConstraint *)con->data : NULL;
926
927         if(data==NULL) {
928                 BKE_report(op->reports, RPT_ERROR, "Childof constraint not found");
929                 return OPERATOR_CANCELLED;
930         }
931
932         /* simply clear the matrix */
933         unit_m4(data->invmat);
934
935         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
936
937         return OPERATOR_FINISHED;
938 }
939
940 static int objectsolver_clear_inverse_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
941 {
942         if (edit_constraint_invoke_properties(C, op))
943                 return objectsolver_clear_inverse_exec(C, op);
944         else
945                 return OPERATOR_CANCELLED;
946 }
947
948 void CONSTRAINT_OT_objectsolver_clear_inverse (wmOperatorType *ot)
949 {
950         /* identifiers */
951         ot->name= "Clear Inverse";
952         ot->idname= "CONSTRAINT_OT_objectsolver_clear_inverse";
953         ot->description= "Clear inverse correction for ObjectSolver constraint";
954
955         ot->exec= objectsolver_clear_inverse_exec;
956         ot->invoke= objectsolver_clear_inverse_invoke;
957         ot->poll= edit_constraint_poll;
958
959         /* flags */
960         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
961         edit_constraint_properties(ot);
962 }
963
964 /***************************** BUTTONS ****************************/
965
966 void ED_object_constraint_set_active(Object *ob, bConstraint *con)
967 {       
968         ListBase *lb = get_constraint_lb(ob, con, NULL);
969         
970         /* lets be nice and escape if its active already */
971         // NOTE: this assumes that the stack doesn't have other active ones set...
972         if ((lb && con) && (con->flag & CONSTRAINT_ACTIVE))
973                 return;
974         
975         constraints_set_active(lb, con);
976 }
977
978 void ED_object_constraint_update(Object *ob)
979 {
980
981         if(ob->pose) update_pose_constraint_flags(ob->pose);
982
983         object_test_constraints(ob);
984
985         if(ob->type==OB_ARMATURE) DAG_id_tag_update(&ob->id, OB_RECALC_DATA|OB_RECALC_OB);
986         else DAG_id_tag_update(&ob->id, OB_RECALC_OB);
987 }
988
989 void ED_object_constraint_dependency_update(Main *bmain, Scene *scene, Object *ob)
990 {
991         ED_object_constraint_update(ob);
992
993         if(ob->pose) ob->pose->flag |= POSE_RECALC;     // checks & sorts pose channels
994         DAG_scene_sort(bmain, scene);
995 }
996
997 static int constraint_poll(bContext *C)
998 {
999         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
1000         return (ptr.id.data && ptr.data);
1001 }
1002
1003 static int constraint_delete_exec (bContext *C, wmOperator *UNUSED(op))
1004 {
1005         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
1006         Object *ob= ptr.id.data;
1007         bConstraint *con= ptr.data;
1008         ListBase *lb = get_constraint_lb(ob, con, NULL);
1009         const short is_ik= ELEM(con->type, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_SPLINEIK);
1010
1011         /* free the constraint */
1012         if (remove_constraint(lb, con)) {
1013                 /* there's no active constraint now, so make sure this is the case */
1014                 constraints_set_active(lb, NULL);
1015                 
1016                 ED_object_constraint_update(ob); /* needed to set the flags on posebones correctly */
1017
1018                 /* ITASC needs to be rebuilt once a constraint is removed [#26920] */
1019                 if(is_ik) {
1020                         BIK_clear_data(ob->pose);
1021                 }
1022
1023                 /* notifiers */
1024                 WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT|NA_REMOVED, ob);
1025                 
1026                 return OPERATOR_FINISHED;
1027         }
1028         else {
1029                 /* couldn't remove due to some invalid data */
1030                 return OPERATOR_CANCELLED;
1031         }
1032 }
1033
1034 void CONSTRAINT_OT_delete (wmOperatorType *ot)
1035 {
1036         /* identifiers */
1037         ot->name= "Delete Constraint";
1038         ot->idname= "CONSTRAINT_OT_delete";
1039         ot->description= "Remove constraint from constraint stack";
1040         
1041         /* callbacks */
1042         ot->exec= constraint_delete_exec;
1043         ot->poll= constraint_poll;
1044         
1045         /* flags */
1046         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
1047 }
1048
1049 static int constraint_move_down_exec (bContext *C, wmOperator *op)
1050 {
1051         Object *ob = ED_object_active_context(C);
1052         bConstraint *con = edit_constraint_property_get(op, ob, 0);
1053         
1054         if (con && con->next) {
1055                 ListBase *conlist= get_constraint_lb(ob, con, NULL);
1056                 bConstraint *nextCon= con->next;
1057                 
1058                 /* insert the nominated constraint after the one that used to be after it */
1059                 BLI_remlink(conlist, con);
1060                 BLI_insertlinkafter(conlist, nextCon, con);
1061                 
1062                 WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
1063                 
1064                 return OPERATOR_FINISHED;
1065         }
1066         
1067         return OPERATOR_CANCELLED;
1068 }
1069
1070 static int constraint_move_down_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1071 {
1072         if (edit_constraint_invoke_properties(C, op))
1073                 return constraint_move_down_exec(C, op);
1074         else
1075                 return OPERATOR_CANCELLED;
1076 }
1077
1078
1079 void CONSTRAINT_OT_move_down (wmOperatorType *ot)
1080 {
1081         /* identifiers */
1082         ot->name= "Move Constraint Down";
1083         ot->idname= "CONSTRAINT_OT_move_down";
1084         ot->description= "Move constraint down in constraint stack";
1085         
1086         /* callbacks */
1087         ot->exec= constraint_move_down_exec;
1088         ot->invoke= constraint_move_down_invoke;
1089         ot->poll= edit_constraint_poll;
1090         
1091         /* flags */
1092         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
1093         edit_constraint_properties(ot);
1094 }
1095
1096
1097 static int constraint_move_up_exec (bContext *C, wmOperator *op)
1098 {
1099         Object *ob = ED_object_active_context(C);
1100         bConstraint *con = edit_constraint_property_get(op, ob, 0);
1101         
1102         if (con && con->prev) {
1103                 ListBase *conlist= get_constraint_lb(ob, con, NULL);
1104                 bConstraint *prevCon= con->prev;
1105                 
1106                 /* insert the nominated constraint before the one that used to be before it */
1107                 BLI_remlink(conlist, con);
1108                 BLI_insertlinkbefore(conlist, prevCon, con);
1109                 
1110                 WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
1111                 
1112                 return OPERATOR_FINISHED;
1113         }
1114         
1115         return OPERATOR_CANCELLED;
1116 }
1117
1118 static int constraint_move_up_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1119 {
1120         if (edit_constraint_invoke_properties(C, op))
1121                 return constraint_move_up_exec(C, op);
1122         else
1123                 return OPERATOR_CANCELLED;
1124 }
1125
1126 void CONSTRAINT_OT_move_up (wmOperatorType *ot)
1127 {
1128         /* identifiers */
1129         ot->name= "Move Constraint Up";
1130         ot->idname= "CONSTRAINT_OT_move_up";
1131         ot->description= "Move constraint up in constraint stack";
1132         
1133         /* callbacks */
1134         ot->exec= constraint_move_up_exec;
1135         ot->invoke= constraint_move_up_invoke;
1136         ot->poll= edit_constraint_poll;
1137         
1138         /* flags */
1139         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
1140         edit_constraint_properties(ot);
1141 }
1142
1143 /***************************** OPERATORS ****************************/
1144
1145 /************************ remove constraint operators *********************/
1146
1147 static int pose_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
1148 {
1149         Main *bmain= CTX_data_main(C);
1150         Scene *scene= CTX_data_scene(C);
1151         Object *ob= object_pose_armature_get(CTX_data_active_object(C));
1152         
1153         /* free constraints for all selected bones */
1154         CTX_DATA_BEGIN(C, bPoseChannel*, pchan, selected_pose_bones)
1155         {
1156                 free_constraints(&pchan->constraints);
1157                 pchan->constflag &= ~(PCHAN_HAS_IK|PCHAN_HAS_SPLINEIK|PCHAN_HAS_CONST);
1158         }
1159         CTX_DATA_END;
1160         
1161         /* force depsgraph to get recalculated since relationships removed */
1162         DAG_scene_sort(bmain, scene);           /* sort order of objects */     
1163         
1164         /* note, calling BIK_clear_data() isnt needed here */
1165
1166         /* do updates */
1167         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1168         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
1169         
1170         return OPERATOR_FINISHED;
1171 }
1172
1173 void POSE_OT_constraints_clear(wmOperatorType *ot)
1174 {
1175         /* identifiers */
1176         ot->name = "Clear Pose Constraints";
1177         ot->idname= "POSE_OT_constraints_clear";
1178         ot->description= "Clear all the constraints for the selected bones";
1179         
1180         /* callbacks */
1181         ot->exec= pose_constraints_clear_exec;
1182         ot->poll= ED_operator_posemode; // XXX - do we want to ensure there are selected bones too?
1183 }
1184
1185
1186 static int object_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
1187 {
1188         Main *bmain= CTX_data_main(C);
1189         Scene *scene= CTX_data_scene(C);
1190         
1191         /* do freeing */
1192         CTX_DATA_BEGIN(C, Object*, ob, selected_editable_objects) 
1193         {
1194                 free_constraints(&ob->constraints);
1195                 DAG_id_tag_update(&ob->id, OB_RECALC_OB);
1196         }
1197         CTX_DATA_END;
1198         
1199         /* force depsgraph to get recalculated since relationships removed */
1200         DAG_scene_sort(bmain, scene);           /* sort order of objects */     
1201         
1202         /* do updates */
1203         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, NULL);
1204         
1205         return OPERATOR_FINISHED;
1206 }
1207
1208 void OBJECT_OT_constraints_clear(wmOperatorType *ot)
1209 {
1210         /* identifiers */
1211         ot->name = "Clear Object Constraints";
1212         ot->idname= "OBJECT_OT_constraints_clear";
1213         ot->description= "Clear all the constraints for the active Object only";
1214         
1215         /* callbacks */
1216         ot->exec= object_constraints_clear_exec;
1217         ot->poll= ED_operator_object_active_editable;
1218 }
1219
1220 /************************ copy all constraints operators *********************/
1221
1222 static int pose_constraint_copy_exec(bContext *C, wmOperator *op)
1223 {
1224         Main *bmain= CTX_data_main(C);
1225         Scene *scene = CTX_data_scene(C);
1226         bPoseChannel *pchan = CTX_data_active_pose_bone(C);
1227         
1228         /* don't do anything if bone doesn't exist or doesn't have any constraints */
1229         if (ELEM(NULL, pchan, pchan->constraints.first)) {
1230                 BKE_report(op->reports, RPT_ERROR, "No active bone with constraints for copying");
1231                 return OPERATOR_CANCELLED;
1232         }
1233         
1234         /* copy all constraints from active posebone to all selected posebones */
1235         CTX_DATA_BEGIN(C, bPoseChannel*, chan, selected_pose_bones) 
1236         {
1237                 /* if we're not handling the object we're copying from, copy all constraints over */
1238                 if (pchan != chan) {
1239                         copy_constraints(&chan->constraints, &pchan->constraints, TRUE);
1240                         /* update flags (need to add here, not just copy) */
1241                         chan->constflag |= pchan->constflag;
1242                 }
1243         }
1244         CTX_DATA_END;
1245         
1246         /* force depsgraph to get recalculated since new relationships added */
1247         DAG_scene_sort(bmain, scene);           /* sort order of objects/bones */
1248
1249         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, NULL);
1250         
1251         return OPERATOR_FINISHED;
1252 }
1253
1254 void POSE_OT_constraints_copy(wmOperatorType *ot)
1255 {
1256         /* identifiers */
1257         ot->name= "Copy Constraints to Selected";
1258         ot->idname= "POSE_OT_constraints_copy";
1259         ot->description = "Copy constraints to other selected bones";
1260         
1261         /* api callbacks */
1262         ot->exec= pose_constraint_copy_exec;
1263         ot->poll= ED_operator_posemode;
1264
1265         /* flags */
1266         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1267 }
1268
1269 static int object_constraint_copy_exec(bContext *C, wmOperator *UNUSED(op))
1270 {
1271         Main *bmain= CTX_data_main(C);
1272         Scene *scene = CTX_data_scene(C);
1273         Object *obact = ED_object_active_context(C);
1274         
1275         /* copy all constraints from active object to all selected objects */
1276         CTX_DATA_BEGIN(C, Object*, ob, selected_editable_objects) 
1277         {
1278                 /* if we're not handling the object we're copying from, copy all constraints over */
1279                 if (obact != ob) {
1280                         copy_constraints(&ob->constraints, &obact->constraints, TRUE);
1281                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1282                 }
1283         }
1284         CTX_DATA_END;
1285         
1286         /* force depsgraph to get recalculated since new relationships added */
1287         DAG_scene_sort(bmain, scene);           /* sort order of objects */
1288         
1289         /* notifiers for updates */
1290         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT|NA_ADDED, NULL);
1291         
1292         return OPERATOR_FINISHED;
1293 }
1294
1295 void OBJECT_OT_constraints_copy(wmOperatorType *ot)
1296 {
1297         /* identifiers */
1298         ot->name= "Copy Constraints to Selected";
1299         ot->idname= "OBJECT_OT_constraints_copy";
1300         ot->description = "Copy constraints to other selected objects";
1301         
1302         /* api callbacks */
1303         ot->exec= object_constraint_copy_exec;
1304         ot->poll= ED_operator_object_active_editable;
1305
1306         /* flags */
1307         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1308 }
1309
1310 /************************ add constraint operators *********************/
1311
1312 /* get the Object and/or PoseChannel to use as target */
1313 static short get_new_constraint_target(bContext *C, int con_type, Object **tar_ob, bPoseChannel **tar_pchan, short add)
1314 {
1315         Object *obact= ED_object_active_context(C);
1316         bPoseChannel *pchanact= get_active_posechannel(obact);
1317         short only_curve= 0, only_mesh= 0, only_ob= 0;
1318         short found= 0;
1319         
1320         /* clear tar_ob and tar_pchan fields before use 
1321          *      - assume for now that both always exist...
1322          */
1323         *tar_ob= NULL;
1324         *tar_pchan= NULL;
1325         
1326         /* check if constraint type doesn't requires a target
1327          *      - if so, no need to get any targets 
1328          */
1329         switch (con_type) {
1330                 /* no-target constraints --------------------------- */
1331                         /* null constraint - shouldn't even be added! */
1332                 case CONSTRAINT_TYPE_NULL:
1333                         /* limit constraints - no targets needed */
1334                 case CONSTRAINT_TYPE_LOCLIMIT:
1335                 case CONSTRAINT_TYPE_ROTLIMIT:
1336                 case CONSTRAINT_TYPE_SIZELIMIT:
1337                 case CONSTRAINT_TYPE_SAMEVOL:
1338                         return 0;
1339                         
1340                 /* restricted target-type constraints -------------- */
1341                 /* NOTE: for these, we cannot try to add a target object if no valid ones are found, since that doesn't work */
1342                         /* curve-based constraints - set the only_curve and only_ob flags */
1343                 case CONSTRAINT_TYPE_CLAMPTO:
1344                 case CONSTRAINT_TYPE_FOLLOWPATH:
1345                 case CONSTRAINT_TYPE_SPLINEIK:
1346                         only_curve= 1;
1347                         only_ob= 1;
1348                         add= 0;
1349                         break;
1350                         
1351                         /* mesh only? */
1352                 case CONSTRAINT_TYPE_SHRINKWRAP:
1353                         only_mesh= 1;
1354                         only_ob= 1;
1355                         add= 0;
1356                         break;
1357                         
1358                         /* object only - add here is ok? */
1359                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
1360                         only_ob= 1;
1361                         break;
1362         }
1363         
1364         /* if the active Object is Armature, and we can search for bones, do so... */
1365         if ((obact->type == OB_ARMATURE) && (only_ob == 0)) {
1366                 /* search in list of selected Pose-Channels for target */
1367                 CTX_DATA_BEGIN(C, bPoseChannel*, pchan, selected_pose_bones) 
1368                 {
1369                         /* just use the first one that we encounter, as long as it is not the active one */
1370                         if (pchan != pchanact) {
1371                                 *tar_ob= obact;
1372                                 *tar_pchan= pchan;
1373                                 found= 1;
1374                                 
1375                                 break;
1376                         }
1377                 }
1378                 CTX_DATA_END;
1379         }
1380         
1381         /* if not yet found, try selected Objects... */
1382         if (found == 0) {
1383                 /* search in selected objects context */
1384                 CTX_DATA_BEGIN(C, Object*, ob, selected_objects) 
1385                 {
1386                         /* just use the first object we encounter (that isn't the active object) 
1387                          * and which fulfills the criteria for the object-target that we've got 
1388                          */
1389                         if ( (ob != obact) &&
1390                                  ((!only_curve) || (ob->type == OB_CURVE)) && 
1391                                  ((!only_mesh) || (ob->type == OB_MESH)) )
1392                         {
1393                                 /* set target */
1394                                 *tar_ob= ob;
1395                                 found= 1;
1396                                 
1397                                 /* perform some special operations on the target */
1398                                 if (only_curve) {
1399                                         /* Curve-Path option must be enabled for follow-path constraints to be able to work */
1400                                         Curve *cu= (Curve *)ob->data;
1401                                         cu->flag |= CU_PATH;
1402                                 }
1403                                 
1404                                 break;
1405                         }
1406                 }
1407                 CTX_DATA_END;
1408         }
1409         
1410         /* if still not found, add a new empty to act as a target (if allowed) */
1411         if ((found == 0) && (add)) {
1412                 Scene *scene= CTX_data_scene(C);
1413                 Base *base= BASACT, *newbase=NULL;
1414                 Object *obt;
1415                 
1416                 /* add new target object */
1417                 obt= add_object(scene, OB_EMPTY);
1418                 
1419                 /* set layers OK */
1420                 newbase= BASACT;
1421                 newbase->lay= base->lay;
1422                 obt->lay= newbase->lay;
1423                 
1424                 /* transform cent to global coords for loc */
1425                 if (pchanact) {
1426                         /* since by default, IK targets the tip of the last bone, use the tip of the active PoseChannel 
1427                          * if adding a target for an IK Constraint
1428                          */
1429                         if (con_type == CONSTRAINT_TYPE_KINEMATIC)
1430                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_tail);
1431                         else
1432                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_head);
1433                 }
1434                 else {
1435                         copy_v3_v3(obt->loc, obact->obmat[3]);
1436                 }
1437
1438                 /* restore, add_object sets active */
1439                 BASACT= base;
1440                 base->flag |= SELECT;
1441                 
1442                 /* make our new target the new object */
1443                 *tar_ob= obt;
1444                 found= 1;
1445         }
1446         
1447         /* return whether there's any target */
1448         return found;
1449 }
1450
1451 /* used by add constraint operators to add the constraint required */
1452 static int constraint_add_exec(bContext *C, wmOperator *op, Object *ob, ListBase *list, int type, short setTarget)
1453 {
1454         Main *bmain= CTX_data_main(C);
1455         Scene *scene= CTX_data_scene(C);
1456         bPoseChannel *pchan;
1457         bConstraint *con;
1458         
1459         if (list == &ob->constraints) {
1460                 pchan= NULL;
1461         }
1462         else {
1463                 pchan= get_active_posechannel(ob);
1464                 
1465                 /* ensure not to confuse object/pose adding */
1466                 if (pchan == NULL) {
1467                         BKE_report(op->reports, RPT_ERROR, "No active pose bone to add a constraint to");
1468                         return OPERATOR_CANCELLED;
1469                 }
1470         }
1471         /* check if constraint to be added is valid for the given constraints stack */
1472         if (type == CONSTRAINT_TYPE_NULL) {
1473                 return OPERATOR_CANCELLED;
1474         }
1475         if ( (type == CONSTRAINT_TYPE_RIGIDBODYJOINT) && (list != &ob->constraints) ) {
1476                 BKE_report(op->reports, RPT_ERROR, "Rigid Body Joint Constraint can only be added to Objects");
1477                 return OPERATOR_CANCELLED;
1478         }
1479         if ( (type == CONSTRAINT_TYPE_KINEMATIC) && ((!pchan) || (list != &pchan->constraints)) ) {
1480                 BKE_report(op->reports, RPT_ERROR, "IK Constraint can only be added to Bones");
1481                 return OPERATOR_CANCELLED;
1482         }
1483         if ( (type == CONSTRAINT_TYPE_SPLINEIK) && ((!pchan) || (list != &pchan->constraints)) ) {
1484                 BKE_report(op->reports, RPT_ERROR, "Spline IK Constraint can only be added to Bones");
1485                 return OPERATOR_CANCELLED;
1486         }
1487         
1488         /* create a new constraint of the type requried, and add it to the active/given constraints list */
1489         if (pchan)
1490                 con = add_pose_constraint(ob, pchan, NULL, type);
1491         else
1492                 con = add_ob_constraint(ob, NULL, type);
1493         
1494         /* get the first selected object/bone, and make that the target
1495          *      - apart from the buttons-window add buttons, we shouldn't add in this way
1496          */
1497         if (setTarget) {
1498                 Object *tar_ob= NULL;
1499                 bPoseChannel *tar_pchan= NULL;
1500                 
1501                 /* get the target objects, adding them as need be */
1502                 if (get_new_constraint_target(C, type, &tar_ob, &tar_pchan, 1)) {
1503                         /* method of setting target depends on the type of target we've got 
1504                          *      - by default, just set the first target (distinction here is only for multiple-targetted constraints)
1505                          */
1506                         if (tar_pchan)
1507                                 set_constraint_nth_target(con, tar_ob, tar_pchan->name, 0);
1508                         else
1509                                 set_constraint_nth_target(con, tar_ob, "", 0);
1510                 }
1511         }
1512         
1513         /* do type-specific tweaking to the constraint settings  */
1514         switch (type) {
1515                 case CONSTRAINT_TYPE_PYTHON: // FIXME: this code is not really valid anymore
1516                 {
1517 #ifdef WITH_PYTHON
1518                         char *menustr;
1519                         int scriptint= 0;
1520                         /* popup a list of usable scripts */
1521                         menustr = buildmenu_pyconstraints(NULL, &scriptint);
1522                         // XXX scriptint = pupmenu(menustr);
1523                         MEM_freeN(menustr);
1524                         
1525                         /* only add constraint if a script was chosen */
1526                         if (scriptint) {
1527                                 /* add constraint */
1528                                 validate_pyconstraint_cb(con->data, &scriptint);
1529                                 
1530                                 /* make sure target allowance is set correctly */
1531                                 BPY_pyconstraint_update(ob, con);
1532                         }
1533 #endif
1534                         break;
1535                 }
1536
1537                 default:
1538                         break;
1539         }
1540         
1541         /* make sure all settings are valid - similar to above checks, but sometimes can be wrong */
1542         object_test_constraints(ob);
1543
1544         if (pchan)
1545                 update_pose_constraint_flags(ob->pose);
1546
1547
1548         /* force depsgraph to get recalculated since new relationships added */
1549         DAG_scene_sort(bmain, scene);           /* sort order of objects */
1550         
1551         if ((ob->type==OB_ARMATURE) && (pchan)) {
1552                 ob->pose->flag |= POSE_RECALC;  /* sort pose channels */
1553                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA|OB_RECALC_OB);
1554         }
1555         else
1556                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1557         
1558         /* notifiers for updates */
1559         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT|NA_ADDED, ob);
1560         
1561         return OPERATOR_FINISHED;
1562 }
1563
1564 /* ------------------ */
1565
1566 /* dummy operator callback */
1567 static int object_constraint_add_exec(bContext *C, wmOperator *op)
1568 {
1569         Object *ob=ED_object_active_context(C);
1570         int type= RNA_enum_get(op->ptr, "type");
1571         short with_targets= 0;
1572         
1573         if (!ob) {
1574                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to");
1575                 return OPERATOR_CANCELLED;
1576         }
1577                 
1578         /* hack: set constraint targets from selected objects in context is allowed when
1579          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1580          */
1581         if (strstr(op->idname, "with_targets"))
1582                 with_targets= 1;
1583
1584         return constraint_add_exec(C, op, ob, &ob->constraints, type, with_targets);
1585 }
1586
1587 /* dummy operator callback */
1588 static int pose_constraint_add_exec(bContext *C, wmOperator *op)
1589 {
1590         Object *ob= object_pose_armature_get(ED_object_active_context(C));
1591         int type= RNA_enum_get(op->ptr, "type");
1592         short with_targets= 0;
1593         
1594         if (!ob) {
1595                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to");
1596                 return OPERATOR_CANCELLED;
1597         }
1598                 
1599         /* hack: set constraint targets from selected objects in context is allowed when
1600          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1601          */
1602         if (strstr(op->idname, "with_targets"))
1603                 with_targets= 1;
1604         
1605         return constraint_add_exec(C, op, ob, get_active_constraints(ob), type, with_targets);
1606 }
1607
1608 /* ------------------ */
1609
1610 void OBJECT_OT_constraint_add(wmOperatorType *ot)
1611 {
1612         /* identifiers */
1613         ot->name= "Add Constraint";
1614         ot->description = "Add a constraint to the active object";
1615         ot->idname= "OBJECT_OT_constraint_add";
1616         
1617         /* api callbacks */
1618         ot->invoke= WM_menu_invoke;
1619         ot->exec= object_constraint_add_exec;
1620         ot->poll= ED_operator_object_active_editable;
1621         
1622         /* flags */
1623         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1624         
1625         /* properties */
1626         ot->prop= RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1627 }
1628
1629 void OBJECT_OT_constraint_add_with_targets(wmOperatorType *ot)
1630 {
1631         /* identifiers */
1632         ot->name= "Add Constraint (with Targets)";
1633         ot->description = "Add a constraint to the active object, with target (where applicable) set to the selected Objects/Bones";
1634         ot->idname= "OBJECT_OT_constraint_add_with_targets";
1635         
1636         /* api callbacks */
1637         ot->invoke= WM_menu_invoke;
1638         ot->exec= object_constraint_add_exec;
1639         ot->poll= ED_operator_object_active_editable;
1640         
1641         /* flags */
1642         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1643         
1644         /* properties */
1645         ot->prop= RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1646 }
1647
1648 void POSE_OT_constraint_add(wmOperatorType *ot)
1649 {
1650         /* identifiers */
1651         ot->name= "Add Constraint";
1652         ot->description = "Add a constraint to the active bone";
1653         ot->idname= "POSE_OT_constraint_add";
1654         
1655         /* api callbacks */
1656         ot->invoke= WM_menu_invoke;
1657         ot->exec= pose_constraint_add_exec;
1658         ot->poll= ED_operator_posemode;
1659         
1660         /* flags */
1661         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1662         
1663         /* properties */
1664         ot->prop= RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1665 }
1666
1667 void POSE_OT_constraint_add_with_targets(wmOperatorType *ot)
1668 {
1669         /* identifiers */
1670         ot->name= "Add Constraint (with Targets)";
1671         ot->description = "Add a constraint to the active bone, with target (where applicable) set to the selected Objects/Bones";
1672         ot->idname= "POSE_OT_constraint_add_with_targets";
1673         
1674         /* api callbacks */
1675         ot->invoke= WM_menu_invoke;
1676         ot->exec= pose_constraint_add_exec;
1677         ot->poll= ED_operator_posemode;
1678         
1679         /* flags */
1680         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1681         
1682         /* properties */
1683         ot->prop= RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1684 }
1685
1686 /************************ IK Constraint operators *********************/
1687 /* NOTE: only for Pose-Channels */
1688 // TODO: should these be here, or back in editors/armature/poseobject.c again?
1689
1690 /* present menu with options + validation for targets to use */
1691 static int pose_ik_add_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(evt))
1692 {
1693         Object *ob= object_pose_armature_get(CTX_data_active_object(C));
1694         bPoseChannel *pchan= get_active_posechannel(ob);
1695         bConstraint *con= NULL;
1696         
1697         uiPopupMenu *pup;
1698         uiLayout *layout;
1699         Object *tar_ob= NULL;
1700         bPoseChannel *tar_pchan= NULL;
1701         
1702         /* must have active bone */
1703         if (ELEM(NULL, ob, pchan)) {
1704                 BKE_report(op->reports, RPT_ERROR, "Must have active bone to add IK Constraint to");
1705                 return OPERATOR_CANCELLED;
1706         }
1707         
1708         /* bone must not have any constraints already */
1709         for (con= pchan->constraints.first; con; con= con->next) {
1710                 if (con->type==CONSTRAINT_TYPE_KINEMATIC) break;
1711         }
1712         if (con) {
1713                 BKE_report(op->reports, RPT_ERROR, "Bone already has IK Constraint");
1714                 return OPERATOR_CANCELLED;
1715         }
1716         
1717         /* prepare popup menu to choose targetting options */
1718         pup= uiPupMenuBegin(C, "Add IK", ICON_NONE);
1719         layout= uiPupMenuLayout(pup);
1720         
1721         /* the type of targets we'll set determines the menu entries to show... */
1722         if (get_new_constraint_target(C, CONSTRAINT_TYPE_KINEMATIC, &tar_ob, &tar_pchan, 0)) {
1723                 /* bone target, or object target? 
1724                  *      - the only thing that matters is that we want a target...
1725                  */
1726                 if (tar_pchan)
1727                         uiItemBooleanO(layout, "To Active Bone", ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1728                 else
1729                         uiItemBooleanO(layout, "To Active Object", ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1730         }
1731         else {
1732                 /* we have a choice of adding to a new empty, or not setting any target (targetless IK) */
1733                 uiItemBooleanO(layout, "To New Empty Object", ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1734                 uiItemBooleanO(layout, "Without Targets", ICON_NONE, "POSE_OT_ik_add", "with_targets", 0);
1735         }
1736         
1737         /* finish building the menu, and process it (should result in calling self again) */
1738         uiPupMenuEnd(C, pup);
1739         
1740         return OPERATOR_CANCELLED;
1741 }
1742
1743 /* call constraint_add_exec() to add the IK constraint */
1744 static int pose_ik_add_exec(bContext *C, wmOperator *op)
1745 {
1746         Object *ob= CTX_data_active_object(C);
1747         int with_targets= RNA_boolean_get(op->ptr, "with_targets");
1748         
1749         /* add the constraint - all necessary checks should have been done by the invoke() callback already... */
1750         return constraint_add_exec(C, op, ob, get_active_constraints(ob), CONSTRAINT_TYPE_KINEMATIC, with_targets);
1751 }
1752
1753 void POSE_OT_ik_add(wmOperatorType *ot)
1754 {
1755         /* identifiers */
1756         ot->name= "Add IK to Bone";
1757         ot->description= "Add IK Constraint to the active Bone";
1758         ot->idname= "POSE_OT_ik_add";
1759         
1760         /* api callbacks */
1761         ot->invoke= pose_ik_add_invoke;
1762         ot->exec= pose_ik_add_exec;
1763         ot->poll= ED_operator_posemode;
1764         
1765         /* flags */
1766         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1767         
1768         /* properties */
1769         RNA_def_boolean(ot->srna, "with_targets", 1, "With Targets", "Assign IK Constraint with targets derived from the select bones/objects");
1770 }
1771
1772 /* ------------------ */
1773
1774 /* remove IK constraints from selected bones */
1775 static int pose_ik_clear_exec(bContext *C, wmOperator *UNUSED(op))
1776 {
1777         Object *ob= object_pose_armature_get(CTX_data_active_object(C));
1778         
1779         /* only remove IK Constraints */
1780         CTX_DATA_BEGIN(C, bPoseChannel*, pchan, selected_pose_bones) 
1781         {
1782                 bConstraint *con, *next;
1783                 
1784                 // TODO: should we be checking if these contraints were local before we try and remove them?
1785                 for (con= pchan->constraints.first; con; con= next) {
1786                         next= con->next;
1787                         if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
1788                                 remove_constraint(&pchan->constraints, con);
1789                         }
1790                 }
1791                 pchan->constflag &= ~(PCHAN_HAS_IK|PCHAN_HAS_TARGET);
1792         }
1793         CTX_DATA_END;
1794         
1795         /* refresh depsgraph */
1796         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1797
1798         /* note, notifier might evolve */
1799         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT|NA_REMOVED, ob);
1800         
1801         return OPERATOR_FINISHED;
1802 }
1803
1804 void POSE_OT_ik_clear(wmOperatorType *ot)
1805 {
1806         /* identifiers */
1807         ot->name= "Remove IK";
1808         ot->description= "Remove all IK Constraints from selected bones";
1809         ot->idname= "POSE_OT_ik_clear";
1810         
1811         /* api callbacks */
1812         ot->exec= pose_ik_clear_exec;
1813         ot->poll= ED_operator_posemode;
1814         
1815         /* flags */
1816         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1817 }
1818