Curve Fitting: Add alternate 'refit' method
[blender-staging.git] / source / blender / editors / curve / editcurve_paint.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  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/editors/curve/editcurve_paint.c
22  *  \ingroup edcurve
23  */
24
25 #include "DNA_object_types.h"
26 #include "DNA_scene_types.h"
27
28 #include "MEM_guardedalloc.h"
29
30 #include "BLI_blenlib.h"
31 #include "BLI_math.h"
32 #include "BLI_mempool.h"
33
34 #include "BKE_context.h"
35 #include "BKE_curve.h"
36 #include "BKE_depsgraph.h"
37 #include "BKE_fcurve.h"
38 #include "BKE_report.h"
39
40 #include "WM_api.h"
41 #include "WM_types.h"
42
43 #include "ED_space_api.h"
44 #include "ED_screen.h"
45 #include "ED_view3d.h"
46 #include "ED_curve.h"
47
48 #include "BIF_gl.h"
49 #include "BIF_glutil.h"
50
51 #include "curve_intern.h"
52
53 #include "UI_resources.h"
54
55 #include "RNA_access.h"
56 #include "RNA_define.h"
57
58 #define USE_SPLINE_FIT
59
60 #ifdef USE_SPLINE_FIT
61 #include "curve_fit_nd.h"
62 #endif
63
64 /* Distance between input samples */
65 #define STROKE_SAMPLE_DIST_MIN_PX 3
66 #define STROKE_SAMPLE_DIST_MAX_PX 6
67
68
69 /* -------------------------------------------------------------------- */
70
71 /** \name Depth Utilities
72  * \{ */
73
74
75 static float depth_read_zbuf(const ViewContext *vc, int x, int y)
76 {
77         ViewDepths *vd = vc->rv3d->depths;
78
79         if (vd && vd->depths && x > 0 && y > 0 && x < vd->w && y < vd->h)
80                 return vd->depths[y * vd->w + x];
81         else
82                 return -1.0f;
83 }
84
85 static bool depth_unproject(
86         const ARegion *ar, const bglMats *mats,
87         const int mval[2], const double depth,
88         float r_location_world[3])
89 {
90         double p[3];
91         if (gluUnProject(
92                 (double)ar->winrct.xmin + mval[0] + 0.5,
93                 (double)ar->winrct.ymin + mval[1] + 0.5,
94                 depth, mats->modelview, mats->projection, (const GLint *)mats->viewport,
95                 &p[0], &p[1], &p[2]))
96         {
97                 copy_v3fl_v3db(r_location_world, p);
98                 return true;
99         }
100         return false;
101 }
102
103 static bool depth_read_normal(
104         const ViewContext *vc, const bglMats *mats, const int mval[2],
105         float r_normal[3])
106 {
107         /* pixels surrounding */
108         bool  depths_valid[9] = {false};
109         float coords[9][3] = {{0}};
110
111         ARegion *ar = vc->ar;
112         const ViewDepths *depths = vc->rv3d->depths;
113
114         for (int x = 0, i = 0; x < 2; x++) {
115                 for (int y = 0; y < 2; y++) {
116                         const int mval_ofs[2] = {mval[0] + (x - 1), mval[1] + (y - 1)};
117
118                         const double depth = (double)depth_read_zbuf(vc, mval_ofs[0], mval_ofs[1]);
119                         if ((depth > depths->depth_range[0]) && (depth < depths->depth_range[1])) {
120                                 if (depth_unproject(ar, mats, mval_ofs, depth, coords[i])) {
121                                         depths_valid[i] = true;
122                                 }
123                         }
124                         i++;
125                 }
126         }
127
128         const int edges[2][6][2] = {
129             /* x edges */
130             {{0, 1}, {1, 2},
131              {3, 4}, {4, 5},
132              {6, 7}, {7, 8}},
133             /* y edges */
134             {{0, 3}, {3, 6},
135              {1, 4}, {4, 7},
136              {2, 5}, {5, 8}},
137         };
138
139         float cross[2][3] = {{0.0f}};
140
141         for (int i = 0; i < 6; i++) {
142                 for (int axis = 0; axis < 2; axis++) {
143                         if (depths_valid[edges[axis][i][0]] && depths_valid[edges[axis][i][1]]) {
144                                 float delta[3];
145                                 sub_v3_v3v3(delta, coords[edges[axis][i][0]], coords[edges[axis][i][1]]);
146                                 add_v3_v3(cross[axis], delta);
147                         }
148                 }
149         }
150
151         cross_v3_v3v3(r_normal, cross[0], cross[1]);
152
153         if (normalize_v3(r_normal) != 0.0f) {
154                 return true;
155         }
156         else {
157                 return false;
158         }
159 }
160
161 /** \} */
162
163
164 /* -------------------------------------------------------------------- */
165
166 /** \name StrokeElem / #RNA_OperatorStrokeElement Conversion Functions
167  * \{ */
168
169 struct StrokeElem {
170         float mval[2];
171         float location_world[3];
172         float location_local[3];
173
174         /* surface normal, may be zero'd */
175         float normal_world[3];
176         float normal_local[3];
177
178         float pressure;
179 };
180
181 struct CurveDrawData {
182         short init_event_type;
183         short curve_type;
184
185         /* projecting 2D into 3D space */
186         struct {
187                 /* use a plane or project to the surface */
188                 bool use_plane;
189                 float    plane[4];
190
191                 /* use 'rv3d->depths', note that this will become 'damaged' while drawing, but thats OK. */
192                 bool use_depth;
193
194                 /* offset projection by this value */
195                 bool use_offset;
196                 float    offset[3];  /* worldspace */
197                 float    surface_offset;
198                 bool     use_surface_offset_absolute;
199         } project;
200
201         /* cursor sampling */
202         struct {
203                 /* use substeps, needed for nicely interpolating depth */
204                 bool use_substeps;
205         } sample;
206
207         struct {
208                 float min, max, range;
209         } radius;
210
211         struct {
212                 float mouse[2];
213                 /* used incase we can't calculate the depth */
214                 float location_world[3];
215
216                 float location_world_valid[3];
217
218                 const struct StrokeElem *selem;
219         } prev;
220
221         ViewContext vc;
222         bglMats mats;
223         enum {
224                 CURVE_DRAW_IDLE = 0,
225                 CURVE_DRAW_PAINTING = 1,
226         } state;
227
228         /* StrokeElem */
229         BLI_mempool *stroke_elem_pool;
230
231         void *draw_handle_view;
232 };
233
234 static float stroke_elem_radius_from_pressure(const struct CurveDrawData *cdd, const float pressure)
235 {
236         const Curve *cu = cdd->vc.obedit->data;
237         return ((pressure * cdd->radius.range) + cdd->radius.min) * cu->ext2;
238 }
239
240 static float stroke_elem_radius(const struct CurveDrawData *cdd, const struct StrokeElem *selem)
241 {
242         return stroke_elem_radius_from_pressure(cdd, selem->pressure);
243 }
244
245 static void stroke_elem_pressure_set(const struct CurveDrawData *cdd, struct StrokeElem *selem, float pressure)
246 {
247         if ((cdd->project.surface_offset != 0.0f) &&
248             !cdd->project.use_surface_offset_absolute &&
249             !is_zero_v3(selem->normal_local))
250         {
251                 const float adjust = stroke_elem_radius_from_pressure(cdd, pressure) -
252                                      stroke_elem_radius_from_pressure(cdd, selem->pressure);
253                 madd_v3_v3fl(selem->location_local, selem->normal_local, adjust);
254                 mul_v3_m4v3(selem->location_world, cdd->vc.obedit->obmat, selem->location_local);
255         }
256         selem->pressure = pressure;
257 }
258
259 static void stroke_elem_interp(
260         struct StrokeElem *selem_out,
261         const struct StrokeElem *selem_a,  const struct StrokeElem *selem_b, float t)
262 {
263         interp_v2_v2v2(selem_out->mval, selem_a->mval, selem_b->mval, t);
264         interp_v3_v3v3(selem_out->location_world, selem_a->location_world, selem_b->location_world, t);
265         interp_v3_v3v3(selem_out->location_local, selem_a->location_local, selem_b->location_local, t);
266         selem_out->pressure = interpf(selem_a->pressure, selem_b->pressure, t);
267 }
268
269
270 /**
271  * Sets the depth from #StrokeElem.mval
272  */
273 static bool stroke_elem_project(
274         const struct CurveDrawData *cdd,
275         const int mval_i[2], const float mval_fl[2],
276         float surface_offset, const float radius,
277         float r_location_world[3], float r_normal_world[3])
278 {
279         View3D *v3d = cdd->vc.v3d;
280         ARegion *ar = cdd->vc.ar;
281         RegionView3D *rv3d = cdd->vc.rv3d;
282
283         bool is_location_world_set = false;
284
285         /* project to 'location_world' */
286         if (cdd->project.use_plane) {
287                 /* get the view vector to 'location' */
288                 float ray_origin[3], ray_direction[3];
289                 ED_view3d_win_to_ray(cdd->vc.ar, v3d, mval_fl, ray_origin, ray_direction, false);
290
291                 float lambda;
292                 if (isect_ray_plane_v3(ray_origin, ray_direction, cdd->project.plane, &lambda, true)) {
293                         madd_v3_v3v3fl(r_location_world, ray_origin, ray_direction, lambda);
294                         if (r_normal_world) {
295                                 zero_v3(r_normal_world);
296                         }
297                         is_location_world_set = true;
298                 }
299         }
300         else {
301                 const ViewDepths *depths = rv3d->depths;
302                 if (depths &&
303                     ((unsigned int)mval_i[0] < depths->w) &&
304                     ((unsigned int)mval_i[1] < depths->h))
305                 {
306                         const double depth = (double)depth_read_zbuf(&cdd->vc, mval_i[0], mval_i[1]);
307                         if ((depth > depths->depth_range[0]) && (depth < depths->depth_range[1])) {
308                                 if (depth_unproject(ar, &cdd->mats, mval_i, depth, r_location_world)) {
309                                         is_location_world_set = true;
310                                         if (r_normal_world) {
311                                                 zero_v3(r_normal_world);
312                                         }
313
314                                         if (surface_offset != 0.0f) {
315                                                 const float offset = cdd->project.use_surface_offset_absolute ? 1.0f : radius;
316                                                 float normal[3];
317                                                 if (depth_read_normal(&cdd->vc, &cdd->mats, mval_i, normal)) {
318                                                         madd_v3_v3fl(r_location_world, normal, offset * surface_offset);
319                                                         if (r_normal_world) {
320                                                                 copy_v3_v3(r_normal_world, normal);
321                                                         }
322                                                 }
323                                         }
324                                 }
325                         }
326                 }
327         }
328
329         if (is_location_world_set) {
330                 if (cdd->project.use_offset) {
331                         add_v3_v3(r_location_world, cdd->project.offset);
332                 }
333         }
334
335         return is_location_world_set;
336 }
337
338 static bool stroke_elem_project_fallback(
339         const struct CurveDrawData *cdd,
340         const int mval_i[2], const float mval_fl[2],
341         const float surface_offset, const float radius,
342         const float location_fallback_depth[3],
343         float r_location_world[3], float r_location_local[3],
344         float r_normal_world[3], float r_normal_local[3])
345 {
346         bool is_depth_found = stroke_elem_project(
347                 cdd, mval_i, mval_fl,
348                 surface_offset, radius,
349                 r_location_world, r_normal_world);
350         if (is_depth_found == false) {
351                 ED_view3d_win_to_3d(cdd->vc.ar, location_fallback_depth, mval_fl, r_location_world);
352                 zero_v3(r_normal_local);
353         }
354         mul_v3_m4v3(r_location_local, cdd->vc.obedit->imat, r_location_world);
355
356         if (!is_zero_v3(r_normal_world)) {
357                 copy_v3_v3(r_normal_local, r_normal_world);
358                 mul_transposed_mat3_m4_v3(cdd->vc.obedit->obmat, r_normal_local);
359                 normalize_v3(r_normal_local);
360         }
361         else {
362                 zero_v3(r_normal_local);
363         }
364
365         return is_depth_found;
366 }
367
368 /**
369  * \note #StrokeElem.mval & #StrokeElem.pressure must be set first.
370  */
371 static bool stroke_elem_project_fallback_elem(
372         const struct CurveDrawData *cdd,
373         const float location_fallback_depth[3],
374         struct StrokeElem *selem)
375 {
376         const int mval_i[2] = {UNPACK2(selem->mval)};
377         const float radius = stroke_elem_radius(cdd, selem);
378         return stroke_elem_project_fallback(
379                 cdd, mval_i, selem->mval,
380                 cdd->project.surface_offset, radius,
381                 location_fallback_depth,
382                 selem->location_world, selem->location_local,
383                 selem->normal_world, selem->normal_local);
384 }
385
386 /** \} */
387
388
389 /* -------------------------------------------------------------------- */
390
391 /** \name Operator/Stroke Conversion
392  * \{ */
393
394 static void curve_draw_stroke_to_operator_elem(
395         wmOperator *op, const struct StrokeElem *selem)
396 {
397         PointerRNA itemptr;
398         RNA_collection_add(op->ptr, "stroke", &itemptr);
399
400         RNA_float_set_array(&itemptr, "mouse", selem->mval);
401         RNA_float_set_array(&itemptr, "location", selem->location_world);
402         RNA_float_set(&itemptr, "pressure", selem->pressure);
403 }
404
405 static void curve_draw_stroke_from_operator_elem(
406         wmOperator *op, PointerRNA *itemptr)
407 {
408         struct CurveDrawData *cdd = op->customdata;
409
410         struct StrokeElem *selem = BLI_mempool_calloc(cdd->stroke_elem_pool);
411
412         RNA_float_get_array(itemptr, "mouse", selem->mval);
413         RNA_float_get_array(itemptr, "location", selem->location_world);
414         mul_v3_m4v3(selem->location_local, cdd->vc.obedit->imat, selem->location_world);
415         selem->pressure = RNA_float_get(itemptr, "pressure");
416 }
417
418 static void curve_draw_stroke_to_operator(wmOperator *op)
419 {
420         struct CurveDrawData *cdd = op->customdata;
421
422         BLI_mempool_iter iter;
423         const struct StrokeElem *selem;
424
425         BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
426         for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter)) {
427                 curve_draw_stroke_to_operator_elem(op, selem);
428         }
429 }
430
431 static void curve_draw_stroke_from_operator(wmOperator *op)
432 {
433         RNA_BEGIN (op->ptr, itemptr, "stroke")
434         {
435                 curve_draw_stroke_from_operator_elem(op, &itemptr);
436         }
437         RNA_END;
438 }
439
440 /** \} */
441
442
443 /* -------------------------------------------------------------------- */
444
445 /** \name Operator Callbacks & Helpers
446  * \{ */
447
448 static void curve_draw_stroke_3d(const struct bContext *UNUSED(C), ARegion *UNUSED(ar), void *arg)
449 {
450         wmOperator *op = arg;
451         struct CurveDrawData *cdd = op->customdata;
452
453         const int stroke_len = BLI_mempool_count(cdd->stroke_elem_pool);
454
455         if (stroke_len == 0) {
456                 return;
457         }
458
459         View3D *v3d = cdd->vc.v3d;
460         Object *obedit = cdd->vc.obedit;
461         Curve *cu = obedit->data;
462
463         UI_ThemeColor(TH_WIRE);
464
465         if (cu->ext2 > 0.0f) {
466                 GLUquadricObj *qobj = gluNewQuadric();
467
468                 gluQuadricDrawStyle(qobj, GLU_FILL);
469
470                 BLI_mempool_iter iter;
471                 const struct StrokeElem *selem;
472
473                 const float  location_zero[3] = {0};
474                 const float *location_prev = location_zero;
475
476                 /* scale to edit-mode space */
477                 glPushMatrix();
478                 glMultMatrixf(obedit->obmat);
479
480                 BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
481                 for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter)) {
482                         glTranslatef(
483                                 selem->location_local[0] - location_prev[0],
484                                 selem->location_local[1] - location_prev[1],
485                                 selem->location_local[2] - location_prev[2]);
486                         location_prev = selem->location_local;
487                         const float radius = stroke_elem_radius(cdd, selem);
488                         gluSphere(qobj, radius, 12, 8);
489
490                         location_prev = selem->location_local;
491                 }
492
493                 glPopMatrix();
494
495                 gluDeleteQuadric(qobj);
496         }
497
498         if (stroke_len > 1) {
499                 float (*coord_array)[3] = MEM_mallocN(sizeof(*coord_array) * stroke_len, __func__);
500
501                 {
502                         BLI_mempool_iter iter;
503                         const struct StrokeElem *selem;
504                         int i;
505                         BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
506                         for (selem = BLI_mempool_iterstep(&iter), i = 0; selem; selem = BLI_mempool_iterstep(&iter), i++) {
507                                 copy_v3_v3(coord_array[i], selem->location_world);
508                         }
509                 }
510
511                 {
512                         glEnable(GL_BLEND);
513                         glEnable(GL_LINE_SMOOTH);
514
515                         glEnableClientState(GL_VERTEX_ARRAY);
516                         glVertexPointer(3, GL_FLOAT, 0, coord_array);
517
518                         cpack(0x0);
519                         glLineWidth(3.0f);
520                         glDrawArrays(GL_LINE_STRIP, 0, stroke_len);
521
522                         if (v3d->zbuf)
523                                 glDisable(GL_DEPTH_TEST);
524
525                         cpack(0xffffffff);
526                         glLineWidth(1.0f);
527                         glDrawArrays(GL_LINE_STRIP, 0, stroke_len);
528
529                         if (v3d->zbuf)
530                                 glEnable(GL_DEPTH_TEST);
531
532                         glDisableClientState(GL_VERTEX_ARRAY);
533
534                         glDisable(GL_BLEND);
535                         glDisable(GL_LINE_SMOOTH);
536                 }
537
538                 MEM_freeN(coord_array);
539         }
540 }
541
542 static void curve_draw_event_add(wmOperator *op, const wmEvent *event)
543 {
544         struct CurveDrawData *cdd = op->customdata;
545         Object *obedit = cdd->vc.obedit;
546
547         invert_m4_m4(obedit->imat, obedit->obmat);
548
549         struct StrokeElem *selem = BLI_mempool_calloc(cdd->stroke_elem_pool);
550
551         ARRAY_SET_ITEMS(selem->mval, event->mval[0], event->mval[1]);
552
553         /* handle pressure sensitivity (which is supplied by tablets) */
554         if (event->tablet_data) {
555                 const wmTabletData *wmtab = event->tablet_data;
556                 selem->pressure = wmtab->Pressure;
557         }
558         else {
559                 selem->pressure = 1.0f;
560         }
561
562         bool is_depth_found = stroke_elem_project_fallback_elem(
563                 cdd, cdd->prev.location_world_valid, selem);
564
565         if (is_depth_found) {
566                 /* use the depth if a fallback wasn't used */
567                 copy_v3_v3(cdd->prev.location_world_valid, selem->location_world);
568         }
569         copy_v3_v3(cdd->prev.location_world, selem->location_world);
570
571         float len_sq = len_squared_v2v2(cdd->prev.mouse, selem->mval);
572         copy_v2_v2(cdd->prev.mouse, selem->mval);
573
574         if (cdd->sample.use_substeps && cdd->prev.selem) {
575                 const struct StrokeElem selem_target = *selem;
576                 struct StrokeElem *selem_new_last = selem;
577                 if (len_sq >= SQUARE(STROKE_SAMPLE_DIST_MAX_PX)) {
578                         int n = (int)ceil(sqrt((double)len_sq)) / STROKE_SAMPLE_DIST_MAX_PX ;
579
580                         for (int i = 1; i < n; i++) {
581                                 struct StrokeElem *selem_new = selem_new_last;
582                                 stroke_elem_interp(selem_new, cdd->prev.selem, &selem_target, (float)i / n);
583
584                                 const bool is_depth_found_substep = stroke_elem_project_fallback_elem(
585                                         cdd, cdd->prev.location_world_valid, selem_new);
586                                 if (is_depth_found == false) {
587                                         if (is_depth_found_substep) {
588                                                 copy_v3_v3(cdd->prev.location_world_valid, selem_new->location_world);
589                                         }
590                                 }
591
592                                 selem_new_last = BLI_mempool_calloc(cdd->stroke_elem_pool);
593                         }
594                 }
595                 selem = selem_new_last;
596                 *selem_new_last = selem_target;
597         }
598
599         cdd->prev.selem = selem;
600
601         ED_region_tag_redraw(cdd->vc.ar);
602 }
603
604 static void curve_draw_event_add_first(wmOperator *op, const wmEvent *event)
605 {
606         struct CurveDrawData *cdd = op->customdata;
607         const CurvePaintSettings *cps = &cdd->vc.scene->toolsettings->curve_paint_settings;
608
609         /* add first point */
610         curve_draw_event_add(op, event);
611
612         if ((cps->depth_mode == CURVE_PAINT_PROJECT_SURFACE) && cdd->project.use_depth &&
613             (cps->flag & CURVE_PAINT_FLAG_DEPTH_STROKE_ENDPOINTS))
614         {
615                 RegionView3D *rv3d = cdd->vc.rv3d;
616
617                 cdd->project.use_depth = false;
618                 cdd->project.use_plane = true;
619
620                 float normal[3] = {0.0f};
621                 if (ELEM(cps->surface_plane,
622                          CURVE_PAINT_SURFACE_PLANE_NORMAL_VIEW,
623                          CURVE_PAINT_SURFACE_PLANE_NORMAL_SURFACE))
624                 {
625                         if (depth_read_normal(&cdd->vc, &cdd->mats, event->mval, normal)) {
626                                 if (cps->surface_plane == CURVE_PAINT_SURFACE_PLANE_NORMAL_VIEW) {
627                                         float cross_a[3], cross_b[3];
628                                         cross_v3_v3v3(cross_a, rv3d->viewinv[2], normal);
629                                         cross_v3_v3v3(cross_b, normal, cross_a);
630                                         copy_v3_v3(normal, cross_b);
631                                 }
632                         }
633                 }
634
635                 /* CURVE_PAINT_SURFACE_PLANE_VIEW or fallback */
636                 if (is_zero_v3(normal)) {
637                         copy_v3_v3(normal, rv3d->viewinv[2]);
638                 }
639
640                 normalize_v3_v3(cdd->project.plane, normal);
641                 cdd->project.plane[3] = -dot_v3v3(cdd->project.plane, cdd->prev.location_world_valid);
642
643                 /* Special case for when we only have offset applied on the first-hit,
644                  * the remaining stroke must be offset too. */
645                 if (cdd->project.surface_offset != 0.0f) {
646                         const float mval_fl[2] = {UNPACK2(event->mval)};
647
648                         float location_no_offset[3];
649
650                         if (stroke_elem_project(
651                                 cdd, event->mval, mval_fl, 0.0f, 0.0f,
652                                 location_no_offset, NULL))
653                         {
654                                 sub_v3_v3v3(cdd->project.offset, cdd->prev.location_world_valid, location_no_offset);
655                                 if (!is_zero_v3(cdd->project.offset)) {
656                                         cdd->project.use_offset = true;
657                                 }
658                         }
659                 }
660                 /* end special case */
661
662         }
663
664         cdd->init_event_type = event->type;
665         cdd->state = CURVE_DRAW_PAINTING;
666 }
667
668 static bool curve_draw_init(bContext *C, wmOperator *op, bool is_invoke)
669 {
670         BLI_assert(op->customdata == NULL);
671
672         struct CurveDrawData *cdd = MEM_callocN(sizeof(*cdd), __func__);
673
674         if (is_invoke) {
675                 view3d_set_viewcontext(C, &cdd->vc);
676                 if (ELEM(NULL, cdd->vc.ar, cdd->vc.rv3d, cdd->vc.v3d, cdd->vc.win, cdd->vc.scene)) {
677                         MEM_freeN(cdd);
678                         BKE_report(op->reports, RPT_ERROR, "Unable to access 3D viewport");
679                         return false;
680                 }
681         }
682         else {
683                 cdd->vc.scene = CTX_data_scene(C);
684                 cdd->vc.obedit = CTX_data_edit_object(C);
685         }
686
687         op->customdata = cdd;
688
689         const CurvePaintSettings *cps = &cdd->vc.scene->toolsettings->curve_paint_settings;
690
691         cdd->curve_type = cps->curve_type;
692
693         cdd->radius.min = cps->radius_min;
694         cdd->radius.max = cps->radius_max;
695         cdd->radius.range = cps->radius_max - cps->radius_min;
696         cdd->project.surface_offset = cps->surface_offset;
697         cdd->project.use_surface_offset_absolute = (cps->flag & CURVE_PAINT_FLAG_DEPTH_STROKE_OFFSET_ABS) != 0;
698
699         cdd->stroke_elem_pool = BLI_mempool_create(
700                 sizeof(struct StrokeElem), 0, 512, BLI_MEMPOOL_ALLOW_ITER);
701
702         return true;
703 }
704
705
706 static void curve_draw_exit(wmOperator *op)
707 {
708         struct CurveDrawData *cdd = op->customdata;
709         if (cdd) {
710                 if (cdd->draw_handle_view) {
711                         ED_region_draw_cb_exit(cdd->vc.ar->type, cdd->draw_handle_view);
712                         WM_cursor_modal_restore(cdd->vc.win);
713                 }
714
715                 if (cdd->stroke_elem_pool) {
716                         BLI_mempool_destroy(cdd->stroke_elem_pool);
717                 }
718
719                 MEM_freeN(cdd);
720                 op->customdata = NULL;
721         }
722 }
723
724 /**
725  * Initialize values before calling 'exec' (when running interactively).
726  */
727 static void curve_draw_exec_precalc(wmOperator *op)
728 {
729         struct CurveDrawData *cdd = op->customdata;
730         const CurvePaintSettings *cps = &cdd->vc.scene->toolsettings->curve_paint_settings;
731         PropertyRNA *prop;
732
733         prop = RNA_struct_find_property(op->ptr, "corner_angle");
734         if (!RNA_property_is_set(op->ptr, prop)) {
735                 const float corner_angle = (cps->flag & CURVE_PAINT_FLAG_CORNERS_DETECT) ? cps->corner_angle : (float)M_PI;
736                 RNA_property_float_set(op->ptr, prop, corner_angle);
737         }
738
739         prop = RNA_struct_find_property(op->ptr, "error_threshold");
740         if (!RNA_property_is_set(op->ptr, prop)) {
741
742                 /* error isnt set so we'll have to calculate it from the pixel values */
743                 BLI_mempool_iter iter;
744                 const struct StrokeElem *selem, *selem_prev;
745
746                 float len_3d = 0.0f, len_2d = 0.0f;
747                 float scale_px;  /* pixel to local space scale */
748
749                 int i = 0;
750                 BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
751                 selem_prev = BLI_mempool_iterstep(&iter);
752                 for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter), i++) {
753                         len_3d += len_v3v3(selem->location_local, selem_prev->location_local);
754                         len_2d += len_v2v2(selem->mval, selem_prev->mval);
755                         selem_prev = selem;
756                 }
757                 scale_px = ((len_3d > 0.0f) && (len_2d > 0.0f)) ?  (len_3d / len_2d) : 0.0f;
758                 float error_threshold = (cps->error_threshold * U.pixelsize) * scale_px;
759                 RNA_property_float_set(op->ptr, prop, error_threshold);
760         }
761
762         if ((cps->radius_taper_start != 0.0f) ||
763             (cps->radius_taper_end   != 0.0f))
764         {
765                 /* note, we could try to de-duplicate the length calculations above */
766                 const int stroke_len = BLI_mempool_count(cdd->stroke_elem_pool);
767
768                 BLI_mempool_iter iter;
769                 struct StrokeElem *selem, *selem_prev;
770
771                 float *lengths = MEM_mallocN(sizeof(float) * stroke_len, __func__);
772                 struct StrokeElem **selem_array = MEM_mallocN(sizeof(*selem_array) * stroke_len, __func__);
773                 lengths[0] = 0.0f;
774
775                 float len_3d = 0.0f;
776
777                 int i = 1;
778                 BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
779                 selem_prev = BLI_mempool_iterstep(&iter);
780                 selem_array[0] = selem_prev;
781                 for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter), i++) {
782                         const float len_3d_segment = len_v3v3(selem->location_local, selem_prev->location_local);
783                         len_3d += len_3d_segment;
784                         lengths[i] = len_3d;
785                         selem_array[i] = selem;
786                         selem_prev = selem;
787                 }
788
789                 if (cps->radius_taper_start != 0.0f) {
790                         const float len_taper_max = cps->radius_taper_start * len_3d;
791                         for (i = 0; i < stroke_len && lengths[i] < len_taper_max; i++) {
792                                 const float pressure_new = selem_array[i]->pressure * (lengths[i] / len_taper_max);
793                                 stroke_elem_pressure_set(cdd, selem_array[i], pressure_new);
794                         }
795                 }
796
797                 if (cps->radius_taper_end != 0.0f) {
798                         const float len_taper_max = cps->radius_taper_end * len_3d;
799                         const float len_taper_min = len_3d - len_taper_max;
800                         for (i = stroke_len - 1; i > 0 && lengths[i] > len_taper_min; i--) {
801                                 const float pressure_new = selem_array[i]->pressure * ((len_3d - lengths[i]) / len_taper_max);
802                                 stroke_elem_pressure_set(cdd, selem_array[i], pressure_new);
803                         }
804                 }
805
806                 MEM_freeN(lengths);
807                 MEM_freeN(selem_array);
808         }
809 }
810
811 static int curve_draw_exec(bContext *C, wmOperator *op)
812 {
813         if (op->customdata == NULL) {
814                 if (!curve_draw_init(C, op, false)) {
815                         return OPERATOR_CANCELLED;
816                 }
817         }
818
819         struct CurveDrawData *cdd = op->customdata;
820
821         const CurvePaintSettings *cps = &cdd->vc.scene->toolsettings->curve_paint_settings;
822         Object *obedit = cdd->vc.scene->obedit;
823         Curve *cu = obedit->data;
824         ListBase *nurblist = object_editcurve_get(obedit);
825
826         int stroke_len = BLI_mempool_count(cdd->stroke_elem_pool);
827
828         const bool is_3d = (cu->flag & CU_3D) != 0;
829         invert_m4_m4(obedit->imat, obedit->obmat);
830
831         if (BLI_mempool_count(cdd->stroke_elem_pool) == 0) {
832                 curve_draw_stroke_from_operator(op);
833                 stroke_len = BLI_mempool_count(cdd->stroke_elem_pool);
834         }
835
836         ED_curve_deselect_all(cu->editnurb);
837
838         const float radius_min = cps->radius_min;
839         const float radius_max = cps->radius_max;
840         const float radius_range = cps->radius_max - cps->radius_min;
841
842         Nurb *nu = MEM_callocN(sizeof(Nurb), __func__);
843         nu->pntsv = 1;
844         nu->resolu = cu->resolu;
845         nu->resolv = cu->resolv;
846         nu->flag |= CU_SMOOTH;
847
848         const bool use_pressure_radius =
849                 (cps->flag & CURVE_PAINT_FLAG_PRESSURE_RADIUS) ||
850                 ((cps->radius_taper_start != 0.0f) ||
851                  (cps->radius_taper_end   != 0.0f));
852
853         if (cdd->curve_type == CU_BEZIER) {
854                 nu->type = CU_BEZIER;
855
856 #ifdef USE_SPLINE_FIT
857
858                 /* Allow to interpolate multiple channels */
859                 int dims = 3;
860                 struct {
861                         int radius;
862                 } coords_indices;
863                 coords_indices.radius = use_pressure_radius ? dims++ : -1;
864
865                 float *coords = MEM_mallocN(sizeof(*coords) * stroke_len * dims, __func__);
866
867                 float       *cubic_spline = NULL;
868                 unsigned int cubic_spline_len = 0;
869
870                 /* error in object local space */
871                 const float error_threshold = RNA_float_get(op->ptr, "error_threshold");
872                 const float corner_angle = RNA_float_get(op->ptr, "corner_angle");
873
874                 {
875                         BLI_mempool_iter iter;
876                         const struct StrokeElem *selem;
877                         float *co = coords;
878
879                         BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
880                         for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter), co += dims) {
881                                 copy_v3_v3(co, selem->location_local);
882                                 if (coords_indices.radius != -1) {
883                                         co[coords_indices.radius] = selem->pressure;
884                                 }
885
886                                 /* remove doubles */
887                                 if ((co != coords) && UNLIKELY(memcmp(co, co - dims, sizeof(float) * dims) == 0)) {
888                                         co -= dims;
889                                         stroke_len--;
890                                 }
891                         }
892                 }
893
894                 unsigned int *corners = NULL;
895                 unsigned int  corners_len = 0;
896
897                 if (corner_angle < (float)M_PI) {
898                         /* this could be configurable... */
899                         const float corner_radius_min = error_threshold / 8;
900                         const float corner_radius_max = error_threshold * 2;
901                         const unsigned int samples_max = 16;
902
903                         curve_fit_corners_detect_fl(
904                                 (const float *)coords, stroke_len, dims,
905                                 corner_radius_min, corner_radius_max,
906                                 samples_max, corner_angle,
907                                 &corners, &corners_len);
908                 }
909
910                 unsigned int *corners_index = NULL;
911                 unsigned int  corners_index_len = 0;
912
913                 const int result = curve_fit_cubic_to_points_fl(
914                         coords, stroke_len, dims, error_threshold, CURVE_FIT_CALC_HIGH_QUALIY,
915                         corners, NULL, corners_len,
916                         &cubic_spline, &cubic_spline_len,
917                         NULL,
918                         &corners_index, &corners_index_len);
919
920                 MEM_freeN(coords);
921                 if (corners) {
922                         free(corners);
923                 }
924
925                 if (result == 0) {
926                         nu->pntsu = cubic_spline_len;
927                         nu->bezt = MEM_callocN(sizeof(BezTriple) * nu->pntsu, __func__);
928
929                         float *co = cubic_spline;
930                         BezTriple *bezt = nu->bezt;
931                         for (int j = 0; j < cubic_spline_len; j++, bezt++, co += (dims * 3)) {
932                                 const float *handle_l = co + (dims * 0);
933                                 const float *pt       = co + (dims * 1);
934                                 const float *handle_r = co + (dims * 2);
935
936                                 copy_v3_v3(bezt->vec[0], handle_l);
937                                 copy_v3_v3(bezt->vec[1], pt);
938                                 copy_v3_v3(bezt->vec[2], handle_r);
939
940                                 if (coords_indices.radius != -1) {
941                                         bezt->radius = (pt[coords_indices.radius] * cdd->radius.range) + cdd->radius.min;
942                                 }
943                                 else {
944                                         bezt->radius = radius_max;
945                                 }
946
947                                 bezt->h1 = bezt->h2 = HD_ALIGN;  /* will set to free in second pass */
948                                 bezt->f1 = bezt->f2 = bezt->f3 = SELECT;
949                         }
950
951                         if (corners_index) {
952                                 /* ignore the first and last */
953                                 for (unsigned int i = 1; i < corners_index_len - 1; i++) {
954                                         bezt = &nu->bezt[corners_index[i]];
955                                         bezt->h1 = bezt->h2 = HD_FREE;
956                                 }
957                         }
958                 }
959
960                 if (corners_index) {
961                         free(corners_index);
962                 }
963
964                 if (cubic_spline) {
965                         free(cubic_spline);
966                 }
967
968 #else
969                 nu->pntsu = stroke_len;
970                 nu->bezt = MEM_callocN(nu->pntsu * sizeof(BezTriple), __func__);
971
972                 BezTriple *bezt = nu->bezt;
973
974                 {
975                         BLI_mempool_iter iter;
976                         const struct StrokeElem *selem;
977
978                         BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
979                         for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter)) {
980                                 copy_v3_v3(bezt->vec[1], selem->location_local);
981                                 if (!is_3d) {
982                                         bezt->vec[1][2] = 0.0f;
983                                 }
984
985                                 if (use_pressure_radius) {
986                                         bezt->radius = selem->pressure;
987                                 }
988                                 else {
989                                         bezt->radius = radius_max;
990                                 }
991
992                                 bezt->h1 = bezt->h2 = HD_AUTO;
993
994                                 bezt->f1 |= SELECT;
995                                 bezt->f2 |= SELECT;
996                                 bezt->f3 |= SELECT;
997
998                                 bezt++;
999                         }
1000                 }
1001 #endif
1002
1003                 BKE_nurb_handles_calc(nu);
1004         }
1005         else {  /* CU_POLY */
1006                 BLI_mempool_iter iter;
1007                 const struct StrokeElem *selem;
1008
1009                 nu->pntsu = stroke_len;
1010                 nu->type = CU_POLY;
1011                 nu->bp = MEM_callocN(nu->pntsu * sizeof(BPoint), __func__);
1012
1013                 BPoint *bp = nu->bp;
1014
1015                 BLI_mempool_iternew(cdd->stroke_elem_pool, &iter);
1016                 for (selem = BLI_mempool_iterstep(&iter); selem; selem = BLI_mempool_iterstep(&iter)) {
1017                         copy_v3_v3(bp->vec, selem->location_local);
1018                         if (!is_3d) {
1019                                 bp->vec[2] = 0.0f;
1020                         }
1021
1022                         if (use_pressure_radius) {
1023                                 bp->radius = (selem->pressure * radius_range) + radius_min;
1024                         }
1025                         else {
1026                                 bp->radius = cps->radius_max;
1027                         }
1028                         bp->f1 = SELECT;
1029                         bp->vec[3] = 1.0f;
1030
1031                         bp++;
1032                 }
1033
1034                 BKE_nurb_knot_calc_u(nu);
1035         }
1036
1037         BLI_addtail(nurblist, nu);
1038
1039         BKE_curve_nurb_active_set(cu, nu);
1040         cu->actvert = nu->pntsu - 1;
1041
1042         WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
1043         DAG_id_tag_update(obedit->data, 0);
1044
1045         curve_draw_exit(op);
1046
1047         return OPERATOR_FINISHED;
1048 }
1049
1050 static int curve_draw_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1051 {
1052         if (RNA_struct_property_is_set(op->ptr, "stroke")) {
1053                 return curve_draw_exec(C, op);
1054         }
1055
1056         if (!curve_draw_init(C, op, true)) {
1057                 return OPERATOR_CANCELLED;
1058         }
1059
1060         struct CurveDrawData *cdd = op->customdata;
1061
1062         const CurvePaintSettings *cps = &cdd->vc.scene->toolsettings->curve_paint_settings;
1063
1064         const bool is_modal = RNA_boolean_get(op->ptr, "wait_for_input");
1065
1066         /* fallback (incase we can't find the depth on first test) */
1067         {
1068                 const float mval_fl[2] = {UNPACK2(event->mval)};
1069                 float center[3];
1070                 negate_v3_v3(center, cdd->vc.rv3d->ofs);
1071                 ED_view3d_win_to_3d(cdd->vc.ar, center, mval_fl, cdd->prev.location_world);
1072                 copy_v3_v3(cdd->prev.location_world_valid, cdd->prev.location_world);
1073         }
1074
1075         cdd->draw_handle_view = ED_region_draw_cb_activate(
1076                 cdd->vc.ar->type, curve_draw_stroke_3d, op, REGION_DRAW_POST_VIEW);
1077         WM_cursor_modal_set(cdd->vc.win, BC_PAINTBRUSHCURSOR);
1078
1079         {
1080                 View3D *v3d = cdd->vc.v3d;
1081                 RegionView3D *rv3d = cdd->vc.rv3d;
1082                 Object *obedit = cdd->vc.obedit;
1083                 Curve *cu = obedit->data;
1084
1085                 const float *plane_no = NULL;
1086                 const float *plane_co = NULL;
1087
1088                 if ((cu->flag & CU_3D) == 0) {
1089                         /* 2D overrides other options */
1090                         plane_co = obedit->obmat[3];
1091                         plane_no = obedit->obmat[2];
1092                         cdd->project.use_plane = true;
1093                 }
1094                 else {
1095                         if ((cps->depth_mode == CURVE_PAINT_PROJECT_SURFACE) &&
1096                             (v3d->drawtype > OB_WIRE))
1097                         {
1098                                 view3d_get_transformation(cdd->vc.ar, cdd->vc.rv3d, NULL, &cdd->mats);
1099
1100                                 /* needed or else the draw matrix can be incorrect */
1101                                 view3d_operator_needs_opengl(C);
1102
1103                                 ED_view3d_autodist_init(cdd->vc.scene, cdd->vc.ar, cdd->vc.v3d, 0);
1104
1105                                 if (cdd->vc.rv3d->depths) {
1106                                         cdd->vc.rv3d->depths->damaged = true;
1107                                 }
1108
1109                                 ED_view3d_depth_update(cdd->vc.ar);
1110
1111                                 if (cdd->vc.rv3d->depths != NULL) {
1112                                         cdd->project.use_depth = true;
1113                                 }
1114                                 else {
1115                                         BKE_report(op->reports, RPT_WARNING, "Unable to access depth buffer, using view plane");
1116                                         cdd->project.use_depth = false;
1117                                 }
1118                         }
1119
1120                         /* use view plane (when set or as fallback when surface can't be found) */
1121                         if (cdd->project.use_depth == false) {
1122                                 plane_co = ED_view3d_cursor3d_get(cdd->vc.scene, v3d);
1123                                 plane_no = rv3d->viewinv[2];
1124                                 cdd->project.use_plane = true;
1125                         }
1126
1127                         if (cdd->project.use_depth && (cdd->curve_type != CU_POLY)) {
1128                                 cdd->sample.use_substeps = true;
1129                         }
1130                 }
1131
1132                 if (cdd->project.use_plane) {
1133                         normalize_v3_v3(cdd->project.plane, plane_no);
1134                         cdd->project.plane[3] = -dot_v3v3(cdd->project.plane, plane_co);
1135                 }
1136         }
1137
1138         if (is_modal == false) {
1139                 curve_draw_event_add_first(op, event);
1140         }
1141
1142         /* add temp handler */
1143         WM_event_add_modal_handler(C, op);
1144
1145         return OPERATOR_RUNNING_MODAL;
1146 }
1147
1148 static void curve_draw_cancel(bContext *UNUSED(C), wmOperator *op)
1149 {
1150         curve_draw_exit(op);
1151 }
1152
1153
1154 /* Modal event handling of frame changing */
1155 static int curve_draw_modal(bContext *C, wmOperator *op, const wmEvent *event)
1156 {
1157         int ret = OPERATOR_RUNNING_MODAL;
1158         struct CurveDrawData *cdd = op->customdata;
1159
1160         UNUSED_VARS(C, op);
1161
1162         if (event->type == cdd->init_event_type) {
1163                 if (event->val == KM_RELEASE) {
1164                         ED_region_tag_redraw(cdd->vc.ar);
1165
1166                         curve_draw_exec_precalc(op);
1167
1168                         curve_draw_stroke_to_operator(op);
1169
1170                         curve_draw_exec(C, op);
1171
1172                         return OPERATOR_FINISHED;
1173                 }
1174         }
1175         else if (ELEM(event->type, ESCKEY, RIGHTMOUSE)) {
1176                 ED_region_tag_redraw(cdd->vc.ar);
1177                 curve_draw_cancel(C, op);
1178                 return OPERATOR_CANCELLED;
1179         }
1180         else if (ELEM(event->type, LEFTMOUSE)) {
1181                 if (event->val == KM_PRESS) {
1182                         curve_draw_event_add_first(op, event);
1183                 }
1184         }
1185         else if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
1186                 if (cdd->state == CURVE_DRAW_PAINTING) {
1187                         const float mval_fl[2] = {UNPACK2(event->mval)};
1188                         if (len_squared_v2v2(mval_fl, cdd->prev.mouse) > SQUARE(STROKE_SAMPLE_DIST_MIN_PX)) {
1189                                 curve_draw_event_add(op, event);
1190                         }
1191                 }
1192         }
1193
1194         return ret;
1195 }
1196
1197 void CURVE_OT_draw(wmOperatorType *ot)
1198 {
1199         /* identifiers */
1200         ot->name = "Draw Curve";
1201         ot->idname = "CURVE_OT_draw";
1202         ot->description = "Draw a freehand spline";
1203
1204         /* api callbacks */
1205         ot->exec = curve_draw_exec;
1206         ot->invoke = curve_draw_invoke;
1207         ot->cancel = curve_draw_cancel;
1208         ot->modal = curve_draw_modal;
1209         ot->poll = ED_operator_editcurve;
1210
1211         /* flags */
1212         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1213
1214         /* properties */
1215         PropertyRNA *prop;
1216
1217         prop = RNA_def_float_distance(
1218                 ot->srna, "error_threshold", 0.0f, 0.0f, 10.0f, "Error",
1219                 "Error distance threshold (in object units)",
1220                 0.0001f, 10.0f);
1221         RNA_def_property_ui_range(prop, 0.0, 10, 1, 4);
1222
1223         prop = RNA_def_float_distance(
1224                 ot->srna, "corner_angle", DEG2RADF(70.0f), 0.0f, M_PI, "Corner Angle", "", 0.0f, M_PI);
1225         RNA_def_property_subtype(prop, PROP_ANGLE);
1226
1227         prop = RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
1228         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1229
1230         prop = RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input", "");
1231         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1232 }
1233
1234 /** \} */