Merged changes in the trunk up to revision 51718.
[blender.git] / source / blender / blenkernel / intern / 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): 2007, Joshua Leung, major recode
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/constraint.c
29  *  \ingroup bke
30  */
31
32
33 #include <stdio.h> 
34 #include <stddef.h>
35 #include <string.h>
36 #include <math.h>
37 #include <float.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "BLI_blenlib.h"
42 #include "BLI_math.h"
43 #include "BLI_kdopbvh.h"
44 #include "BLI_utildefines.h"
45
46 #include "DNA_armature_types.h"
47 #include "DNA_camera_types.h"
48 #include "DNA_constraint_types.h"
49 #include "DNA_modifier_types.h"
50 #include "DNA_object_types.h"
51 #include "DNA_action_types.h"
52 #include "DNA_curve_types.h"
53 #include "DNA_mesh_types.h"
54 #include "DNA_meshdata_types.h"
55
56 #include "DNA_lattice_types.h"
57 #include "DNA_scene_types.h"
58 #include "DNA_text_types.h"
59 #include "DNA_tracking_types.h"
60 #include "DNA_movieclip_types.h"
61
62
63 #include "BKE_action.h"
64 #include "BKE_anim.h" /* for the curve calculation part */
65 #include "BKE_armature.h"
66 #include "BKE_blender.h"
67 #include "BKE_bvhutils.h"
68 #include "BKE_camera.h"
69 #include "BKE_constraint.h"
70 #include "BKE_displist.h"
71 #include "BKE_deform.h"
72 #include "BKE_DerivedMesh.h"    /* for geometry targets */
73 #include "BKE_cdderivedmesh.h" /* for geometry targets */
74 #include "BKE_object.h"
75 #include "BKE_ipo.h"
76 #include "BKE_global.h"
77 #include "BKE_library.h"
78 #include "BKE_idprop.h"
79 #include "BKE_mesh.h"
80 #include "BKE_shrinkwrap.h"
81 #include "BKE_mesh.h"
82 #include "BKE_tessmesh.h"
83 #include "BKE_tracking.h"
84 #include "BKE_movieclip.h"
85
86 #ifdef WITH_PYTHON
87 #include "BPY_extern.h"
88 #endif
89
90 #ifndef M_PI
91 #define M_PI        3.14159265358979323846
92 #endif
93
94
95
96 /* ************************ Constraints - General Utilities *************************** */
97 /* These functions here don't act on any specific constraints, and are therefore should/will
98  * not require any of the special function-pointers afforded by the relevant constraint 
99  * type-info structs.
100  */
101
102 /* -------------- Naming -------------- */
103
104 /* Find the first available, non-duplicate name for a given constraint */
105 void unique_constraint_name(bConstraint *con, ListBase *list)
106 {
107         BLI_uniquename(list, con, "Const", '.', offsetof(bConstraint, name), sizeof(con->name));
108 }
109
110 /* ----------------- Evaluation Loop Preparation --------------- */
111
112 /* package an object/bone for use in constraint evaluation */
113 /* This function MEM_calloc's a bConstraintOb struct, that will need to be freed after evaluation */
114 bConstraintOb *constraints_make_evalob(Scene *scene, Object *ob, void *subdata, short datatype)
115 {
116         bConstraintOb *cob;
117         
118         /* create regardless of whether we have any data! */
119         cob = MEM_callocN(sizeof(bConstraintOb), "bConstraintOb");
120         
121         /* for system time, part of deglobalization, code nicer later with local time (ton) */
122         cob->scene = scene;
123         
124         /* based on type of available data */
125         switch (datatype) {
126                 case CONSTRAINT_OBTYPE_OBJECT:
127                 {
128                         /* disregard subdata... calloc should set other values right */
129                         if (ob) {
130                                 cob->ob = ob;
131                                 cob->type = datatype;
132                                 cob->rotOrder = EULER_ORDER_DEFAULT; // TODO: when objects have rotation order too, use that
133                                 copy_m4_m4(cob->matrix, ob->obmat);
134                         }
135                         else
136                                 unit_m4(cob->matrix);
137                         
138                         copy_m4_m4(cob->startmat, cob->matrix);
139                 }
140                 break;
141                 case CONSTRAINT_OBTYPE_BONE:
142                 {
143                         /* only set if we have valid bone, otherwise default */
144                         if (ob && subdata) {
145                                 cob->ob = ob;
146                                 cob->pchan = (bPoseChannel *)subdata;
147                                 cob->type = datatype;
148                                 
149                                 if (cob->pchan->rotmode > 0) {
150                                         /* should be some type of Euler order */
151                                         cob->rotOrder = cob->pchan->rotmode;
152                                 }
153                                 else {
154                                         /* Quats, so eulers should just use default order */
155                                         cob->rotOrder = EULER_ORDER_DEFAULT;
156                                 }
157                                 
158                                 /* matrix in world-space */
159                                 mult_m4_m4m4(cob->matrix, ob->obmat, cob->pchan->pose_mat);
160                         }
161                         else
162                                 unit_m4(cob->matrix);
163                                 
164                         copy_m4_m4(cob->startmat, cob->matrix);
165                 }
166                 break;
167                         
168                 default: /* other types not yet handled */
169                         unit_m4(cob->matrix);
170                         unit_m4(cob->startmat);
171                         break;
172         }
173         
174         return cob;
175 }
176
177 /* cleanup after constraint evaluation */
178 void constraints_clear_evalob(bConstraintOb *cob)
179 {
180         float delta[4][4], imat[4][4];
181         
182         /* prevent crashes */
183         if (cob == NULL) 
184                 return;
185         
186         /* calculate delta of constraints evaluation */
187         invert_m4_m4(imat, cob->startmat);
188         mult_m4_m4m4(delta, cob->matrix, imat);
189         
190         /* copy matrices back to source */
191         switch (cob->type) {
192                 case CONSTRAINT_OBTYPE_OBJECT:
193                 {
194                         /* cob->ob might not exist! */
195                         if (cob->ob) {
196                                 /* copy new ob-matrix back to owner */
197                                 copy_m4_m4(cob->ob->obmat, cob->matrix);
198                                 
199                                 /* copy inverse of delta back to owner */
200                                 invert_m4_m4(cob->ob->constinv, delta);
201                         }
202                 }
203                 break;
204                 case CONSTRAINT_OBTYPE_BONE:
205                 {
206                         /* cob->ob or cob->pchan might not exist */
207                         if (cob->ob && cob->pchan) {
208                                 /* copy new pose-matrix back to owner */
209                                 mult_m4_m4m4(cob->pchan->pose_mat, cob->ob->imat, cob->matrix);
210                                 
211                                 /* copy inverse of delta back to owner */
212                                 invert_m4_m4(cob->pchan->constinv, delta);
213                         }
214                 }
215                 break;
216         }
217         
218         /* free tempolary struct */
219         MEM_freeN(cob);
220 }
221
222 /* -------------- Space-Conversion API -------------- */
223
224 /* This function is responsible for the correct transformations/conversions 
225  * of a matrix from one space to another for constraint evaluation.
226  * For now, this is only implemented for Objects and PoseChannels.
227  */
228 void constraint_mat_convertspace(Object *ob, bPoseChannel *pchan, float mat[][4], short from, short to)
229 {
230         float diff_mat[4][4];
231         float imat[4][4];
232         
233         /* prevent crashes in these unlikely events  */
234         if (ob == NULL || mat == NULL) return;
235         /* optimize trick - check if need to do anything */
236         if (from == to) return;
237         
238         /* are we dealing with pose-channels or objects */
239         if (pchan) {
240                 /* pose channels */
241                 switch (from) {
242                         case CONSTRAINT_SPACE_WORLD: /* ---------- FROM WORLDSPACE ---------- */
243                         {
244                                 /* world to pose */
245                                 invert_m4_m4(imat, ob->obmat);
246                                 mult_m4_m4m4(mat, imat, mat);
247                                 
248                                 /* use pose-space as stepping stone for other spaces... */
249                                 if (ELEM(to, CONSTRAINT_SPACE_LOCAL, CONSTRAINT_SPACE_PARLOCAL)) {
250                                         /* call self with slightly different values */
251                                         constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
252                                 }
253                         }
254                         break;
255                         case CONSTRAINT_SPACE_POSE: /* ---------- FROM POSESPACE ---------- */
256                         {
257                                 /* pose to world */
258                                 if (to == CONSTRAINT_SPACE_WORLD) {
259                                         mult_m4_m4m4(mat, ob->obmat, mat);
260                                 }
261                                 /* pose to local */
262                                 else if (to == CONSTRAINT_SPACE_LOCAL) {
263                                         if (pchan->bone) {
264                                                 BKE_armature_mat_pose_to_bone(pchan, mat, mat);
265                                         }
266                                 }
267                                 /* pose to local with parent */
268                                 else if (to == CONSTRAINT_SPACE_PARLOCAL) {
269                                         if (pchan->bone) {
270                                                 invert_m4_m4(imat, pchan->bone->arm_mat);
271                                                 mult_m4_m4m4(mat, imat, mat);
272                                         }
273                                 }
274                         }
275                         break;
276                         case CONSTRAINT_SPACE_LOCAL: /* ------------ FROM LOCALSPACE --------- */
277                         {
278                                 /* local to pose - do inverse procedure that was done for pose to local */
279                                 if (pchan->bone) {
280                                         /* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */
281                                         BKE_armature_mat_bone_to_pose(pchan, mat, mat);
282                                 }
283                                 
284                                 /* use pose-space as stepping stone for other spaces */
285                                 if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_PARLOCAL)) {
286                                         /* call self with slightly different values */
287                                         constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
288                                 }
289                         }
290                         break;
291                         case CONSTRAINT_SPACE_PARLOCAL: /* -------------- FROM LOCAL WITH PARENT ---------- */
292                         {
293                                 /* local + parent to pose */
294                                 if (pchan->bone) {
295                                         copy_m4_m4(diff_mat, pchan->bone->arm_mat);
296                                         mult_m4_m4m4(mat, mat, diff_mat);
297                                 }
298                                 
299                                 /* use pose-space as stepping stone for other spaces */
300                                 if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL)) {
301                                         /* call self with slightly different values */
302                                         constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to);
303                                 }
304                         }
305                         break;
306                 }
307         }
308         else {
309                 /* objects */
310                 if (from == CONSTRAINT_SPACE_WORLD && to == CONSTRAINT_SPACE_LOCAL) {
311                         /* check if object has a parent */
312                         if (ob->parent) {
313                                 /* 'subtract' parent's effects from owner */
314                                 mult_m4_m4m4(diff_mat, ob->parent->obmat, ob->parentinv);
315                                 invert_m4_m4(imat, diff_mat);
316                                 mult_m4_m4m4(mat, imat, mat);
317                         }
318                         else {
319                                 /* Local space in this case will have to be defined as local to the owner's 
320                                  * transform-property-rotated axes. So subtract this rotation component.
321                                  */
322                                 BKE_object_to_mat4(ob, diff_mat);
323                                 normalize_m4(diff_mat);
324                                 zero_v3(diff_mat[3]);
325                                 
326                                 invert_m4_m4(imat, diff_mat);
327                                 mult_m4_m4m4(mat, imat, mat);
328                         }
329                 }
330                 else if (from == CONSTRAINT_SPACE_LOCAL && to == CONSTRAINT_SPACE_WORLD) {
331                         /* check that object has a parent - otherwise this won't work */
332                         if (ob->parent) {
333                                 /* 'add' parent's effect back to owner */
334                                 mult_m4_m4m4(diff_mat, ob->parent->obmat, ob->parentinv);
335                                 mult_m4_m4m4(mat, diff_mat, mat);
336                         }
337                         else {
338                                 /* Local space in this case will have to be defined as local to the owner's 
339                                  * transform-property-rotated axes. So add back this rotation component.
340                                  */
341                                 BKE_object_to_mat4(ob, diff_mat);
342                                 normalize_m4(diff_mat);
343                                 zero_v3(diff_mat[3]);
344                                 
345                                 mult_m4_m4m4(mat, diff_mat, mat);
346                         }
347                 }
348         }
349 }
350
351 /* ------------ General Target Matrix Tools ---------- */
352
353 /* function that sets the given matrix based on given vertex group in mesh */
354 static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[][4])
355 {
356         DerivedMesh *dm = NULL;
357         BMEditMesh *em = BMEdit_FromObject(ob);
358         float vec[3] = {0.0f, 0.0f, 0.0f};
359         float normal[3] = {0.0f, 0.0f, 0.0f}, plane[3];
360         float imat[3][3], tmat[3][3];
361         const int defgroup = defgroup_name_index(ob, substring);
362         short freeDM = 0;
363         
364         /* initialize target matrix using target matrix */
365         copy_m4_m4(mat, ob->obmat);
366         
367         /* get index of vertex group */
368         if (defgroup == -1) return;
369
370         /* get DerivedMesh */
371         if (em) {
372                 /* target is in editmode, so get a special derived mesh */
373                 dm = CDDM_from_editbmesh(em, FALSE, FALSE);
374                 freeDM = 1;
375         }
376         else {
377                 /* when not in EditMode, use the 'final' derived mesh, depsgraph
378                  * ensures we build with CD_MDEFORMVERT layer 
379                  */
380                 dm = (DerivedMesh *)ob->derivedFinal;
381         }
382         
383         /* only continue if there's a valid DerivedMesh */
384         if (dm) {
385                 MDeformVert *dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
386                 int numVerts = dm->getNumVerts(dm);
387                 int i, count = 0;
388                 float co[3], nor[3];
389                 
390                 /* check that dvert is a valid pointers (just in case) */
391                 if (dvert) {
392                         MDeformVert *dv = dvert;
393                         /* get the average of all verts with that are in the vertex-group */
394                         for (i = 0; i < numVerts; i++, dv++) {
395                                 MDeformWeight *dw = defvert_find_index(dv, defgroup);
396                                 if (dw && dw->weight != 0.0f) {
397                                         dm->getVertCo(dm, i, co);
398                                         dm->getVertNo(dm, i, nor);
399                                         add_v3_v3(vec, co);
400                                         add_v3_v3(normal, nor);
401                                         count++;
402                                         
403                                 }
404                         }
405
406                         /* calculate averages of normal and coordinates */
407                         if (count > 0) {
408                                 mul_v3_fl(vec, 1.0f / count);
409                                 mul_v3_fl(normal, 1.0f / count);
410                         }
411                         
412                         
413                         /* derive the rotation from the average normal: 
414                          *              - code taken from transform_manipulator.c, 
415                          *                      calc_manipulator_stats, V3D_MANIP_NORMAL case
416                          */
417                         /*      we need the transpose of the inverse for a normal... */
418                         copy_m3_m4(imat, ob->obmat);
419                         
420                         invert_m3_m3(tmat, imat);
421                         transpose_m3(tmat);
422                         mul_m3_v3(tmat, normal);
423                         
424                         normalize_v3(normal);
425                         copy_v3_v3(plane, tmat[1]);
426                         
427                         cross_v3_v3v3(mat[0], normal, plane);
428                         if (len_v3(mat[0]) < 1e-3f) {
429                                 copy_v3_v3(plane, tmat[0]);
430                                 cross_v3_v3v3(mat[0], normal, plane);
431                         }
432
433                         copy_v3_v3(mat[2], normal);
434                         cross_v3_v3v3(mat[1], mat[2], mat[0]);
435
436                         normalize_m4(mat);
437
438                         
439                         /* apply the average coordinate as the new location */
440                         mul_v3_m4v3(mat[3], ob->obmat, vec);
441                 }
442         }
443         
444         /* free temporary DerivedMesh created (in EditMode case) */
445         if (dm && freeDM)
446                 dm->release(dm);
447 }
448
449 /* function that sets the given matrix based on given vertex group in lattice */
450 static void contarget_get_lattice_mat(Object *ob, const char *substring, float mat[][4])
451 {
452         Lattice *lt = (Lattice *)ob->data;
453         
454         DispList *dl = BKE_displist_find(&ob->disp, DL_VERTS);
455         float *co = dl ? dl->verts : NULL;
456         BPoint *bp = lt->def;
457         
458         MDeformVert *dv = lt->dvert;
459         int tot_verts = lt->pntsu * lt->pntsv * lt->pntsw;
460         float vec[3] = {0.0f, 0.0f, 0.0f}, tvec[3];
461         int grouped = 0;
462         int i, n;
463         const int defgroup = defgroup_name_index(ob, substring);
464         
465         /* initialize target matrix using target matrix */
466         copy_m4_m4(mat, ob->obmat);
467
468         /* get index of vertex group */
469         if (defgroup == -1) return;
470         if (dv == NULL) return;
471         
472         /* 1. Loop through control-points checking if in nominated vertex-group.
473          * 2. If it is, add it to vec to find the average point.
474          */
475         for (i = 0; i < tot_verts; i++, dv++) {
476                 for (n = 0; n < dv->totweight; n++) {
477                         MDeformWeight *dw = defvert_find_index(dv, defgroup);
478                         if (dw && dw->weight > 0.0f) {
479                                 /* copy coordinates of point to temporary vector, then add to find average */
480                                 memcpy(tvec, co ? co : bp->vec, 3 * sizeof(float));
481
482                                 add_v3_v3(vec, tvec);
483                                 grouped++;
484                         }
485                 }
486                 
487                 /* advance pointer to coordinate data */
488                 if (co) co += 3;
489                 else bp++;
490         }
491         
492         /* find average location, then multiply by ob->obmat to find world-space location */
493         if (grouped)
494                 mul_v3_fl(vec, 1.0f / grouped);
495         mul_v3_m4v3(tvec, ob->obmat, vec);
496         
497         /* copy new location to matrix */
498         copy_v3_v3(mat[3], tvec);
499 }
500
501 /* generic function to get the appropriate matrix for most target cases */
502 /* The cases where the target can be object data have not been implemented */
503 static void constraint_target_to_mat4(Object *ob, const char *substring, float mat[][4], short from, short to, float headtail)
504 {
505         /*      Case OBJECT */
506         if (!strlen(substring)) {
507                 copy_m4_m4(mat, ob->obmat);
508                 constraint_mat_convertspace(ob, NULL, mat, from, to);
509         }
510         /*  Case VERTEXGROUP */
511         /* Current method just takes the average location of all the points in the
512          * VertexGroup, and uses that as the location value of the targets. Where 
513          * possible, the orientation will also be calculated, by calculating an
514          * 'average' vertex normal, and deriving the rotation from that.
515          *
516          * NOTE: EditMode is not currently supported, and will most likely remain that
517          *              way as constraints can only really affect things on object/bone level.
518          */
519         else if (ob->type == OB_MESH) {
520                 contarget_get_mesh_mat(ob, substring, mat);
521                 constraint_mat_convertspace(ob, NULL, mat, from, to);
522         }
523         else if (ob->type == OB_LATTICE) {
524                 contarget_get_lattice_mat(ob, substring, mat);
525                 constraint_mat_convertspace(ob, NULL, mat, from, to);
526         }
527         /*      Case BONE */
528         else {
529                 bPoseChannel *pchan;
530                 
531                 pchan = BKE_pose_channel_find_name(ob->pose, substring);
532                 if (pchan) {
533                         /* Multiply the PoseSpace accumulation/final matrix for this
534                          * PoseChannel by the Armature Object's Matrix to get a worldspace
535                          * matrix.
536                          */
537                         if (headtail < 0.000001f) {
538                                 /* skip length interpolation if set to head */
539                                 mult_m4_m4m4(mat, ob->obmat, pchan->pose_mat);
540                         }
541                         else {
542                                 float tempmat[4][4], loc[3];
543                                 
544                                 /* interpolate along length of bone */
545                                 interp_v3_v3v3(loc, pchan->pose_head, pchan->pose_tail, headtail);
546                                 
547                                 /* use interpolated distance for subtarget */
548                                 copy_m4_m4(tempmat, pchan->pose_mat);
549                                 copy_v3_v3(tempmat[3], loc);
550                                 
551                                 mult_m4_m4m4(mat, ob->obmat, tempmat);
552                         }
553                 }
554                 else
555                         copy_m4_m4(mat, ob->obmat);
556                         
557                 /* convert matrix space as required */
558                 constraint_mat_convertspace(ob, pchan, mat, from, to);
559         }
560 }
561
562 /* ************************* Specific Constraints ***************************** */
563 /* Each constraint defines a set of functions, which will be called at the appropriate
564  * times. In addition to this, each constraint should have a type-info struct, where
565  * its functions are attached for use. 
566  */
567  
568 /* Template for type-info data:
569  *  - make a copy of this when creating new constraints, and just change the functions
570  *    pointed to as necessary
571  *  - although the naming of functions doesn't matter, it would help for code
572  *    readability, to follow the same naming convention as is presented here
573  *  - any functions that a constraint doesn't need to define, don't define
574  *    for such cases, just use NULL 
575  *  - these should be defined after all the functions have been defined, so that
576  *    forward-definitions/prototypes don't need to be used!
577  *      - keep this copy #if-def'd so that future constraints can get based off this
578  */
579 #if 0
580 static bConstraintTypeInfo CTI_CONSTRNAME = {
581         CONSTRAINT_TYPE_CONSTRNAME, /* type */
582         sizeof(bConstrNameConstraint), /* size */
583         "ConstrName", /* name */
584         "bConstrNameConstraint", /* struct name */
585         constrname_free, /* free data */
586         constrname_id_looper, /* id looper */
587         constrname_copy, /* copy data */
588         constrname_new_data, /* new data */
589         constrname_get_tars, /* get constraint targets */
590         constrname_flush_tars, /* flush constraint targets */
591         constrname_get_tarmat, /* get target matrix */
592         constrname_evaluate /* evaluate */
593 };
594 #endif
595
596 /* This function should be used for the get_target_matrix member of all 
597  * constraints that are not picky about what happens to their target matrix.
598  */
599 static void default_get_tarmat(bConstraint *con, bConstraintOb *UNUSED(cob), bConstraintTarget *ct, float UNUSED(ctime))
600 {
601         if (VALID_CONS_TARGET(ct))
602                 constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->headtail);
603         else if (ct)
604                 unit_m4(ct->matrix);
605 }
606
607 /* This following macro should be used for all standard single-target *_get_tars functions 
608  * to save typing and reduce maintenance woes.
609  * (Hopefully all compilers will be happy with the lines with just a space on them. Those are
610  *  really just to help this code easier to read)
611  */
612 // TODO: cope with getting rotation order...
613 #define SINGLETARGET_GET_TARS(con, datatar, datasubtarget, ct, list) \
614         { \
615                 ct = MEM_callocN(sizeof(bConstraintTarget), "tempConstraintTarget"); \
616                  \
617                 ct->tar = datatar; \
618                 BLI_strncpy(ct->subtarget, datasubtarget, sizeof(ct->subtarget)); \
619                 ct->space = con->tarspace; \
620                 ct->flag = CONSTRAINT_TAR_TEMP; \
621                  \
622                 if (ct->tar) { \
623                         if ((ct->tar->type == OB_ARMATURE) && (ct->subtarget[0])) { \
624                                 bPoseChannel *pchan = BKE_pose_channel_find_name(ct->tar->pose, ct->subtarget); \
625                                 ct->type = CONSTRAINT_OBTYPE_BONE; \
626                                 ct->rotOrder = (pchan) ? (pchan->rotmode) : EULER_ORDER_DEFAULT; \
627                         } \
628                         else if (OB_TYPE_SUPPORT_VGROUP(ct->tar->type) && (ct->subtarget[0])) { \
629                                 ct->type = CONSTRAINT_OBTYPE_VERT; \
630                                 ct->rotOrder = EULER_ORDER_DEFAULT; \
631                         } \
632                         else { \
633                                 ct->type = CONSTRAINT_OBTYPE_OBJECT; \
634                                 ct->rotOrder = ct->tar->rotmode; \
635                         } \
636                 } \
637                  \
638                 BLI_addtail(list, ct); \
639         } (void)0
640         
641 /* This following macro should be used for all standard single-target *_get_tars functions 
642  * to save typing and reduce maintenance woes. It does not do the subtarget related operations
643  * (Hopefully all compilers will be happy with the lines with just a space on them. Those are
644  *  really just to help this code easier to read)
645  */
646 // TODO: cope with getting rotation order...
647 #define SINGLETARGETNS_GET_TARS(con, datatar, ct, list) \
648         { \
649                 ct = MEM_callocN(sizeof(bConstraintTarget), "tempConstraintTarget"); \
650                  \
651                 ct->tar = datatar; \
652                 ct->space = con->tarspace; \
653                 ct->flag = CONSTRAINT_TAR_TEMP; \
654                  \
655                 if (ct->tar) ct->type = CONSTRAINT_OBTYPE_OBJECT; \
656                  \
657                 BLI_addtail(list, ct); \
658         } (void)0
659
660 /* This following macro should be used for all standard single-target *_flush_tars functions
661  * to save typing and reduce maintenance woes.
662  * Note: the pointer to ct will be changed to point to the next in the list (as it gets removed)
663  * (Hopefully all compilers will be happy with the lines with just a space on them. Those are
664  *  really just to help this code easier to read)
665  */
666 #define SINGLETARGET_FLUSH_TARS(con, datatar, datasubtarget, ct, list, nocopy) \
667         { \
668                 if (ct) { \
669                         bConstraintTarget *ctn = ct->next; \
670                         if (nocopy == 0) { \
671                                 datatar = ct->tar; \
672                                 BLI_strncpy(datasubtarget, ct->subtarget, sizeof(datasubtarget)); \
673                                 con->tarspace = (char)ct->space; \
674                         } \
675                          \
676                         BLI_freelinkN(list, ct); \
677                         ct = ctn; \
678                 } \
679         } (void)0
680         
681 /* This following macro should be used for all standard single-target *_flush_tars functions
682  * to save typing and reduce maintenance woes. It does not do the subtarget related operations.
683  * Note: the pointer to ct will be changed to point to the next in the list (as it gets removed)
684  * (Hopefully all compilers will be happy with the lines with just a space on them. Those are
685  *  really just to help this code easier to read)
686  */
687 #define SINGLETARGETNS_FLUSH_TARS(con, datatar, ct, list, nocopy) \
688         { \
689                 if (ct) { \
690                         bConstraintTarget *ctn = ct->next; \
691                         if (nocopy == 0) { \
692                                 datatar = ct->tar; \
693                                 con->tarspace = (char)ct->space; \
694                         } \
695                          \
696                         BLI_freelinkN(list, ct); \
697                         ct = ctn; \
698                 } \
699         } (void)0
700  
701 /* --------- ChildOf Constraint ------------ */
702
703 static void childof_new_data(void *cdata)
704 {
705         bChildOfConstraint *data = (bChildOfConstraint *)cdata;
706         
707         data->flag = (CHILDOF_LOCX | CHILDOF_LOCY | CHILDOF_LOCZ |
708                       CHILDOF_ROTX | CHILDOF_ROTY | CHILDOF_ROTZ |
709                       CHILDOF_SIZEX | CHILDOF_SIZEY | CHILDOF_SIZEZ);
710         unit_m4(data->invmat);
711 }
712
713 static void childof_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
714 {
715         bChildOfConstraint *data = con->data;
716         
717         /* target only */
718         func(con, (ID **)&data->tar, FALSE, userdata);
719 }
720
721 static int childof_get_tars(bConstraint *con, ListBase *list)
722 {
723         if (con && list) {
724                 bChildOfConstraint *data = con->data;
725                 bConstraintTarget *ct;
726                 
727                 /* standard target-getting macro for single-target constraints */
728                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
729                 
730                 return 1;
731         }
732         
733         return 0;
734 }
735
736 static void childof_flush_tars(bConstraint *con, ListBase *list, short nocopy)
737 {
738         if (con && list) {
739                 bChildOfConstraint *data = con->data;
740                 bConstraintTarget *ct = list->first;
741                 
742                 /* the following macro is used for all standard single-target constraints */
743                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy);
744         }
745 }
746
747 static void childof_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
748 {
749         bChildOfConstraint *data = con->data;
750         bConstraintTarget *ct = targets->first;
751
752         /* only evaluate if there is a target */
753         if (VALID_CONS_TARGET(ct)) {
754                 float parmat[4][4];
755                 
756                 /* simple matrix parenting */
757                 if (data->flag == CHILDOF_ALL) {
758                         
759                         /* multiply target (parent matrix) by offset (parent inverse) to get 
760                          * the effect of the parent that will be exerted on the owner
761                          */
762                         mult_m4_m4m4(parmat, ct->matrix, data->invmat);
763                         
764                         /* now multiply the parent matrix by the owner matrix to get the 
765                          * the effect of this constraint (i.e. owner is 'parented' to parent)
766                          */
767                         mult_m4_m4m4(cob->matrix, parmat, cob->matrix);
768                 }
769                 else {
770                         float invmat[4][4], tempmat[4][4];
771                         float loc[3], eul[3], size[3];
772                         float loco[3], eulo[3], sizo[3];
773                         
774                         /* get offset (parent-inverse) matrix */
775                         copy_m4_m4(invmat, data->invmat);
776                         
777                         /* extract components of both matrices */
778                         copy_v3_v3(loc, ct->matrix[3]);
779                         mat4_to_eulO(eul, ct->rotOrder, ct->matrix);
780                         mat4_to_size(size, ct->matrix);
781                         
782                         copy_v3_v3(loco, invmat[3]);
783                         mat4_to_eulO(eulo, cob->rotOrder, invmat);
784                         mat4_to_size(sizo, invmat);
785                         
786                         /* disable channels not enabled */
787                         if (!(data->flag & CHILDOF_LOCX)) loc[0] = loco[0] = 0.0f;
788                         if (!(data->flag & CHILDOF_LOCY)) loc[1] = loco[1] = 0.0f;
789                         if (!(data->flag & CHILDOF_LOCZ)) loc[2] = loco[2] = 0.0f;
790                         if (!(data->flag & CHILDOF_ROTX)) eul[0] = eulo[0] = 0.0f;
791                         if (!(data->flag & CHILDOF_ROTY)) eul[1] = eulo[1] = 0.0f;
792                         if (!(data->flag & CHILDOF_ROTZ)) eul[2] = eulo[2] = 0.0f;
793                         if (!(data->flag & CHILDOF_SIZEX)) size[0] = sizo[0] = 1.0f;
794                         if (!(data->flag & CHILDOF_SIZEY)) size[1] = sizo[1] = 1.0f;
795                         if (!(data->flag & CHILDOF_SIZEZ)) size[2] = sizo[2] = 1.0f;
796                         
797                         /* make new target mat and offset mat */
798                         loc_eulO_size_to_mat4(ct->matrix, loc, eul, size, ct->rotOrder);
799                         loc_eulO_size_to_mat4(invmat, loco, eulo, sizo, cob->rotOrder);
800                         
801                         /* multiply target (parent matrix) by offset (parent inverse) to get 
802                          * the effect of the parent that will be exerted on the owner
803                          */
804                         mult_m4_m4m4(parmat, ct->matrix, invmat);
805                         
806                         /* now multiply the parent matrix by the owner matrix to get the 
807                          * the effect of this constraint (i.e.  owner is 'parented' to parent)
808                          */
809                         copy_m4_m4(tempmat, cob->matrix);
810                         mult_m4_m4m4(cob->matrix, parmat, tempmat);
811                         
812                         /* without this, changes to scale and rotation can change location
813                          * of a parentless bone or a disconnected bone. Even though its set
814                          * to zero above. */
815                         if (!(data->flag & CHILDOF_LOCX)) cob->matrix[3][0] = tempmat[3][0];
816                         if (!(data->flag & CHILDOF_LOCY)) cob->matrix[3][1] = tempmat[3][1];
817                         if (!(data->flag & CHILDOF_LOCZ)) cob->matrix[3][2] = tempmat[3][2];
818                 }
819         }
820 }
821
822 /* XXX note, con->flag should be CONSTRAINT_SPACEONCE for bone-childof, patched in readfile.c */
823 static bConstraintTypeInfo CTI_CHILDOF = {
824         CONSTRAINT_TYPE_CHILDOF, /* type */
825         sizeof(bChildOfConstraint), /* size */
826         "ChildOf", /* name */
827         "bChildOfConstraint", /* struct name */
828         NULL, /* free data */
829         childof_id_looper, /* id looper */
830         NULL, /* copy data */
831         childof_new_data, /* new data */
832         childof_get_tars, /* get constraint targets */
833         childof_flush_tars, /* flush constraint targets */
834         default_get_tarmat, /* get a target matrix */
835         childof_evaluate /* evaluate */
836 };
837
838 /* -------- TrackTo Constraint ------- */
839
840 static void trackto_new_data(void *cdata)
841 {
842         bTrackToConstraint *data = (bTrackToConstraint *)cdata;
843         
844         data->reserved1 = TRACK_Y;
845         data->reserved2 = UP_Z;
846 }       
847
848 static void trackto_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
849 {
850         bTrackToConstraint *data = con->data;
851         
852         /* target only */
853         func(con, (ID **)&data->tar, FALSE, userdata);
854 }
855
856 static int trackto_get_tars(bConstraint *con, ListBase *list)
857 {
858         if (con && list) {
859                 bTrackToConstraint *data = con->data;
860                 bConstraintTarget *ct;
861                 
862                 /* standard target-getting macro for single-target constraints */
863                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
864                 
865                 return 1;
866         }
867         
868         return 0;
869 }
870
871 static void trackto_flush_tars(bConstraint *con, ListBase *list, short nocopy)
872 {
873         if (con && list) {
874                 bTrackToConstraint *data = con->data;
875                 bConstraintTarget *ct = list->first;
876                 
877                 /* the following macro is used for all standard single-target constraints */
878                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy);
879         }
880 }
881
882
883 static int basis_cross(int n, int m)
884 {
885         switch (n - m) {
886                 case 1: 
887                 case -2:
888                         return 1;
889                         
890                 case -1: 
891                 case 2:
892                         return -1;
893                         
894                 default:
895                         return 0;
896         }
897 }
898
899 static void vectomat(const float vec[3], const float target_up[3], short axis, short upflag, short flags, float m[][3])
900 {
901         float n[3];
902         float u[3]; /* vector specifying the up axis */
903         float proj[3];
904         float right[3];
905         float neg = -1;
906         int right_index;
907
908         if (normalize_v3_v3(n, vec) == 0.0f) {
909                 n[0] = 0.0f;
910                 n[1] = 0.0f;
911                 n[2] = 1.0f;
912         }
913         if (axis > 2) axis -= 3;
914         else negate_v3(n);
915
916         /* n specifies the transformation of the track axis */
917         if (flags & TARGET_Z_UP) {
918                 /* target Z axis is the global up axis */
919                 copy_v3_v3(u, target_up);
920         }
921         else {
922                 /* world Z axis is the global up axis */
923                 u[0] = 0;
924                 u[1] = 0;
925                 u[2] = 1;
926         }
927
928         /* project the up vector onto the plane specified by n */
929         project_v3_v3v3(proj, u, n); /* first u onto n... */
930         sub_v3_v3v3(proj, u, proj); /* then onto the plane */
931         /* proj specifies the transformation of the up axis */
932
933         if (normalize_v3(proj) == 0.0f) { /* degenerate projection */
934                 proj[0] = 0.0f;
935                 proj[1] = 1.0f;
936                 proj[2] = 0.0f;
937         }
938
939         /* Normalized cross product of n and proj specifies transformation of the right axis */
940         cross_v3_v3v3(right, proj, n);
941         normalize_v3(right);
942
943         if (axis != upflag) {
944                 right_index = 3 - axis - upflag;
945                 neg = (float)basis_cross(axis, upflag);
946                 
947                 /* account for up direction, track direction */
948                 m[right_index][0] = neg * right[0];
949                 m[right_index][1] = neg * right[1];
950                 m[right_index][2] = neg * right[2];
951                 
952                 copy_v3_v3(m[upflag], proj);
953                 
954                 copy_v3_v3(m[axis], n);
955         }
956         /* identity matrix - don't do anything if the two axes are the same */
957         else {
958                 unit_m3(m);
959         }
960 }
961
962
963 static void trackto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
964 {
965         bTrackToConstraint *data = con->data;
966         bConstraintTarget *ct = targets->first;
967         
968         if (VALID_CONS_TARGET(ct)) {
969                 float size[3], vec[3];
970                 float totmat[3][3];
971                 
972                 /* Get size property, since ob->size is only the object's own relative size, not its global one */
973                 mat4_to_size(size, cob->matrix);
974                 
975                 /* Clear the object's rotation */
976                 cob->matrix[0][0] = size[0];
977                 cob->matrix[0][1] = 0;
978                 cob->matrix[0][2] = 0;
979                 cob->matrix[1][0] = 0;
980                 cob->matrix[1][1] = size[1];
981                 cob->matrix[1][2] = 0;
982                 cob->matrix[2][0] = 0;
983                 cob->matrix[2][1] = 0;
984                 cob->matrix[2][2] = size[2];
985                 
986                 /* targetmat[2] instead of ownermat[2] is passed to vectomat
987                  * for backwards compatibility it seems... (Aligorith)
988                  */
989                 sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);
990                 vectomat(vec, ct->matrix[2], 
991                          (short)data->reserved1, (short)data->reserved2,
992                          data->flags, totmat);
993
994                 mul_m4_m3m4(cob->matrix, totmat, cob->matrix);
995         }
996 }
997
998 static bConstraintTypeInfo CTI_TRACKTO = {
999         CONSTRAINT_TYPE_TRACKTO, /* type */
1000         sizeof(bTrackToConstraint), /* size */
1001         "TrackTo", /* name */
1002         "bTrackToConstraint", /* struct name */
1003         NULL, /* free data */
1004         trackto_id_looper, /* id looper */
1005         NULL, /* copy data */
1006         trackto_new_data, /* new data */
1007         trackto_get_tars, /* get constraint targets */
1008         trackto_flush_tars, /* flush constraint targets */
1009         default_get_tarmat, /* get target matrix */
1010         trackto_evaluate /* evaluate */
1011 };
1012
1013 /* --------- Inverse-Kinemetics --------- */
1014
1015 static void kinematic_new_data(void *cdata)
1016 {
1017         bKinematicConstraint *data = (bKinematicConstraint *)cdata;
1018         
1019         data->weight = 1.0f;
1020         data->orientweight = 1.0f;
1021         data->iterations = 500;
1022         data->dist = 1.0f;
1023         data->flag = CONSTRAINT_IK_TIP | CONSTRAINT_IK_STRETCH | CONSTRAINT_IK_POS;
1024 }
1025
1026 static void kinematic_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1027 {
1028         bKinematicConstraint *data = con->data;
1029         
1030         /* chain target */
1031         func(con, (ID **)&data->tar, FALSE, userdata);
1032         
1033         /* poletarget */
1034         func(con, (ID **)&data->poletar, FALSE, userdata);
1035 }
1036
1037 static int kinematic_get_tars(bConstraint *con, ListBase *list)
1038 {
1039         if (con && list) {
1040                 bKinematicConstraint *data = con->data;
1041                 bConstraintTarget *ct;
1042                 
1043                 /* standard target-getting macro for single-target constraints is used twice here */
1044                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1045                 SINGLETARGET_GET_TARS(con, data->poletar, data->polesubtarget, ct, list);
1046                 
1047                 return 2;
1048         }
1049         
1050         return 0;
1051 }
1052
1053 static void kinematic_flush_tars(bConstraint *con, ListBase *list, short nocopy)
1054 {
1055         if (con && list) {
1056                 bKinematicConstraint *data = con->data;
1057                 bConstraintTarget *ct = list->first;
1058                 
1059                 /* the following macro is used for all standard single-target constraints */
1060                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy);
1061                 SINGLETARGET_FLUSH_TARS(con, data->poletar, data->polesubtarget, ct, list, nocopy);
1062         }
1063 }
1064
1065 static void kinematic_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
1066 {
1067         bKinematicConstraint *data = con->data;
1068         
1069         if (VALID_CONS_TARGET(ct)) 
1070                 constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->headtail);
1071         else if (ct) {
1072                 if (data->flag & CONSTRAINT_IK_AUTO) {
1073                         Object *ob = cob->ob;
1074                         
1075                         if (ob == NULL) {
1076                                 unit_m4(ct->matrix);
1077                         }
1078                         else {
1079                                 float vec[3];
1080                                 /* move grabtarget into world space */
1081                                 mul_v3_m4v3(vec, ob->obmat, data->grabtarget);
1082                                 copy_m4_m4(ct->matrix, ob->obmat);
1083                                 copy_v3_v3(ct->matrix[3], vec);
1084                         }
1085                 }
1086                 else
1087                         unit_m4(ct->matrix);
1088         }
1089 }
1090
1091 static bConstraintTypeInfo CTI_KINEMATIC = {
1092         CONSTRAINT_TYPE_KINEMATIC, /* type */
1093         sizeof(bKinematicConstraint), /* size */
1094         "IK", /* name */
1095         "bKinematicConstraint", /* struct name */
1096         NULL, /* free data */
1097         kinematic_id_looper, /* id looper */
1098         NULL, /* copy data */
1099         kinematic_new_data, /* new data */
1100         kinematic_get_tars, /* get constraint targets */
1101         kinematic_flush_tars, /* flush constraint targets */
1102         kinematic_get_tarmat, /* get target matrix */
1103         NULL /* evaluate - solved as separate loop */
1104 };
1105
1106 /* -------- Follow-Path Constraint ---------- */
1107
1108 static void followpath_new_data(void *cdata)
1109 {
1110         bFollowPathConstraint *data = (bFollowPathConstraint *)cdata;
1111         
1112         data->trackflag = TRACK_Y;
1113         data->upflag = UP_Z;
1114         data->offset = 0;
1115         data->followflag = 0;
1116 }
1117
1118 static void followpath_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1119 {
1120         bFollowPathConstraint *data = con->data;
1121         
1122         /* target only */
1123         func(con, (ID **)&data->tar, FALSE, userdata);
1124 }
1125
1126 static int followpath_get_tars(bConstraint *con, ListBase *list)
1127 {
1128         if (con && list) {
1129                 bFollowPathConstraint *data = con->data;
1130                 bConstraintTarget *ct;
1131                 
1132                 /* standard target-getting macro for single-target constraints without subtargets */
1133                 SINGLETARGETNS_GET_TARS(con, data->tar, ct, list);
1134                 
1135                 return 1;
1136         }
1137         
1138         return 0;
1139 }
1140
1141 static void followpath_flush_tars(bConstraint *con, ListBase *list, short nocopy)
1142 {
1143         if (con && list) {
1144                 bFollowPathConstraint *data = con->data;
1145                 bConstraintTarget *ct = list->first;
1146                 
1147                 /* the following macro is used for all standard single-target constraints */
1148                 SINGLETARGETNS_FLUSH_TARS(con, data->tar, ct, list, nocopy);
1149         }
1150 }
1151
1152 static void followpath_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
1153 {
1154         bFollowPathConstraint *data = con->data;
1155         
1156         if (VALID_CONS_TARGET(ct)) {
1157                 Curve *cu = ct->tar->data;
1158                 float vec[4], dir[3], radius;
1159                 float totmat[4][4] = MAT4_UNITY;
1160                 float curvetime;
1161
1162                 unit_m4(ct->matrix);
1163
1164                 /* note: when creating constraints that follow path, the curve gets the CU_PATH set now,
1165                  *              currently for paths to work it needs to go through the bevlist/displist system (ton) 
1166                  */
1167                 
1168                 /* only happens on reload file, but violates depsgraph still... fix! */
1169                 if (cu->path == NULL || cu->path->data == NULL)
1170                         BKE_displist_make_curveTypes(cob->scene, ct->tar, 0);
1171                 
1172                 if (cu->path && cu->path->data) {
1173                         float quat[4];
1174                         if ((data->followflag & FOLLOWPATH_STATIC) == 0) {
1175                                 /* animated position along curve depending on time */
1176                                 Nurb *nu = cu->nurb.first;
1177                                 curvetime = cu->ctime - data->offset;
1178                                 
1179                                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1180                                  * but this will only work if it actually is animated... 
1181                                  *
1182                                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1183                                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1184                                  */
1185                                 curvetime /= cu->pathlen;
1186
1187                                 if (nu && nu->flagu & CU_NURB_CYCLIC) {
1188                                         /* If the curve is cyclic, enable looping around if the time is
1189                                          * outside the bounds 0..1 */
1190                                         if ((curvetime < 0.0f) || (curvetime > 1.0f)) {
1191                                                 curvetime -= floorf(curvetime);
1192                                         }
1193                                 }
1194                                 else {
1195                                         /* The curve is not cyclic, so clamp to the begin/end points. */
1196                                         CLAMP(curvetime, 0.0f, 1.0f);
1197                                 }
1198                         }
1199                         else {
1200                                 /* fixed position along curve */
1201                                 curvetime = data->offset_fac;
1202                         }
1203                         
1204                         if (where_on_path(ct->tar, curvetime, vec, dir, (data->followflag & FOLLOWPATH_FOLLOW) ? quat : NULL, &radius, NULL) ) {  /* quat_pt is quat or NULL*/
1205                                 if (data->followflag & FOLLOWPATH_FOLLOW) {
1206 #if 0
1207                                         float x1, q[4];
1208                                         vec_to_quat(quat, dir, (short)data->trackflag, (short)data->upflag);
1209                                         
1210                                         normalize_v3(dir);
1211                                         q[0] = (float)cos(0.5 * vec[3]);
1212                                         x1 = (float)sin(0.5 * vec[3]);
1213                                         q[1] = -x1 * dir[0];
1214                                         q[2] = -x1 * dir[1];
1215                                         q[3] = -x1 * dir[2];
1216                                         mul_qt_qtqt(quat, q, quat);
1217 #else
1218                                         quat_apply_track(quat, data->trackflag, data->upflag);
1219 #endif
1220
1221                                         quat_to_mat4(totmat, quat);
1222                                 }
1223
1224                                 if (data->followflag & FOLLOWPATH_RADIUS) {
1225                                         float tmat[4][4], rmat[4][4];
1226                                         scale_m4_fl(tmat, radius);
1227                                         mult_m4_m4m4(rmat, tmat, totmat);
1228                                         copy_m4_m4(totmat, rmat);
1229                                 }
1230                                 
1231                                 copy_v3_v3(totmat[3], vec);
1232                                 
1233                                 mul_serie_m4(ct->matrix, ct->tar->obmat, totmat, NULL, NULL, NULL, NULL, NULL, NULL);
1234                         }
1235                 }
1236         }
1237         else if (ct)
1238                 unit_m4(ct->matrix);
1239 }
1240
1241 static void followpath_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1242 {
1243         bConstraintTarget *ct = targets->first;
1244         
1245         /* only evaluate if there is a target */
1246         if (VALID_CONS_TARGET(ct)) {
1247                 float obmat[4][4];
1248                 float size[3];
1249                 bFollowPathConstraint *data = con->data;
1250                 
1251                 /* get Object transform (loc/rot/size) to determine transformation from path */
1252                 /* TODO: this used to be local at one point, but is probably more useful as-is */
1253                 copy_m4_m4(obmat, cob->matrix);
1254                 
1255                 /* get scaling of object before applying constraint */
1256                 mat4_to_size(size, cob->matrix);
1257                 
1258                 /* apply targetmat - containing location on path, and rotation */
1259                 mul_serie_m4(cob->matrix, ct->matrix, obmat, NULL, NULL, NULL, NULL, NULL, NULL);
1260                 
1261                 /* un-apply scaling caused by path */
1262                 if ((data->followflag & FOLLOWPATH_RADIUS) == 0) { /* XXX - assume that scale correction means that radius will have some scale error in it - Campbell */
1263                         float obsize[3];
1264                         
1265                         mat4_to_size(obsize, cob->matrix);
1266                         if (obsize[0])
1267                                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1268                         if (obsize[1])
1269                                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1270                         if (obsize[2])
1271                                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1272                 }
1273         }
1274 }
1275
1276 static bConstraintTypeInfo CTI_FOLLOWPATH = {
1277         CONSTRAINT_TYPE_FOLLOWPATH, /* type */
1278         sizeof(bFollowPathConstraint), /* size */
1279         "Follow Path", /* name */
1280         "bFollowPathConstraint", /* struct name */
1281         NULL, /* free data */
1282         followpath_id_looper, /* id looper */
1283         NULL, /* copy data */
1284         followpath_new_data, /* new data */
1285         followpath_get_tars, /* get constraint targets */
1286         followpath_flush_tars, /* flush constraint targets */
1287         followpath_get_tarmat, /* get target matrix */
1288         followpath_evaluate /* evaluate */
1289 };
1290
1291 /* --------- Limit Location --------- */
1292
1293
1294 static void loclimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1295 {
1296         bLocLimitConstraint *data = con->data;
1297         
1298         if (data->flag & LIMIT_XMIN) {
1299                 if (cob->matrix[3][0] < data->xmin)
1300                         cob->matrix[3][0] = data->xmin;
1301         }
1302         if (data->flag & LIMIT_XMAX) {
1303                 if (cob->matrix[3][0] > data->xmax)
1304                         cob->matrix[3][0] = data->xmax;
1305         }
1306         if (data->flag & LIMIT_YMIN) {
1307                 if (cob->matrix[3][1] < data->ymin)
1308                         cob->matrix[3][1] = data->ymin;
1309         }
1310         if (data->flag & LIMIT_YMAX) {
1311                 if (cob->matrix[3][1] > data->ymax)
1312                         cob->matrix[3][1] = data->ymax;
1313         }
1314         if (data->flag & LIMIT_ZMIN) {
1315                 if (cob->matrix[3][2] < data->zmin) 
1316                         cob->matrix[3][2] = data->zmin;
1317         }
1318         if (data->flag & LIMIT_ZMAX) {
1319                 if (cob->matrix[3][2] > data->zmax)
1320                         cob->matrix[3][2] = data->zmax;
1321         }
1322 }
1323
1324 static bConstraintTypeInfo CTI_LOCLIMIT = {
1325         CONSTRAINT_TYPE_LOCLIMIT, /* type */
1326         sizeof(bLocLimitConstraint), /* size */
1327         "Limit Location", /* name */
1328         "bLocLimitConstraint", /* struct name */
1329         NULL, /* free data */
1330         NULL, /* id looper */
1331         NULL, /* copy data */
1332         NULL, /* new data */
1333         NULL, /* get constraint targets */
1334         NULL, /* flush constraint targets */
1335         NULL, /* get target matrix */
1336         loclimit_evaluate /* evaluate */
1337 };
1338
1339 /* -------- Limit Rotation --------- */
1340
1341 static void rotlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1342 {
1343         bRotLimitConstraint *data = con->data;
1344         float loc[3];
1345         float eul[3];
1346         float size[3];
1347         
1348         copy_v3_v3(loc, cob->matrix[3]);
1349         mat4_to_size(size, cob->matrix);
1350
1351         mat4_to_eulO(eul, cob->rotOrder, cob->matrix);
1352
1353         /* constraint data uses radians internally */
1354         
1355         /* limiting of euler values... */
1356         if (data->flag & LIMIT_XROT) {
1357                 if (eul[0] < data->xmin) 
1358                         eul[0] = data->xmin;
1359                         
1360                 if (eul[0] > data->xmax)
1361                         eul[0] = data->xmax;
1362         }
1363         if (data->flag & LIMIT_YROT) {
1364                 if (eul[1] < data->ymin)
1365                         eul[1] = data->ymin;
1366                         
1367                 if (eul[1] > data->ymax)
1368                         eul[1] = data->ymax;
1369         }
1370         if (data->flag & LIMIT_ZROT) {
1371                 if (eul[2] < data->zmin)
1372                         eul[2] = data->zmin;
1373                         
1374                 if (eul[2] > data->zmax)
1375                         eul[2] = data->zmax;
1376         }
1377                 
1378         loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder);
1379 }
1380
1381 static bConstraintTypeInfo CTI_ROTLIMIT = {
1382         CONSTRAINT_TYPE_ROTLIMIT, /* type */
1383         sizeof(bRotLimitConstraint), /* size */
1384         "Limit Rotation", /* name */
1385         "bRotLimitConstraint", /* struct name */
1386         NULL, /* free data */
1387         NULL, /* id looper */
1388         NULL, /* copy data */
1389         NULL, /* new data */
1390         NULL, /* get constraint targets */
1391         NULL, /* flush constraint targets */
1392         NULL, /* get target matrix */
1393         rotlimit_evaluate /* evaluate */
1394 };
1395
1396 /* --------- Limit Scale --------- */
1397
1398
1399 static void sizelimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1400 {
1401         bSizeLimitConstraint *data = con->data;
1402         float obsize[3], size[3];
1403         
1404         mat4_to_size(size, cob->matrix);
1405         mat4_to_size(obsize, cob->matrix);
1406         
1407         if (data->flag & LIMIT_XMIN) {
1408                 if (size[0] < data->xmin) 
1409                         size[0] = data->xmin;
1410         }
1411         if (data->flag & LIMIT_XMAX) {
1412                 if (size[0] > data->xmax) 
1413                         size[0] = data->xmax;
1414         }
1415         if (data->flag & LIMIT_YMIN) {
1416                 if (size[1] < data->ymin) 
1417                         size[1] = data->ymin;
1418         }
1419         if (data->flag & LIMIT_YMAX) {
1420                 if (size[1] > data->ymax) 
1421                         size[1] = data->ymax;
1422         }
1423         if (data->flag & LIMIT_ZMIN) {
1424                 if (size[2] < data->zmin) 
1425                         size[2] = data->zmin;
1426         }
1427         if (data->flag & LIMIT_ZMAX) {
1428                 if (size[2] > data->zmax) 
1429                         size[2] = data->zmax;
1430         }
1431         
1432         if (obsize[0]) 
1433                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1434         if (obsize[1]) 
1435                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1436         if (obsize[2]) 
1437                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1438 }
1439
1440 static bConstraintTypeInfo CTI_SIZELIMIT = {
1441         CONSTRAINT_TYPE_SIZELIMIT, /* type */
1442         sizeof(bSizeLimitConstraint), /* size */
1443         "Limit Scale", /* name */
1444         "bSizeLimitConstraint", /* struct name */
1445         NULL, /* free data */
1446         NULL, /* id looper */
1447         NULL, /* copy data */
1448         NULL, /* new data */
1449         NULL, /* get constraint targets */
1450         NULL, /* flush constraint targets */
1451         NULL, /* get target matrix */
1452         sizelimit_evaluate /* evaluate */
1453 };
1454
1455 /* ----------- Copy Location ------------- */
1456
1457 static void loclike_new_data(void *cdata)
1458 {
1459         bLocateLikeConstraint *data = (bLocateLikeConstraint *)cdata;
1460         
1461         data->flag = LOCLIKE_X | LOCLIKE_Y | LOCLIKE_Z;
1462 }
1463
1464 static void loclike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1465 {
1466         bLocateLikeConstraint *data = con->data;
1467         
1468         /* target only */
1469         func(con, (ID **)&data->tar, FALSE, userdata);
1470 }
1471
1472 static int loclike_get_tars(bConstraint *con, ListBase *list)
1473 {
1474         if (con && list) {
1475                 bLocateLikeConstraint *data = con->data;
1476                 bConstraintTarget *ct;
1477                 
1478                 /* standard target-getting macro for single-target constraints */
1479                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1480                 
1481                 return 1;
1482         }
1483         
1484         return 0;
1485 }
1486
1487 static void loclike_flush_tars(bConstraint *con, ListBase *list, short nocopy)
1488 {
1489         if (con && list) {
1490                 bLocateLikeConstraint *data = con->data;
1491                 bConstraintTarget *ct = list->first;
1492                 
1493                 /* the following macro is used for all standard single-target constraints */
1494                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy);
1495         }
1496 }
1497
1498 static void loclike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1499 {
1500         bLocateLikeConstraint *data = con->data;
1501         bConstraintTarget *ct = targets->first;
1502         
1503         if (VALID_CONS_TARGET(ct)) {
1504                 float offset[3] = {0.0f, 0.0f, 0.0f};
1505                 
1506                 if (data->flag & LOCLIKE_OFFSET)
1507                         copy_v3_v3(offset, cob->matrix[3]);
1508                         
1509                 if (data->flag & LOCLIKE_X) {
1510                         cob->matrix[3][0] = ct->matrix[3][0];
1511                         
1512                         if (data->flag & LOCLIKE_X_INVERT) cob->matrix[3][0] *= -1;
1513                         cob->matrix[3][0] += offset[0];
1514                 }
1515                 if (data->flag & LOCLIKE_Y) {
1516                         cob->matrix[3][1] = ct->matrix[3][1];
1517                         
1518                         if (data->flag & LOCLIKE_Y_INVERT) cob->matrix[3][1] *= -1;
1519                         cob->matrix[3][1] += offset[1];
1520                 }
1521                 if (data->flag & LOCLIKE_Z) {
1522                         cob->matrix[3][2] = ct->matrix[3][2];
1523                         
1524                         if (data->flag & LOCLIKE_Z_INVERT) cob->matrix[3][2] *= -1;
1525                         cob->matrix[3][2] += offset[2];
1526                 }
1527         }
1528 }
1529
1530 static bConstraintTypeInfo CTI_LOCLIKE = {
1531         CONSTRAINT_TYPE_LOCLIKE, /* type */
1532         sizeof(bLocateLikeConstraint), /* size */
1533         "Copy Location", /* name */
1534         "bLocateLikeConstraint", /* struct name */
1535         NULL, /* free data */
1536         loclike_id_looper, /* id looper */
1537         NULL, /* copy data */
1538         loclike_new_data, /* new data */
1539         loclike_get_tars, /* get constraint targets */
1540         loclike_flush_tars, /* flush constraint targets */
1541         default_get_tarmat, /* get target matrix */
1542         loclike_evaluate /* evaluate */
1543 };
1544
1545 /* ----------- Copy Rotation ------------- */
1546
1547 static void rotlike_new_data(void *cdata)
1548 {
1549         bRotateLikeConstraint *data = (bRotateLikeConstraint *)cdata;
1550         
1551         data->flag = ROTLIKE_X | ROTLIKE_Y | ROTLIKE_Z;
1552 }
1553
1554 static void rotlike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1555 {
1556         bRotateLikeConstraint *data = con->data;
1557         
1558         /* target only */
1559         func(con, (ID **)&data->tar, FALSE, userdata);
1560 }
1561
1562 static int rotlike_get_tars(bConstraint *con, ListBase *list)
1563 {
1564         if (con && list) {
1565                 bRotateLikeConstraint *data = con->data;
1566                 bConstraintTarget *ct;
1567                 
1568                 /* standard target-getting macro for single-target constraints */
1569                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1570                 
1571                 return 1;
1572         }
1573         
1574         return 0;
1575 }
1576
1577 static void rotlike_flush_tars(bConstraint *con, ListBase *list, short nocopy)
1578 {
1579         if (con && list) {
1580                 bRotateLikeConstraint *data = con->data;
1581                 bConstraintTarget *ct = list->first;
1582                 
1583                 /* the following macro is used for all standard single-target constraints */
1584                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy);
1585         }
1586 }
1587
1588 static void rotlike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1589 {
1590         bRotateLikeConstraint *data = con->data;
1591         bConstraintTarget *ct = targets->first;
1592         
1593         if (VALID_CONS_TARGET(ct)) {
1594                 float loc[3];
1595                 float eul[3], obeul[3];
1596                 float size[3];
1597                 
1598                 copy_v3_v3(loc, cob->matrix[3]);
1599                 mat4_to_size(size, cob->matrix);
1600                 
1601                 /* to allow compatible rotations, must get both rotations in the order of the owner... */
1602                 mat4_to_eulO(obeul, cob->rotOrder, cob->matrix);
1603                 /* we must get compatible eulers from the beginning because some of them can be modified below (see bug #21875) */
1604                 mat4_to_compatible_eulO(eul, obeul, cob->rotOrder, ct->matrix);
1605                 
1606                 if ((data->flag & ROTLIKE_X) == 0)
1607                         eul[0] = obeul[0];
1608                 else {
1609                         if (data->flag & ROTLIKE_OFFSET)
1610                                 rotate_eulO(eul, cob->rotOrder, 'X', obeul[0]);
1611                         
1612                         if (data->flag & ROTLIKE_X_INVERT)
1613                                 eul[0] *= -1;
1614                 }
1615                 
1616                 if ((data->flag & ROTLIKE_Y) == 0)
1617                         eul[1] = obeul[1];
1618                 else {
1619                         if (data->flag & ROTLIKE_OFFSET)
1620                                 rotate_eulO(eul, cob->rotOrder, 'Y', obeul[1]);
1621                         
1622                         if (data->flag & ROTLIKE_Y_INVERT)
1623                                 eul[1] *= -1;
1624                 }
1625                 
1626                 if ((data->flag & ROTLIKE_Z) == 0)
1627                         eul[2] = obeul[2];
1628                 else {
1629                         if (data->flag & ROTLIKE_OFFSET)
1630                                 rotate_eulO(eul, cob->rotOrder, 'Z', obeul[2]);
1631                         
1632                         if (data->flag & ROTLIKE_Z_INVERT)
1633                                 eul[2] *= -1;
1634                 }
1635                 
1636                 /* good to make eulers compatible again, since we don't know how much they were changed above */
1637                 compatible_eul(eul, obeul);
1638                 loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder);
1639         }
1640 }
1641
1642 static bConstraintTypeInfo CTI_ROTLIKE = {
1643         CONSTRAINT_TYPE_ROTLIKE, /* type */
1644         sizeof(bRotateLikeConstraint), /* size */
1645         "Copy Rotation", /* name */
1646         "bRotateLikeConstraint", /* struct name */
1647         NULL, /* free data */
1648         rotlike_id_looper, /* id looper */
1649         NULL, /* copy data */
1650         rotlike_new_data, /* new data */
1651         rotlike_get_tars, /* get constraint targets */
1652         rotlike_flush_tars, /* flush constraint targets */
1653         default_get_tarmat, /* get target matrix */
1654         rotlike_evaluate /* evaluate */
1655 };
1656
1657 /* ---------- Copy Scale ---------- */
1658
1659 static void sizelike_new_data(void *cdata)
1660 {
1661         bSizeLikeConstraint *data = (bSizeLikeConstraint *)cdata;
1662         
1663         data->flag = SIZELIKE_X | SIZELIKE_Y | SIZELIKE_Z;
1664 }
1665
1666 static void sizelike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1667 {
1668         bSizeLikeConstraint *data = con->data;
1669         
1670         /* target only */
1671         func(con, (ID **)&data->tar, FALSE, userdata);
1672 }
1673
1674 static int sizelike_get_tars(bConstraint *con, ListBase *list)
1675 {
1676         if (con && list) {
1677                 bSizeLikeConstraint *data = con->data;
1678                 bConstraintTarget *ct;
1679                 
1680                 /* standard target-getting macro for single-target constraints */
1681                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1682                 
1683                 return 1;
1684         }
1685         
1686         return 0;
1687 }
1688
1689 static void sizelike_flush_tars(bConstraint *con, ListBase *list, short nocopy)
1690 {
1691         if (con && list) {
1692                 bSizeLikeConstraint *data = con->data;
1693                 bConstraintTarget *ct = list->first;
1694                 
1695                 /* the following macro is used for all standard single-target constraints */
1696                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy);
1697         }
1698 }
1699
1700 static void sizelike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1701 {
1702         bSizeLikeConstraint *data = con->data;
1703         bConstraintTarget *ct = targets->first;
1704         
1705         if (VALID_CONS_TARGET(ct)) {
1706                 float obsize[3], size[3];
1707                 
1708                 mat4_to_size(size, ct->matrix);
1709                 mat4_to_size(obsize, cob->matrix);
1710                 
1711                 if ((data->flag & SIZELIKE_X) && (obsize[0] != 0)) {
1712                         if (data->flag & SIZELIKE_OFFSET) {
1713                                 size[0] += (obsize[0] - 1.0f);
1714                                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1715                         }
1716                         else
1717                                 mul_v3_fl(cob->matrix[0], size[0] / obsize[0]);
1718                 }
1719                 if ((data->flag & SIZELIKE_Y) && (obsize[1] != 0)) {
1720                         if (data->flag & SIZELIKE_OFFSET) {
1721                                 size[1] += (obsize[1] - 1.0f);
1722                                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1723                         }
1724                         else
1725                                 mul_v3_fl(cob->matrix[1], size[1] / obsize[1]);
1726                 }
1727                 if ((data->flag & SIZELIKE_Z) && (obsize[2] != 0)) {
1728                         if (data->flag & SIZELIKE_OFFSET) {
1729                                 size[2] += (obsize[2] - 1.0f);
1730                                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1731                         }
1732                         else
1733                                 mul_v3_fl(cob->matrix[2], size[2] / obsize[2]);
1734                 }
1735         }
1736 }
1737
1738 static bConstraintTypeInfo CTI_SIZELIKE = {
1739         CONSTRAINT_TYPE_SIZELIKE, /* type */
1740         sizeof(bSizeLikeConstraint), /* size */
1741         "Copy Scale", /* name */
1742         "bSizeLikeConstraint", /* struct name */
1743         NULL, /* free data */
1744         sizelike_id_looper, /* id looper */
1745         NULL, /* copy data */
1746         sizelike_new_data, /* new data */
1747         sizelike_get_tars, /* get constraint targets */
1748         sizelike_flush_tars, /* flush constraint targets */
1749         default_get_tarmat, /* get target matrix */
1750         sizelike_evaluate /* evaluate */
1751 };
1752
1753 /* ----------- Copy Transforms ------------- */
1754
1755 static void translike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1756 {
1757         bTransLikeConstraint *data = con->data;
1758         
1759         /* target only */
1760         func(con, (ID **)&data->tar, FALSE, userdata);
1761 }
1762
1763 static int translike_get_tars(bConstraint *con, ListBase *list)
1764 {
1765         if (con && list) {
1766                 bTransLikeConstraint *data = con->data;
1767                 bConstraintTarget *ct;
1768                 
1769                 /* standard target-getting macro for single-target constraints */
1770                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
1771                 
1772                 return 1;
1773         }
1774         
1775         return 0;
1776 }
1777
1778 static void translike_flush_tars(bConstraint *con, ListBase *list, short nocopy)
1779 {
1780         if (con && list) {
1781                 bTransLikeConstraint *data = con->data;
1782                 bConstraintTarget *ct = list->first;
1783                 
1784                 /* the following macro is used for all standard single-target constraints */
1785                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy);
1786         }
1787 }
1788
1789 static void translike_evaluate(bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets)
1790 {
1791         bConstraintTarget *ct = targets->first;
1792         
1793         if (VALID_CONS_TARGET(ct)) {
1794                 /* just copy the entire transform matrix of the target */
1795                 copy_m4_m4(cob->matrix, ct->matrix);
1796         }
1797 }
1798
1799 static bConstraintTypeInfo CTI_TRANSLIKE = {
1800         CONSTRAINT_TYPE_TRANSLIKE, /* type */
1801         sizeof(bTransLikeConstraint), /* size */
1802         "Copy Transforms", /* name */
1803         "bTransLikeConstraint", /* struct name */
1804         NULL, /* free data */
1805         translike_id_looper, /* id looper */
1806         NULL, /* copy data */
1807         NULL, /* new data */
1808         translike_get_tars, /* get constraint targets */
1809         translike_flush_tars, /* flush constraint targets */
1810         default_get_tarmat, /* get target matrix */
1811         translike_evaluate /* evaluate */
1812 };
1813
1814 /* ---------- Maintain Volume ---------- */
1815
1816 static void samevolume_new_data(void *cdata)
1817 {
1818         bSameVolumeConstraint *data = (bSameVolumeConstraint *)cdata;
1819
1820         data->flag = SAMEVOL_Y;
1821         data->volume = 1.0f;
1822 }
1823
1824 static void samevolume_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets))
1825 {
1826         bSameVolumeConstraint *data = con->data;
1827
1828         float volume = data->volume;
1829         float fac = 1.0f;
1830         float obsize[3];
1831
1832         mat4_to_size(obsize, cob->matrix);
1833         
1834         /* calculate normalizing scale factor for non-essential values */
1835         if (obsize[data->flag] != 0) 
1836                 fac = sqrtf(volume / obsize[data->flag]) / obsize[data->flag];
1837         
1838         /* apply scaling factor to the channels not being kept */
1839         switch (data->flag) {
1840                 case SAMEVOL_X:
1841                         mul_v3_fl(cob->matrix[1], fac);
1842                         mul_v3_fl(cob->matrix[2], fac);
1843                         break;
1844                 case SAMEVOL_Y:
1845                         mul_v3_fl(cob->matrix[0], fac);
1846                         mul_v3_fl(cob->matrix[2], fac);
1847                         break;
1848                 case SAMEVOL_Z:
1849                         mul_v3_fl(cob->matrix[0], fac);
1850                         mul_v3_fl(cob->matrix[1], fac);
1851                         break;
1852         }
1853 }
1854
1855 static bConstraintTypeInfo CTI_SAMEVOL = {
1856         CONSTRAINT_TYPE_SAMEVOL, /* type */
1857         sizeof(bSameVolumeConstraint), /* size */
1858         "Maintain Volume", /* name */
1859         "bSameVolumeConstraint", /* struct name */
1860         NULL, /* free data */
1861         NULL, /* id looper */
1862         NULL, /* copy data */
1863         samevolume_new_data, /* new data */
1864         NULL, /* get constraint targets */
1865         NULL, /* flush constraint targets */
1866         NULL, /* get target matrix */
1867         samevolume_evaluate /* evaluate */
1868 };
1869
1870 /* ----------- Python Constraint -------------- */
1871
1872 static void pycon_free(bConstraint *con)
1873 {
1874         bPythonConstraint *data = con->data;
1875         
1876         /* id-properties */
1877         IDP_FreeProperty(data->prop);
1878         MEM_freeN(data->prop);
1879         
1880         /* multiple targets */
1881         BLI_freelistN(&data->targets);
1882 }       
1883
1884 static void pycon_copy(bConstraint *con, bConstraint *srccon)
1885 {
1886         bPythonConstraint *pycon = (bPythonConstraint *)con->data;
1887         bPythonConstraint *opycon = (bPythonConstraint *)srccon->data;
1888         
1889         pycon->prop = IDP_CopyProperty(opycon->prop);
1890         BLI_duplicatelist(&pycon->targets, &opycon->targets);
1891 }
1892
1893 static void pycon_new_data(void *cdata)
1894 {
1895         bPythonConstraint *data = (bPythonConstraint *)cdata;
1896         
1897         /* everything should be set correctly by calloc, except for the prop->type constant.*/
1898         data->prop = MEM_callocN(sizeof(IDProperty), "PyConstraintProps");
1899         data->prop->type = IDP_GROUP;
1900 }
1901
1902 static int pycon_get_tars(bConstraint *con, ListBase *list)
1903 {
1904         if (con && list) {
1905                 bPythonConstraint *data = con->data;
1906                 
1907                 list->first = data->targets.first;
1908                 list->last = data->targets.last;
1909                 
1910                 return data->tarnum;
1911         }
1912         
1913         return 0;
1914 }
1915
1916 static void pycon_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
1917 {
1918         bPythonConstraint *data = con->data;
1919         bConstraintTarget *ct;
1920         
1921         /* targets */
1922         for (ct = data->targets.first; ct; ct = ct->next)
1923                 func(con, (ID **)&ct->tar, FALSE, userdata);
1924                 
1925         /* script */
1926         func(con, (ID **)&data->text, TRUE, userdata);
1927 }
1928
1929 /* Whether this approach is maintained remains to be seen (aligorith) */
1930 static void pycon_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
1931 {
1932 #ifdef WITH_PYTHON
1933         bPythonConstraint *data = con->data;
1934 #endif
1935
1936         if (VALID_CONS_TARGET(ct)) {
1937                 /* special exception for curves - depsgraph issues */
1938                 if (ct->tar->type == OB_CURVE) {
1939                         Curve *cu = ct->tar->data;
1940                         
1941                         /* this check is to make sure curve objects get updated on file load correctly.*/
1942                         if (cu->path == NULL || cu->path->data == NULL) /* only happens on reload file, but violates depsgraph still... fix! */
1943                                 BKE_displist_make_curveTypes(cob->scene, ct->tar, 0);
1944                 }
1945                 
1946                 /* firstly calculate the matrix the normal way, then let the py-function override
1947                  * this matrix if it needs to do so
1948                  */
1949                 constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->headtail);
1950                 
1951                 /* only execute target calculation if allowed */
1952 #ifdef WITH_PYTHON
1953                 if (G.f & G_SCRIPT_AUTOEXEC)
1954                         BPY_pyconstraint_target(data, ct);
1955 #endif
1956         }
1957         else if (ct)
1958                 unit_m4(ct->matrix);
1959 }
1960
1961 static void pycon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
1962 {
1963 #ifndef WITH_PYTHON
1964         (void)con; (void)cob; (void)targets; /* unused */
1965         return;
1966 #else
1967         bPythonConstraint *data = con->data;
1968         
1969         /* only evaluate in python if we're allowed to do so */
1970         if ((G.f & G_SCRIPT_AUTOEXEC) == 0) return;
1971         
1972 /* currently removed, until I this can be re-implemented for multiple targets */
1973 #if 0
1974         /* Firstly, run the 'driver' function which has direct access to the objects involved 
1975          * Technically, this is potentially dangerous as users may abuse this and cause dependency-problems,
1976          * but it also allows certain 'clever' rigging hacks to work.
1977          */
1978         BPY_pyconstraint_driver(data, cob, targets);
1979 #endif
1980         
1981         /* Now, run the actual 'constraint' function, which should only access the matrices */
1982         BPY_pyconstraint_exec(data, cob, targets);
1983 #endif /* WITH_PYTHON */
1984 }
1985
1986 static bConstraintTypeInfo CTI_PYTHON = {
1987         CONSTRAINT_TYPE_PYTHON, /* type */
1988         sizeof(bPythonConstraint), /* size */
1989         "Script", /* name */
1990         "bPythonConstraint", /* struct name */
1991         pycon_free, /* free data */
1992         pycon_id_looper, /* id looper */
1993         pycon_copy, /* copy data */
1994         pycon_new_data, /* new data */
1995         pycon_get_tars, /* get constraint targets */
1996         NULL, /* flush constraint targets */
1997         pycon_get_tarmat, /* get target matrix */
1998         pycon_evaluate /* evaluate */
1999 };
2000
2001 /* -------- Action Constraint ----------- */
2002
2003 static void actcon_new_data(void *cdata)
2004 {
2005         bActionConstraint *data = (bActionConstraint *)cdata;
2006         
2007         /* set type to 20 (Loc X), as 0 is Rot X for backwards compatibility */
2008         data->type = 20;
2009 }
2010
2011 static void actcon_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2012 {
2013         bActionConstraint *data = con->data;
2014         
2015         /* target */
2016         func(con, (ID **)&data->tar, FALSE, userdata);
2017         
2018         /* action */
2019         func(con, (ID **)&data->act, TRUE, userdata);
2020 }
2021
2022 static int actcon_get_tars(bConstraint *con, ListBase *list)
2023 {
2024         if (con && list) {
2025                 bActionConstraint *data = con->data;
2026                 bConstraintTarget *ct;
2027                 
2028                 /* standard target-getting macro for single-target constraints */
2029                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2030                 
2031                 return 1;
2032         }
2033         
2034         return 0;
2035 }
2036
2037 static void actcon_flush_tars(bConstraint *con, ListBase *list, short nocopy)
2038 {
2039         if (con && list) {
2040                 bActionConstraint *data = con->data;
2041                 bConstraintTarget *ct = list->first;
2042                 
2043                 /* the following macro is used for all standard single-target constraints */
2044                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy);
2045         }
2046 }
2047
2048 static void actcon_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime))
2049 {
2050         bActionConstraint *data = con->data;
2051         
2052         if (VALID_CONS_TARGET(ct)) {
2053                 float tempmat[4][4], vec[3];
2054                 float s, t;
2055                 short axis;
2056                 
2057                 /* initialize return matrix */
2058                 unit_m4(ct->matrix);
2059                 
2060                 /* get the transform matrix of the target */
2061                 constraint_target_to_mat4(ct->tar, ct->subtarget, tempmat, CONSTRAINT_SPACE_WORLD, ct->space, con->headtail);
2062                 
2063                 /* determine where in transform range target is */
2064                 /* data->type is mapped as follows for backwards compatibility:
2065                  *      00,01,02        - rotation (it used to be like this)
2066                  *  10,11,12    - scaling
2067                  *      20,21,22        - location
2068                  */
2069                 if (data->type < 10) {
2070                         /* extract rotation (is in whatever space target should be in) */
2071                         mat4_to_eul(vec, tempmat);
2072                         mul_v3_fl(vec, RAD2DEGF(1.0f)); /* rad -> deg */
2073                         axis = data->type;
2074                 }
2075                 else if (data->type < 20) {
2076                         /* extract scaling (is in whatever space target should be in) */
2077                         mat4_to_size(vec, tempmat);
2078                         axis = data->type - 10;
2079                 }
2080                 else {
2081                         /* extract location */
2082                         copy_v3_v3(vec, tempmat[3]);
2083                         axis = data->type - 20;
2084                 }
2085                 
2086                 /* Target defines the animation */
2087                 s = (vec[axis] - data->min) / (data->max - data->min);
2088                 CLAMP(s, 0, 1);
2089                 t = (s * (data->end - data->start)) + data->start;
2090                 
2091                 if (G.debug & G_DEBUG)
2092                         printf("do Action Constraint %s - Ob %s Pchan %s\n", con->name, cob->ob->id.name + 2, (cob->pchan) ? cob->pchan->name : NULL);
2093                 
2094                 /* Get the appropriate information from the action */
2095                 if (cob->type == CONSTRAINT_OBTYPE_OBJECT || (data->flag & ACTCON_BONE_USE_OBJECT_ACTION)) {
2096                         Object workob;
2097                         
2098                         /* evaluate using workob */
2099                         /* FIXME: we don't have any consistent standards on limiting effects on object... */
2100                         what_does_obaction(cob->ob, &workob, NULL, data->act, NULL, t);
2101                         BKE_object_to_mat4(&workob, ct->matrix);
2102                 }
2103                 else if (cob->type == CONSTRAINT_OBTYPE_BONE) {
2104                         Object workob;
2105                         bPose *pose;
2106                         bPoseChannel *pchan, *tchan;
2107                         
2108                         /* make a temporary pose and evaluate using that */
2109                         pose = MEM_callocN(sizeof(bPose), "pose");
2110                         
2111                         /* make a copy of the bone of interest in the temp pose before evaluating action, so that it can get set 
2112                          *      - we need to manually copy over a few settings, including rotation order, otherwise this fails
2113                          */
2114                         pchan = cob->pchan;
2115                         
2116                         tchan = BKE_pose_channel_verify(pose, pchan->name);
2117                         tchan->rotmode = pchan->rotmode;
2118                         
2119                         /* evaluate action using workob (it will only set the PoseChannel in question) */
2120                         what_does_obaction(cob->ob, &workob, pose, data->act, pchan->name, t);
2121                         
2122                         /* convert animation to matrices for use here */
2123                         BKE_pchan_calc_mat(tchan);
2124                         copy_m4_m4(ct->matrix, tchan->chan_mat);
2125                         
2126                         /* Clean up */
2127                         BKE_pose_free(pose);
2128                 }
2129                 else {
2130                         /* behavior undefined... */
2131                         puts("Error: unknown owner type for Action Constraint");
2132                 }
2133         }
2134 }
2135
2136 static void actcon_evaluate(bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets)
2137 {
2138         bConstraintTarget *ct = targets->first;
2139         
2140         if (VALID_CONS_TARGET(ct)) {
2141                 float temp[4][4];
2142                 
2143                 /* Nice and simple... we just need to multiply the matrices, as the get_target_matrix
2144                  * function has already taken care of everything else.
2145                  */
2146                 copy_m4_m4(temp, cob->matrix);
2147                 mult_m4_m4m4(cob->matrix, temp, ct->matrix);
2148         }
2149 }
2150
2151 static bConstraintTypeInfo CTI_ACTION = {
2152         CONSTRAINT_TYPE_ACTION, /* type */
2153         sizeof(bActionConstraint), /* size */
2154         "Action", /* name */
2155         "bActionConstraint", /* struct name */
2156         NULL, /* free data */
2157         actcon_id_looper, /* id looper */
2158         NULL, /* copy data */
2159         actcon_new_data, /* new data */
2160         actcon_get_tars, /* get constraint targets */
2161         actcon_flush_tars, /* flush constraint targets */
2162         actcon_get_tarmat, /* get target matrix */
2163         actcon_evaluate /* evaluate */
2164 };
2165
2166 /* --------- Locked Track ---------- */
2167
2168 static void locktrack_new_data(void *cdata)
2169 {
2170         bLockTrackConstraint *data = (bLockTrackConstraint *)cdata;
2171         
2172         data->trackflag = TRACK_Y;
2173         data->lockflag = LOCK_Z;
2174 }       
2175
2176 static void locktrack_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2177 {
2178         bLockTrackConstraint *data = con->data;
2179         
2180         /* target only */
2181         func(con, (ID **)&data->tar, FALSE, userdata);
2182 }
2183
2184 static int locktrack_get_tars(bConstraint *con, ListBase *list)
2185 {
2186         if (con && list) {
2187                 bLockTrackConstraint *data = con->data;
2188                 bConstraintTarget *ct;
2189                 
2190                 /* the following macro is used for all standard single-target constraints */
2191                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2192                 
2193                 return 1;
2194         }
2195         
2196         return 0;
2197 }
2198
2199 static void locktrack_flush_tars(bConstraint *con, ListBase *list, short nocopy)
2200 {
2201         if (con && list) {
2202                 bLockTrackConstraint *data = con->data;
2203                 bConstraintTarget *ct = list->first;
2204                 
2205                 /* the following macro is used for all standard single-target constraints */
2206                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy);
2207         }
2208 }
2209
2210 static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
2211 {
2212         bLockTrackConstraint *data = con->data;
2213         bConstraintTarget *ct = targets->first;
2214         
2215         if (VALID_CONS_TARGET(ct)) {
2216                 float vec[3], vec2[3];
2217                 float totmat[3][3];
2218                 float tmpmat[3][3];
2219                 float invmat[3][3];
2220                 float mdet;
2221                 
2222                 /* Vector object -> target */
2223                 sub_v3_v3v3(vec, ct->matrix[3], cob->matrix[3]);
2224                 switch (data->lockflag) {
2225                         case LOCK_X: /* LOCK X */
2226                         {
2227                                 switch (data->trackflag) {
2228                                         case TRACK_Y: /* LOCK X TRACK Y */
2229                                         {
2230                                                 /* Projection of Vector on the plane */
2231                                                 project_v3_v3v3(vec2, vec, cob->matrix[0]);
2232                                                 sub_v3_v3v3(totmat[1], vec, vec2);
2233                                                 normalize_v3(totmat[1]);
2234                                         
2235                                                 /* the x axis is fixed */
2236                                                 normalize_v3_v3(totmat[0], cob->matrix[0]);
2237                                         
2238                                                 /* the z axis gets mapped onto a third orthogonal vector */
2239                                                 cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2240                                         }
2241                                         break;
2242                                         case TRACK_Z: /* LOCK X TRACK Z */
2243                                         {
2244                                                 /* Projection of Vector on the plane */
2245                                                 project_v3_v3v3(vec2, vec, cob->matrix[0]);
2246                                                 sub_v3_v3v3(totmat[2], vec, vec2);
2247                                                 normalize_v3(totmat[2]);
2248                                         
2249                                                 /* the x axis is fixed */
2250                                                 normalize_v3_v3(totmat[0], cob->matrix[0]);
2251                                         
2252                                                 /* the z axis gets mapped onto a third orthogonal vector */
2253                                                 cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2254                                         }
2255                                         break;
2256                                         case TRACK_nY: /* LOCK X TRACK -Y */
2257                                         {
2258                                                 /* Projection of Vector on the plane */
2259                                                 project_v3_v3v3(vec2, vec, cob->matrix[0]);
2260                                                 sub_v3_v3v3(totmat[1], vec, vec2);
2261                                                 normalize_v3(totmat[1]);
2262                                                 negate_v3(totmat[1]);
2263                                         
2264                                                 /* the x axis is fixed */
2265                                                 normalize_v3_v3(totmat[0], cob->matrix[0]);
2266                                         
2267                                                 /* the z axis gets mapped onto a third orthogonal vector */
2268                                                 cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2269                                         }
2270                                         break;
2271                                         case TRACK_nZ: /* LOCK X TRACK -Z */
2272                                         {
2273                                                 /* Projection of Vector on the plane */
2274                                                 project_v3_v3v3(vec2, vec, cob->matrix[0]);
2275                                                 sub_v3_v3v3(totmat[2], vec, vec2);
2276                                                 normalize_v3(totmat[2]);
2277                                                 negate_v3(totmat[2]);
2278                                                 
2279                                                 /* the x axis is fixed */
2280                                                 normalize_v3_v3(totmat[0], cob->matrix[0]);
2281                                                 
2282                                                 /* the z axis gets mapped onto a third orthogonal vector */
2283                                                 cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2284                                         }
2285                                         break;
2286                                         default:
2287                                         {
2288                                                 unit_m3(totmat);
2289                                         }
2290                                         break;
2291                                 }
2292                         }
2293                         break;
2294                         case LOCK_Y: /* LOCK Y */
2295                         {
2296                                 switch (data->trackflag) {
2297                                         case TRACK_X: /* LOCK Y TRACK X */
2298                                         {
2299                                                 /* Projection of Vector on the plane */
2300                                                 project_v3_v3v3(vec2, vec, cob->matrix[1]);
2301                                                 sub_v3_v3v3(totmat[0], vec, vec2);
2302                                                 normalize_v3(totmat[0]);
2303                                         
2304                                                 /* the y axis is fixed */
2305                                                 normalize_v3_v3(totmat[1], cob->matrix[1]);
2306
2307                                                 /* the z axis gets mapped onto a third orthogonal vector */
2308                                                 cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2309                                         }
2310                                         break;
2311                                         case TRACK_Z: /* LOCK Y TRACK Z */
2312                                         {
2313                                                 /* Projection of Vector on the plane */
2314                                                 project_v3_v3v3(vec2, vec, cob->matrix[1]);
2315                                                 sub_v3_v3v3(totmat[2], vec, vec2);
2316                                                 normalize_v3(totmat[2]);
2317                                         
2318                                                 /* the y axis is fixed */
2319                                                 normalize_v3_v3(totmat[1], cob->matrix[1]);
2320                                         
2321                                                 /* the z axis gets mapped onto a third orthogonal vector */
2322                                                 cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2323                                         }
2324                                         break;
2325                                         case TRACK_nX: /* LOCK Y TRACK -X */
2326                                         {
2327                                                 /* Projection of Vector on the plane */
2328                                                 project_v3_v3v3(vec2, vec, cob->matrix[1]);
2329                                                 sub_v3_v3v3(totmat[0], vec, vec2);
2330                                                 normalize_v3(totmat[0]);
2331                                                 negate_v3(totmat[0]);
2332                                         
2333                                                 /* the y axis is fixed */
2334                                                 normalize_v3_v3(totmat[1], cob->matrix[1]);
2335                                         
2336                                                 /* the z axis gets mapped onto a third orthogonal vector */
2337                                                 cross_v3_v3v3(totmat[2], totmat[0], totmat[1]);
2338                                         }
2339                                         break;
2340                                         case TRACK_nZ: /* LOCK Y TRACK -Z */
2341                                         {
2342                                                 /* Projection of Vector on the plane */
2343                                                 project_v3_v3v3(vec2, vec, cob->matrix[1]);
2344                                                 sub_v3_v3v3(totmat[2], vec, vec2);
2345                                                 normalize_v3(totmat[2]);
2346                                                 negate_v3(totmat[2]);
2347                                         
2348                                                 /* the y axis is fixed */
2349                                                 normalize_v3_v3(totmat[1], cob->matrix[1]);
2350                                         
2351                                                 /* the z axis gets mapped onto a third orthogonal vector */
2352                                                 cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2353                                         }
2354                                         break;
2355                                         default:
2356                                         {
2357                                                 unit_m3(totmat);
2358                                         }
2359                                         break;
2360                                 }
2361                         }
2362                         break;
2363                         case LOCK_Z: /* LOCK Z */
2364                         {
2365                                 switch (data->trackflag) {
2366                                         case TRACK_X: /* LOCK Z TRACK X */
2367                                         {
2368                                                 /* Projection of Vector on the plane */
2369                                                 project_v3_v3v3(vec2, vec, cob->matrix[2]);
2370                                                 sub_v3_v3v3(totmat[0], vec, vec2);
2371                                                 normalize_v3(totmat[0]);
2372                                         
2373                                                 /* the z axis is fixed */
2374                                                 normalize_v3_v3(totmat[2], cob->matrix[2]);
2375                                         
2376                                                 /* the x axis gets mapped onto a third orthogonal vector */
2377                                                 cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2378                                         }
2379                                         break;
2380                                         case TRACK_Y: /* LOCK Z TRACK Y */
2381                                         {
2382                                                 /* Projection of Vector on the plane */
2383                                                 project_v3_v3v3(vec2, vec, cob->matrix[2]);
2384                                                 sub_v3_v3v3(totmat[1], vec, vec2);
2385                                                 normalize_v3(totmat[1]);
2386                                         
2387                                                 /* the z axis is fixed */
2388                                                 normalize_v3_v3(totmat[2], cob->matrix[2]);
2389                                                 
2390                                                 /* the x axis gets mapped onto a third orthogonal vector */
2391                                                 cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2392                                         }
2393                                         break;
2394                                         case TRACK_nX: /* LOCK Z TRACK -X */
2395                                         {
2396                                                 /* Projection of Vector on the plane */
2397                                                 project_v3_v3v3(vec2, vec, cob->matrix[2]);
2398                                                 sub_v3_v3v3(totmat[0], vec, vec2);
2399                                                 normalize_v3(totmat[0]);
2400                                                 negate_v3(totmat[0]);
2401                                         
2402                                                 /* the z axis is fixed */
2403                                                 normalize_v3_v3(totmat[2], cob->matrix[2]);
2404                                         
2405                                                 /* the x axis gets mapped onto a third orthogonal vector */
2406                                                 cross_v3_v3v3(totmat[1], totmat[2], totmat[0]);
2407                                         }
2408                                         break;
2409                                         case TRACK_nY: /* LOCK Z TRACK -Y */
2410                                         {
2411                                                 /* Projection of Vector on the plane */
2412                                                 project_v3_v3v3(vec2, vec, cob->matrix[2]);
2413                                                 sub_v3_v3v3(totmat[1], vec, vec2);
2414                                                 normalize_v3(totmat[1]);
2415                                                 negate_v3(totmat[1]);
2416                                         
2417                                                 /* the z axis is fixed */
2418                                                 normalize_v3_v3(totmat[2], cob->matrix[2]);
2419                                                 
2420                                                 /* the x axis gets mapped onto a third orthogonal vector */
2421                                                 cross_v3_v3v3(totmat[0], totmat[1], totmat[2]);
2422                                         }
2423                                         break;
2424                                         default:
2425                                         {
2426                                                 unit_m3(totmat);
2427                                         }
2428                                         break;
2429                                 }
2430                         }
2431                         break;
2432                         default:
2433                         {
2434                                 unit_m3(totmat);
2435                         }
2436                         break;
2437                 }
2438                 /* Block to keep matrix heading */
2439                 copy_m3_m4(tmpmat, cob->matrix);
2440                 normalize_m3(tmpmat);
2441                 invert_m3_m3(invmat, tmpmat);
2442                 mul_m3_m3m3(tmpmat, totmat, invmat);
2443                 totmat[0][0] = tmpmat[0][0]; totmat[0][1] = tmpmat[0][1]; totmat[0][2] = tmpmat[0][2];
2444                 totmat[1][0] = tmpmat[1][0]; totmat[1][1] = tmpmat[1][1]; totmat[1][2] = tmpmat[1][2];
2445                 totmat[2][0] = tmpmat[2][0]; totmat[2][1] = tmpmat[2][1]; totmat[2][2] = tmpmat[2][2];
2446                 
2447                 mdet = determinant_m3(totmat[0][0], totmat[0][1], totmat[0][2],
2448                                       totmat[1][0], totmat[1][1], totmat[1][2],
2449                                       totmat[2][0], totmat[2][1], totmat[2][2]);
2450                 if (mdet == 0) {
2451                         unit_m3(totmat);
2452                 }
2453                 
2454                 /* apply out transformaton to the object */
2455                 mul_m4_m3m4(cob->matrix, totmat, cob->matrix);
2456         }
2457 }
2458
2459 static bConstraintTypeInfo CTI_LOCKTRACK = {
2460         CONSTRAINT_TYPE_LOCKTRACK, /* type */
2461         sizeof(bLockTrackConstraint), /* size */
2462         "Locked Track", /* name */
2463         "bLockTrackConstraint", /* struct name */
2464         NULL, /* free data */
2465         locktrack_id_looper, /* id looper */
2466         NULL, /* copy data */
2467         locktrack_new_data, /* new data */
2468         locktrack_get_tars, /* get constraint targets */
2469         locktrack_flush_tars, /* flush constraint targets */
2470         default_get_tarmat, /* get target matrix */
2471         locktrack_evaluate /* evaluate */
2472 };
2473
2474 /* ---------- Limit Distance Constraint ----------- */
2475
2476 static void distlimit_new_data(void *cdata)
2477 {
2478         bDistLimitConstraint *data = (bDistLimitConstraint *)cdata;
2479         
2480         data->dist = 0.0f;
2481 }
2482
2483 static void distlimit_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2484 {
2485         bDistLimitConstraint *data = con->data;
2486         
2487         /* target only */
2488         func(con, (ID **)&data->tar, FALSE, userdata);
2489 }
2490
2491 static int distlimit_get_tars(bConstraint *con, ListBase *list)
2492 {
2493         if (con && list) {
2494                 bDistLimitConstraint *data = con->data;
2495                 bConstraintTarget *ct;
2496                 
2497                 /* standard target-getting macro for single-target constraints */
2498                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2499                 
2500                 return 1;
2501         }
2502         
2503         return 0;
2504 }
2505
2506 static void distlimit_flush_tars(bConstraint *con, ListBase *list, short nocopy)
2507 {
2508         if (con && list) {
2509                 bDistLimitConstraint *data = con->data;
2510                 bConstraintTarget *ct = list->first;
2511                 
2512                 /* the following macro is used for all standard single-target constraints */
2513                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy);
2514         }
2515 }
2516
2517 static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
2518 {
2519         bDistLimitConstraint *data = con->data;
2520         bConstraintTarget *ct = targets->first;
2521         
2522         /* only evaluate if there is a target */
2523         if (VALID_CONS_TARGET(ct)) {
2524                 float dvec[3], dist = 0.0f, sfac = 1.0f;
2525                 short clamp_surf = 0;
2526                 
2527                 /* calculate our current distance from the target */
2528                 dist = len_v3v3(cob->matrix[3], ct->matrix[3]);
2529                 
2530                 /* set distance (flag is only set when user demands it) */
2531                 if (data->dist == 0)
2532                         data->dist = dist;
2533                 
2534                 /* check if we're which way to clamp from, and calculate interpolation factor (if needed) */
2535                 if (data->mode == LIMITDIST_OUTSIDE) {
2536                         /* if inside, then move to surface */
2537                         if (dist <= data->dist) {
2538                                 clamp_surf = 1;
2539                                 if (dist != 0.0f) sfac = data->dist / dist;
2540                         }
2541                         /* if soft-distance is enabled, start fading once owner is dist+softdist from the target */
2542                         else if (data->flag & LIMITDIST_USESOFT) {
2543                                 if (dist <= (data->dist + data->soft)) {
2544                                         
2545                                 }
2546                         }
2547                 }
2548                 else if (data->mode == LIMITDIST_INSIDE) {
2549                         /* if outside, then move to surface */
2550                         if (dist >= data->dist) {
2551                                 clamp_surf = 1;
2552                                 if (dist != 0.0f) sfac = data->dist / dist;
2553                         }
2554                         /* if soft-distance is enabled, start fading once owner is dist-soft from the target */
2555                         else if (data->flag & LIMITDIST_USESOFT) {
2556                                 /* FIXME: there's a problem with "jumping" when this kicks in */
2557                                 if (dist >= (data->dist - data->soft)) {
2558                                         sfac = (float)(data->soft * (1.0f - expf(-(dist - data->dist) / data->soft)) + data->dist);
2559                                         if (dist != 0.0f) sfac /= dist;
2560                                         
2561                                         clamp_surf = 1;
2562                                 }
2563                         }
2564                 }
2565                 else {
2566                         if (IS_EQF(dist, data->dist) == 0) {
2567                                 clamp_surf = 1;
2568                                 if (dist != 0.0f) sfac = data->dist / dist;
2569                         }
2570                 }
2571                 
2572                 /* clamp to 'surface' (i.e. move owner so that dist == data->dist) */
2573                 if (clamp_surf) {
2574                         /* simply interpolate along line formed by target -> owner */
2575                         interp_v3_v3v3(dvec, ct->matrix[3], cob->matrix[3], sfac);
2576                         
2577                         /* copy new vector onto owner */
2578                         copy_v3_v3(cob->matrix[3], dvec);
2579                 }
2580         }
2581 }
2582
2583 static bConstraintTypeInfo CTI_DISTLIMIT = {
2584         CONSTRAINT_TYPE_DISTLIMIT, /* type */
2585         sizeof(bDistLimitConstraint), /* size */
2586         "Limit Distance", /* name */
2587         "bDistLimitConstraint", /* struct name */
2588         NULL, /* free data */
2589         distlimit_id_looper, /* id looper */
2590         NULL, /* copy data */
2591         distlimit_new_data, /* new data */
2592         distlimit_get_tars, /* get constraint targets */
2593         distlimit_flush_tars, /* flush constraint targets */
2594         default_get_tarmat, /* get a target matrix */
2595         distlimit_evaluate /* evaluate */
2596 };
2597
2598 /* ---------- Stretch To ------------ */
2599
2600 static void stretchto_new_data(void *cdata)
2601 {
2602         bStretchToConstraint *data = (bStretchToConstraint *)cdata;
2603         
2604         data->volmode = 0;
2605         data->plane = 0;
2606         data->orglength = 0.0; 
2607         data->bulge = 1.0;
2608 }
2609
2610 static void stretchto_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2611 {
2612         bStretchToConstraint *data = con->data;
2613         
2614         /* target only */
2615         func(con, (ID **)&data->tar, FALSE, userdata);
2616 }
2617
2618 static int stretchto_get_tars(bConstraint *con, ListBase *list)
2619 {
2620         if (con && list) {
2621                 bStretchToConstraint *data = con->data;
2622                 bConstraintTarget *ct;
2623                 
2624                 /* standard target-getting macro for single-target constraints */
2625                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2626                 
2627                 return 1;
2628         }
2629         
2630         return 0;
2631 }
2632
2633 static void stretchto_flush_tars(bConstraint *con, ListBase *list, short nocopy)
2634 {
2635         if (con && list) {
2636                 bStretchToConstraint *data = con->data;
2637                 bConstraintTarget *ct = list->first;
2638                 
2639                 /* the following macro is used for all standard single-target constraints */
2640                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy);
2641         }
2642 }
2643
2644 static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
2645 {
2646         bStretchToConstraint *data = con->data;
2647         bConstraintTarget *ct = targets->first;
2648         
2649         /* only evaluate if there is a target */
2650         if (VALID_CONS_TARGET(ct)) {
2651                 float size[3], scale[3], vec[3], xx[3], zz[3], orth[3];
2652                 float totmat[3][3];
2653                 float dist;
2654                 
2655                 /* store scaling before destroying obmat */
2656                 mat4_to_size(size, cob->matrix);
2657                 
2658                 /* store X orientation before destroying obmat */
2659                 normalize_v3_v3(xx, cob->matrix[0]);
2660                 
2661                 /* store Z orientation before destroying obmat */
2662                 normalize_v3_v3(zz, cob->matrix[2]);
2663                 
2664                 /* XXX That makes the constraint buggy with asymmetrically scaled objects, see #29940. */
2665 /*              sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);*/
2666 /*              vec[0] /= size[0];*/
2667 /*              vec[1] /= size[1];*/
2668 /*              vec[2] /= size[2];*/
2669                 
2670 /*              dist = normalize_v3(vec);*/
2671                 
2672                 dist = len_v3v3(cob->matrix[3], ct->matrix[3]);
2673                 /* Only Y constrained object axis scale should be used, to keep same length when scaling it. */
2674                 dist /= size[1];
2675                 
2676                 /* data->orglength==0 occurs on first run, and after 'R' button is clicked */
2677                 if (data->orglength == 0)
2678                         data->orglength = dist;
2679                 if (data->bulge == 0)
2680                         data->bulge = 1.0;
2681                 
2682                 scale[1] = dist / data->orglength;
2683                 switch (data->volmode) {
2684                         /* volume preserving scaling */
2685                         case VOLUME_XZ:
2686                                 scale[0] = 1.0f - (float)sqrt(data->bulge) + (float)sqrt(data->bulge * (data->orglength / dist));
2687                                 scale[2] = scale[0];
2688                                 break;
2689                         case VOLUME_X:
2690                                 scale[0] = 1.0f + data->bulge * (data->orglength / dist - 1);
2691                                 scale[2] = 1.0;
2692                                 break;
2693                         case VOLUME_Z:
2694                                 scale[0] = 1.0;
2695                                 scale[2] = 1.0f + data->bulge * (data->orglength / dist - 1);
2696                                 break;
2697                         /* don't care for volume */
2698                         case NO_VOLUME:
2699                                 scale[0] = 1.0;
2700                                 scale[2] = 1.0;
2701                                 break;
2702                         default: /* should not happen, but in case*/
2703                                 return;
2704                 } /* switch (data->volmode) */
2705                 
2706                 /* Clear the object's rotation and scale */
2707                 cob->matrix[0][0] = size[0] * scale[0];
2708                 cob->matrix[0][1] = 0;
2709                 cob->matrix[0][2] = 0;
2710                 cob->matrix[1][0] = 0;
2711                 cob->matrix[1][1] = size[1] * scale[1];
2712                 cob->matrix[1][2] = 0;
2713                 cob->matrix[2][0] = 0;
2714                 cob->matrix[2][1] = 0;
2715                 cob->matrix[2][2] = size[2] * scale[2];
2716                 
2717                 sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);
2718                 normalize_v3(vec);
2719                 
2720                 /* new Y aligns  object target connection*/
2721                 negate_v3_v3(totmat[1], vec);
2722                 switch (data->plane) {
2723                         case PLANE_X:
2724                                 /* build new Z vector */
2725                                 /* othogonal to "new Y" "old X! plane */
2726                                 cross_v3_v3v3(orth, vec, xx);
2727                                 normalize_v3(orth);
2728                                 
2729                                 /* new Z*/
2730                                 copy_v3_v3(totmat[2], orth);
2731                                 
2732                                 /* we decided to keep X plane*/
2733                                 cross_v3_v3v3(xx, orth, vec);
2734                                 normalize_v3_v3(totmat[0], xx);
2735                                 break;
2736                         case PLANE_Z:
2737                                 /* build new X vector */
2738                                 /* othogonal to "new Y" "old Z! plane */
2739                                 cross_v3_v3v3(orth, vec, zz);
2740                                 normalize_v3(orth);
2741                                 
2742                                 /* new X */
2743                                 negate_v3_v3(totmat[0], orth);
2744                                 
2745                                 /* we decided to keep Z */
2746                                 cross_v3_v3v3(zz, orth, vec);
2747                                 normalize_v3_v3(totmat[2], zz);
2748                                 break;
2749                 } /* switch (data->plane) */
2750                 
2751                 mul_m4_m3m4(cob->matrix, totmat, cob->matrix);
2752         }
2753 }
2754
2755 static bConstraintTypeInfo CTI_STRETCHTO = {
2756         CONSTRAINT_TYPE_STRETCHTO, /* type */
2757         sizeof(bStretchToConstraint), /* size */
2758         "Stretch To", /* name */
2759         "bStretchToConstraint", /* struct name */
2760         NULL, /* free data */
2761         stretchto_id_looper, /* id looper */
2762         NULL, /* copy data */
2763         stretchto_new_data, /* new data */
2764         stretchto_get_tars, /* get constraint targets */
2765         stretchto_flush_tars, /* flush constraint targets */
2766         default_get_tarmat, /* get target matrix */
2767         stretchto_evaluate /* evaluate */
2768 };
2769
2770 /* ---------- Floor ------------ */
2771
2772 static void minmax_new_data(void *cdata)
2773 {
2774         bMinMaxConstraint *data = (bMinMaxConstraint *)cdata;
2775         
2776         data->minmaxflag = TRACK_Z;
2777         data->offset = 0.0f;
2778         zero_v3(data->cache);
2779         data->flag = 0;
2780 }
2781
2782 static void minmax_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2783 {
2784         bMinMaxConstraint *data = con->data;
2785         
2786         /* target only */
2787         func(con, (ID **)&data->tar, FALSE, userdata);
2788 }
2789
2790 static int minmax_get_tars(bConstraint *con, ListBase *list)
2791 {
2792         if (con && list) {
2793                 bMinMaxConstraint *data = con->data;
2794                 bConstraintTarget *ct;
2795                 
2796                 /* standard target-getting macro for single-target constraints */
2797                 SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list);
2798                 
2799                 return 1;
2800         }
2801         
2802         return 0;
2803 }
2804
2805 static void minmax_flush_tars(bConstraint *con, ListBase *list, short nocopy)
2806 {
2807         if (con && list) {
2808                 bMinMaxConstraint *data = con->data;
2809                 bConstraintTarget *ct = list->first;
2810                 
2811                 /* the following macro is used for all standard single-target constraints */
2812                 SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, nocopy);
2813         }
2814 }
2815
2816 static void minmax_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets)
2817 {
2818         bMinMaxConstraint *data = con->data;
2819         bConstraintTarget *ct = targets->first;
2820         
2821         /* only evaluate if there is a target */
2822         if (VALID_CONS_TARGET(ct)) {
2823                 float obmat[4][4], imat[4][4], tarmat[4][4], tmat[4][4];
2824                 float val1, val2;
2825                 int index;
2826                 
2827                 copy_m4_m4(obmat, cob->matrix);
2828                 copy_m4_m4(tarmat, ct->matrix);
2829                 
2830                 if (data->flag & MINMAX_USEROT) {
2831                         /* take rotation of target into account by doing the transaction in target's localspace */
2832                         invert_m4_m4(imat, tarmat);
2833                         mult_m4_m4m4(tmat, imat, obmat);
2834                         copy_m4_m4(obmat, tmat);
2835                         unit_m4(tarmat);
2836                 }
2837                 
2838                 switch (data->minmaxflag) {
2839                         case TRACK_Z:
2840                                 val1 = tarmat[3][2];
2841                                 val2 = obmat[3][2] - data->offset;
2842                                 index = 2;
2843                                 break;
2844                         case TRACK_Y:
2845                                 val1 = tarmat[3][1];
2846                                 val2 = obmat[3][1] - data->offset;
2847                                 index = 1;
2848                                 break;
2849                         case TRACK_X:
2850                                 val1 = tarmat[3][0];
2851                                 val2 = obmat[3][0] - data->offset;
2852                                 index = 0;
2853                                 break;
2854                         case TRACK_nZ:
2855                                 val2 = tarmat[3][2];
2856                                 val1 = obmat[3][2] - data->offset;
2857                                 index = 2;
2858                                 break;
2859                         case TRACK_nY:
2860                                 val2 = tarmat[3][1];
2861                                 val1 = obmat[3][1] - data->offset;
2862                                 index = 1;
2863                                 break;
2864                         case TRACK_nX:
2865                                 val2 = tarmat[3][0];
2866                                 val1 = obmat[3][0] - data->offset;
2867                                 index = 0;
2868                                 break;
2869                         default:
2870                                 return;
2871                 }
2872                 
2873                 if (val1 > val2) {
2874                         obmat[3][index] = tarmat[3][index] + data->offset;
2875                         if (data->flag & MINMAX_STICKY) {
2876                                 if (data->flag & MINMAX_STUCK) {
2877                                         copy_v3_v3(obmat[3], data->cache);
2878                                 }
2879                                 else {
2880                                         copy_v3_v3(data->cache, obmat[3]);
2881                                         data->flag |= MINMAX_STUCK;
2882                                 }
2883                         }
2884                         if (data->flag & MINMAX_USEROT) {
2885                                 /* get out of localspace */
2886                                 mult_m4_m4m4(tmat, ct->matrix, obmat);
2887                                 copy_m4_m4(cob->matrix, tmat);
2888                         }
2889                         else {
2890                                 copy_v3_v3(cob->matrix[3], obmat[3]);
2891                         }
2892                 }
2893                 else {
2894                         data->flag &= ~MINMAX_STUCK;
2895                 }
2896         }
2897 }
2898
2899 static bConstraintTypeInfo CTI_MINMAX = {
2900         CONSTRAINT_TYPE_MINMAX, /* type */
2901         sizeof(bMinMaxConstraint), /* size */
2902         "Floor", /* name */
2903         "bMinMaxConstraint", /* struct name */
2904         NULL, /* free data */
2905         minmax_id_looper, /* id looper */
2906         NULL, /* copy data */
2907         minmax_new_data, /* new data */
2908         minmax_get_tars, /* get constraint targets */
2909         minmax_flush_tars, /* flush constraint targets */
2910         default_get_tarmat, /* get target matrix */
2911         minmax_evaluate /* evaluate */
2912 };
2913
2914 /* ------- RigidBody Joint ---------- */
2915
2916 static void rbj_new_data(void *cdata)
2917 {
2918         bRigidBodyJointConstraint *data = (bRigidBodyJointConstraint *)cdata;
2919         
2920         /* removed code which set target of this constraint */
2921         data->type = 1;
2922 }
2923
2924 static void rbj_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata)
2925 {
2926         bRigidBodyJointConstraint *data = con->data;
2927         
2928         /* target only */
2929         func(con, (ID **)&data->tar, FALSE, userdata);
2930         func(con, (ID **)&data->child, FALSE, userdata);
2931 }
2932
2933 static int rbj_get_tars(bConstraint *con, ListBase *list)
2934 {
2935         if (con && list) {
2936                 bRigidBodyJointConstraint *data = con->data;
2937                 bConstraintTarget *ct;
2938                 
2939                 /* standard target-getting macro for single-target constraints without subtargets */
2940                 SINGLETARGETNS_GET_TARS(con, data->tar, ct, list);
2941                 
2942                 return 1;
2943         }
2944         
2945         return 0;
2946 }
2947
2948 static void rbj_flush_tars(bConstraint *con, ListBase *list, short nocopy)
2949 {
2950         if (con && list) {
2951                 bRigidBodyJointConstraint *data = con->data;
2952                 bConstraintTarget *ct = list->first;
2953                 
2954                 /* the following macro is used for all standard single-target constraints */
2955                 SINGLETARGETNS_FLUSH_TARS(con, data->tar, ct, list, nocopy);
2956         }
2957 }
2958
2959 static bConstraintTypeInfo CTI_RIGIDBODYJOINT = {
2960         CONSTRAINT_TYPE_RIGIDBODYJOINT, /*