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