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