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