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