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