97f7d7bf132e61e5b3e8e3e720d37bd332e04d2c
[blender.git] / source / blender / editors / space_clip / tracking_ops.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) 2011 Blender Foundation.
19  * All rights reserved.
20  *
21  *
22  * Contributor(s): Blender Foundation,
23  *                 Sergey Sharybin
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/space_clip/tracking_ops.c
29  *  \ingroup spclip
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "DNA_camera_types.h"
35 #include "DNA_constraint_types.h"
36 #include "DNA_gpencil_types.h"
37 #include "DNA_movieclip_types.h"
38 #include "DNA_object_types.h"   /* SELECT */
39 #include "DNA_scene_types.h"
40
41 #include "BLI_utildefines.h"
42 #include "BLI_math.h"
43 #include "BLI_listbase.h"
44 #include "BLI_rect.h"
45 #include "BLI_blenlib.h"
46
47 #include "BKE_main.h"
48 #include "BKE_context.h"
49 #include "BKE_constraint.h"
50 #include "BKE_movieclip.h"
51 #include "BKE_tracking.h"
52 #include "BKE_global.h"
53 #include "BKE_depsgraph.h"
54 #include "BKE_object.h"
55 #include "BKE_report.h"
56 #include "BKE_scene.h"
57 #include "BKE_library.h"
58 #include "BKE_sound.h"
59
60 #include "WM_api.h"
61 #include "WM_types.h"
62
63 #include "ED_screen.h"
64 #include "ED_clip.h"
65 #include "ED_keyframing.h"
66
67 #include "IMB_imbuf_types.h"
68 #include "IMB_imbuf.h"
69
70 #include "UI_interface.h"
71
72 #include "RNA_access.h"
73 #include "RNA_define.h"
74
75 #include "PIL_time.h"
76
77 #include "UI_view2d.h"
78
79 #include "clip_intern.h"    // own include
80
81 /********************** add marker operator *********************/
82
83 static void add_marker(const bContext *C, float x, float y)
84 {
85         SpaceClip *sc = CTX_wm_space_clip(C);
86         MovieClip *clip = ED_space_clip_get_clip(sc);
87         MovieTracking *tracking = &clip->tracking;
88         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
89         MovieTrackingTrack *track;
90         int width, height;
91         int framenr = ED_space_clip_get_clip_frame_number(sc);
92
93         ED_space_clip_get_size(sc, &width, &height);
94
95         track = BKE_tracking_track_add(tracking, tracksbase, x, y, framenr, width, height);
96
97         BKE_tracking_track_select(tracksbase, track, TRACK_AREA_ALL, 0);
98
99         clip->tracking.act_track = track;
100 }
101
102 static int add_marker_exec(bContext *C, wmOperator *op)
103 {
104         SpaceClip *sc = CTX_wm_space_clip(C);
105         MovieClip *clip = ED_space_clip_get_clip(sc);
106         float pos[2];
107         int width, height;
108
109         ED_space_clip_get_size(sc, &width, &height);
110
111         if (!width || !height)
112                 return OPERATOR_CANCELLED;
113
114         RNA_float_get_array(op->ptr, "location", pos);
115
116         add_marker(C, pos[0], pos[1]);
117
118         /* reset offset from locked position, so frame jumping wouldn't be so confusing */
119         sc->xlockof = 0;
120         sc->ylockof = 0;
121
122         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
123
124         return OPERATOR_FINISHED;
125 }
126
127 static int add_marker_invoke(bContext *C, wmOperator *op, wmEvent *event)
128 {
129         SpaceClip *sc = CTX_wm_space_clip(C);
130         ARegion *ar = CTX_wm_region(C);
131
132         float co[2];
133
134         ED_clip_mouse_pos(sc, ar, event->mval, co);
135
136         RNA_float_set_array(op->ptr, "location", co);
137
138         return add_marker_exec(C, op);
139 }
140
141 void CLIP_OT_add_marker(wmOperatorType *ot)
142 {
143         /* identifiers */
144         ot->name = "Add Marker";
145         ot->idname = "CLIP_OT_add_marker";
146         ot->description = "Place new marker at specified location";
147
148         /* api callbacks */
149         ot->invoke = add_marker_invoke;
150         ot->exec = add_marker_exec;
151         ot->poll = ED_space_clip_tracking_poll;
152
153         /* flags */
154         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
155
156         /* properties */
157         RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MIN, FLT_MAX,
158                              "Location", "Location of marker on frame", -1.0f, 1.0f);
159 }
160
161 /********************** delete track operator *********************/
162
163 static int delete_track_exec(bContext *C, wmOperator *UNUSED(op))
164 {
165         SpaceClip *sc = CTX_wm_space_clip(C);
166         MovieClip *clip = ED_space_clip_get_clip(sc);
167         MovieTracking *tracking = &clip->tracking;
168         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
169         MovieTrackingTrack *track = tracksbase->first, *next;
170
171         while (track) {
172                 next = track->next;
173
174                 if (TRACK_VIEW_SELECTED(sc, track))
175                         clip_delete_track(C, clip, tracksbase, track);
176
177                 track = next;
178         }
179
180         /* nothing selected now, unlock view so it can be scrolled nice again */
181         sc->flag &= ~SC_LOCK_SELECTION;
182
183         return OPERATOR_FINISHED;
184 }
185
186 void CLIP_OT_delete_track(wmOperatorType *ot)
187 {
188         /* identifiers */
189         ot->name = "Delete Track";
190         ot->idname = "CLIP_OT_delete_track";
191         ot->description = "Delete selected tracks";
192
193         /* api callbacks */
194         ot->invoke = WM_operator_confirm;
195         ot->exec = delete_track_exec;
196         ot->poll = ED_space_clip_tracking_poll;
197
198         /* flags */
199         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
200 }
201
202 /********************** delete marker operator *********************/
203
204 static int delete_marker_exec(bContext *C, wmOperator *UNUSED(op))
205 {
206         SpaceClip *sc = CTX_wm_space_clip(C);
207         MovieClip *clip = ED_space_clip_get_clip(sc);
208         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
209         MovieTrackingTrack *track = tracksbase->first, *next;
210         int framenr = ED_space_clip_get_clip_frame_number(sc);
211         int has_selection = 0;
212
213         while (track) {
214                 next = track->next;
215
216                 if (TRACK_VIEW_SELECTED(sc, track)) {
217                         MovieTrackingMarker *marker = BKE_tracking_marker_get_exact(track, framenr);
218
219                         if (marker) {
220                                 has_selection |= track->markersnr > 1;
221
222                                 clip_delete_marker(C, clip, tracksbase, track, marker);
223                         }
224                 }
225
226                 track = next;
227         }
228
229         if (!has_selection) {
230                 /* nothing selected now, unlock view so it can be scrolled nice again */
231                 sc->flag &= ~SC_LOCK_SELECTION;
232         }
233
234         return OPERATOR_FINISHED;
235 }
236
237 void CLIP_OT_delete_marker(wmOperatorType *ot)
238 {
239         /* identifiers */
240         ot->name = "Delete Marker";
241         ot->idname = "CLIP_OT_delete_marker";
242         ot->description = "Delete marker for current frame from selected tracks";
243
244         /* api callbacks */
245         ot->invoke = WM_operator_confirm;
246         ot->exec = delete_marker_exec;
247         ot->poll = ED_space_clip_tracking_poll;
248
249         /* flags */
250         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
251 }
252
253 /********************** slide marker operator *********************/
254
255 #define SLIDE_ACTION_POS       0
256 #define SLIDE_ACTION_SIZE      1
257 #define SLIDE_ACTION_OFFSET    2
258 #define SLIDE_ACTION_TILT_SIZE 3
259
260 typedef struct {
261         short area, action;
262         MovieTrackingTrack *track;
263         MovieTrackingMarker *marker;
264
265         int mval[2];
266         int width, height;
267         float *min, *max, *pos, *offset, (*corners)[2];
268         float spos[2];
269
270         short lock, accurate;
271
272         /* data to restore on cancel */
273         float old_search_min[2], old_search_max[2], old_pos[2], old_offset[2];
274         float old_corners[4][2];
275         float (*old_markers)[2];
276 } SlideMarkerData;
277
278 static void slide_marker_tilt_slider(MovieTrackingMarker *marker, float slider[2])
279 {
280         add_v2_v2v2(slider, marker->pattern_corners[1], marker->pattern_corners[2]);
281         add_v2_v2(slider, marker->pos);
282 }
283
284 static SlideMarkerData *create_slide_marker_data(SpaceClip *sc, MovieTrackingTrack *track,
285                                                  MovieTrackingMarker *marker, wmEvent *event,
286                                                  int area, int corner, int action, int width, int height)
287 {
288         SlideMarkerData *data = MEM_callocN(sizeof(SlideMarkerData), "slide marker data");
289         int framenr = ED_space_clip_get_clip_frame_number(sc);
290
291         marker = BKE_tracking_marker_ensure(track, framenr);
292
293         data->area = area;
294         data->action = action;
295         data->track = track;
296         data->marker = marker;
297
298         if (area == TRACK_AREA_POINT) {
299                 data->pos = marker->pos;
300                 data->offset = track->offset;
301         }
302         else if (area == TRACK_AREA_PAT) {
303                 if (action == SLIDE_ACTION_SIZE) {
304                         data->corners = marker->pattern_corners;
305                 }
306                 else if (action == SLIDE_ACTION_OFFSET) {
307                         int a;
308
309                         data->pos = marker->pos;
310                         data->offset = track->offset;
311
312                         data->old_markers = MEM_callocN(sizeof(*data->old_markers) * track->markersnr, "slide marekrs");
313                         for (a = 0; a < track->markersnr; a++)
314                                 copy_v2_v2(data->old_markers[a], track->markers[a].pos);
315                 }
316                 else if (action == SLIDE_ACTION_POS) {
317                         data->corners = marker->pattern_corners;
318                         data->pos = marker->pattern_corners[corner];
319                         copy_v2_v2(data->spos, data->pos);
320                 }
321                 else if (action == SLIDE_ACTION_TILT_SIZE) {
322                         data->corners = marker->pattern_corners;
323                         slide_marker_tilt_slider(marker, data->spos);
324                 }
325         }
326         else if (area == TRACK_AREA_SEARCH) {
327                 data->min = marker->search_min;
328                 data->max = marker->search_max;
329         }
330
331         data->mval[0] = event->mval[0];
332         data->mval[1] = event->mval[1];
333
334         data->width = width;
335         data->height = height;
336
337         if (action == SLIDE_ACTION_SIZE)
338                 data->lock = 1;
339
340         /* backup marker's settings */
341         memcpy(data->old_corners, marker->pattern_corners, sizeof(data->old_corners));
342         copy_v2_v2(data->old_search_min, marker->search_min);
343         copy_v2_v2(data->old_search_max, marker->search_max);
344         copy_v2_v2(data->old_pos, marker->pos);
345         copy_v2_v2(data->old_offset, track->offset);
346
347         return data;
348 }
349
350 static int mouse_on_slide_zone(SpaceClip *sc, MovieTrackingMarker *marker,
351                                int area, float co[2], float slide_zone[2],
352                                float padding, int width, int height)
353 {
354         const float size = 12.0f;
355         int inside = 0;
356         float min[2], max[2];
357         float dx, dy;
358
359         if (area == TRACK_AREA_SEARCH) {
360                 copy_v2_v2(min, marker->search_min);
361                 copy_v2_v2(max, marker->search_max);
362         }
363         else {
364                 BKE_tracking_marker_pattern_minmax(marker, min, max);
365         }
366
367         min[0] -= padding / width;
368         min[1] -= padding / height;
369         max[0] += padding / width;
370         max[1] += padding / height;
371
372         dx = size / width / sc->zoom;
373         dy = size / height / sc->zoom;
374
375         dx = minf(dx, (max[0] - min[0]) / 6.0f);
376         dy = minf(dy, (max[1] - min[1]) / 6.0f);
377
378         return IN_RANGE_INCL(co[0], slide_zone[0] - dx, slide_zone[0] + dx) &&
379                IN_RANGE_INCL(co[1], slide_zone[1] - dy, slide_zone[1] + dy);
380
381         return inside;
382 }
383
384 static int mouse_on_corner(SpaceClip *sc, MovieTrackingMarker *marker,
385                            int area, float co[2], int corner, float padding,
386                            int width, int height)
387 {
388         float min[2], max[2], crn[2];
389
390         if (area == TRACK_AREA_SEARCH) {
391                 copy_v2_v2(min, marker->search_min);
392                 copy_v2_v2(max, marker->search_max);
393         }
394         else {
395                 BKE_tracking_marker_pattern_minmax(marker, min, max);
396         }
397
398         min[0] -= padding / width;
399         min[1] -= padding / height;
400         max[0] += padding / width;
401         max[1] += padding / height;
402
403         if (corner == 0) {
404                 crn[0] = marker->pos[0] + max[0];
405                 crn[1] = marker->pos[1] + min[1];
406         }
407         else {
408                 crn[0] = marker->pos[0] + min[0];
409                 crn[1] = marker->pos[1] + max[1];
410         }
411
412         return mouse_on_slide_zone(sc, marker, area, co, crn, padding, width, height);
413 }
414
415 static int get_mouse_pattern_corner(SpaceClip *sc, MovieTrackingMarker *marker, float co[2], int width, int height)
416 {
417         int i, next;
418         float len = FLT_MAX, dx, dy;
419
420         for (i = 0; i < 4; i++) {
421                 float cur_len;
422
423                 next = (i + 1) % 4;
424
425                 cur_len = len_v2v2(marker->pattern_corners[i], marker->pattern_corners[next]);
426
427                 len = minf(cur_len, len);
428         }
429
430         dx = 12.0f / width / sc->zoom;
431         dy = 12.0f / height / sc->zoom;
432
433         dx = minf(dx, len * 2.0f / 3.0f);
434         dy = minf(dy, len * width / height * 2.0f / 3.0f);
435
436         for (i = 0; i < 4; i++) {
437                 float crn[2];
438                 int inside;
439
440                 add_v2_v2v2(crn, marker->pattern_corners[i], marker->pos);
441
442                 inside = IN_RANGE_INCL(co[0], crn[0] - dx, crn[0] + dx) &&
443                          IN_RANGE_INCL(co[1], crn[1] - dy, crn[1] + dy);
444
445                 if (inside)
446                         return i;
447         }
448
449         return -1;
450 }
451
452 static int mouse_on_offset(SpaceClip *sc, MovieTrackingTrack *track, MovieTrackingMarker *marker,
453                            float co[2], int width, int height)
454 {
455         float pos[2], dx, dy;
456         float pat_min[2], pat_max[2];
457
458         BKE_tracking_marker_pattern_minmax(marker, pat_min, pat_max);
459
460         add_v2_v2v2(pos, marker->pos, track->offset);
461
462         dx = 12.0f / width / sc->zoom;
463         dy = 12.0f / height / sc->zoom;
464
465         dx = minf(dx, (pat_max[0] - pat_min[0]) / 2.0f);
466         dy = minf(dy, (pat_max[1] - pat_min[1]) / 2.0f);
467
468         return co[0] >= pos[0] - dx && co[0] <= pos[0] + dx && co[1] >= pos[1] - dy && co[1] <= pos[1] + dy;
469 }
470
471 static int mouse_on_tilt(SpaceClip *sc, MovieTrackingMarker *marker, float co[2], int width, int height)
472 {
473         float slider[2];
474
475         slide_marker_tilt_slider(marker, slider);
476
477         return mouse_on_slide_zone(sc, marker, TRACK_AREA_PAT, co, slider, 0.0f, width, height);
478 }
479
480 static int slide_check_corners(float (*corners)[2])
481 {
482         int i, next, prev;
483         float cross = 0.0f;
484         float p[2] = {0.0f, 0.0f};
485
486         if (!isect_point_quad_v2(p, corners[0], corners[1], corners[2], corners[3]))
487                 return FALSE;
488
489         for (i = 0; i < 4; i++) {
490                 float v1[2], v2[2], cur_cross;
491
492                 next = (i + 1) % 4;
493                 prev = (4 + i - 1) % 4;
494
495                 sub_v2_v2v2(v1, corners[i], corners[prev]);
496                 sub_v2_v2v2(v2, corners[next], corners[i]);
497
498                 cur_cross = cross_v2v2(v1, v2);
499
500                 if (fabsf(cur_cross) > FLT_EPSILON) {
501                         if (cross == 0.0f) {
502                                 cross = cur_cross;
503                         }
504                         else if (cross * cur_cross < 0.0f) {
505                                 return FALSE;
506                         }
507                 }
508         }
509
510         return TRUE;
511 }
512
513 static void hide_cursor(bContext *C)
514 {
515         wmWindow *win = CTX_wm_window(C);
516
517         WM_cursor_set(win, CURSOR_NONE);
518 }
519
520 static void show_cursor(bContext *C)
521 {
522         wmWindow *win = CTX_wm_window(C);
523
524         WM_cursor_set(win, CURSOR_STD);
525 }
526
527 MovieTrackingTrack *tracking_marker_check_slide(bContext *C, wmEvent *event, int *area_r, int *action_r, int *corner_r)
528 {
529         SpaceClip *sc = CTX_wm_space_clip(C);
530         ARegion *ar = CTX_wm_region(C);
531
532         MovieClip *clip = ED_space_clip_get_clip(sc);
533         MovieTrackingTrack *track;
534         int width, height;
535         float co[2];
536         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
537         int framenr = ED_space_clip_get_clip_frame_number(sc);
538         int action = -1, area = 0, corner = -1;
539
540         ED_space_clip_get_size(sc, &width, &height);
541
542         if (width == 0 || height == 0)
543                 return NULL;
544
545         ED_clip_mouse_pos(sc, ar, event->mval, co);
546
547         track = tracksbase->first;
548         while (track) {
549                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
550                         MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
551                         int ok = FALSE;
552
553                         if ((marker->flag & MARKER_DISABLED) == 0) {
554                                 if (mouse_on_offset(sc, track, marker, co, width, height)) {
555                                         area = TRACK_AREA_POINT;
556                                         action = SLIDE_ACTION_POS;
557                                         ok = TRUE;
558                                 }
559
560                                 if (!ok && (sc->flag & SC_SHOW_MARKER_SEARCH)) {
561                                         if (mouse_on_corner(sc, marker, TRACK_AREA_SEARCH, co, 1, 0.0f, width, height)) {
562                                                 area = TRACK_AREA_SEARCH;
563                                                 action = SLIDE_ACTION_OFFSET;
564                                                 ok = TRUE;
565                                         }
566                                         else if (mouse_on_corner(sc, marker, TRACK_AREA_SEARCH, co, 0, 0.0f, width, height)) {
567                                                 area = TRACK_AREA_SEARCH;
568                                                 action = SLIDE_ACTION_SIZE;
569                                                 ok = TRUE;
570                                         }
571                                 }
572
573                                 if (!ok && (sc->flag & SC_SHOW_MARKER_PATTERN)) {
574                                         int current_corner = get_mouse_pattern_corner(sc, marker, co, width, height);
575
576                                         if (current_corner != -1) {
577                                                 area = TRACK_AREA_PAT;
578                                                 action = SLIDE_ACTION_POS;
579                                                 corner = current_corner;
580                                                 ok = TRUE;
581                                         }
582                                         else {
583 #if 0
584                                                 /* TODO: disable for now, needs better approaches for visualization */
585
586                                                 if (mouse_on_corner(sc, marker, TRACK_AREA_PAT, co, 1, 12.0f, width, height)) {
587                                                         area = TRACK_AREA_PAT;
588                                                         action = SLIDE_ACTION_OFFSET;
589                                                         ok = TRUE;
590                                                 }
591                                                 if (!ok && mouse_on_corner(sc, marker, TRACK_AREA_PAT, co, 0, 12.0f, width, height)) {
592                                                         area = TRACK_AREA_PAT;
593                                                         action = SLIDE_ACTION_SIZE;
594                                                         ok = TRUE;
595                                                 }
596 #endif
597                                                 if (!ok && mouse_on_tilt(sc, marker, co, width, height)) {
598                                                         area = TRACK_AREA_PAT;
599                                                         action = SLIDE_ACTION_TILT_SIZE;
600                                                         ok = TRUE;
601                                                 }
602                                         }
603                                 }
604
605                                 if (ok) {
606                                         if (area_r)
607                                                 *area_r = area;
608
609                                         if (action_r)
610                                                 *action_r = action;
611
612                                         if (corner_r)
613                                                 *corner_r = corner;
614
615                                         return track;
616                                 }
617                         }
618                 }
619
620                 track = track->next;
621         }
622
623         return NULL;
624 }
625
626 static void *slide_marker_customdata(bContext *C, wmEvent *event)
627 {
628         SpaceClip *sc = CTX_wm_space_clip(C);
629         ARegion *ar = CTX_wm_region(C);
630
631         MovieTrackingTrack *track;
632         int width, height;
633         float co[2];
634         void *customdata = NULL;
635         int framenr = ED_space_clip_get_clip_frame_number(sc);
636         int area, action, corner;
637
638         ED_space_clip_get_size(sc, &width, &height);
639
640         if (width == 0 || height == 0)
641                 return NULL;
642
643         ED_clip_mouse_pos(sc, ar, event->mval, co);
644
645         track = tracking_marker_check_slide(C, event, &area, &action, &corner);
646         if (track) {
647                 MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
648
649                 customdata = create_slide_marker_data(sc, track, marker, event, area, corner, action, width, height);
650         }
651
652         return customdata;
653 }
654
655 static int slide_marker_invoke(bContext *C, wmOperator *op, wmEvent *event)
656 {
657         SlideMarkerData *slidedata = slide_marker_customdata(C, event);
658
659         if (slidedata) {
660                 SpaceClip *sc = CTX_wm_space_clip(C);
661                 MovieClip *clip = ED_space_clip_get_clip(sc);
662                 MovieTracking *tracking = &clip->tracking;
663
664                 tracking->act_track = slidedata->track;
665
666                 op->customdata = slidedata;
667
668                 hide_cursor(C);
669                 WM_event_add_modal_handler(C, op);
670
671                 WM_event_add_notifier(C, NC_GEOM | ND_SELECT, NULL);
672
673                 return OPERATOR_RUNNING_MODAL;
674         }
675
676         return OPERATOR_PASS_THROUGH;
677 }
678
679 static void cancel_mouse_slide(SlideMarkerData *data)
680 {
681         MovieTrackingTrack *track = data->track;
682         MovieTrackingMarker *marker = data->marker;
683
684         memcpy(marker->pattern_corners, data->old_corners, sizeof(marker->pattern_corners));
685         copy_v2_v2(marker->search_min, data->old_search_min);
686         copy_v2_v2(marker->search_max, data->old_search_max);
687         copy_v2_v2(marker->pos, data->old_pos);
688         copy_v2_v2(track->offset, data->old_offset);
689
690         if (data->old_markers) {
691                 int a;
692
693                 for (a = 0; a < data->track->markersnr; a++)
694                         copy_v2_v2(data->track->markers[a].pos, data->old_markers[a]);
695         }
696 }
697
698 static void free_slide_data(SlideMarkerData *data)
699 {
700         if (data->old_markers)
701                 MEM_freeN(data->old_markers);
702
703         MEM_freeN(data);
704 }
705
706 static int slide_marker_modal(bContext *C, wmOperator *op, wmEvent *event)
707 {
708         SpaceClip *sc = CTX_wm_space_clip(C);
709         ARegion *ar = CTX_wm_region(C);
710
711         SlideMarkerData *data = (SlideMarkerData *)op->customdata;
712         float dx, dy, mdelta[2];
713
714         switch (event->type) {
715                 case LEFTCTRLKEY:
716                 case RIGHTCTRLKEY:
717                 case LEFTSHIFTKEY:
718                 case RIGHTSHIFTKEY:
719                         if (data->action == SLIDE_ACTION_SIZE)
720                                 if (ELEM(event->type, LEFTCTRLKEY, RIGHTCTRLKEY))
721                                         data->lock = event->val == KM_RELEASE;
722
723                         if (ELEM(event->type, LEFTSHIFTKEY, RIGHTSHIFTKEY))
724                                 data->accurate = event->val == KM_PRESS;
725
726                 /* no break! update area size */
727
728                 case MOUSEMOVE:
729                         mdelta[0] = event->mval[0] - data->mval[0];
730                         mdelta[1] = event->mval[1] - data->mval[1];
731
732                         dx = mdelta[0] / data->width / sc->zoom;
733
734                         if (data->lock)
735                                 dy = -dx / data->height * data->width;
736                         else
737                                 dy = mdelta[1] / data->height / sc->zoom;
738
739                         if (data->accurate) {
740                                 dx /= 5;
741                                 dy /= 5;
742                         }
743
744                         if (data->area == TRACK_AREA_POINT) {
745                                 if (data->action == SLIDE_ACTION_OFFSET) {
746                                         data->offset[0] = data->old_offset[0] + dx;
747                                         data->offset[1] = data->old_offset[1] + dy;
748                                 }
749                                 else {
750                                         data->pos[0] = data->old_pos[0] + dx;
751                                         data->pos[1] = data->old_pos[1] + dy;
752                                 }
753
754                                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
755                                 DAG_id_tag_update(&sc->clip->id, 0);
756                         }
757                         else if (data->area == TRACK_AREA_PAT) {
758                                 if (data->action == SLIDE_ACTION_SIZE) {
759                                         float start[2], end[2];
760                                         float scale;
761
762                                         ED_clip_point_stable_pos(sc, ar, data->mval[0], data->mval[1], &start[0], &start[1]);
763
764                                         sub_v2_v2(start, data->old_pos);
765
766                                         if (len_v2(start) > 0.0f) {
767                                                 float mval[2];
768
769                                                 if (data->accurate) {
770                                                         mval[0] = data->mval[0] + (event->mval[0] - data->mval[0]) / 5.0f;
771                                                         mval[1] = data->mval[1] + (event->mval[1] - data->mval[1]) / 5.0f;
772                                                 }
773                                                 else {
774                                                         mval[0] = event->mval[0];
775                                                         mval[1] = event->mval[1];
776                                                 }
777
778                                                 ED_clip_point_stable_pos(sc, ar, mval[0], mval[1], &end[0], &end[1]);
779
780                                                 sub_v2_v2(end, data->old_pos);
781
782                                                 scale = len_v2(end) / len_v2(start);
783
784                                                 if (scale > 0.0f) {
785                                                         int a;
786
787                                                         for (a = 0; a < 4; a++) {
788                                                                 mul_v2_v2fl(data->corners[a], data->old_corners[a], scale);
789                                                         }
790                                                 }
791                                         }
792
793                                         BKE_tracking_marker_clamp(data->marker, CLAMP_PAT_DIM);
794                                 }
795                                 else if (data->action == SLIDE_ACTION_OFFSET) {
796                                         float d[2] = {dx, dy};
797                                         int a;
798
799                                         for (a = 0; a < data->track->markersnr; a++)
800                                                 add_v2_v2v2(data->track->markers[a].pos, data->old_markers[a], d);
801
802                                         sub_v2_v2v2(data->offset, data->old_offset, d);
803                                 }
804                                 else if (data->action == SLIDE_ACTION_POS) {
805                                         float spos[2];
806
807                                         copy_v2_v2(spos, data->pos);
808
809                                         data->pos[0] = data->spos[0] + dx;
810                                         data->pos[1] = data->spos[1] + dy;
811
812                                         if (!slide_check_corners(data->corners)) {
813                                                 copy_v2_v2(data->pos, spos);
814                                         }
815
816                                         /* currently only patterns are allowed to have such combination of event and data */
817                                         BKE_tracking_marker_clamp(data->marker, CLAMP_PAT_DIM);
818                                 }
819                                 else if (data->action == SLIDE_ACTION_TILT_SIZE) {
820                                         float start[2], end[2];
821                                         float scale = 1.0f, angle = 0.0f;
822                                         int a;
823                                         float mval[2];
824
825                                         if (data->accurate) {
826                                                 mval[0] = data->mval[0] + (event->mval[0] - data->mval[0]) / 5.0f;
827                                                 mval[1] = data->mval[1] + (event->mval[1] - data->mval[1]) / 5.0f;
828                                         }
829                                         else {
830                                                 mval[0] = event->mval[0];
831                                                 mval[1] = event->mval[1];
832                                         }
833
834                                         sub_v2_v2v2(start, data->spos, data->old_pos);
835
836                                         ED_clip_point_stable_pos(sc, ar, mval[0], mval[1], &end[0], &end[1]);
837                                         sub_v2_v2(end, data->old_pos);
838
839                                         if (len_v2(start) > 0.0f) {
840                                                 scale = len_v2(end) / len_v2(start);
841
842                                                 if (scale < 0.0f) {
843                                                         scale = 0.0;
844                                                 }
845                                         }
846
847                                         angle = -angle_signed_v2v2(start, end);
848
849                                         for (a = 0; a < 4; a++) {
850                                                 float vec[2];
851
852                                                 mul_v2_v2fl(data->corners[a], data->old_corners[a], scale);
853
854                                                 copy_v2_v2(vec, data->corners[a]);
855                                                 vec[0] *= data->width;
856                                                 vec[1] *= data->height;
857
858                                                 data->corners[a][0] = (vec[0] * cos(angle) - vec[1] * sin(angle)) / data->width;
859                                                 data->corners[a][1] = (vec[1] * cos(angle) + vec[0] * sin(angle)) / data->height;
860                                         }
861
862                                         BKE_tracking_marker_clamp(data->marker, CLAMP_PAT_DIM);
863
864                                 }
865                         }
866                         else if (data->area == TRACK_AREA_SEARCH) {
867                                 if (data->action == SLIDE_ACTION_SIZE) {
868                                         data->min[0] = data->old_search_min[0] - dx;
869                                         data->max[0] = data->old_search_max[0] + dx;
870
871                                         data->min[1] = data->old_search_min[1] + dy;
872                                         data->max[1] = data->old_search_max[1] - dy;
873
874                                         BKE_tracking_marker_clamp(data->marker, CLAMP_SEARCH_DIM);
875                                 }
876                                 else if (data->area == TRACK_AREA_SEARCH) {
877                                         float d[2] = {dx, dy};
878
879                                         add_v2_v2v2(data->min, data->old_search_min, d);
880                                         add_v2_v2v2(data->max, data->old_search_max, d);
881                                 }
882
883                                 BKE_tracking_marker_clamp(data->marker, CLAMP_SEARCH_POS);
884                         }
885
886                         data->marker->flag &= ~MARKER_TRACKED;
887
888                         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, NULL);
889
890                         break;
891
892                 case LEFTMOUSE:
893                         if (event->val == KM_RELEASE) {
894                                 free_slide_data(op->customdata);
895
896                                 show_cursor(C);
897
898                                 return OPERATOR_FINISHED;
899                         }
900
901                         break;
902
903                 case ESCKEY:
904                         cancel_mouse_slide(op->customdata);
905
906                         free_slide_data(op->customdata);
907
908                         show_cursor(C);
909
910                         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, NULL);
911
912                         return OPERATOR_CANCELLED;
913         }
914
915         return OPERATOR_RUNNING_MODAL;
916 }
917
918 void CLIP_OT_slide_marker(wmOperatorType *ot)
919 {
920         /* identifiers */
921         ot->name = "Slide Marker";
922         ot->description = "Slide marker areas";
923         ot->idname = "CLIP_OT_slide_marker";
924
925         /* api callbacks */
926         ot->poll = ED_space_clip_tracking_poll;
927         ot->invoke = slide_marker_invoke;
928         ot->modal = slide_marker_modal;
929
930         /* flags */
931         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_GRAB_POINTER | OPTYPE_BLOCKING;
932
933         /* properties */
934         RNA_def_float_vector(ot->srna, "offset", 2, NULL, -FLT_MAX, FLT_MAX,
935                              "Offset", "Offset in floating point units, 1.0 is the width and height of the image", -FLT_MAX, FLT_MAX);
936 }
937
938 /********************** track operator *********************/
939
940 typedef struct TrackMarkersJob {
941         struct MovieTrackingContext *context;   /* tracking context */
942         int sfra, efra, lastfra;    /* Start, end and recently tracked frames */
943         int backwards;              /* Backwards tracking flag */
944         MovieClip *clip;            /* Clip which is tracking */
945         float delay;                /* Delay in milliseconds to allow tracking at fixed FPS */
946
947         struct Main *main;
948         struct Scene *scene;
949         struct bScreen *screen;
950 } TrackMarkersJob;
951
952 static int track_markers_testbreak(void)
953 {
954         return G.is_break;
955 }
956
957 static int track_count_markers(SpaceClip *sc, MovieClip *clip)
958 {
959         int tot = 0;
960         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
961         MovieTrackingTrack *track;
962         int framenr = ED_space_clip_get_clip_frame_number(sc);
963
964         track = tracksbase->first;
965         while (track) {
966                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
967                         MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
968
969                         if (!marker || (marker->flag & MARKER_DISABLED) == 0)
970                                 tot++;
971                 }
972
973                 track = track->next;
974         }
975
976         return tot;
977 }
978
979 static void clear_invisible_track_selection(SpaceClip *sc, MovieClip *clip)
980 {
981         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
982         int hidden = 0;
983
984         if ((sc->flag & SC_SHOW_MARKER_PATTERN) == 0)
985                 hidden |= TRACK_AREA_PAT;
986
987         if ((sc->flag & SC_SHOW_MARKER_SEARCH) == 0)
988                 hidden |= TRACK_AREA_SEARCH;
989
990         if (hidden) {
991                 MovieTrackingTrack *track = tracksbase->first;
992
993                 while (track) {
994                         if ((track->flag & TRACK_HIDDEN) == 0)
995                                 BKE_tracking_track_flag_clear(track, hidden, SELECT);
996
997                         track = track->next;
998                 }
999         }
1000 }
1001
1002 static void track_init_markers(SpaceClip *sc, MovieClip *clip, int *frames_limit_r)
1003 {
1004         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
1005         MovieTrackingTrack *track;
1006         int framenr = ED_space_clip_get_clip_frame_number(sc);
1007         int frames_limit = 0;
1008
1009         clear_invisible_track_selection(sc, clip);
1010
1011         track = tracksbase->first;
1012         while (track) {
1013                 if (TRACK_VIEW_SELECTED(sc, track)) {
1014                         if ((track->flag & TRACK_HIDDEN) == 0 && (track->flag & TRACK_LOCKED) == 0) {
1015                                 BKE_tracking_marker_ensure(track, framenr);
1016
1017                                 if (track->frames_limit) {
1018                                         if (frames_limit == 0)
1019                                                 frames_limit = track->frames_limit;
1020                                         else
1021                                                 frames_limit = MIN2(frames_limit, track->frames_limit);
1022                                 }
1023                         }
1024                 }
1025
1026                 track = track->next;
1027         }
1028
1029         *frames_limit_r = frames_limit;
1030 }
1031
1032 static int track_markers_check_direction(int backwards, int curfra, int efra)
1033 {
1034         if (backwards) {
1035                 if (curfra < efra)
1036                         return FALSE;
1037         }
1038         else {
1039                 if (curfra > efra)
1040                         return FALSE;
1041         }
1042
1043         return TRUE;
1044 }
1045
1046 static int track_markers_initjob(bContext *C, TrackMarkersJob *tmj, int backwards)
1047 {
1048         SpaceClip *sc = CTX_wm_space_clip(C);
1049         MovieClip *clip = ED_space_clip_get_clip(sc);
1050         Scene *scene = CTX_data_scene(C);
1051         MovieTrackingSettings *settings = &clip->tracking.settings;
1052         int frames_limit;
1053
1054         track_init_markers(sc, clip, &frames_limit);
1055
1056         tmj->sfra = ED_space_clip_get_clip_frame_number(sc);
1057         tmj->clip = clip;
1058         tmj->backwards = backwards;
1059
1060         if (backwards)
1061                 tmj->efra = SFRA;
1062         else
1063                 tmj->efra = EFRA;
1064
1065         /* limit frames to be tracked by user setting */
1066         if (frames_limit) {
1067                 if (backwards)
1068                         tmj->efra = MAX2(tmj->efra, tmj->sfra - frames_limit);
1069                 else
1070                         tmj->efra = MIN2(tmj->efra, tmj->sfra + frames_limit);
1071         }
1072
1073         tmj->efra = BKE_movieclip_remap_scene_to_clip_frame(clip, tmj->efra);
1074
1075         if (settings->speed != TRACKING_SPEED_FASTEST) {
1076                 tmj->delay = 1.0f / scene->r.frs_sec * 1000.0f;
1077
1078                 if (settings->speed == TRACKING_SPEED_HALF)
1079                         tmj->delay *= 2;
1080                 else if (settings->speed == TRACKING_SPEED_QUARTER)
1081                         tmj->delay *= 4;
1082                 else if (settings->speed == TRACKING_SPEED_DOUBLE)
1083                         tmj->delay /= 2;
1084         }
1085
1086         tmj->context = BKE_tracking_context_new(clip, &sc->user, backwards, 1);
1087
1088         clip->tracking_context = tmj->context;
1089
1090         tmj->lastfra = tmj->sfra;
1091
1092         /* XXX: silly to store this, but this data is needed to update scene and movie-clip
1093          *      frame numbers when tracking is finished. This introduces better feedback for artists.
1094          *      Maybe there's another way to solve this problem, but can't think better way atm.
1095          *      Anyway, this way isn't more unstable as animation rendering animation
1096          *      which uses the same approach (except storing screen). */
1097         tmj->scene = scene;
1098         tmj->main = CTX_data_main(C);
1099         tmj->screen = CTX_wm_screen(C);
1100
1101         return track_markers_check_direction(backwards, tmj->sfra, tmj->efra);
1102 }
1103
1104 static void track_markers_startjob(void *tmv, short *stop, short *do_update, float *progress)
1105 {
1106         TrackMarkersJob *tmj = (TrackMarkersJob *)tmv;
1107         int framenr = tmj->sfra;
1108         //double t = PIL_check_seconds_timer();
1109
1110         while (framenr != tmj->efra) {
1111                 if (tmj->delay > 0) {
1112                         /* tracking should happen with fixed fps. Calculate time
1113                          * using current timer value before tracking frame and after.
1114                          *
1115                          * Small (and maybe unneeded optimization): do not calculate exec_time
1116                          * for "Fastest" tracking */
1117
1118                         double start_time = PIL_check_seconds_timer(), exec_time;
1119
1120                         if (!BKE_tracking_context_step(tmj->context))
1121                                 break;
1122
1123                         exec_time = PIL_check_seconds_timer() - start_time;
1124                         if (tmj->delay > (float)exec_time)
1125                                 PIL_sleep_ms(tmj->delay - (float)exec_time);
1126                 }
1127                 else if (!BKE_tracking_context_step(tmj->context))
1128                         break;
1129
1130                 *do_update = TRUE;
1131                 *progress = (float)(framenr - tmj->sfra) / (tmj->efra - tmj->sfra);
1132
1133                 if (tmj->backwards)
1134                         framenr--;
1135                 else
1136                         framenr++;
1137
1138                 tmj->lastfra = framenr;
1139
1140                 if (*stop || track_markers_testbreak())
1141                         break;
1142         }
1143
1144         //printf("Tracking time: %lf\n", PIL_check_seconds_timer()-t);
1145 }
1146
1147 static void track_markers_updatejob(void *tmv)
1148 {
1149         TrackMarkersJob *tmj = (TrackMarkersJob *)tmv;
1150
1151         BKE_tracking_context_sync(tmj->context);
1152 }
1153
1154 static void track_markers_freejob(void *tmv)
1155 {
1156         TrackMarkersJob *tmj = (TrackMarkersJob *)tmv;
1157
1158         tmj->clip->tracking_context = NULL;
1159         tmj->scene->r.cfra = BKE_movieclip_remap_clip_to_scene_frame(tmj->clip, tmj->lastfra);
1160         ED_update_for_newframe(tmj->main, tmj->scene, 0);
1161
1162         BKE_tracking_context_sync(tmj->context);
1163         BKE_tracking_context_free(tmj->context);
1164
1165         MEM_freeN(tmj);
1166
1167         WM_main_add_notifier(NC_SCENE | ND_FRAME, tmj->scene);
1168 }
1169
1170 static int track_markers_exec(bContext *C, wmOperator *op)
1171 {
1172         SpaceClip *sc = CTX_wm_space_clip(C);
1173         MovieClip *clip = ED_space_clip_get_clip(sc);
1174         Scene *scene = CTX_data_scene(C);
1175         struct MovieTrackingContext *context;
1176         int framenr = ED_space_clip_get_clip_frame_number(sc);
1177         int sfra = framenr, efra;
1178         int backwards = RNA_boolean_get(op->ptr, "backwards");
1179         int sequence = RNA_boolean_get(op->ptr, "sequence");
1180         int frames_limit;
1181
1182         if (track_count_markers(sc, clip) == 0)
1183                 return OPERATOR_CANCELLED;
1184
1185         track_init_markers(sc, clip, &frames_limit);
1186
1187         if (backwards)
1188                 efra = SFRA;
1189         else
1190                 efra = EFRA;
1191
1192         /* limit frames to be tracked by user setting */
1193         if (frames_limit) {
1194                 if (backwards)
1195                         efra = MAX2(efra, sfra - frames_limit);
1196                 else
1197                         efra = MIN2(efra, sfra + frames_limit);
1198         }
1199
1200         efra = BKE_movieclip_remap_scene_to_clip_frame(clip, efra);
1201
1202         if (!track_markers_check_direction(backwards, framenr, efra))
1203                 return OPERATOR_CANCELLED;
1204
1205         /* do not disable tracks due to threshold when tracking frame-by-frame */
1206         context = BKE_tracking_context_new(clip, &sc->user, backwards, sequence);
1207
1208         while (framenr != efra) {
1209                 if (!BKE_tracking_context_step(context))
1210                         break;
1211
1212                 if (backwards) framenr--;
1213                 else framenr++;
1214
1215                 if (!sequence)
1216                         break;
1217         }
1218
1219         BKE_tracking_context_sync(context);
1220         BKE_tracking_context_free(context);
1221
1222         /* update scene current frame to the lastes tracked frame */
1223         scene->r.cfra = BKE_movieclip_remap_clip_to_scene_frame(clip, framenr);
1224
1225         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
1226         WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
1227
1228         return OPERATOR_FINISHED;
1229 }
1230
1231 static int track_markers_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1232 {
1233         TrackMarkersJob *tmj;
1234         ScrArea *sa = CTX_wm_area(C);
1235         SpaceClip *sc = CTX_wm_space_clip(C);
1236         MovieClip *clip = ED_space_clip_get_clip(sc);
1237         wmJob *wm_job;
1238         int backwards = RNA_boolean_get(op->ptr, "backwards");
1239         int sequence = RNA_boolean_get(op->ptr, "sequence");
1240
1241         if (WM_jobs_test(CTX_wm_manager(C), CTX_wm_area(C), WM_JOB_TYPE_ANY)) {
1242                 /* only one tracking is allowed at a time */
1243                 return OPERATOR_CANCELLED;
1244         }
1245
1246         if (clip->tracking_context)
1247                 return OPERATOR_CANCELLED;
1248
1249         if (track_count_markers(sc, clip) == 0)
1250                 return OPERATOR_CANCELLED;
1251
1252         if (!sequence)
1253                 return track_markers_exec(C, op);
1254
1255         tmj = MEM_callocN(sizeof(TrackMarkersJob), "TrackMarkersJob data");
1256         if (!track_markers_initjob(C, tmj, backwards)) {
1257                 track_markers_freejob(tmj);
1258
1259                 return OPERATOR_CANCELLED;
1260         }
1261
1262         /* setup job */
1263         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), sa, "Track Markers",
1264                              WM_JOB_PROGRESS, WM_JOB_TYPE_CLIP_TRACK_MARKERS);
1265         WM_jobs_customdata_set(wm_job, tmj, track_markers_freejob);
1266
1267         /* if there's delay set in tracking job, tracking should happen
1268          * with fixed FPS. To deal with editor refresh we have to synchronize
1269          * tracks from job and tracks in clip. Do this in timer callback
1270          * to prevent threading conflicts. */
1271         if (tmj->delay > 0)
1272                 WM_jobs_timer(wm_job, tmj->delay / 1000.0f, NC_MOVIECLIP | NA_EVALUATED, 0);
1273         else
1274                 WM_jobs_timer(wm_job, 0.2, NC_MOVIECLIP | NA_EVALUATED, 0);
1275
1276         WM_jobs_callbacks(wm_job, track_markers_startjob, NULL, track_markers_updatejob, NULL);
1277
1278         G.is_break = FALSE;
1279
1280         WM_jobs_start(CTX_wm_manager(C), wm_job);
1281         WM_cursor_wait(0);
1282
1283         /* add modal handler for ESC */
1284         WM_event_add_modal_handler(C, op);
1285
1286         return OPERATOR_RUNNING_MODAL;
1287 }
1288
1289 static int track_markers_modal(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
1290 {
1291         /* no running tracking, remove handler and pass through */
1292         if (0 == WM_jobs_test(CTX_wm_manager(C), CTX_wm_area(C), WM_JOB_TYPE_ANY))
1293                 return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
1294
1295         /* running tracking */
1296         switch (event->type) {
1297                 case ESCKEY:
1298                         return OPERATOR_RUNNING_MODAL;
1299                         break;
1300         }
1301
1302         return OPERATOR_PASS_THROUGH;
1303 }
1304
1305 void CLIP_OT_track_markers(wmOperatorType *ot)
1306 {
1307         /* identifiers */
1308         ot->name = "Track Markers";
1309         ot->description = "Track selected markers";
1310         ot->idname = "CLIP_OT_track_markers";
1311
1312         /* api callbacks */
1313         ot->exec = track_markers_exec;
1314         ot->invoke = track_markers_invoke;
1315         ot->poll = ED_space_clip_tracking_poll;
1316         ot->modal = track_markers_modal;
1317
1318         /* flags */
1319         ot->flag = OPTYPE_UNDO;
1320
1321         /* properties */
1322         RNA_def_boolean(ot->srna, "backwards", 0, "Backwards", "Do backwards tracking");
1323         RNA_def_boolean(ot->srna, "sequence", 0, "Track Sequence", "Track marker during image sequence rather than single image");
1324 }
1325
1326 /********************** solve camera operator *********************/
1327
1328 typedef struct {
1329         Scene *scene;
1330         MovieClip *clip;
1331         MovieClipUser user;
1332
1333         ReportList *reports;
1334
1335         char stats_message[256];
1336
1337         struct MovieReconstructContext *context;
1338 } SolveCameraJob;
1339
1340 static int solve_camera_initjob(bContext *C, SolveCameraJob *scj, wmOperator *op, char *error_msg, int max_error)
1341 {
1342         SpaceClip *sc = CTX_wm_space_clip(C);
1343         MovieClip *clip = ED_space_clip_get_clip(sc);
1344         Scene *scene = CTX_data_scene(C);
1345         MovieTracking *tracking = &clip->tracking;
1346         MovieTrackingSettings *settings = &clip->tracking.settings;
1347         MovieTrackingObject *object = BKE_tracking_object_get_active(tracking);
1348         int width, height;
1349
1350         if (!BKE_tracking_reconstruction_check(tracking, object, error_msg, max_error))
1351                 return 0;
1352
1353         /* could fail if footage uses images with different sizes */
1354         BKE_movieclip_get_size(clip, &sc->user, &width, &height);
1355
1356         scj->clip = clip;
1357         scj->scene = scene;
1358         scj->reports = op->reports;
1359         scj->user = sc->user;
1360
1361         scj->context = BKE_tracking_reconstruction_context_new(tracking, object,
1362                                                                settings->keyframe1, settings->keyframe2, width, height);
1363
1364         tracking->stats = MEM_callocN(sizeof(MovieTrackingStats), "solve camera stats");
1365
1366         return 1;
1367 }
1368
1369 static void solve_camera_updatejob(void *scv)
1370 {
1371         SolveCameraJob *scj = (SolveCameraJob *)scv;
1372         MovieTracking *tracking = &scj->clip->tracking;
1373
1374         BLI_strncpy(tracking->stats->message, scj->stats_message, sizeof(tracking->stats->message));
1375 }
1376
1377 static void solve_camera_startjob(void *scv, short *stop, short *do_update, float *progress)
1378 {
1379         SolveCameraJob *scj = (SolveCameraJob *)scv;
1380
1381         BKE_tracking_reconstruction_solve(scj->context, stop, do_update, progress,
1382                                           scj->stats_message, sizeof(scj->stats_message));
1383 }
1384
1385 static void solve_camera_freejob(void *scv)
1386 {
1387         SolveCameraJob *scj = (SolveCameraJob *)scv;
1388         MovieTracking *tracking = &scj->clip->tracking;
1389         Scene *scene = scj->scene;
1390         MovieClip *clip = scj->clip;
1391         int solved;
1392
1393         if (!scj->context) {
1394                 /* job weren't fully initialized due to some error */
1395                 MEM_freeN(scj);
1396                 return;
1397         }
1398
1399         solved = BKE_tracking_reconstruction_finish(scj->context, tracking);
1400
1401         if (!solved)
1402                 BKE_report(scj->reports, RPT_WARNING, "Some data failed to reconstruct, see console for details");
1403         else
1404                 BKE_reportf(scj->reports, RPT_INFO, "Average re-projection error %.3f", tracking->reconstruction.error);
1405
1406         /* set currently solved clip as active for scene */
1407         if (scene->clip)
1408                 id_us_min(&clip->id);
1409
1410         scene->clip = clip;
1411         id_us_plus(&clip->id);
1412
1413         /* set blender camera focal length so result would look fine there */
1414         if (scene->camera) {
1415                 Camera *camera = (Camera *)scene->camera->data;
1416                 int width, height;
1417
1418                 BKE_movieclip_get_size(clip, &scj->user, &width, &height);
1419
1420                 BKE_tracking_camera_to_blender(tracking, scene, camera, width, height);
1421
1422                 WM_main_add_notifier(NC_OBJECT, camera);
1423         }
1424
1425         MEM_freeN(tracking->stats);
1426         tracking->stats = NULL;
1427
1428         DAG_id_tag_update(&clip->id, 0);
1429
1430         WM_main_add_notifier(NC_MOVIECLIP | NA_EVALUATED, clip);
1431         WM_main_add_notifier(NC_OBJECT | ND_TRANSFORM, NULL);
1432
1433         /* update active clip displayed in scene buttons */
1434         WM_main_add_notifier(NC_SCENE, scene);
1435
1436         BKE_tracking_reconstruction_context_free(scj->context);
1437         MEM_freeN(scj);
1438 }
1439
1440 static int solve_camera_exec(bContext *C, wmOperator *op)
1441 {
1442         SolveCameraJob *scj;
1443         char error_msg[256] = "\0";
1444
1445         scj = MEM_callocN(sizeof(SolveCameraJob), "SolveCameraJob data");
1446         if (!solve_camera_initjob(C, scj, op, error_msg, sizeof(error_msg))) {
1447                 if (error_msg[0])
1448                         BKE_report(op->reports, RPT_ERROR, error_msg);
1449
1450                 solve_camera_freejob(scj);
1451
1452                 return OPERATOR_CANCELLED;
1453         }
1454
1455         solve_camera_startjob(scj, NULL, NULL, NULL);
1456
1457         solve_camera_freejob(scj);
1458
1459         return OPERATOR_FINISHED;
1460 }
1461
1462 static int solve_camera_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1463 {
1464         SolveCameraJob *scj;
1465         ScrArea *sa = CTX_wm_area(C);
1466         SpaceClip *sc = CTX_wm_space_clip(C);
1467         MovieClip *clip = ED_space_clip_get_clip(sc);
1468         MovieTracking *tracking = &clip->tracking;
1469         MovieTrackingReconstruction *reconstruction = BKE_tracking_get_active_reconstruction(tracking);
1470         wmJob *wm_job;
1471         char error_msg[256] = "\0";
1472
1473         if (WM_jobs_test(CTX_wm_manager(C), CTX_wm_area(C), WM_JOB_TYPE_ANY)) {
1474                 /* only one solve is allowed at a time */
1475                 return OPERATOR_CANCELLED;
1476         }
1477
1478         scj = MEM_callocN(sizeof(SolveCameraJob), "SolveCameraJob data");
1479         if (!solve_camera_initjob(C, scj, op, error_msg, sizeof(error_msg))) {
1480                 if (error_msg[0])
1481                         BKE_report(op->reports, RPT_ERROR, error_msg);
1482
1483                 solve_camera_freejob(scj);
1484
1485                 return OPERATOR_CANCELLED;
1486         }
1487
1488         BLI_strncpy(tracking->stats->message, "Solving camera | Preparing solve", sizeof(tracking->stats->message));
1489
1490         /* hide reconstruction statistics from previous solve */
1491         reconstruction->flag &= ~TRACKING_RECONSTRUCTED;
1492         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
1493
1494         /* setup job */
1495         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), sa, "Solve Camera",
1496                              WM_JOB_PROGRESS, WM_JOB_TYPE_CLIP_SOLVE_CAMERA);
1497         WM_jobs_customdata_set(wm_job, scj, solve_camera_freejob);
1498         WM_jobs_timer(wm_job, 0.1, NC_MOVIECLIP | NA_EVALUATED, 0);
1499         WM_jobs_callbacks(wm_job, solve_camera_startjob, NULL, solve_camera_updatejob, NULL);
1500
1501         G.is_break = FALSE;
1502
1503         WM_jobs_start(CTX_wm_manager(C), wm_job);
1504         WM_cursor_wait(0);
1505
1506         /* add modal handler for ESC */
1507         WM_event_add_modal_handler(C, op);
1508
1509         return OPERATOR_RUNNING_MODAL;
1510 }
1511
1512 static int solve_camera_modal(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
1513 {
1514         /* no running solver, remove handler and pass through */
1515         if (0 == WM_jobs_test(CTX_wm_manager(C), CTX_wm_area(C), WM_JOB_TYPE_ANY))
1516                 return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
1517
1518         /* running tracking */
1519         switch (event->type) {
1520                 case ESCKEY:
1521                         return OPERATOR_RUNNING_MODAL;
1522                         break;
1523         }
1524
1525         return OPERATOR_PASS_THROUGH;
1526 }
1527
1528 void CLIP_OT_solve_camera(wmOperatorType *ot)
1529 {
1530         /* identifiers */
1531         ot->name = "Solve Camera";
1532         ot->description = "Solve camera motion from tracks";
1533         ot->idname = "CLIP_OT_solve_camera";
1534
1535         /* api callbacks */
1536         ot->exec = solve_camera_exec;
1537         ot->invoke = solve_camera_invoke;
1538         ot->modal = solve_camera_modal;
1539         ot->poll = ED_space_clip_tracking_poll;
1540
1541         /* flags */
1542         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1543 }
1544
1545 /********************** clear solution operator *********************/
1546
1547 static int clear_solution_exec(bContext *C, wmOperator *UNUSED(op))
1548 {
1549         SpaceClip *sc = CTX_wm_space_clip(C);
1550         MovieClip *clip = ED_space_clip_get_clip(sc);
1551         MovieTracking *tracking = &clip->tracking;
1552         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
1553         MovieTrackingReconstruction *reconstruction = BKE_tracking_get_active_reconstruction(tracking);
1554         MovieTrackingTrack *track = tracksbase->first;
1555
1556         while (track) {
1557                 track->flag &= ~TRACK_HAS_BUNDLE;
1558
1559                 track = track->next;
1560         }
1561
1562         if (reconstruction->cameras)
1563                 MEM_freeN(reconstruction->cameras);
1564
1565         reconstruction->cameras = NULL;
1566         reconstruction->camnr = 0;
1567
1568         reconstruction->flag &= ~TRACKING_RECONSTRUCTED;
1569
1570         DAG_id_tag_update(&clip->id, 0);
1571
1572         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
1573         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, NULL);
1574
1575         return OPERATOR_FINISHED;
1576 }
1577
1578 void CLIP_OT_clear_solution(wmOperatorType *ot)
1579 {
1580         /* identifiers */
1581         ot->name = "Clear Solution";
1582         ot->description = "Clear all calculated data";
1583         ot->idname = "CLIP_OT_clear_solution";
1584
1585         /* api callbacks */
1586         ot->exec = clear_solution_exec;
1587         ot->poll = ED_space_clip_tracking_poll;
1588
1589         /* flags */
1590         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1591 }
1592
1593 /********************** clear track operator *********************/
1594
1595 static int clear_track_path_exec(bContext *C, wmOperator *op)
1596 {
1597         SpaceClip *sc = CTX_wm_space_clip(C);
1598         MovieClip *clip = ED_space_clip_get_clip(sc);
1599         MovieTracking *tracking = &clip->tracking;
1600         MovieTrackingTrack *track;
1601         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
1602         int action = RNA_enum_get(op->ptr, "action");
1603         int clear_active = RNA_boolean_get(op->ptr, "clear_active");
1604         int framenr = ED_space_clip_get_clip_frame_number(sc);
1605
1606         if (clear_active) {
1607                 track = BKE_tracking_track_get_active(tracking);
1608                 BKE_tracking_track_path_clear(track, framenr, action);
1609         }
1610         else {
1611                 track = tracksbase->first;
1612                 while (track) {
1613                         if (TRACK_VIEW_SELECTED(sc, track))
1614                                 BKE_tracking_track_path_clear(track, framenr, action);
1615
1616                         track = track->next;
1617                 }
1618         }
1619
1620         BKE_tracking_dopesheet_tag_update(tracking);
1621         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
1622
1623         return OPERATOR_FINISHED;
1624 }
1625
1626 void CLIP_OT_clear_track_path(wmOperatorType *ot)
1627 {
1628         static EnumPropertyItem clear_path_actions[] = {
1629                 {TRACK_CLEAR_UPTO, "UPTO", 0, "Clear up-to", "Clear path up to current frame"},
1630                 {TRACK_CLEAR_REMAINED, "REMAINED", 0, "Clear remained", "Clear path at remaining frames (after current)"},
1631                 {TRACK_CLEAR_ALL, "ALL", 0, "Clear all", "Clear the whole path"},
1632                 {0, NULL, 0, NULL, NULL}
1633         };
1634
1635         /* identifiers */
1636         ot->name = "Clear Track Path";
1637         ot->description = "Clear tracks after/before current position or clear the whole track";
1638         ot->idname = "CLIP_OT_clear_track_path";
1639
1640         /* api callbacks */
1641         ot->exec = clear_track_path_exec;
1642         ot->poll = ED_space_clip_tracking_poll;
1643
1644         /* flags */
1645         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1646
1647         /* proeprties */
1648         RNA_def_enum(ot->srna, "action", clear_path_actions, TRACK_CLEAR_REMAINED, "Action", "Clear action to execute");
1649         RNA_def_boolean(ot->srna, "clear_active", 0, "Clear Active", "Clear active track only instead of all selected tracks");
1650 }
1651
1652 /********************** disable markers operator *********************/
1653
1654 static int disable_markers_exec(bContext *C, wmOperator *op)
1655 {
1656         SpaceClip *sc = CTX_wm_space_clip(C);
1657         MovieClip *clip = ED_space_clip_get_clip(sc);
1658         MovieTracking *tracking = &clip->tracking;
1659         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
1660         MovieTrackingTrack *track = tracksbase->first;
1661         int action = RNA_enum_get(op->ptr, "action");
1662         int framenr = ED_space_clip_get_clip_frame_number(sc);
1663
1664         while (track) {
1665                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
1666                         MovieTrackingMarker *marker = BKE_tracking_marker_ensure(track, framenr);
1667
1668                         if (action == 0)
1669                                 marker->flag |= MARKER_DISABLED;
1670                         else if (action == 1)
1671                                 marker->flag &= ~MARKER_DISABLED;
1672                         else marker->flag ^= MARKER_DISABLED;
1673                 }
1674
1675                 track = track->next;
1676         }
1677
1678         DAG_id_tag_update(&clip->id, 0);
1679
1680         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
1681
1682         return OPERATOR_FINISHED;
1683 }
1684
1685 void CLIP_OT_disable_markers(wmOperatorType *ot)
1686 {
1687         static EnumPropertyItem actions_items[] = {
1688                 {0, "DISABLE", 0, "Disable", "Disable selected markers"},
1689                 {1, "ENABLE", 0, "Enable", "Enable selected markers"},
1690                 {2, "TOGGLE", 0, "Toggle", "Toggle disabled flag for selected markers"},
1691                 {0, NULL, 0, NULL, NULL}
1692         };
1693
1694         /* identifiers */
1695         ot->name = "Disable Markers";
1696         ot->description = "Disable/enable selected markers";
1697         ot->idname = "CLIP_OT_disable_markers";
1698
1699         /* api callbacks */
1700         ot->exec = disable_markers_exec;
1701         ot->poll = ED_space_clip_tracking_poll;
1702
1703         /* flags */
1704         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1705
1706         /* properties */
1707         RNA_def_enum(ot->srna, "action", actions_items, 0, "Action", "Disable action to execute");
1708 }
1709
1710 /********************** set origin operator *********************/
1711
1712 static Object *get_camera_with_movieclip(Scene *scene, MovieClip *clip)
1713 {
1714         Object *camera = scene->camera;
1715         Base *base;
1716
1717         if (camera && BKE_object_movieclip_get(scene, camera, 0) == clip)
1718                 return camera;
1719
1720         base = scene->base.first;
1721         while (base) {
1722                 if (base->object->type == OB_CAMERA) {
1723                         if (BKE_object_movieclip_get(scene, base->object, 0) == clip) {
1724                                 camera = base->object;
1725                                 break;
1726                         }
1727                 }
1728
1729                 base = base->next;
1730         }
1731
1732         return camera;
1733 }
1734
1735 static Object *get_orientation_object(bContext *C)
1736 {
1737         Scene *scene = CTX_data_scene(C);
1738         SpaceClip *sc = CTX_wm_space_clip(C);
1739         MovieClip *clip = ED_space_clip_get_clip(sc);
1740         MovieTracking *tracking = &clip->tracking;
1741         MovieTrackingObject *tracking_object = BKE_tracking_object_get_active(tracking);
1742         Object *object = NULL;
1743
1744         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
1745                 object = get_camera_with_movieclip(scene, clip);
1746         }
1747         else {
1748                 object = OBACT;
1749         }
1750
1751         if (object && object->parent)
1752                 object = object->parent;
1753
1754         return object;
1755 }
1756
1757 static int set_orientation_poll(bContext *C)
1758 {
1759         SpaceClip *sc = CTX_wm_space_clip(C);
1760
1761         if (sc) {
1762                 Scene *scene = CTX_data_scene(C);
1763                 MovieClip *clip = ED_space_clip_get_clip(sc);
1764
1765                 if (clip) {
1766                         MovieTracking *tracking = &clip->tracking;
1767                         MovieTrackingObject *tracking_object = BKE_tracking_object_get_active(tracking);
1768
1769                         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
1770                                 return TRUE;
1771                         }
1772                         else {
1773                                 return OBACT != NULL;
1774                         }
1775                 }
1776         }
1777
1778         return FALSE;
1779 }
1780
1781 static int count_selected_bundles(bContext *C)
1782 {
1783         SpaceClip *sc = CTX_wm_space_clip(C);
1784         MovieClip *clip = ED_space_clip_get_clip(sc);
1785         ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
1786         MovieTrackingTrack *track;
1787         int tot = 0;
1788
1789         track = tracksbase->first;
1790         while (track) {
1791                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_HAS_BUNDLE))
1792                         tot++;
1793
1794                 track = track->next;
1795         }
1796
1797         return tot;
1798 }
1799
1800 static void object_solver_inverted_matrix(Scene *scene, Object *ob, float invmat[4][4])
1801 {
1802         bConstraint *con;
1803         int found = FALSE;
1804
1805         for (con = ob->constraints.first; con; con = con->next) {
1806                 bConstraintTypeInfo *cti = constraint_get_typeinfo(con);
1807
1808                 if (!cti)
1809                         continue;
1810
1811                 if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
1812                         bObjectSolverConstraint *data = (bObjectSolverConstraint *)con->data;
1813
1814                         if (!found) {
1815                                 Object *cam = data->camera ? data->camera : scene->camera;
1816
1817                                 BKE_object_where_is_calc_mat4(scene, cam, invmat);
1818                         }
1819
1820                         mult_m4_m4m4(invmat, invmat, data->invmat);
1821
1822                         found = TRUE;
1823                 }
1824         }
1825
1826         if (found)
1827                 invert_m4(invmat);
1828         else
1829                 unit_m4(invmat);
1830 }
1831
1832 static Object *object_solver_camera(Scene *scene, Object *ob)
1833 {
1834         bConstraint *con;
1835
1836         for (con = ob->constraints.first; con; con = con->next) {
1837                 bConstraintTypeInfo *cti = constraint_get_typeinfo(con);
1838
1839                 if (!cti)
1840                         continue;
1841
1842                 if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
1843                         bObjectSolverConstraint *data = (bObjectSolverConstraint *)con->data;
1844
1845                         return data->camera ? data->camera : scene->camera;
1846                 }
1847         }
1848
1849         return NULL;
1850 }
1851
1852 static int set_origin_exec(bContext *C, wmOperator *op)
1853 {
1854         SpaceClip *sc = CTX_wm_space_clip(C);
1855         MovieClip *clip = ED_space_clip_get_clip(sc);
1856         MovieTracking *tracking = &clip->tracking;
1857         MovieTrackingTrack *track;
1858         MovieTrackingObject *tracking_object;
1859         Scene *scene = CTX_data_scene(C);
1860         Object *object;
1861         Object *camera = get_camera_with_movieclip(scene, clip);
1862         ListBase *tracksbase;
1863         float mat[4][4], vec[3], median[3];
1864         int selected_count = count_selected_bundles(C);
1865
1866         if (selected_count == 0) {
1867                 BKE_report(op->reports, RPT_ERROR,
1868                            "At least one track with bundle should be selected to define origin position");
1869
1870                 return OPERATOR_CANCELLED;
1871         }
1872
1873         object = get_orientation_object(C);
1874         if (!object) {
1875                 BKE_report(op->reports, RPT_ERROR, "No object to apply orientation on");
1876
1877                 return OPERATOR_CANCELLED;
1878         }
1879
1880         tracking_object = BKE_tracking_object_get_active(tracking);
1881
1882         tracksbase = BKE_tracking_object_get_tracks(tracking, tracking_object);
1883
1884         track = tracksbase->first;
1885         zero_v3(median);
1886         while (track) {
1887                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_HAS_BUNDLE)) {
1888                         add_v3_v3(median, track->bundle_pos);
1889                 }
1890
1891                 track = track->next;
1892         }
1893         mul_v3_fl(median, 1.0f / selected_count);
1894
1895         BKE_tracking_get_camera_object_matrix(scene, camera, mat);
1896
1897         mul_v3_m4v3(vec, mat, median);
1898
1899         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
1900                 sub_v3_v3(object->loc, vec);
1901         }
1902         else {
1903                 object_solver_inverted_matrix(scene, object, mat);
1904                 mul_v3_m4v3(vec, mat, vec);
1905                 copy_v3_v3(object->loc, vec);
1906         }
1907
1908         DAG_id_tag_update(&clip->id, 0);
1909         DAG_id_tag_update(&object->id, OB_RECALC_OB);
1910
1911         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
1912         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1913
1914         return OPERATOR_FINISHED;
1915 }
1916
1917 void CLIP_OT_set_origin(wmOperatorType *ot)
1918 {
1919         /* identifiers */
1920         ot->name = "Set Origin";
1921         ot->description = "Set active marker as origin by moving camera (or it's parent if present) in 3D space";
1922         ot->idname = "CLIP_OT_set_origin";
1923
1924         /* api callbacks */
1925         ot->exec = set_origin_exec;
1926         ot->poll = set_orientation_poll;
1927
1928         /* flags */
1929         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1930
1931         /* properties */
1932         RNA_def_boolean(ot->srna, "use_median", 0, "Use Median", "Set origin to median point of selected bundles");
1933 }
1934
1935 /********************** set floor operator *********************/
1936
1937 static void set_axis(Scene *scene,  Object *ob, MovieClip *clip, MovieTrackingObject *tracking_object,
1938                      MovieTrackingTrack *track, char axis)
1939 {
1940         Object *camera = get_camera_with_movieclip(scene, clip);
1941         int is_camera = tracking_object->flag & TRACKING_OBJECT_CAMERA;
1942         int flip = FALSE;
1943         float mat[4][4], vec[3], obmat[4][4], dvec[3];
1944
1945         BKE_object_to_mat4(ob, obmat);
1946
1947         BKE_tracking_get_camera_object_matrix(scene, camera, mat);
1948         mul_v3_m4v3(vec, mat, track->bundle_pos);
1949         copy_v3_v3(dvec, vec);
1950
1951         if (!is_camera) {
1952                 float imat[4][4];
1953
1954                 object_solver_inverted_matrix(scene, ob, imat);
1955                 mul_v3_m4v3(vec, imat, vec);
1956
1957                 invert_m4_m4(imat, obmat);
1958                 mul_v3_m4v3(dvec, imat, vec);
1959
1960                 sub_v3_v3(vec, obmat[3]);
1961         }
1962
1963         if (len_v2(vec) < 1e-3f)
1964                 return;
1965
1966         unit_m4(mat);
1967
1968         if (axis == 'X') {
1969                 if (fabsf(dvec[1]) < 1e-3f) {
1970                         flip = TRUE;
1971
1972                         mat[0][0] = -1.0f; mat[0][1] = 0.0f; mat[0][2] = 0.0f;
1973                         mat[1][0] = 0.0f; mat[1][1] = -1.0f; mat[1][2] = 0.0f;
1974                         mat[2][0] = 0.0f; mat[2][1] = 0.0f; mat[2][2] = 1.0f;
1975                 }
1976                 else {
1977                         copy_v3_v3(mat[0], vec);
1978
1979                         if (is_camera || fabsf(vec[2]) < 1e-3f) {
1980                                 mat[0][2] = 0.0f;
1981                                 mat[2][0] = 0.0f; mat[2][1] = 0.0f; mat[2][2] = 1.0f;
1982                                 cross_v3_v3v3(mat[1], mat[2], mat[0]);
1983                         }
1984                         else {
1985                                 vec[2] = 0.0f;
1986
1987                                 cross_v3_v3v3(mat[1], mat[0], vec);
1988                                 cross_v3_v3v3(mat[2], mat[0], mat[1]);
1989                         }
1990                 }
1991         }
1992         else {
1993                 if (fabsf(dvec[0]) < 1e-3f) {
1994                         flip = TRUE;
1995
1996                         mat[0][0] = -1.0f; mat[0][1] = 0.0f; mat[0][2] = 0.0f;
1997                         mat[1][0] = 0.0f; mat[1][1] = -1.0f; mat[1][2] = 0.0f;
1998                         mat[2][0] = 0.0f; mat[2][1] = 0.0f; mat[2][2] = 1.0f;
1999                 }
2000                 else {
2001                         copy_v3_v3(mat[1], vec);
2002
2003                         if (is_camera || fabsf(vec[2]) < 1e-3f) {
2004                                 mat[1][2] = 0.0f;
2005                                 mat[2][0] = 0.0f; mat[2][1] = 0.0f; mat[2][2] = 1.0f;
2006                                 cross_v3_v3v3(mat[0], mat[1], mat[2]);
2007                         }
2008                         else {
2009                                 vec[2] = 0.0f;
2010
2011                                 cross_v3_v3v3(mat[0], vec, mat[1]);
2012                                 cross_v3_v3v3(mat[2], mat[0], mat[1]);
2013                         }
2014                 }
2015         }
2016
2017         normalize_v3(mat[0]);
2018         normalize_v3(mat[1]);
2019         normalize_v3(mat[2]);
2020
2021         if (is_camera) {
2022                 invert_m4(mat);
2023
2024                 mult_m4_m4m4(mat, mat, obmat);
2025         }
2026         else {
2027                 if (!flip) {
2028                         float lmat[4][4], ilmat[4][4], rmat[3][3];
2029
2030                         BKE_object_rot_to_mat3(ob, rmat);
2031                         invert_m3(rmat);
2032                         mul_m4_m4m3(mat, mat, rmat);
2033
2034                         unit_m4(lmat);
2035                         copy_v3_v3(lmat[3], obmat[3]);
2036                         invert_m4_m4(ilmat, lmat);
2037
2038                         mul_serie_m4(mat, lmat, mat, ilmat, obmat, NULL, NULL, NULL, NULL);
2039                 }
2040                 else {
2041                         mult_m4_m4m4(mat, obmat, mat);
2042                 }
2043         }
2044
2045         BKE_object_apply_mat4(ob, mat, 0, 0);
2046 }
2047
2048 static int set_plane_exec(bContext *C, wmOperator *op)
2049 {
2050         SpaceClip *sc = CTX_wm_space_clip(C);
2051         MovieClip *clip = ED_space_clip_get_clip(sc);
2052         Scene *scene = CTX_data_scene(C);
2053         MovieTracking *tracking = &clip->tracking;
2054         MovieTrackingObject *tracking_object;
2055         MovieTrackingTrack *track, *axis_track = NULL, *act_track;
2056         ListBase *tracksbase;
2057         Object *object;
2058         Object *camera = get_camera_with_movieclip(scene, clip);
2059         int tot = 0;
2060         float vec[3][3], mat[4][4], obmat[4][4], newmat[4][4], orig[3] = {0.0f, 0.0f, 0.0f};
2061         int plane = RNA_enum_get(op->ptr, "plane");
2062         float rot[4][4] = {{0.0f, 0.0f, -1.0f, 0.0f},
2063                            {0.0f, 1.0f, 0.0f, 0.0f},
2064                            {1.0f, 0.0f, 0.0f, 0.0f},
2065                            {0.0f, 0.0f, 0.0f, 1.0f}};  /* 90 degrees Y-axis rotation matrix */
2066
2067         if (count_selected_bundles(C) != 3) {
2068                 BKE_report(op->reports, RPT_ERROR, "Three tracks with bundles are needed to orient the floor");
2069
2070                 return OPERATOR_CANCELLED;
2071         }
2072
2073         tracking_object = BKE_tracking_object_get_active(tracking);
2074         tracksbase = BKE_tracking_object_get_tracks(tracking, tracking_object);
2075         act_track = BKE_tracking_track_get_active(tracking);
2076
2077         object = get_orientation_object(C);
2078         if (!object) {
2079                 BKE_report(op->reports, RPT_ERROR, "No object to apply orientation on");
2080
2081                 return OPERATOR_CANCELLED;
2082         }
2083
2084         BKE_tracking_get_camera_object_matrix(scene, camera, mat);
2085
2086         /* get 3 bundles to use as reference */
2087         track = tracksbase->first;
2088         while (track && tot < 3) {
2089                 if (track->flag & TRACK_HAS_BUNDLE && TRACK_VIEW_SELECTED(sc, track)) {
2090                         mul_v3_m4v3(vec[tot], mat, track->bundle_pos);
2091
2092                         if (tot == 0 || track == act_track)
2093                                 copy_v3_v3(orig, vec[tot]);
2094                         else
2095                                 axis_track = track;
2096
2097                         tot++;
2098                 }
2099
2100                 track = track->next;
2101         }
2102
2103         sub_v3_v3(vec[1], vec[0]);
2104         sub_v3_v3(vec[2], vec[0]);
2105
2106         /* construct ortho-normal basis */
2107         unit_m4(mat);
2108
2109         if (plane == 0) { /* floor */
2110                 cross_v3_v3v3(mat[0], vec[1], vec[2]);
2111                 copy_v3_v3(mat[1], vec[1]);
2112                 cross_v3_v3v3(mat[2], mat[0], mat[1]);
2113         }
2114         else if (plane == 1) { /* wall */
2115                 cross_v3_v3v3(mat[2], vec[1], vec[2]);
2116                 copy_v3_v3(mat[1], vec[1]);
2117                 cross_v3_v3v3(mat[0], mat[1], mat[2]);
2118         }
2119
2120         normalize_v3(mat[0]);
2121         normalize_v3(mat[1]);
2122         normalize_v3(mat[2]);
2123
2124         /* move to origin point */
2125         mat[3][0] = orig[0];
2126         mat[3][1] = orig[1];
2127         mat[3][2] = orig[2];
2128
2129         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
2130                 invert_m4(mat);
2131
2132                 BKE_object_to_mat4(object, obmat);
2133                 mult_m4_m4m4(mat, mat, obmat);
2134                 mult_m4_m4m4(newmat, rot, mat);
2135                 BKE_object_apply_mat4(object, newmat, 0, 0);
2136
2137                 /* make camera have positive z-coordinate */
2138                 if (object->loc[2] < 0) {
2139                         invert_m4(rot);
2140                         mult_m4_m4m4(newmat, rot, mat);
2141                         BKE_object_apply_mat4(object, newmat, 0, 0);
2142                 }
2143         }
2144         else {
2145                 BKE_object_apply_mat4(object, mat, 0, 0);
2146         }
2147
2148         BKE_object_where_is_calc(scene, object);
2149         set_axis(scene, object, clip, tracking_object, axis_track, 'X');
2150
2151         DAG_id_tag_update(&clip->id, 0);
2152         DAG_id_tag_update(&object->id, OB_RECALC_OB);
2153
2154         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2155         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
2156
2157         return OPERATOR_FINISHED;
2158 }
2159
2160 void CLIP_OT_set_plane(wmOperatorType *ot)
2161 {
2162         static EnumPropertyItem plane_items[] = {
2163                 {0, "FLOOR", 0, "Floor", "Set floor plane"},
2164                 {1, "WALL", 0, "Wall", "Set wall plane"},
2165                 {0, NULL, 0, NULL, NULL}
2166         };
2167
2168         /* identifiers */
2169         ot->name = "Set Plane";
2170         ot->description = "Set plane based on 3 selected bundles by moving camera (or it's parent if present) in 3D space";
2171         ot->idname = "CLIP_OT_set_plane";
2172
2173         /* api callbacks */
2174         ot->exec = set_plane_exec;
2175         ot->poll = set_orientation_poll;
2176
2177         /* flags */
2178         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2179
2180         /* properties */
2181         RNA_def_enum(ot->srna, "plane", plane_items, 0, "Plane", "Plane to be used for orientation");
2182 }
2183
2184 /********************** set axis operator *********************/
2185
2186 static int set_axis_exec(bContext *C, wmOperator *op)
2187 {
2188         SpaceClip *sc = CTX_wm_space_clip(C);
2189         MovieClip *clip = ED_space_clip_get_clip(sc);
2190         MovieTracking *tracking = &clip->tracking;
2191         MovieTrackingObject *tracking_object = BKE_tracking_object_get_active(tracking);
2192         MovieTrackingTrack *track;
2193         Scene *scene = CTX_data_scene(C);
2194         Object *object;
2195         ListBase *tracksbase;
2196         int axis = RNA_enum_get(op->ptr, "axis");
2197
2198         if (count_selected_bundles(C) != 1) {
2199                 BKE_report(op->reports, RPT_ERROR, "Single track with bundle should be selected to define axis");
2200
2201                 return OPERATOR_CANCELLED;
2202         }
2203
2204         object = get_orientation_object(C);
2205         if (!object) {
2206                 BKE_report(op->reports, RPT_ERROR, "No object to apply orientation on");
2207
2208                 return OPERATOR_CANCELLED;
2209         }
2210
2211         tracksbase = BKE_tracking_object_get_tracks(tracking, tracking_object);
2212
2213         track = tracksbase->first;
2214         while (track) {
2215                 if (TRACK_VIEW_SELECTED(sc, track))
2216                         break;
2217
2218                 track = track->next;
2219         }
2220
2221         set_axis(scene, object, clip, tracking_object, track, axis == 0 ? 'X' : 'Y');
2222
2223         DAG_id_tag_update(&clip->id, 0);
2224         DAG_id_tag_update(&object->id, OB_RECALC_OB);
2225
2226         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2227         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
2228
2229         return OPERATOR_FINISHED;
2230 }
2231
2232 void CLIP_OT_set_axis(wmOperatorType *ot)
2233 {
2234         static EnumPropertyItem axis_actions[] = {
2235                 {0, "X", 0, "X", "Align bundle align X axis"},
2236                 {1, "Y", 0, "Y", "Align bundle align Y axis"},
2237                 {0, NULL, 0, NULL, NULL}
2238         };
2239
2240         /* identifiers */
2241         ot->name = "Set Axis";
2242         ot->description = "Set direction of scene axis rotating camera (or it's parent if present) and assuming selected track lies on real axis joining it with the origin";
2243         ot->idname = "CLIP_OT_set_axis";
2244
2245         /* api callbacks */
2246         ot->exec = set_axis_exec;
2247         ot->poll = set_orientation_poll;
2248
2249         /* flags */
2250         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2251
2252         /* properties */
2253         RNA_def_enum(ot->srna, "axis", axis_actions, 0, "Axis", "Axis to use to align bundle along");
2254 }
2255
2256 /********************** set scale operator *********************/
2257
2258 static int do_set_scale(bContext *C, wmOperator *op, int scale_solution)
2259 {
2260         SpaceClip *sc = CTX_wm_space_clip(C);
2261         MovieClip *clip = ED_space_clip_get_clip(sc);
2262         MovieTracking *tracking = &clip->tracking;
2263         MovieTrackingObject *tracking_object = BKE_tracking_object_get_active(tracking);
2264         MovieTrackingTrack *track;
2265         Scene *scene = CTX_data_scene(C);
2266         Object *object = NULL;
2267         Object *camera = get_camera_with_movieclip(scene, clip);
2268         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
2269         int tot = 0;
2270         float vec[2][3], mat[4][4], scale;
2271         float dist = RNA_float_get(op->ptr, "distance");
2272
2273         if (count_selected_bundles(C) != 2) {
2274                 BKE_report(op->reports, RPT_ERROR, "Two tracks with bundles should be selected to set scale");
2275
2276                 return OPERATOR_CANCELLED;
2277         }
2278
2279         object = get_orientation_object(C);
2280         if (!object) {
2281                 BKE_report(op->reports, RPT_ERROR, "No object to apply orientation on");
2282
2283                 return OPERATOR_CANCELLED;
2284         }
2285
2286         BKE_tracking_get_camera_object_matrix(scene, camera, mat);
2287
2288         track = tracksbase->first;
2289         while (track) {
2290                 if (TRACK_VIEW_SELECTED(sc, track)) {
2291                         mul_v3_m4v3(vec[tot], mat, track->bundle_pos);
2292                         tot++;
2293                 }
2294
2295                 track = track->next;
2296         }
2297
2298         sub_v3_v3(vec[0], vec[1]);
2299
2300         if (len_v3(vec[0]) > 1e-5f) {
2301                 scale = dist / len_v3(vec[0]);
2302
2303                 if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
2304                         mul_v3_fl(object->size, scale);
2305                         mul_v3_fl(object->loc, scale);
2306                 }
2307                 else if (!scale_solution) {
2308                         Object *solver_camera = object_solver_camera(scene, object);
2309
2310                         object->size[0] = object->size[1] = object->size[2] = 1.0f / scale;
2311
2312                         if (solver_camera) {
2313                                 object->size[0] /= solver_camera->size[0];
2314                                 object->size[1] /= solver_camera->size[1];
2315                                 object->size[2] /= solver_camera->size[2];
2316                         }
2317                 }
2318                 else {
2319                         tracking_object->scale = scale;
2320                 }
2321
2322                 DAG_id_tag_update(&clip->id, 0);
2323
2324                 if (object)
2325                         DAG_id_tag_update(&object->id, OB_RECALC_OB);
2326
2327                 WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2328                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
2329         }
2330
2331         return OPERATOR_FINISHED;
2332 }
2333
2334 static int set_scale_exec(bContext *C, wmOperator *op)
2335 {
2336         return do_set_scale(C, op, 0);
2337 }
2338
2339 static int set_scale_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2340 {
2341         SpaceClip *sc = CTX_wm_space_clip(C);
2342         MovieClip *clip = ED_space_clip_get_clip(sc);
2343
2344         if (!RNA_struct_property_is_set(op->ptr, "distance"))
2345                 RNA_float_set(op->ptr, "distance", clip->tracking.settings.dist);
2346
2347         return set_scale_exec(C, op);
2348 }
2349
2350 void CLIP_OT_set_scale(wmOperatorType *ot)
2351 {
2352         /* identifiers */
2353         ot->name = "Set Scale";
2354         ot->description = "Set scale of scene by scaling camera (or it's parent if present)";
2355         ot->idname = "CLIP_OT_set_scale";
2356
2357         /* api callbacks */
2358         ot->exec = set_scale_exec;
2359         ot->invoke = set_scale_invoke;
2360         ot->poll = set_orientation_poll;
2361
2362         /* flags */
2363         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2364
2365         /* properties */
2366         RNA_def_float(ot->srna, "distance", 0.0f, -FLT_MAX, FLT_MAX,
2367                       "Distance", "Distance between selected tracks", -100.0f, 100.0f);
2368 }
2369
2370 /********************** set solution scale operator *********************/
2371
2372 static int set_solution_scale_poll(bContext *C)
2373 {
2374         SpaceClip *sc = CTX_wm_space_clip(C);
2375
2376         if (sc) {
2377                 MovieClip *clip = ED_space_clip_get_clip(sc);
2378
2379                 if (clip) {
2380                         MovieTracking *tracking = &clip->tracking;
2381                         MovieTrackingObject *tracking_object = BKE_tracking_object_get_active(tracking);
2382
2383                         return (tracking_object->flag & TRACKING_OBJECT_CAMERA) == 0;
2384                 }
2385         }
2386
2387         return FALSE;
2388 }
2389
2390 static int set_solution_scale_exec(bContext *C, wmOperator *op)
2391 {
2392         return do_set_scale(C, op, 1);
2393 }
2394
2395 static int set_solution_scale_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
2396 {
2397         SpaceClip *sc = CTX_wm_space_clip(C);
2398         MovieClip *clip = ED_space_clip_get_clip(sc);
2399
2400         if (!RNA_struct_property_is_set(op->ptr, "distance"))
2401                 RNA_float_set(op->ptr, "distance", clip->tracking.settings.object_distance);
2402
2403         return set_solution_scale_exec(C, op);
2404 }
2405
2406 void CLIP_OT_set_solution_scale(wmOperatorType *ot)
2407 {
2408         /* identifiers */
2409         ot->name = "Set Solution Scale";
2410         ot->description = "Set object solution scale using distance between two selected tracks";
2411         ot->idname = "CLIP_OT_set_solution_scale";
2412
2413         /* api callbacks */
2414         ot->exec = set_solution_scale_exec;
2415         ot->invoke = set_solution_scale_invoke;
2416         ot->poll = set_solution_scale_poll;
2417
2418         /* flags */
2419         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2420
2421         /* properties */
2422         RNA_def_float(ot->srna, "distance", 0.0f, -FLT_MAX, FLT_MAX,
2423                       "Distance", "Distance between selected tracks", -100.0f, 100.0f);
2424 }
2425
2426 /********************** set principal center operator *********************/
2427
2428 static int set_center_principal_exec(bContext *C, wmOperator *UNUSED(op))
2429 {
2430         SpaceClip *sc = CTX_wm_space_clip(C);
2431         MovieClip *clip = ED_space_clip_get_clip(sc);
2432         int width, height;
2433
2434         BKE_movieclip_get_size(clip, &sc->user, &width, &height);
2435
2436         if (width == 0 || height == 0)
2437                 return OPERATOR_CANCELLED;
2438
2439         clip->tracking.camera.principal[0] = ((float)width) / 2.0f;
2440         clip->tracking.camera.principal[1] = ((float)height) / 2.0f;
2441
2442         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
2443
2444         return OPERATOR_FINISHED;
2445 }
2446
2447 void CLIP_OT_set_center_principal(wmOperatorType *ot)
2448 {
2449         /* identifiers */
2450         ot->name = "Set Principal to Center";
2451         ot->description = "Set optical center to center of footage";
2452         ot->idname = "CLIP_OT_set_center_principal";
2453
2454         /* api callbacks */
2455         ot->exec = set_center_principal_exec;
2456         ot->poll = ED_space_clip_tracking_poll;
2457
2458         /* flags */
2459         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2460 }
2461
2462 /********************** hide tracks operator *********************/
2463
2464 static int hide_tracks_exec(bContext *C, wmOperator *op)
2465 {
2466         SpaceClip *sc = CTX_wm_space_clip(C);
2467         MovieClip *clip = ED_space_clip_get_clip(sc);
2468         MovieTrackingTrack *track;
2469         MovieTracking *tracking = &clip->tracking;
2470         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
2471         MovieTrackingTrack *act_track = BKE_tracking_track_get_active(tracking);
2472         int unselected;
2473
2474         unselected = RNA_boolean_get(op->ptr, "unselected");
2475
2476         track = tracksbase->first;
2477         while (track) {
2478                 if (unselected == 0 && TRACK_VIEW_SELECTED(sc, track)) {
2479                         track->flag |= TRACK_HIDDEN;
2480                 }
2481                 else if (unselected == 1 && !TRACK_VIEW_SELECTED(sc, track)) {
2482                         track->flag |= TRACK_HIDDEN;
2483                 }
2484
2485                 track = track->next;
2486         }
2487
2488         if (act_track && act_track->flag & TRACK_HIDDEN)
2489                 clip->tracking.act_track = NULL;
2490
2491         if (unselected == 0) {
2492                 /* no selection on screen now, unlock view so it can be scrolled nice again */
2493                 sc->flag &= ~SC_LOCK_SELECTION;
2494         }
2495
2496         BKE_tracking_dopesheet_tag_update(tracking);
2497
2498         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, NULL);
2499
2500         return OPERATOR_FINISHED;
2501 }
2502
2503 void CLIP_OT_hide_tracks(wmOperatorType *ot)
2504 {
2505         /* identifiers */
2506         ot->name = "Hide Tracks";
2507         ot->description = "Hide selected tracks";
2508         ot->idname = "CLIP_OT_hide_tracks";
2509
2510         /* api callbacks */
2511         ot->exec = hide_tracks_exec;
2512         ot->poll = ED_space_clip_tracking_poll;
2513
2514         /* flags */
2515         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2516
2517         /* properties */
2518         RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected tracks");
2519 }
2520
2521 /********************** hide tracks clear operator *********************/
2522
2523 static int hide_tracks_clear_exec(bContext *C, wmOperator *UNUSED(op))
2524 {
2525         SpaceClip *sc = CTX_wm_space_clip(C);
2526         MovieClip *clip = ED_space_clip_get_clip(sc);
2527         MovieTracking *tracking = &clip->tracking;
2528         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
2529         MovieTrackingTrack *track;
2530
2531         track = tracksbase->first;
2532         while (track) {
2533                 track->flag &= ~TRACK_HIDDEN;
2534
2535                 track = track->next;
2536         }
2537
2538         BKE_tracking_dopesheet_tag_update(tracking);
2539
2540         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, NULL);
2541
2542         return OPERATOR_FINISHED;
2543 }
2544
2545 void CLIP_OT_hide_tracks_clear(wmOperatorType *ot)
2546 {
2547         /* identifiers */
2548         ot->name = "Hide Tracks Clear";
2549         ot->description = "Clear hide selected tracks";
2550         ot->idname = "CLIP_OT_hide_tracks_clear";
2551
2552         /* api callbacks */
2553         ot->exec = hide_tracks_clear_exec;
2554         ot->poll = ED_space_clip_tracking_poll;
2555
2556         /* flags */
2557         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2558 }
2559
2560 /********************** detect features operator *********************/
2561
2562 static bGPDlayer *detect_get_layer(MovieClip *clip)
2563 {
2564         bGPDlayer *layer;
2565
2566         if (!clip->gpd)
2567                 return NULL;
2568
2569         layer = clip->gpd->layers.first;
2570         while (layer) {
2571                 if (layer->flag & GP_LAYER_ACTIVE)
2572                         return layer;
2573
2574                 layer = layer->next;
2575         }
2576
2577         return NULL;
2578 }
2579
2580 static int detect_features_exec(bContext *C, wmOperator *op)
2581 {
2582         SpaceClip *sc = CTX_wm_space_clip(C);
2583         MovieClip *clip = ED_space_clip_get_clip(sc);
2584         int clip_flag = clip->flag & MCLIP_TIMECODE_FLAGS;
2585         ImBuf *ibuf = BKE_movieclip_get_ibuf_flag(clip, &sc->user, clip_flag, MOVIECLIP_CACHE_SKIP);
2586         MovieTracking *tracking = &clip->tracking;
2587         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
2588         MovieTrackingTrack *track = tracksbase->first;
2589         int placement = RNA_enum_get(op->ptr, "placement");
2590         int margin = RNA_int_get(op->ptr, "margin");
2591         int min_trackability = RNA_int_get(op->ptr, "min_trackability");
2592         int min_distance = RNA_int_get(op->ptr, "min_distance");
2593         int place_outside_layer = 0;
2594         int framenr = ED_space_clip_get_clip_frame_number(sc);
2595         bGPDlayer *layer = NULL;
2596
2597         if (!ibuf) {
2598                 BKE_report(op->reports, RPT_ERROR, "Feature detection requires valid clip frame");
2599                 return OPERATOR_CANCELLED;
2600         }
2601
2602         if (placement != 0) {
2603                 layer = detect_get_layer(clip);
2604                 place_outside_layer = placement == 2;
2605         }
2606
2607         /* deselect existing tracks */
2608         while (track) {
2609                 track->flag &= ~SELECT;
2610                 track->pat_flag &= ~SELECT;
2611                 track->search_flag &= ~SELECT;
2612
2613                 track = track->next;
2614         }
2615
2616         BKE_tracking_detect_fast(tracking, tracksbase, ibuf, framenr, margin,
2617                                  min_trackability, min_distance, layer, place_outside_layer);
2618
2619         IMB_freeImBuf(ibuf);
2620
2621         BKE_tracking_dopesheet_tag_update(tracking);
2622         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, NULL);
2623
2624         return OPERATOR_FINISHED;
2625 }
2626
2627 void CLIP_OT_detect_features(wmOperatorType *ot)
2628 {
2629         static EnumPropertyItem placement_items[] = {
2630                 {0, "FRAME",            0, "Whole Frame",           "Place markers across the whole frame"},
2631                 {1, "INSIDE_GPENCIL",   0, "Inside grease pencil",  "Place markers only inside areas outlined with grease pencil"},
2632                 {2, "OUTSIDE_GPENCIL",  0, "Outside grease pencil", "Place markers only outside areas outlined with grease pencil"},
2633                 {0, NULL, 0, NULL, NULL}
2634         };
2635
2636         /* identifiers */
2637         ot->name = "Detect Features";
2638         ot->description = "Automatically detect features and place markers to track";
2639         ot->idname = "CLIP_OT_detect_features";
2640
2641         /* api callbacks */
2642         ot->exec = detect_features_exec;
2643         ot->poll = ED_space_clip_tracking_poll;
2644
2645         /* flags */
2646         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2647
2648         /* properties */
2649         RNA_def_enum(ot->srna, "placement", placement_items, 0, "Placement", "Placement for detected features");
2650         RNA_def_int(ot->srna, "margin", 16, 0, INT_MAX, "Margin", "Only corners further than margin pixels from the image edges are considered", 0, 300);
2651         RNA_def_int(ot->srna, "min_trackability", 16, 0, INT_MAX, "Trackability", "Minimum trackability score to add a corner", 0, 300);
2652         RNA_def_int(ot->srna, "min_distance", 120, 0, INT_MAX, "Distance", "Minimal distance accepted between two corners", 0, 300);
2653 }
2654
2655 /********************** frame jump operator *********************/
2656
2657 static int frame_jump_exec(bContext *C, wmOperator *op)
2658 {
2659         Scene *scene = CTX_data_scene(C);
2660         SpaceClip *sc = CTX_wm_space_clip(C);
2661         MovieClip *clip = ED_space_clip_get_clip(sc);
2662         MovieTrackingTrack *track;
2663         int pos = RNA_enum_get(op->ptr, "position");
2664         int delta;
2665
2666         if (pos <= 1) { /* jump to path */
2667                 track = BKE_tracking_track_get_active(&clip->tracking);
2668
2669                 if (!track)
2670                         return OPERATOR_CANCELLED;
2671
2672                 delta = pos == 1 ? 1 : -1;
2673
2674                 while (sc->user.framenr + delta >= SFRA && sc->user.framenr + delta <= EFRA) {
2675                         int framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, sc->user.framenr + delta);
2676                         MovieTrackingMarker *marker = BKE_tracking_marker_get_exact(track, framenr);
2677
2678                         if (!marker || marker->flag & MARKER_DISABLED)
2679                                 break;
2680
2681                         sc->user.framenr += delta;
2682                 }
2683         }
2684         else {  /* to to failed frame */
2685                 if (clip->tracking.reconstruction.flag & TRACKING_RECONSTRUCTED) {
2686                         int a = ED_space_clip_get_clip_frame_number(sc);
2687                         MovieTracking *tracking = &clip->tracking;
2688                         MovieTrackingObject *object = BKE_tracking_object_get_active(tracking);
2689
2690                         delta = pos == 3 ? 1 : -1;
2691
2692                         a += delta;
2693
2694                         while (a + delta >= SFRA && a + delta <= EFRA) {
2695                                 MovieReconstructedCamera *cam;
2696
2697                                 cam = BKE_tracking_camera_get_reconstructed(tracking, object, a);
2698
2699                                 if (!cam) {
2700                                         sc->user.framenr = BKE_movieclip_remap_clip_to_scene_frame(clip, a);
2701
2702                                         break;
2703                                 }
2704
2705                                 a += delta;
2706                         }
2707                 }
2708         }
2709
2710         if (CFRA != sc->user.framenr) {
2711                 CFRA = sc->user.framenr;
2712                 sound_seek_scene(CTX_data_main(C), CTX_data_scene(C));
2713
2714                 WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
2715         }
2716
2717         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, NULL);
2718
2719         return OPERATOR_FINISHED;
2720 }
2721
2722 void CLIP_OT_frame_jump(wmOperatorType *ot)
2723 {
2724         static EnumPropertyItem position_items[] = {
2725                 {0, "PATHSTART",    0, "Path Start",        "Jump to start of current path"},
2726                 {1, "PATHEND",      0, "Path End",          "Jump to end of current path"},
2727                 {2, "FAILEDPREV",   0, "Previous Failed",   "Jump to previous failed frame"},
2728                 {2, "FAILNEXT",     0, "Next Failed",       "Jump to next failed frame"},
2729                 {0, NULL, 0, NULL, NULL}
2730         };
2731
2732         /* identifiers */
2733         ot->name = "Jump to Frame";
2734         ot->description = "Jump to special frame";
2735         ot->idname = "CLIP_OT_frame_jump";
2736
2737         /* api callbacks */
2738         ot->exec = frame_jump_exec;
2739         ot->poll = ED_space_clip_tracking_poll;
2740
2741         /* flags */
2742         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2743
2744         /* properties */
2745         RNA_def_enum(ot->srna, "position", position_items, 0, "Position", "Position to jump to");
2746 }
2747
2748 /********************** join tracks operator *********************/
2749
2750 static int join_tracks_exec(bContext *C, wmOperator *op)
2751 {
2752         SpaceClip *sc = CTX_wm_space_clip(C);
2753         MovieClip *clip = ED_space_clip_get_clip(sc);
2754         MovieTracking *tracking = &clip->tracking;
2755         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
2756         MovieTrackingTrack *act_track, *track, *next;
2757
2758         act_track = BKE_tracking_track_get_active(tracking);
2759
2760         if (!act_track) {
2761                 BKE_report(op->reports, RPT_ERROR, "No active track to join to");
2762                 return OPERATOR_CANCELLED;
2763         }
2764
2765         track = tracksbase->first;
2766         while (track) {
2767                 next = track->next;
2768
2769                 if (TRACK_VIEW_SELECTED(sc, track) && track != act_track) {
2770                         BKE_tracking_tracks_join(act_track, track);
2771
2772                         if (tracking->stabilization.rot_track == track)
2773                                 tracking->stabilization.rot_track = act_track;
2774
2775                         BKE_tracking_track_free(track);
2776                         BLI_freelinkN(tracksbase, track);
2777                 }
2778
2779                 track = next;
2780         }
2781
2782         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
2783
2784         return OPERATOR_FINISHED;
2785 }
2786
2787 void CLIP_OT_join_tracks(wmOperatorType *ot)
2788 {
2789         /* identifiers */
2790         ot->name = "Join Tracks";
2791         ot->description = "Join selected tracks";
2792         ot->idname = "CLIP_OT_join_tracks";
2793
2794         /* api callbacks */
2795         ot->exec = join_tracks_exec;
2796         ot->poll = ED_space_clip_tracking_poll;
2797
2798         /* flags */
2799         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2800 }
2801
2802 /********************** lock tracks operator *********************/
2803
2804 static int lock_tracks_exec(bContext *C, wmOperator *op)
2805 {
2806         SpaceClip *sc = CTX_wm_space_clip(C);
2807         MovieClip *clip = ED_space_clip_get_clip(sc);
2808         MovieTracking *tracking = &clip->tracking;
2809         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
2810         MovieTrackingTrack *track = tracksbase->first;
2811         int action = RNA_enum_get(op->ptr, "action");
2812
2813         while (track) {
2814                 if (TRACK_VIEW_SELECTED(sc, track)) {
2815                         if (action == 0)
2816                                 track->flag |= TRACK_LOCKED;
2817                         else if (action == 1)
2818                                 track->flag &= ~TRACK_LOCKED;
2819                         else track->flag ^= TRACK_LOCKED;
2820                 }
2821
2822                 track = track->next;
2823         }
2824
2825         WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
2826
2827         return OPERATOR_FINISHED;
2828 }
2829
2830 void CLIP_OT_lock_tracks(wmOperatorType *ot)
2831 {
2832         static EnumPropertyItem actions_items[] = {
2833                 {0, "LOCK", 0, "Lock", "Lock selected tracks"},
2834                 {1, "UNLOCK", 0, "Unlock", "Unlock selected tracks"},
2835                 {2, "TOGGLE", 0, "Toggle", "Toggle locked flag for selected tracks"},
2836                 {0, NULL, 0, NULL, NULL}
2837         };
2838
2839         /* identifiers */
2840         ot->name = "Lock Tracks";
2841         ot->description = "Lock/unlock selected tracks";
2842         ot->idname = "CLIP_OT_lock_tracks";
2843
2844         /* api callbacks */
2845         ot->exec = lock_tracks_exec;
2846         ot->poll = ED_space_clip_tracking_poll;
2847
2848         /* flags */
2849         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2850
2851         /* properties */
2852         RNA_def_enum(ot->srna, "action", actions_items, 0, "Action", "Lock action to execute");
2853 }
2854
2855 /********************** set keyframe operator *********************/
2856
2857 static int set_solver_keyframe_exec(bContext *C, wmOperator *op)
2858 {
2859         SpaceClip *sc = CTX_wm_space_clip(C);
2860         MovieClip *clip = ED_space_clip_get_clip(sc);
2861         MovieTracking *tracking = &clip->tracking;
2862         MovieTrackingSettings *settings = &tracking->settings;
2863         int keyframe = RNA_enum_get(op->ptr, "keyframe");
2864         int framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, sc->user.framenr);
2865
2866         if (keyframe == 0)
2867                 settings->keyframe1 = framenr;
2868         else
2869                 settings->keyframe2 = framenr;
2870
2871         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
2872
2873         return OPERATOR_FINISHED;
2874 }
2875
2876 void CLIP_OT_set_solver_keyframe(wmOperatorType *ot)
2877 {
2878         static EnumPropertyItem keyframe_items[] = {
2879                 {0, "KEYFRAME_A", 0, "Keyframe A", ""},
2880                 {1, "KEYFRAME_B", 0, "Keyframe B", ""},
2881                 {0, NULL, 0, NULL, NULL}
2882         };
2883
2884         /* identifiers */
2885         ot->name = "Set Solver Keyframe";
2886         ot->description = "Set keyframe used by solver";
2887         ot->idname = "CLIP_OT_set_solver_keyframe";
2888
2889         /* api callbacks */
2890         ot->exec = set_solver_keyframe_exec;
2891         ot->poll = ED_space_clip_tracking_poll;
2892
2893         /* flags */
2894         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2895
2896         /* properties */
2897         RNA_def_enum(ot->srna, "keyframe", keyframe_items, 0, "Keyframe", "keyframe to set");
2898 }
2899
2900 /********************** track copy color operator *********************/
2901
2902 static int track_copy_color_exec(bContext *C, wmOperator *UNUSED(op))
2903 {
2904         SpaceClip *sc = CTX_wm_space_clip(C);
2905         MovieClip *clip = ED_space_clip_get_clip(sc);
2906         MovieTracking *tracking = &clip->tracking;
2907         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
2908         MovieTrackingTrack *track, *act_track = BKE_tracking_track_get_active(tracking);
2909
2910         if (!act_track)
2911                 return OPERATOR_CANCELLED;
2912
2913         track = tracksbase->first;
2914         while (track) {
2915                 if (TRACK_VIEW_SELECTED(sc, track) && track != act_track) {
2916                         track->flag &= ~TRACK_CUSTOMCOLOR;
2917
2918                         if (act_track->flag & TRACK_CUSTOMCOLOR) {
2919                                 copy_v3_v3(track->color, act_track->color);
2920                                 track->flag |= TRACK_CUSTOMCOLOR;
2921                         }
2922                 }
2923
2924                 track = track->next;
2925         }
2926
2927         WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
2928
2929         return OPERATOR_FINISHED;
2930 }
2931
2932 void CLIP_OT_track_copy_color(wmOperatorType *ot)
2933 {
2934         /* identifiers */
2935         ot->name = "Copy Color";
2936         ot->description = "Copy color to all selected tracks";
2937         ot->idname = "CLIP_OT_track_copy_color";
2938
2939         /* api callbacks */
2940         ot->exec = track_copy_color_exec;
2941         ot->poll = ED_space_clip_tracking_poll;
2942
2943         /* flags */
2944         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2945 }
2946
2947 /********************** add 2d stabilization tracks operator *********************/
2948
2949 static int stabilize_2d_add_exec(bContext *C, wmOperator *UNUSED(op))
2950 {
2951         SpaceClip *sc = CTX_wm_space_clip(C);
2952         MovieClip *clip = ED_space_clip_get_clip(sc);
2953         MovieTracking *tracking = &clip->tracking;
2954         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
2955         MovieTrackingTrack *track;
2956         MovieTrackingStabilization *stab = &tracking->stabilization;
2957         int update = 0;
2958
2959         track = tracksbase->first;
2960         while (track) {
2961                 if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_USE_2D_STAB) == 0) {
2962                         track->flag |= TRACK_USE_2D_STAB;
2963                         stab->tot_track++;
2964
2965                         update = 1;
2966                 }
2967
2968                 track = track->next;
2969         }
2970
2971         if (update) {
2972                 stab->ok = 0;
2973
2974                 DAG_id_tag_update(&clip->id, 0);
2975                 WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
2976         }
2977
2978         return OPERATOR_FINISHED;
2979 }
2980
2981 void CLIP_OT_stabilize_2d_add(wmOperatorType *ot)
2982 {
2983         /* identifiers */
2984         ot->name = "Add Stabilization Tracks";
2985         ot->description = "Add selected tracks to 2D stabilization tool";
2986         ot->idname = "CLIP_OT_stabilize_2d_add";
2987
2988         /* api callbacks */
2989         ot->exec = stabilize_2d_add_exec;
2990         ot->poll = ED_space_clip_tracking_poll;
2991
2992         /* flags */
2993         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2994 }
2995
2996 /********************** remove 2d stabilization tracks operator *********************/
2997
2998 static int stabilize_2d_remove_exec(bContext *C, wmOperator *UNUSED(op))
2999 {
3000         SpaceClip *sc = CTX_wm_space_clip(C);
3001         MovieClip *clip = ED_space_clip_get_clip(sc);
3002         MovieTracking *tracking = &clip->tracking;
3003         MovieTrackingStabilization *stab = &tracking->stabilization;
3004         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
3005         MovieTrackingTrack *track;
3006         int a = 0, update = 0;
3007
3008         track = tracksbase->first;
3009         while (track) {
3010                 if (track->flag & TRACK_USE_2D_STAB) {
3011                         if (a == stab->act_track) {
3012                                 track->flag &= ~TRACK_USE_2D_STAB;
3013
3014                                 stab->act_track--;
3015                                 stab->tot_track--;
3016
3017                                 if (stab->act_track < 0)
3018                                         stab->act_track = 0;
3019
3020                                 update = 1;
3021
3022                                 break;
3023                         }
3024
3025                         a++;
3026                 }
3027
3028                 track = track->next;
3029         }
3030
3031         if (update) {
3032                 stab->ok = 0;
3033
3034                 DAG_id_tag_update(&clip->id, 0);
3035                 WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
3036         }
3037
3038         return OPERATOR_FINISHED;
3039 }
3040
3041 void CLIP_OT_stabilize_2d_remove(wmOperatorType *ot)
3042 {
3043         /* identifiers */
3044         ot->name = "Remove Stabilization Track";
3045         ot->description = "Remove selected track from stabilization";
3046         ot->idname = "CLIP_OT_stabilize_2d_remove";
3047
3048         /* api callbacks */
3049         ot->exec = stabilize_2d_remove_exec;
3050         ot->poll = ED_space_clip_tracking_poll;
3051
3052         /* flags */
3053         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3054 }
3055
3056 /********************** select 2d stabilization tracks operator *********************/
3057
3058 static int stabilize_2d_select_exec(bContext *C, wmOperator *UNUSED(op))
3059 {
3060         SpaceClip *sc = CTX_wm_space_clip(C);
3061         MovieClip *clip = ED_space_clip_get_clip(sc);
3062         MovieTracking *tracking = &clip->tracking;
3063         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
3064         MovieTrackingTrack *track;
3065         int update = 0;
3066
3067         track = tracksbase->first;
3068         while (track) {
3069                 if (track->flag & TRACK_USE_2D_STAB) {
3070                         BKE_tracking_track_flag_set(track, TRACK_AREA_ALL, SELECT);
3071
3072                         update = 1;
3073                 }
3074
3075                 track = track->next;
3076         }
3077
3078         if (update)
3079                 WM_event_add_notifier(C, NC_MOVIECLIP | ND_SELECT, clip);
3080
3081         return OPERATOR_FINISHED;
3082 }
3083
3084 void CLIP_OT_stabilize_2d_select(wmOperatorType *ot)
3085 {
3086         /* identifiers */
3087         ot->name = "Select Stabilization Tracks";
3088         ot->description = "Select track which are used for stabilization";
3089         ot->idname = "CLIP_OT_stabilize_2d_select";
3090
3091         /* api callbacks */
3092         ot->exec = stabilize_2d_select_exec;
3093         ot->poll = ED_space_clip_tracking_poll;
3094
3095         /* flags */
3096         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3097 }
3098
3099 /********************** set 2d stabilization rotation track operator *********************/
3100
3101 static int stabilize_2d_set_rotation_exec(bContext *C, wmOperator *UNUSED(op))
3102 {
3103         SpaceClip *sc = CTX_wm_space_clip(C);
3104         MovieClip *clip = ED_space_clip_get_clip(sc);
3105         MovieTracking *tracking = &clip->tracking;
3106         MovieTrackingTrack *act_track = BKE_tracking_track_get_active(tracking);
3107
3108         if (act_track) {
3109                 MovieTrackingStabilization *stab = &tracking->stabilization;
3110
3111                 stab->rot_track = act_track;
3112                 stab->ok = 0;
3113
3114                 DAG_id_tag_update(&clip->id, 0);
3115                 WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
3116         }
3117
3118         return OPERATOR_FINISHED;
3119 }
3120
3121 void CLIP_OT_stabilize_2d_set_rotation(wmOperatorType *ot)
3122 {
3123         /* identifiers */
3124         ot->name = "Set Rotation Track";
3125         ot->description = "Use active track to compensate rotation when doing 2D stabilization";
3126         ot->idname = "CLIP_OT_stabilize_2d_set_rotation";
3127
3128         /* api callbacks */
3129         ot->exec = stabilize_2d_set_rotation_exec;
3130         ot->poll = ED_space_clip_tracking_poll;
3131
3132         /* flags */
3133         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3134 }
3135
3136 /********************** clean tracks operator *********************/
3137
3138 static int is_track_clean(MovieTrackingTrack *track, int frames, int del)
3139 {
3140         int ok = 1, a, prev = -1, count = 0;
3141         MovieTrackingMarker *markers = track->markers, *new_markers = NULL;
3142         int start_disabled = 0;
3143         int markersnr = track->markersnr;
3144
3145         if (del)
3146                 new_markers = MEM_callocN(markersnr * sizeof(MovieTrackingMarker), "track cleaned markers");
3147
3148         for (a = 0; a < markersnr; a++) {
3149                 int end = 0;
3150
3151                 if (prev == -1) {
3152                         if ((markers[a].flag & MARKER_DISABLED) == 0)
3153                                 prev = a;
3154                         else
3155                                 start_disabled = 1;
3156                 }
3157
3158                 if (prev >= 0) {
3159                         end =  a == markersnr - 1;
3160                         end |= (a < markersnr - 1) && (markers[a].framenr != markers[a + 1].framenr - 1 ||
3161                                                        markers[a].flag & MARKER_DISABLED);
3162                 }
3163
3164                 if (end) {
3165                         int segok = 1, len = 0;
3166
3167                         if (a != prev && markers[a].framenr != markers[a - 1].framenr + 1)
3168                                 len = a - prev;
3169                         else if (markers[a].flag & MARKER_DISABLED)
3170                                 len = a - prev;
3171                         else len = a - prev + 1;
3172
3173                         if (frames) {
3174                                 if (len < frames) {
3175                                         segok = 0;
3176                                         ok = 0;
3177
3178                                         if (!del)
3179                                                 break;
3180                                 }
3181                         }
3182
3183                         if (del) {
3184                                 if (segok) {
3185                                         int t = len;
3186
3187                                         if (markers[a].flag & MARKER_DISABLED)
3188                                                 t++;
3189
3190                                         /* place disabled marker in front of current segment */
3191                                         if (start_disabled) {
3192                                                 memcpy(new_markers + count, markers + prev, sizeof(MovieTrackingMarker));
3193                                                 new_markers[count].framenr--;
3194                                                 new_markers[count].flag |= MARKER_DISABLED;
3195
3196                                                 count++;
3197                                                 start_disabled = 0;
3198                                         }
3199
3200                                         memcpy(new_markers + count, markers + prev, t * sizeof(MovieTrackingMarker));
3201                                         count += t;
3202                                 }
3203                                 else if (markers[a].flag & MARKER_DISABLED) {
3204                                         /* current segment which would be deleted was finished by disabled marker,
3205                                          * so next segment should be started from disabled marker */
3206                                         start_disabled = 1;
3207                                 }
3208                         }
3209
3210                         prev = -1;
3211                 }
3212         }
3213
3214         if (del) {
3215                 MEM_freeN(track->markers);
3216
3217                 if (count) {
3218                         track->markers = new_markers;
3219                 }
3220                 else {
3221                         track->markers = NULL;
3222                         MEM_freeN(new_markers);
3223                 }
3224
3225                 track->markersnr = count;
3226         }
3227
3228         return ok;
3229 }
3230
3231 static int clean_tracks_exec(bContext *C, wmOperator *op)
3232 {
3233         SpaceClip *sc = CTX_wm_space_clip(C);
3234         MovieClip *clip = ED_space_clip_get_clip(sc);
3235         MovieTracking *tracking = &clip->tracking;
3236         ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
3237         MovieTrackingTrack *track, *next, *act_track = BKE_tracking_track_get_active(tracking);
3238         int frames = RNA_int_get(op->ptr, "frames");
3239         int action = RNA_enum_get(op->ptr, "action");
3240         float error = RNA_float_get(op->ptr, "error");
3241
3242         if (error && action == TRACKING_CLEAN_DELETE_SEGMENT)
3243                 action = TRACKING_CLEAN_DELETE_TRACK;
3244
3245         track = tracksbase->first;
3246         while (track) {
3247                 next = track->next;
3248
3249                 if ((track->flag & TRACK_HIDDEN) == 0 && (track->flag & TRACK_LOCKED) == 0) {
3250                         int ok = 1;
3251
3252                         ok = (is_track_clean(track, frames, action == TRACKING_CLEAN_DELETE_SEGMENT)) &&
3253                              (error == 0.0f || (track->flag & TRACK_HAS_BUNDLE) == 0  || track->error < error);
3254
3255                         if (!ok) {
3256                                 if (action == TRACKING_CLEAN_SELECT) {