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