Blender V5.3
dynamicpaint.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "MEM_guardedalloc.h"
10
11#include <algorithm>
12#include <cmath>
13#include <cstdio>
14
15#include "BLI_assert.hh"
16#include "BLI_fileops.hh"
17#include "BLI_kdtree.hh"
18#include "BLI_listbase.hh"
19#include "BLI_math_color_c.hh"
20#include "BLI_math_geom_c.hh"
21#include "BLI_math_matrix_c.hh"
22#include "BLI_math_vector_c.hh"
23#include "BLI_mutex.hh"
24#include "BLI_path_utils.hh"
25#include "BLI_string.hh"
26#include "BLI_string_utf8.hh"
27#include "BLI_string_utils.hh"
28#include "BLI_task_c.hh"
29#include "BLI_threads.hh"
30#include "BLI_utildefines.hh"
31
32#include "BLT_translation.hh"
33
35#include "DNA_mesh_types.h"
36#include "DNA_meshdata_types.h"
37#include "DNA_modifier_types.h"
39#include "DNA_object_types.h"
40#include "DNA_scene_types.h"
41#include "DNA_texture_types.h"
42
43#include "BKE_armature.hh"
44#include "BKE_bvhutils.hh" /* bvh tree */
45#include "BKE_collision.h"
46#include "BKE_colorband.hh"
47#include "BKE_constraint.h"
48#include "BKE_customdata.hh"
49#include "BKE_deform.hh"
50#include "BKE_dynamicpaint.h"
51#include "BKE_effect.h"
52#include "BKE_image.hh"
53#include "BKE_image_format.hh"
54#include "BKE_lib_id.hh"
55#include "BKE_main.hh"
56#include "BKE_material.hh"
57#include "BKE_mesh.hh"
58#include "BKE_mesh_mapping.hh"
59#include "BKE_mesh_runtime.hh"
60#include "BKE_modifier.hh"
61#include "BKE_object.hh"
62#include "BKE_particle.h"
63#include "BKE_pointcache.h"
64#include "BKE_scene.hh"
65
66#include "DEG_depsgraph.hh"
68
69/* for image output */
70#include "IMB_imbuf.hh"
71#include "IMB_imbuf_types.hh"
72
73#include "RE_texture.h"
74
75#include "atomic_ops.h"
76
77#include "CLG_log.h"
78
79namespace blender {
80
81/* could enable at some point but for now there are far too many conversions */
82#ifdef __GNUC__
83// # pragma GCC diagnostic ignored "-Wdouble-promotion"
84#endif
85
86static CLG_LogRef LOG = {"object.dynamicpaint"};
87
88/* precalculated gaussian factors for 5x super sampling */
89static const float gaussianFactors[5] = {
90 0.996849f,
91 0.596145f,
92 0.596145f,
93 0.596145f,
94 0.524141f,
95};
96static const float gaussianTotal = 3.309425f;
97
98/* UV Image neighboring pixel table x and y list */
99static int neighX[8] = {1, 1, 0, -1, -1, -1, 0, 1};
100static int neighY[8] = {0, 1, 1, 1, 0, -1, -1, -1};
101
102/* Neighbor x/y list that prioritizes grid directions over diagonals */
103static int neighStraightX[8] = {1, 0, -1, 0, 1, -1, -1, 1};
104static int neighStraightY[8] = {0, 1, 0, -1, 1, 1, -1, -1};
105
106/* subframe_updateObject() flags */
107#define SUBFRAME_RECURSION OBJECT_MODIFIER_UPDATE_SUBFRAME_RECURSION_DEFAULT
108/* #surface_getBrushFlags() return values. */
109#define BRUSH_USES_VELOCITY (1 << 0)
110/* Brush mesh ray-cast status. */
111#define HIT_VOLUME 1
112#define HIT_PROXIMITY 2
113/* dynamicPaint_findNeighborPixel() return codes */
114#define NOT_FOUND -1
115#define ON_MESH_EDGE -2
116#define OUT_OF_TEXTURE -3
117/* paint effect default movement per frame in global units */
118#define EFF_MOVEMENT_PER_FRAME 0.05f
119/* initial wave time factor */
120#define WAVE_TIME_FAC (1.0f / 24.0f)
121#define CANVAS_REL_SIZE 5.0f
122/* drying limits */
123#define MIN_WETNESS 0.001f
124#define MAX_WETNESS 5.0f
125
136
137/* dissolve inline function */
138BLI_INLINE void value_dissolve(float *r_value,
139 const float time,
140 const float scale,
141 const bool is_log)
142{
143 *r_value = (is_log) ? (*r_value) * powf(MIN_WETNESS, 1.0f / (1.2f * time / scale)) :
144 (*r_value) - 1.0f / time * scale;
145}
146
147/***************************** Internal Structs ***************************/
148
149struct Bounds2D {
150 float min[2], max[2];
151};
152
153struct Bounds3D {
154 float min[3], max[3];
155 bool valid;
156};
157
174
175struct Vec3f {
176 float v[3];
177};
178
181 float dir[3];
183 float dist;
184};
185
189 float invNorm[3];
192};
193
196 /* point space data */
199 int *s_pos;
201 int *s_num;
205 float dim[3];
206
207 /* adjacency info */
211 /* space partitioning */
214
215 /* velocity and movement */
227 float prev_obmat[4][4];
229 int clear;
230};
231
234 /* Pixel / mesh data */
238 /* vertex indexes */
240
243};
244
247 Vec3f *barycentricWeights; /* b-weights for all pixel samples */
248};
249
250/* adjacency data flags */
251#define ADJ_ON_MESH_EDGE (1 << 0)
252#define ADJ_BORDER_PIXEL (1 << 1)
253
270
271/************************* Runtime evaluation store ***************************/
272
274{
275 if (runtime_data == nullptr) {
276 return;
277 }
278 if (runtime_data->canvas_mesh) {
279 BKE_id_free(nullptr, runtime_data->canvas_mesh);
280 }
281 {
282 std::lock_guard lock(runtime_data->brush_mutex);
283 if (runtime_data->brush_mesh) {
284 BKE_id_free(nullptr, runtime_data->brush_mesh);
285 }
286 }
287 MEM_delete(runtime_data);
288}
289
291{
292 if (pmd->modifier.runtime == nullptr) {
293 pmd->modifier.runtime = MEM_new<DynamicPaintRuntime>("dynamic paint runtime");
294 }
295 return static_cast<DynamicPaintRuntime *>(pmd->modifier.runtime);
296}
297
299{
300 if (canvas->pmd->modifier.runtime == nullptr) {
301 return nullptr;
302 }
303 DynamicPaintRuntime *runtime_data = static_cast<DynamicPaintRuntime *>(
304 canvas->pmd->modifier.runtime);
305 return runtime_data->canvas_mesh;
306}
307
308/***************************** General Utils ******************************/
309
310/* Set canvas error string to display at the bake report */
311static bool setError(DynamicPaintCanvasSettings *canvas, const char *string)
312{
313 /* Add error to canvas ui info label */
314 STRNCPY(canvas->error, string);
315 CLOG_STR_ERROR(&LOG, string);
316 return false;
317}
318
319/* Get number of surface points for cached types */
321{
322 if (surface->format == MOD_DPAINT_SURFACE_F_PTEX) {
323 return 0; /* Not supported at the moment. */
324 }
325 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
326 const Mesh *canvas_mesh = dynamicPaint_canvas_mesh_get(surface->canvas);
327 return (canvas_mesh) ? canvas_mesh->verts_num : 0;
328 }
329
330 return 0;
331}
332
337
339{
340 using namespace blender::bke;
341 const char *name;
342
343 if (output == 0) {
344 name = surface->output_name;
345 }
346 else if (output == 1) {
347 name = surface->output_name2;
348 }
349 else {
350 return false;
351 }
352
353 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
354 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
355 Mesh *mesh = id_cast<Mesh *>(ob->data);
356 const AttributeAccessor attributes = mesh->attributes();
357 const std::optional<AttributeMetaData> meta_data = attributes.lookup_meta_data(name);
359 }
360 if (surface->type == MOD_DPAINT_SURFACE_T_WEIGHT) {
361 return (BKE_object_defgroup_name_index(ob, name) != -1);
362 }
363 }
364
365 return false;
366}
367
369{
370 DynamicPaintSurface *surface = static_cast<DynamicPaintSurface *>(
371 t_surface->canvas->surfaces.first());
372
373 for (; surface; surface = surface->next) {
374 if (surface != t_surface && surface->type == t_surface->type &&
375 surface->format == t_surface->format)
376 {
377 if ((surface->output_name[0] != '\0' && !BLI_path_cmp(name.c_str(), surface->output_name)) ||
378 (surface->output_name2[0] != '\0' && !BLI_path_cmp(name.c_str(), surface->output_name2)))
379 {
380 return true;
381 }
382 }
383 }
384 return false;
385}
386
387static void surface_setUniqueOutputName(DynamicPaintSurface *surface, char *basename, int output)
388{
389 auto is_unique_fn = [&](const StringRefNull check_name) {
390 return surface_duplicateOutputExists(surface, check_name);
391 };
392
393 char name[64];
394 STRNCPY(name, basename); /* in case basename is surface->name use a copy */
395 if (output == 0) {
396 BLI_uniquename_cb(is_unique_fn, name, '.', surface->output_name, sizeof(surface->output_name));
397 }
398 else if (output == 1) {
400 is_unique_fn, name, '.', surface->output_name2, sizeof(surface->output_name2));
401 }
402}
403
405{
406 DynamicPaintSurface *surface = static_cast<DynamicPaintSurface *>(
407 t_surface->canvas->surfaces.first());
408
409 for (; surface; surface = surface->next) {
410 if (surface != t_surface && STREQ(name.c_str(), surface->name)) {
411 return true;
412 }
413 }
414 return false;
415}
416
417void dynamicPaintSurface_setUniqueName(DynamicPaintSurface *surface, const char *basename)
418{
419 char name[64];
420 STRNCPY_UTF8(name, basename); /* in case basename is surface->name use a copy */
422 [&](const StringRefNull check_name) {
423 return surface_duplicateNameExists(surface, check_name);
424 },
425 name,
426 '.',
427 surface->name,
428 sizeof(surface->name));
429}
430
432{
433 const char *name_prefix = "";
434 const char *name_suffix_1 = "";
435 const char *name_suffix_2 = "";
436
437 if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
438 surface->output_name[0] = '\0';
439 surface->output_name2[0] = '\0';
440 surface->flags |= MOD_DPAINT_ANTIALIAS;
441 surface->depth_clamp = 1.0f;
442 }
443 else {
444 name_prefix = "dp_";
445 surface->flags &= ~MOD_DPAINT_ANTIALIAS;
446 surface->depth_clamp = 0.0f;
447 }
448
449 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
450 name_suffix_1 = "paintmap";
451 name_suffix_2 = "wetmap";
452 }
453 else if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE) {
454 name_suffix_1 = name_suffix_2 = "displace";
455 }
456 else if (surface->type == MOD_DPAINT_SURFACE_T_WEIGHT) {
457 name_suffix_1 = name_suffix_2 = "weight";
458 }
459 else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) {
460 name_suffix_1 = name_suffix_2 = "wave";
461 }
462
463 SNPRINTF(surface->output_name, "%s%s", name_prefix, name_suffix_1);
464 SNPRINTF(surface->output_name2, "%s%s", name_prefix, name_suffix_2);
465 const bool output_name_equal = STREQ(surface->output_name, surface->output_name2);
466
467 surface_setUniqueOutputName(surface, surface->output_name, 0);
468 if (!output_name_equal) {
469 surface_setUniqueOutputName(surface, surface->output_name2, 1);
470 }
471}
472
474{
475 if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ && surface->flags & MOD_DPAINT_ANTIALIAS) {
476 return (surface->data->total_points * 5);
477 }
478 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX && surface->flags & MOD_DPAINT_ANTIALIAS &&
479 surface->data->adj_data)
480 {
481 return (surface->data->total_points + surface->data->adj_data->total_targets);
482 }
483
484 return surface->data->total_points;
485}
486
487static void blendColors(const float t_color[3],
488 const float t_alpha,
489 const float s_color[3],
490 const float s_alpha,
491 float result[4])
492{
493 /* Same thing as BLI's blend_color_mix_float(), but for non-premultiplied alpha. */
494 float i_alpha = 1.0f - s_alpha;
495 float f_alpha = t_alpha * i_alpha + s_alpha;
496
497 /* blend colors */
498 if (f_alpha) {
499 for (int i = 0; i < 3; i++) {
500 result[i] = (t_color[i] * t_alpha * i_alpha + s_color[i] * s_alpha) / f_alpha;
501 }
502 }
503 else {
504 copy_v3_v3(result, t_color);
505 }
506 /* return final alpha */
507 result[3] = f_alpha;
508}
509
510/* Mix two alpha weighed colors by a defined ratio. output is saved at a_color */
511static float mixColors(
512 float a_color[3], float a_weight, const float b_color[3], float b_weight, float ratio)
513{
514 float weight_ratio, factor;
515 if (b_weight) {
516 /* if first value has no weight just use b_color */
517 if (!a_weight) {
518 copy_v3_v3(a_color, b_color);
519 return b_weight * ratio;
520 }
521 weight_ratio = b_weight / (a_weight + b_weight);
522 }
523 else {
524 return a_weight * (1.0f - ratio);
525 }
526
527 /* calculate final interpolation factor */
528 if (ratio <= 0.5f) {
529 factor = weight_ratio * (ratio * 2.0f);
530 }
531 else {
532 ratio = (ratio * 2.0f - 1.0f);
533 factor = weight_ratio * (1.0f - ratio) + ratio;
534 }
535 /* mix final color */
536 interp_v3_v3v3(a_color, a_color, b_color, factor);
537 return (1.0f - factor) * a_weight + factor * b_weight;
538}
539
540static void scene_setSubframe(Scene *scene, float subframe)
541{
542 /* Dynamic paint sub-frames must be done on previous frame. */
543 scene->r.cfra -= 1;
544 scene->r.subframe = subframe;
545}
546
547static int surface_getBrushFlags(DynamicPaintSurface *surface, Depsgraph *depsgraph)
548{
549 uint numobjects;
551 depsgraph, nullptr, surface->brush_group, &numobjects, eModifierType_DynamicPaint);
552
553 int flags = 0;
554
555 for (int i = 0; i < numobjects; i++) {
556 Object *brushObj = objects[i];
557
560 DynamicPaintModifierData *pmd2 = reinterpret_cast<DynamicPaintModifierData *>(md);
561
562 if (pmd2->brush) {
564
565 if (brush->flags & MOD_DPAINT_USES_VELOCITY) {
566 flags |= BRUSH_USES_VELOCITY;
567 }
568 }
569 }
570 }
571
573
574 return flags;
575}
576
577/* check whether two bounds intersect */
578static bool boundsIntersect(Bounds3D *b1, Bounds3D *b2)
579{
580 if (!b1->valid || !b2->valid) {
581 return false;
582 }
583 for (int i = 2; i--;) {
584 if (!(b1->min[i] <= b2->max[i] && b1->max[i] >= b2->min[i])) {
585 return false;
586 }
587 }
588 return true;
589}
590
591/* check whether two bounds intersect inside defined proximity */
592static bool boundsIntersectDist(Bounds3D *b1, Bounds3D *b2, const float dist)
593{
594 if (!b1->valid || !b2->valid) {
595 return false;
596 }
597 for (int i = 2; i--;) {
598 if (!(b1->min[i] <= (b2->max[i] + dist) && b1->max[i] >= (b2->min[i] - dist))) {
599 return false;
600 }
601 }
602 return true;
603}
604
605/* check whether bounds intersects a point with given radius */
606static bool boundIntersectPoint(Bounds3D *b, const float point[3], const float radius)
607{
608 if (!b->valid) {
609 return false;
610 }
611 for (int i = 2; i--;) {
612 if (!(b->min[i] <= (point[i] + radius) && b->max[i] >= (point[i] - radius))) {
613 return false;
614 }
615 }
616 return true;
617}
618
619/* expand bounds by a new point */
620static void boundInsert(Bounds3D *b, const float point[3])
621{
622 if (!b->valid) {
623 copy_v3_v3(b->min, point);
624 copy_v3_v3(b->max, point);
625 b->valid = true;
626 return;
627 }
628
629 minmax_v3v3_v3(b->min, b->max, point);
630}
631
633{
634 Bounds3D *mb = &sData->bData->mesh_bounds;
635 return std::max(
636 {(mb->max[0] - mb->min[0]), (mb->max[1] - mb->min[1]), (mb->max[2] - mb->min[2])});
637}
638
640{
641 PaintBakeData *bData = data->bData;
642 DynamicPaintVolumeGrid *grid = bData->grid;
643
644 if (grid->bounds) {
645 MEM_delete(grid->bounds);
646 }
647 if (grid->s_pos) {
648 MEM_delete(grid->s_pos);
649 }
650 if (grid->s_num) {
651 MEM_delete(grid->s_num);
652 }
653 if (grid->t_index) {
654 MEM_delete(grid->t_index);
655 }
656
657 MEM_delete(bData->grid);
658 bData->grid = nullptr;
659}
660
661static void grid_bound_insert_cb_ex(void *__restrict userdata,
662 const int i,
663 const TaskParallelTLS *__restrict tls)
664{
665 PaintBakeData *bData = static_cast<PaintBakeData *>(userdata);
666
667 Bounds3D *grid_bound = static_cast<Bounds3D *>(tls->userdata_chunk);
668
669 boundInsert(grid_bound, bData->realCoord[bData->s_pos[i]].v);
670}
671
672static void grid_bound_insert_reduce(const void *__restrict /*userdata*/,
673 void *__restrict chunk_join,
674 void *__restrict chunk)
675{
676 Bounds3D *join = static_cast<Bounds3D *>(chunk_join);
677 Bounds3D *grid_bound = static_cast<Bounds3D *>(chunk);
678
679 boundInsert(join, grid_bound->min);
680 boundInsert(join, grid_bound->max);
681}
682
683static void grid_cell_points_cb_ex(void *__restrict userdata,
684 const int i,
685 const TaskParallelTLS *__restrict tls)
686{
687 PaintBakeData *bData = static_cast<PaintBakeData *>(userdata);
688 DynamicPaintVolumeGrid *grid = bData->grid;
689 int *temp_t_index = grid->temp_t_index;
690 int *s_num = static_cast<int *>(tls->userdata_chunk);
691
692 int co[3];
693
694 for (int j = 3; j--;) {
695 co[j] = int(floorf((bData->realCoord[bData->s_pos[i]].v[j] - grid->grid_bounds.min[j]) /
696 bData->dim[j] * grid->dim[j]));
697 CLAMP(co[j], 0, grid->dim[j] - 1);
698 }
699
700 temp_t_index[i] = co[0] + co[1] * grid->dim[0] + co[2] * grid->dim[0] * grid->dim[1];
701 s_num[temp_t_index[i]]++;
702}
703
704static void grid_cell_points_reduce(const void *__restrict userdata,
705 void *__restrict chunk_join,
706 void *__restrict chunk)
707{
708 const PaintBakeData *bData = static_cast<const PaintBakeData *>(userdata);
709 const DynamicPaintVolumeGrid *grid = bData->grid;
710 const int grid_cells = grid->dim[0] * grid->dim[1] * grid->dim[2];
711
712 int *join_s_num = static_cast<int *>(chunk_join);
713 int *s_num = static_cast<int *>(chunk);
714
715 /* calculate grid indexes */
716 for (int i = 0; i < grid_cells; i++) {
717 join_s_num[i] += s_num[i];
718 }
719}
720
721static void grid_cell_bounds_cb(void *__restrict userdata,
722 const int x,
723 const TaskParallelTLS *__restrict /*tls*/)
724{
725 PaintBakeData *bData = static_cast<PaintBakeData *>(userdata);
726 DynamicPaintVolumeGrid *grid = bData->grid;
727 float *dim = bData->dim;
728 int *grid_dim = grid->dim;
729
730 for (int y = 0; y < grid_dim[1]; y++) {
731 for (int z = 0; z < grid_dim[2]; z++) {
732 const int b_index = x + y * grid_dim[0] + z * grid_dim[0] * grid_dim[1];
733 /* set bounds */
734 for (int j = 3; j--;) {
735 const int s = (j == 0) ? x : ((j == 1) ? y : z);
736 grid->bounds[b_index].min[j] = grid->grid_bounds.min[j] + dim[j] / grid_dim[j] * s;
737 grid->bounds[b_index].max[j] = grid->grid_bounds.min[j] + dim[j] / grid_dim[j] * (s + 1);
738 }
739 grid->bounds[b_index].valid = true;
740 }
741 }
742}
743
745{
746 PaintSurfaceData *sData = surface->data;
747 PaintBakeData *bData = sData->bData;
749 int grid_cells, axis = 3;
750 int *temp_t_index = nullptr;
751 int *temp_s_num = nullptr;
752
753 if (bData->grid) {
754 freeGrid(sData);
755 }
756
758 grid = bData->grid;
759
760 {
761 int i, error = 0;
762 float dim_factor, volume, dim[3];
763 float td[3];
764 float min_dim;
765
766 /* calculate canvas dimensions */
767 /* Important to init correctly our ref grid_bound... */
768 boundInsert(&grid->grid_bounds, bData->realCoord[bData->s_pos[0]].v);
769 {
770 TaskParallelSettings settings;
772 settings.use_threading = (sData->total_points > 1000);
773 settings.userdata_chunk = &grid->grid_bounds;
774 settings.userdata_chunk_size = sizeof(grid->grid_bounds);
777 }
778 /* get dimensions */
779 sub_v3_v3v3(dim, grid->grid_bounds.max, grid->grid_bounds.min);
780 copy_v3_v3(td, dim);
781 copy_v3_v3(bData->dim, dim);
782 min_dim = std::max({td[0], td[1], td[2]}) / 1000.0f;
783
784 /* deactivate zero axes */
785 for (i = 0; i < 3; i++) {
786 if (td[i] < min_dim) {
787 td[i] = 1.0f;
788 axis--;
789 }
790 }
791
792 if (axis == 0 || std::max({td[0], td[1], td[2]}) < 0.0001f) {
793 MEM_delete(bData->grid);
794 bData->grid = nullptr;
795 return;
796 }
797
798 /* now calculate grid volume/area/width depending on num of active axis */
799 volume = td[0] * td[1] * td[2];
800
801 /* determine final grid size by trying to fit average 10.000 points per grid cell */
802 dim_factor = float(
803 pow(double(volume) / (double(sData->total_points) / 10000.0), 1.0 / double(axis)));
804
805 /* define final grid size using dim_factor, use min 3 for active axes */
806 for (i = 0; i < 3; i++) {
807 grid->dim[i] = int(floor(td[i] / dim_factor));
808 CLAMP(grid->dim[i], (dim[i] >= min_dim) ? 3 : 1, 100);
809 }
810 grid_cells = grid->dim[0] * grid->dim[1] * grid->dim[2];
811
812 /* allocate memory for grids */
813 grid->bounds = MEM_new_array_zeroed<Bounds3D>(grid_cells, "Surface Grid Bounds");
814 grid->s_pos = MEM_new_array_zeroed<int>(grid_cells, "Surface Grid Position");
815
816 grid->s_num = MEM_new_array_zeroed<int>(grid_cells, "Surface Grid Points");
817 temp_s_num = MEM_new_array_zeroed<int>(grid_cells, "Temp Surface Grid Points");
818 grid->t_index = MEM_new_array_zeroed<int>(sData->total_points, "Surface Grid Target Ids");
819 grid->temp_t_index = temp_t_index = MEM_new_array_zeroed<int>(sData->total_points,
820 "Temp Surface Grid Target Ids");
821
822 /* in case of an allocation failure abort here */
823 if (!grid->bounds || !grid->s_pos || !grid->s_num || !grid->t_index || !temp_s_num ||
824 !temp_t_index)
825 {
826 error = 1;
827 }
828
829 if (!error) {
830 /* calculate number of points within each cell */
831 {
832 TaskParallelSettings settings;
834 settings.use_threading = (sData->total_points > 1000);
835 settings.userdata_chunk = grid->s_num;
836 settings.userdata_chunk_size = sizeof(*grid->s_num) * grid_cells;
838 BLI_task_parallel_range(0, sData->total_points, bData, grid_cell_points_cb_ex, &settings);
839 }
840
841 /* calculate grid indexes (not needed for first cell, which is zero). */
842 for (i = 1; i < grid_cells; i++) {
843 grid->s_pos[i] = grid->s_pos[i - 1] + grid->s_num[i - 1];
844 }
845
846 /* save point indexes to final array */
847 for (i = 0; i < sData->total_points; i++) {
848 int pos = grid->s_pos[temp_t_index[i]] + temp_s_num[temp_t_index[i]];
849 grid->t_index[pos] = i;
850
851 temp_s_num[temp_t_index[i]]++;
852 }
853
854 /* calculate cell bounds */
855 {
856 TaskParallelSettings settings;
858 settings.use_threading = (grid_cells > 1000);
859 BLI_task_parallel_range(0, grid->dim[0], bData, grid_cell_bounds_cb, &settings);
860 }
861 }
862
863 if (temp_s_num) {
864 MEM_delete(temp_s_num);
865 }
866 MEM_SAFE_DELETE(temp_t_index);
867
868 if (error || !grid->s_num) {
869 setError(surface->canvas, N_("Not enough free memory"));
870 freeGrid(sData);
871 }
872 }
873}
874
875/***************************** Freeing data ******************************/
876
878{
879 if (pmd->brush) {
880 if (pmd->brush->paint_ramp) {
881 MEM_delete(pmd->brush->paint_ramp);
882 }
883 if (pmd->brush->vel_ramp) {
884 MEM_delete(pmd->brush->vel_ramp);
885 }
886
887 MEM_delete(pmd->brush);
888 pmd->brush = nullptr;
889 }
890}
891
893{
894 if (data->adj_data) {
895 if (data->adj_data->n_index) {
896 MEM_delete(data->adj_data->n_index);
897 }
898 if (data->adj_data->n_num) {
899 MEM_delete(data->adj_data->n_num);
900 }
901 if (data->adj_data->n_target) {
902 MEM_delete(data->adj_data->n_target);
903 }
904 if (data->adj_data->flags) {
905 MEM_delete(data->adj_data->flags);
906 }
907 if (data->adj_data->border) {
908 MEM_delete(data->adj_data->border);
909 }
910 MEM_delete(data->adj_data);
911 data->adj_data = nullptr;
912 }
913}
914
916{
917 PaintBakeData *bData = data->bData;
918 if (bData) {
919 if (bData->bNormal) {
920 MEM_delete(bData->bNormal);
921 }
922 if (bData->s_pos) {
923 MEM_delete(bData->s_pos);
924 }
925 if (bData->s_num) {
926 MEM_delete(bData->s_num);
927 }
928 if (bData->realCoord) {
929 MEM_delete(bData->realCoord);
930 }
931 if (bData->bNeighs) {
932 MEM_delete(bData->bNeighs);
933 }
934 if (bData->grid) {
935 freeGrid(data);
936 }
937 if (bData->prev_positions) {
938 MEM_delete(bData->prev_positions);
939 }
940 if (bData->velocity) {
941 MEM_delete(bData->velocity);
942 }
943 if (bData->prev_velocity) {
944 MEM_delete(bData->prev_velocity);
945 }
946
947 MEM_delete(data->bData);
948 data->bData = nullptr;
949 }
950}
951
952/* free surface data if it's not used anymore */
954{
955 if (!surface->data) {
956 return;
957 }
958
959 /* Free bake-data if not active or surface is baked. */
960 if (!(surface->flags & MOD_DPAINT_ACTIVE) ||
961 (surface->pointcache && surface->pointcache->flag & PTCACHE_BAKED))
962 {
963 free_bakeData(surface->data);
964 }
965}
966
968{
969 PaintSurfaceData *data = surface->data;
970 if (!data) {
971 return;
972 }
973
974 if (data->format_data) {
975 /* format specific free */
976 if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
977 ImgSeqFormatData *format_data = data->format_data;
978 if (format_data->uv_p) {
979 MEM_delete(format_data->uv_p);
980 }
981 if (format_data->barycentricWeights) {
982 MEM_delete(format_data->barycentricWeights);
983 }
984 }
985 MEM_delete(data->format_data);
986 }
987 /* type data */
988 if (data->type_data) {
989 switch (surface->type) {
991 MEM_delete(static_cast<PaintPoint *>(data->type_data));
992 break;
995 MEM_delete(static_cast<float *>(data->type_data));
996 break;
998 MEM_delete(static_cast<PaintWavePoint *>(data->type_data));
999 break;
1000 }
1001 }
1003 /* bake data */
1005
1006 MEM_delete(surface->data);
1007 surface->data = nullptr;
1008}
1009
1011{
1012 /* point cache */
1013 if ((pmd->modifier.flag & eModifierFlag_SharedCaches) == 0) {
1014 BKE_ptcache_free_list(&(surface->ptcaches));
1015 }
1016 surface->pointcache = nullptr;
1017
1018 MEM_SAFE_DELETE(surface->effector_weights);
1019
1020 BLI_remlink(&(surface->canvas->surfaces), surface);
1022 MEM_delete(surface);
1023}
1024
1026{
1027 if (pmd->canvas) {
1028 /* Free surface data */
1029 DynamicPaintSurface *surface = pmd->canvas->surfaces.first();
1030 DynamicPaintSurface *next_surface = nullptr;
1031
1032 while (surface) {
1033 next_surface = surface->next;
1034 dynamicPaint_freeSurface(pmd, surface);
1035 surface = next_surface;
1036 }
1037
1038 MEM_delete(pmd->canvas);
1039 pmd->canvas = nullptr;
1040 }
1041}
1042
1044{
1045 if (pmd == nullptr) {
1046 return;
1047 }
1051}
1052
1053/***************************** Initialize and reset ******************************/
1054
1056 Scene *scene)
1057{
1058 DynamicPaintSurface *surface = MEM_new<DynamicPaintSurface>(__func__);
1059 if (!surface) {
1060 return nullptr;
1061 }
1062
1063 surface->canvas = canvas;
1066
1067 /* cache */
1068 surface->pointcache = BKE_ptcache_add(&(surface->ptcaches));
1069 surface->pointcache->flag |= PTCACHE_DISK_CACHE;
1070 surface->pointcache->step = 1;
1071
1072 /* Set initial values */
1076 surface->effect = eDynamicPaint_EffectFlags{};
1077 surface->effect_ui = 1;
1078
1079 surface->diss_speed = 250;
1080 surface->dry_speed = 500;
1081 surface->color_dry_threshold = 1.0f;
1082 surface->depth_clamp = 0.0f;
1083 surface->disp_factor = 1.0f;
1086
1087 surface->influence_scale = 1.0f;
1088 surface->radius_scale = 1.0f;
1089
1090 surface->init_color[0] = 1.0f;
1091 surface->init_color[1] = 1.0f;
1092 surface->init_color[2] = 1.0f;
1093 surface->init_color[3] = 1.0f;
1094
1095 surface->image_resolution = 256;
1096 surface->substeps = 0;
1097
1098 if (scene) {
1099 surface->start_frame = scene->r.sfra;
1100 surface->end_frame = scene->r.efra;
1101 }
1102 else {
1103 surface->start_frame = 1;
1104 surface->end_frame = 250;
1105 }
1106
1107 surface->spread_speed = 1.0f;
1108 surface->color_spread_speed = 1.0f;
1109 surface->shrink_speed = 1.0f;
1110
1111 surface->wave_damping = 0.04f;
1112 surface->wave_speed = 1.0f;
1113 surface->wave_timescale = 1.0f;
1114 surface->wave_spring = 0.20f;
1115 surface->wave_smoothness = 1.0f;
1116
1118 surface->image_output_path, sizeof(surface->image_output_path), "cache_dynamicpaint");
1119
1120 /* Using ID_BRUSH i18n context, as we have no physics/dynamic-paint one for now. */
1122
1123 surface->effector_weights = BKE_effector_add_weights(nullptr);
1124
1126
1127 BLI_addtail(&canvas->surfaces, surface);
1128
1129 return surface;
1130}
1131
1133{
1134 if (pmd) {
1135 if (type == MOD_DYNAMICPAINT_TYPE_CANVAS) {
1137 if (pmd->canvas) {
1139 }
1140
1141 canvas = pmd->canvas = MEM_new<DynamicPaintCanvasSettings>(__func__);
1142 if (!canvas) {
1143 return false;
1144 }
1145 canvas->pmd = pmd;
1146
1147 /* Create one surface */
1149 return false;
1150 }
1151 }
1152 else if (type == MOD_DYNAMICPAINT_TYPE_BRUSH) {
1154 if (pmd->brush) {
1156 }
1157
1158 brush = pmd->brush = MEM_new<DynamicPaintBrushSettings>(__func__);
1159 if (!brush) {
1160 return false;
1161 }
1162 brush->pmd = pmd;
1163
1164 brush->psys = nullptr;
1165
1167 brush->collision = MOD_DPAINT_COL_VOLUME;
1168
1169 brush->r = 0.15f;
1170 brush->g = 0.4f;
1171 brush->b = 0.8f;
1172 brush->alpha = 1.0f;
1173 brush->wetness = 1.0f;
1174
1175 brush->paint_distance = 1.0f;
1176 brush->proximity_falloff = MOD_DPAINT_PRFALL_SMOOTH;
1177
1178 brush->particle_radius = 0.2f;
1179 brush->particle_smooth = 0.05f;
1180
1181 brush->wave_type = MOD_DPAINT_WAVEB_CHANGE;
1182 brush->wave_factor = 1.0f;
1183 brush->wave_clamp = 0.0f;
1184 brush->smudge_strength = 0.3f;
1185 brush->max_velocity = 1.0f;
1186
1187 /* Paint proximity falloff color-ramp. */
1188 {
1189 CBData *ramp;
1190
1191 brush->paint_ramp = BKE_colorband_add(false);
1192 if (!brush->paint_ramp) {
1193 return false;
1194 }
1195 ramp = brush->paint_ramp->data;
1196 /* Add default smooth-falloff ramp. */
1197 ramp[0].r = ramp[0].g = ramp[0].b = ramp[0].a = 1.0f;
1198 ramp[0].pos = 0.0f;
1199 ramp[1].r = ramp[1].g = ramp[1].b = ramp[1].pos = 1.0f;
1200 ramp[1].a = 0.0f;
1201 pmd->brush->paint_ramp->tot = 2;
1202 }
1203
1204 /* Brush velocity ramp. */
1205 {
1206 CBData *ramp;
1207
1208 brush->vel_ramp = BKE_colorband_add(false);
1209 if (!brush->vel_ramp) {
1210 return false;
1211 }
1212 ramp = brush->vel_ramp->data;
1213 ramp[0].r = ramp[0].g = ramp[0].b = ramp[0].a = ramp[0].pos = 0.0f;
1214 ramp[1].r = ramp[1].g = ramp[1].b = ramp[1].a = ramp[1].pos = 1.0f;
1215 brush->paint_ramp->tot = 2;
1216 }
1217 }
1218 }
1219 else {
1220 return false;
1221 }
1222
1223 return true;
1224}
1225
1228 int flag)
1229{
1230 /* Init modifier */
1231 tpmd->type = pmd->type;
1232 if (pmd->canvas) {
1234 }
1235 if (pmd->brush) {
1237 }
1238
1239 /* Copy data */
1240 if (tpmd->canvas) {
1241 DynamicPaintSurface *surface;
1242 tpmd->canvas->pmd = tpmd;
1243 /* free default surface */
1244 if (tpmd->canvas->surfaces.first()) {
1245 dynamicPaint_freeSurface(tpmd, tpmd->canvas->surfaces.first());
1246 }
1247
1248 tpmd->canvas->active_sur = pmd->canvas->active_sur;
1249
1250 /* copy existing surfaces */
1251 for (surface = pmd->canvas->surfaces.first(); surface; surface = surface->next) {
1252 DynamicPaintSurface *t_surface = dynamicPaint_createNewSurface(tpmd->canvas, nullptr);
1254 /* TODO(sergey): Consider passing some tips to the surface
1255 * creation to avoid this allocate-and-free cache behavior. */
1256 BKE_ptcache_free_list(&t_surface->ptcaches);
1258 t_surface->ptcaches = surface->ptcaches;
1259 t_surface->pointcache = surface->pointcache;
1260 }
1261
1262 /* surface settings */
1263 t_surface->brush_group = surface->brush_group;
1264 MEM_delete(t_surface->effector_weights);
1265 t_surface->effector_weights = static_cast<EffectorWeights *>(
1266 MEM_dupalloc(surface->effector_weights));
1267
1268 STRNCPY(t_surface->name, surface->name);
1269 t_surface->format = surface->format;
1270 t_surface->type = surface->type;
1271 t_surface->disp_type = surface->disp_type;
1272 t_surface->image_fileformat = surface->image_fileformat;
1273 t_surface->effect_ui = surface->effect_ui;
1274 t_surface->init_color_type = surface->init_color_type;
1275 t_surface->flags = surface->flags;
1276 t_surface->effect = surface->effect;
1277
1278 t_surface->image_resolution = surface->image_resolution;
1279 t_surface->substeps = surface->substeps;
1280 t_surface->start_frame = surface->start_frame;
1281 t_surface->end_frame = surface->end_frame;
1282
1283 copy_v4_v4(t_surface->init_color, surface->init_color);
1284 t_surface->init_texture = surface->init_texture;
1285 STRNCPY(t_surface->init_layername, surface->init_layername);
1286
1287 t_surface->dry_speed = surface->dry_speed;
1288 t_surface->diss_speed = surface->diss_speed;
1289 t_surface->color_dry_threshold = surface->color_dry_threshold;
1290 t_surface->depth_clamp = surface->depth_clamp;
1291 t_surface->disp_factor = surface->disp_factor;
1292
1293 t_surface->spread_speed = surface->spread_speed;
1294 t_surface->color_spread_speed = surface->color_spread_speed;
1295 t_surface->shrink_speed = surface->shrink_speed;
1296 t_surface->drip_vel = surface->drip_vel;
1297 t_surface->drip_acc = surface->drip_acc;
1298
1299 t_surface->influence_scale = surface->influence_scale;
1300 t_surface->radius_scale = surface->radius_scale;
1301
1302 t_surface->wave_damping = surface->wave_damping;
1303 t_surface->wave_speed = surface->wave_speed;
1304 t_surface->wave_timescale = surface->wave_timescale;
1305 t_surface->wave_spring = surface->wave_spring;
1306 t_surface->wave_smoothness = surface->wave_smoothness;
1307
1308 STRNCPY(t_surface->uvlayer_name, surface->uvlayer_name);
1309 STRNCPY(t_surface->image_output_path, surface->image_output_path);
1310 STRNCPY(t_surface->output_name, surface->output_name);
1311 STRNCPY(t_surface->output_name2, surface->output_name2);
1312 }
1313 }
1314 if (tpmd->brush) {
1315 DynamicPaintBrushSettings *brush = pmd->brush, *t_brush = tpmd->brush;
1316 t_brush->pmd = tpmd;
1317
1318 t_brush->flags = brush->flags;
1319 t_brush->collision = brush->collision;
1320
1321 t_brush->r = brush->r;
1322 t_brush->g = brush->g;
1323 t_brush->b = brush->b;
1324 t_brush->alpha = brush->alpha;
1325 t_brush->wetness = brush->wetness;
1326
1327 t_brush->particle_radius = brush->particle_radius;
1328 t_brush->particle_smooth = brush->particle_smooth;
1329 t_brush->paint_distance = brush->paint_distance;
1330
1331 /* NOTE: This is dangerous, as it will generate invalid data in case we are copying between
1332 * different objects. Extra external code has to be called to ensure proper remapping of
1333 * that pointer. See e.g. `BKE_object_copy_particlesystems` or `BKE_object_copy_modifier`. */
1334 t_brush->psys = brush->psys;
1335
1336 if (brush->paint_ramp) {
1337 memcpy(t_brush->paint_ramp, brush->paint_ramp, sizeof(ColorBand));
1338 }
1339 if (brush->vel_ramp) {
1340 memcpy(t_brush->vel_ramp, brush->vel_ramp, sizeof(ColorBand));
1341 }
1342
1343 t_brush->proximity_falloff = brush->proximity_falloff;
1344 t_brush->wave_type = brush->wave_type;
1345 t_brush->ray_dir = brush->ray_dir;
1346
1347 t_brush->wave_factor = brush->wave_factor;
1348 t_brush->wave_clamp = brush->wave_clamp;
1349 t_brush->max_velocity = brush->max_velocity;
1350 t_brush->smudge_strength = brush->smudge_strength;
1351 }
1352}
1353
1354/* allocates surface data depending on surface type */
1356{
1357 PaintSurfaceData *sData = surface->data;
1358
1359 switch (surface->type) {
1362 "DynamicPaintSurface Data");
1363 break;
1366 "DynamicPaintSurface DepthData");
1367 break;
1370 "DynamicPaintSurface WeightData");
1371 break;
1374 "DynamicPaintSurface WaveData");
1375 break;
1376 }
1377
1378 if (sData->type_data == nullptr) {
1379 setError(surface->canvas, N_("Not enough free memory"));
1380 }
1381}
1382
1384{
1385 return ((surface->type == MOD_DPAINT_SURFACE_T_PAINT && surface->effect) ||
1386 (surface->type == MOD_DPAINT_SURFACE_T_WAVE));
1387}
1388
1390{
1391 return (surface_usesAdjDistance(surface) || (surface->format == MOD_DPAINT_SURFACE_F_VERTEX &&
1392 surface->flags & MOD_DPAINT_ANTIALIAS));
1393}
1394
1395/* initialize surface adjacency data */
1396static void dynamicPaint_initAdjacencyData(DynamicPaintSurface *surface, const bool force_init)
1397{
1398 PaintSurfaceData *sData = surface->data;
1400 PaintAdjData *ad;
1401 int *temp_data;
1402 int neigh_points = 0;
1403
1404 if (!force_init && !surface_usesAdjData(surface)) {
1405 return;
1406 }
1407
1408 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1409 /* For vertex format, neighbors are connected by edges */
1410 neigh_points = 2 * mesh->edges_num;
1411 }
1412 else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
1413 neigh_points = sData->total_points * 8;
1414 }
1415
1416 if (!neigh_points) {
1417 return;
1418 }
1419
1420 /* allocate memory */
1421 ad = sData->adj_data = MEM_new_zeroed<PaintAdjData>(__func__);
1422 if (!ad) {
1423 return;
1424 }
1425 ad->n_index = MEM_new_array_zeroed<int>(sData->total_points, "Surface Adj Index");
1426 ad->n_num = MEM_new_array_zeroed<int>(sData->total_points, "Surface Adj Counts");
1427 temp_data = MEM_new_array_zeroed<int>(sData->total_points, "Temp Adj Data");
1428 ad->n_target = MEM_new_array_zeroed<int>(neigh_points, "Surface Adj Targets");
1429 ad->flags = MEM_new_array_zeroed<int>(sData->total_points, "Surface Adj Flags");
1430 ad->total_targets = neigh_points;
1431 ad->border = nullptr;
1432 ad->total_border = 0;
1433
1434 /* in case of allocation error, free memory */
1435 if (!ad->n_index || !ad->n_num || !ad->n_target || !temp_data) {
1437 if (temp_data) {
1438 MEM_delete(temp_data);
1439 }
1440 setError(surface->canvas, N_("Not enough free memory"));
1441 return;
1442 }
1443
1444 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1445 /* For vertex format, count every vertex that is connected by an edge */
1446 int numOfEdges = mesh->edges_num;
1447 int numOfPolys = mesh->faces_num;
1448 const Span<int2> edges = mesh->edges();
1449 const OffsetIndices faces = mesh->faces();
1450 const Span<int> corner_verts = mesh->corner_verts();
1451
1452 /* count number of edges per vertex */
1453 for (int i = 0; i < numOfEdges; i++) {
1454 ad->n_num[edges[i][0]]++;
1455 ad->n_num[edges[i][1]]++;
1456
1457 temp_data[edges[i][0]]++;
1458 temp_data[edges[i][1]]++;
1459 }
1460
1461 /* also add number of vertices to temp_data
1462 * to locate points on "mesh edge" */
1463 for (int i = 0; i < numOfPolys; i++) {
1464 for (const int vert : corner_verts.slice(faces[i])) {
1465 temp_data[vert]++;
1466 }
1467 }
1468
1469 /* now check if total number of edges+faces for
1470 * each vertex is even, if not -> vertex is on mesh edge */
1471 for (int i = 0; i < sData->total_points; i++) {
1472 if ((temp_data[i] % 2) || (temp_data[i] < 4)) {
1473 ad->flags[i] |= ADJ_ON_MESH_EDGE;
1474 }
1475
1476 /* reset temp data */
1477 temp_data[i] = 0;
1478 }
1479
1480 /* order n_index array */
1481 int n_pos = 0;
1482 for (int i = 0; i < sData->total_points; i++) {
1483 ad->n_index[i] = n_pos;
1484 n_pos += ad->n_num[i];
1485 }
1486
1487 /* and now add neighbor data using that info */
1488 for (int i = 0; i < numOfEdges; i++) {
1489 /* first vertex */
1490 int index = edges[i][0];
1491 n_pos = ad->n_index[index] + temp_data[index];
1492 ad->n_target[n_pos] = edges[i][1];
1493 temp_data[index]++;
1494
1495 /* second vertex */
1496 index = edges[i][1];
1497 n_pos = ad->n_index[index] + temp_data[index];
1498 ad->n_target[n_pos] = edges[i][0];
1499 temp_data[index]++;
1500 }
1501 }
1502 else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
1503 /* for image sequences, only allocate memory.
1504 * bake initialization takes care of rest */
1505 }
1506
1507 MEM_delete(temp_data);
1508}
1509
1519
1520static void dynamic_paint_set_init_color_tex_to_vcol_cb(void *__restrict userdata,
1521 const int i,
1522 const TaskParallelTLS *__restrict /*tls*/)
1523{
1524 const DynamicPaintSetInitColorData *data = static_cast<DynamicPaintSetInitColorData *>(userdata);
1525
1526 const PaintSurfaceData *sData = data->surface->data;
1527 PaintPoint *pPoint = static_cast<PaintPoint *>(sData->type_data);
1528
1529 const Span<int> corner_verts = data->corner_verts;
1530 const Span<int3> corner_tris = data->corner_tris;
1531 const Span<float2> uv_map = data->uv_map;
1532 ImagePool *pool = data->pool;
1533 Tex *tex = data->surface->init_texture;
1534
1535 float uv[3] = {0.0f};
1536
1537 for (int j = 3; j--;) {
1538 TexResult texres = {0};
1539 const int vert = corner_verts[corner_tris[i][j]];
1540
1541 /* remap to [-1.0, 1.0] */
1542 uv[0] = uv_map[corner_tris[i][j]][0] * 2.0f - 1.0f;
1543 uv[1] = uv_map[corner_tris[i][j]][1] * 2.0f - 1.0f;
1544
1545 multitex_ext_safe(tex, uv, &texres, pool, true, false);
1546
1547 if (texres.tin > pPoint[vert].color[3]) {
1548 copy_v3_v3(pPoint[vert].color, texres.trgba);
1549 pPoint[vert].color[3] = texres.tin;
1550 }
1551 }
1552}
1553
1554static void dynamic_paint_set_init_color_tex_to_imseq_cb(void *__restrict userdata,
1555 const int i,
1556 const TaskParallelTLS *__restrict /*tls*/)
1557{
1558 const DynamicPaintSetInitColorData *data = static_cast<DynamicPaintSetInitColorData *>(userdata);
1559
1560 const PaintSurfaceData *sData = data->surface->data;
1561 PaintPoint *pPoint = static_cast<PaintPoint *>(sData->type_data);
1562
1563 const Span<int3> corner_tris = data->corner_tris;
1564 const Span<float2> uv_map = data->uv_map;
1565 Tex *tex = data->surface->init_texture;
1566 ImgSeqFormatData *f_data = sData->format_data;
1567 const int samples = (data->surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
1568
1569 float uv[9] = {0.0f};
1570 float uv_final[3] = {0.0f};
1571
1572 TexResult texres = {0};
1573
1574 /* collect all uvs */
1575 for (int j = 3; j--;) {
1576 copy_v2_v2(&uv[j * 3], uv_map[corner_tris[f_data->uv_p[i].tri_index][j]]);
1577 }
1578
1579 /* interpolate final uv pos */
1580 interp_v3_v3v3v3(uv_final, &uv[0], &uv[3], &uv[6], f_data->barycentricWeights[i * samples].v);
1581 /* remap to [-1.0, 1.0] */
1582 uv_final[0] = uv_final[0] * 2.0f - 1.0f;
1583 uv_final[1] = uv_final[1] * 2.0f - 1.0f;
1584
1585 multitex_ext_safe(tex, uv_final, &texres, nullptr, true, false);
1586
1587 /* apply color */
1588 copy_v3_v3(pPoint[i].color, texres.trgba);
1589 pPoint[i].color[3] = texres.tin;
1590}
1591
1593 void *__restrict userdata, const int i, const TaskParallelTLS *__restrict /*tls*/)
1594{
1595 const DynamicPaintSetInitColorData *data = static_cast<DynamicPaintSetInitColorData *>(userdata);
1596
1597 const PaintSurfaceData *sData = data->surface->data;
1598 PaintPoint *pPoint = static_cast<PaintPoint *>(sData->type_data);
1599
1600 const Span<int3> corner_tris = data->corner_tris;
1601 const Span<ColorGeometry4b> mloopcol = data->mloopcol;
1602 ImgSeqFormatData *f_data = sData->format_data;
1603 const int samples = (data->surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
1604
1605 const int tri_idx = f_data->uv_p[i].tri_index;
1606 float colors[3][4];
1607 float final_color[4];
1608
1609 /* collect color values */
1610 for (int j = 3; j--;) {
1611 rgba_uchar_to_float(colors[j],
1612 static_cast<const uchar *>(&mloopcol[corner_tris[tri_idx][j]].r));
1613 }
1614
1615 /* interpolate final color */
1616 interp_v4_v4v4v4(final_color, UNPACK3(colors), f_data->barycentricWeights[i * samples].v);
1617
1618 copy_v4_v4(pPoint[i].color, final_color);
1619}
1620
1621static void dynamicPaint_setInitialColor(const Scene * /*scene*/, DynamicPaintSurface *surface)
1622{
1623 PaintSurfaceData *sData = surface->data;
1624 PaintPoint *pPoint = static_cast<PaintPoint *>(sData->type_data);
1626 const bke::AttributeAccessor attributes = mesh->attributes();
1627
1628 if (surface->type != MOD_DPAINT_SURFACE_T_PAINT) {
1629 return;
1630 }
1631
1632 if (surface->init_color_type == MOD_DPAINT_INITIAL_NONE) {
1633 return;
1634 }
1635
1636 /* Single color */
1637 if (surface->init_color_type == MOD_DPAINT_INITIAL_COLOR) {
1638 /* apply color to every surface point */
1639 for (int i = 0; i < sData->total_points; i++) {
1640 copy_v4_v4(pPoint[i].color, surface->init_color);
1641 }
1642 }
1643 /* UV mapped texture */
1644 else if (surface->init_color_type == MOD_DPAINT_INITIAL_TEXTURE) {
1645 Tex *tex = surface->init_texture;
1646
1647 const Span<int> corner_verts = mesh->corner_verts();
1648 const Span<int3> corner_tris = mesh->corner_tris();
1649
1650 if (!tex) {
1651 return;
1652 }
1653
1654 /* get uv map */
1655 const StringRef uvname = mesh->uv_map_names().contains(surface->init_layername) ?
1656 surface->init_layername :
1657 mesh->active_uv_map_name();
1658 const VArraySpan uv_map = *attributes.lookup<float2>(uvname, bke::AttrDomain::Corner);
1659
1660 if (uv_map.is_empty()) {
1661 return;
1662 }
1663
1664 /* For vertex surface loop through `corner_tris` and find UV color
1665 * that provides highest alpha. */
1666 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1667 ImagePool *pool = BKE_image_pool_new();
1668
1670 data.surface = surface;
1671 data.corner_verts = corner_verts;
1672 data.corner_tris = corner_tris;
1673 data.uv_map = uv_map;
1674 data.pool = pool;
1675
1676 TaskParallelSettings settings;
1678 settings.use_threading = (corner_tris.size() > 1000);
1680 0, corner_tris.size(), &data, dynamic_paint_set_init_color_tex_to_vcol_cb, &settings);
1681 BKE_image_pool_free(pool);
1682 }
1683 else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
1685 data.surface = surface;
1686 data.corner_tris = corner_tris;
1687 data.uv_map = uv_map;
1688
1689 TaskParallelSettings settings;
1691 settings.use_threading = (sData->total_points > 1000);
1694 }
1695 }
1696 /* vertex color layer */
1697 else if (surface->init_color_type == MOD_DPAINT_INITIAL_VERTEXCOLOR) {
1698
1699 /* For vertex surface, just copy colors from #MLoopCol. */
1700 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1701 const Span<int> corner_verts = mesh->corner_verts();
1702 const VArraySpan col = *attributes.lookup<ColorGeometry4b>(surface->init_layername,
1704 if (col.is_empty()) {
1705 return;
1706 }
1707
1708 for (const int i : corner_verts.index_range()) {
1709 rgba_uchar_to_float(pPoint[corner_verts[i]].color, static_cast<const uchar *>(&col[i].r));
1710 }
1711 }
1712 else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
1713 const Span<int3> corner_tris = mesh->corner_tris();
1714 const VArraySpan col = *attributes.lookup<ColorGeometry4b>(surface->init_layername,
1716 if (col.is_empty()) {
1717 return;
1718 }
1719
1721 data.surface = surface;
1722 data.corner_tris = corner_tris;
1723 data.mloopcol = col;
1724
1725 TaskParallelSettings settings;
1727 settings.use_threading = (sData->total_points > 1000);
1730 }
1731 }
1732}
1733
1735{
1736 PaintSurfaceData *sData = surface->data;
1737 if (sData && sData->type_data) {
1738 uint data_size;
1739
1740 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
1741 data_size = sizeof(PaintPoint);
1742 }
1743 else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) {
1744 data_size = sizeof(PaintWavePoint);
1745 }
1746 else {
1747 data_size = sizeof(float);
1748 }
1749
1750 memset(sData->type_data, 0, data_size * sData->total_points);
1751
1752 /* set initial color */
1753 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
1754 dynamicPaint_setInitialColor(scene, surface);
1755 }
1756
1757 if (sData->bData) {
1758 sData->bData->clear = 1;
1759 }
1760 }
1761}
1762
1764{
1765 int numOfPoints = dynamicPaint_surfaceNumOfPoints(surface);
1766 /* free existing data */
1767 if (surface->data) {
1769 }
1770
1771 /* don't reallocate for image sequence types. they get handled only on bake */
1772 if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
1773 return true;
1774 }
1775 if (numOfPoints < 1) {
1776 return false;
1777 }
1778
1779 /* allocate memory */
1780 surface->data = MEM_new_zeroed<PaintSurfaceData>(__func__);
1781 if (!surface->data) {
1782 return false;
1783 }
1784
1785 /* allocate data depending on surface type and format */
1786 surface->data->total_points = numOfPoints;
1788 dynamicPaint_initAdjacencyData(surface, false);
1789
1790 /* set initial color */
1791 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
1792 dynamicPaint_setInitialColor(scene, surface);
1793 }
1794
1795 return true;
1796}
1797
1798/* make sure allocated surface size matches current requirements */
1800{
1801 if (!surface->data || (dynamicPaint_surfaceNumOfPoints(surface) != surface->data->total_points))
1802 {
1803 return dynamicPaint_resetSurface(scene, surface);
1804 }
1805 return true;
1806}
1807
1808/***************************** Modifier processing ******************************/
1809
1823
1824static void dynamic_paint_apply_surface_displace_cb(void *__restrict userdata,
1825 const int i,
1826 const TaskParallelTLS *__restrict /*tls*/)
1827{
1829 userdata);
1830
1831 const DynamicPaintSurface *surface = data->surface;
1832
1833 const float *value = static_cast<float *>(surface->data->type_data);
1834 const float val = value[i] * surface->disp_factor;
1835
1836 madd_v3_v3fl(data->vert_positions[i], data->vert_normals[i], -val);
1837}
1838
1841{
1842 PaintSurfaceData *sData = surface->data;
1843
1844 if (!sData || surface->format != MOD_DPAINT_SURFACE_F_VERTEX) {
1845 return;
1846 }
1847
1848 /* displace paint */
1849 if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE) {
1851 data.surface = surface;
1852 data.vert_positions = result->vert_positions_for_write();
1853 data.vert_normals = result->vert_normals();
1854
1855 TaskParallelSettings settings;
1857 settings.use_threading = (sData->total_points > 10000);
1860 }
1861}
1862
1863static void dynamic_paint_apply_surface_vpaint_blend_cb(void *__restrict userdata,
1864 const int i,
1865 const TaskParallelTLS *__restrict /*tls*/)
1866{
1868 userdata);
1869
1870 PaintPoint *pPoint = static_cast<PaintPoint *>(data->surface->data->type_data);
1871 float (*fcolor)[4] = data->fcolor;
1872
1873 /* blend dry and wet layer */
1875 pPoint[i].color, pPoint[i].color[3], pPoint[i].e_color, pPoint[i].e_color[3], fcolor[i]);
1876}
1877
1878static void dynamic_paint_apply_surface_vpaint_cb(void *__restrict userdata,
1879 const int p_index,
1880 const TaskParallelTLS *__restrict /*tls*/)
1881{
1883 userdata);
1884
1885 const Span<int> corner_verts = data->corner_verts;
1886
1887 const DynamicPaintSurface *surface = data->surface;
1888 PaintPoint *pPoint = static_cast<PaintPoint *>(surface->data->type_data);
1889 float (*fcolor)[4] = data->fcolor;
1890
1891 MutableSpan<ColorGeometry4b> mloopcol = data->mloopcol;
1892 MutableSpan<ColorGeometry4b> mloopcol_wet = data->mloopcol_wet;
1893
1894 for (const int l_index : data->faces[p_index]) {
1895 const int v_index = corner_verts[l_index];
1896
1897 /* save layer data to output layer */
1898 /* apply color */
1899 if (!mloopcol.is_empty()) {
1900 rgba_float_to_uchar(mloopcol[l_index], fcolor[v_index]);
1901 }
1902 /* apply wetness */
1903 if (!mloopcol_wet.is_empty()) {
1904 const char c = unit_float_to_uchar_clamp(pPoint[v_index].wetness);
1905 mloopcol_wet[l_index].r = c;
1906 mloopcol_wet[l_index].g = c;
1907 mloopcol_wet[l_index].b = c;
1908 mloopcol_wet[l_index].a = 255;
1909 }
1910 }
1911}
1912
1913static void dynamic_paint_apply_surface_wave_cb(void *__restrict userdata,
1914 const int i,
1915 const TaskParallelTLS *__restrict /*tls*/)
1916{
1918 userdata);
1919
1920 PaintWavePoint *wPoint = static_cast<PaintWavePoint *>(data->surface->data->type_data);
1921
1922 madd_v3_v3fl(data->vert_positions[i], data->vert_normals[i], wPoint[i].height);
1923}
1924
1929{
1930 using namespace blender::bke;
1932
1933 if (pmd->canvas && !(pmd->canvas->flags & MOD_DPAINT_BAKING) &&
1935 {
1936
1937 DynamicPaintSurface *surface;
1938
1939 /* loop through surfaces */
1940 for (surface = pmd->canvas->surfaces.first(); surface; surface = surface->next) {
1941 PaintSurfaceData *sData = surface->data;
1942
1943 if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ && sData) {
1944 if (!(surface->flags & MOD_DPAINT_ACTIVE)) {
1945 continue;
1946 }
1947
1948 /* process vertex surface previews */
1949 if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
1950
1951 /* vertex color paint */
1952 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
1953 const OffsetIndices faces = result->faces();
1954 const Span<int> corner_verts = result->corner_verts();
1955
1956 /* paint is stored on dry and wet layers, so mix final color first */
1958 "Temp paint color");
1959
1961 data.surface = surface;
1962 data.fcolor = fcolor;
1963
1964 {
1965 TaskParallelSettings settings;
1967 settings.use_threading = (sData->total_points > 1000);
1969 sData->total_points,
1970 &data,
1972 &settings);
1973 }
1974
1975 MutableAttributeAccessor attributes = result->attributes_for_write();
1976
1977 /* paint layer */
1979 if (attributes.lookup_meta_data(surface->output_name) ==
1980 AttributeMetaData{AttrDomain::Corner, AttrType::ColorByte})
1981 {
1982 mloopcol = attributes.lookup_for_write_span<ColorGeometry4b>(surface->output_name);
1983 }
1984 /* if output layer is lost from a constructive modifier, re-add it */
1985 if (!mloopcol && dynamicPaint_outputLayerExists(surface, ob, 0)) {
1986 mloopcol = attributes.lookup_or_add_for_write_span<ColorGeometry4b>(
1988 }
1989
1991 if (attributes.lookup_meta_data(surface->output_name2) ==
1992 AttributeMetaData{AttrDomain::Corner, AttrType::ColorByte})
1993 {
1994 mloopcol_wet = attributes.lookup_for_write_span<ColorGeometry4b>(
1995 surface->output_name2);
1996 }
1997 /* if output layer is lost from a constructive modifier, re-add it */
1998 if (!mloopcol_wet && dynamicPaint_outputLayerExists(surface, ob, 1)) {
1999 mloopcol_wet = attributes.lookup_or_add_for_write_span<ColorGeometry4b>(
2001 }
2002
2003 data.ob = ob;
2004 data.corner_verts = corner_verts;
2005 data.faces = faces;
2006 data.mloopcol = mloopcol.span;
2007 data.mloopcol_wet = mloopcol_wet.span;
2008
2009 {
2010 TaskParallelSettings settings;
2012 settings.use_threading = (faces.size() > 1000);
2014 0, faces.size(), &data, dynamic_paint_apply_surface_vpaint_cb, &settings);
2015 }
2016
2017 mloopcol.finish();
2018 mloopcol_wet.finish();
2019
2020 MEM_delete(fcolor);
2021 }
2022 /* vertex group paint */
2023 else if (surface->type == MOD_DPAINT_SURFACE_T_WEIGHT) {
2024 int defgrp_index = BKE_object_defgroup_name_index(ob, surface->output_name);
2025 float *weight = static_cast<float *>(sData->type_data);
2026
2027 /* apply weights into a vertex group, if doesn't exists add a new layer */
2028 MutableSpan<MDeformVert> dverts = result->deform_verts_for_write();
2029 if (defgrp_index != -1) {
2030 for (int i = 0; i < sData->total_points; i++) {
2031 MDeformVert *dv = &dverts[i];
2032 MDeformWeight *def_weight = BKE_defvert_find_index(dv, defgrp_index);
2033
2034 /* skip if weight value is 0 and no existing weight is found */
2035 if ((def_weight != nullptr) || (weight[i] != 0.0f)) {
2036 /* if not found, add a weight for it */
2037 if (def_weight == nullptr) {
2038 def_weight = BKE_defvert_ensure_index(dv, defgrp_index);
2039 }
2040
2041 /* set weight value */
2042 def_weight->weight = weight[i];
2043 }
2044 }
2045 }
2046 }
2047 /* wave simulation */
2048 else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) {
2050 data.surface = surface;
2051 data.vert_positions = result->vert_positions_for_write();
2052 data.vert_normals = result->vert_normals();
2053
2054 TaskParallelSettings settings;
2056 settings.use_threading = (sData->total_points > 1000);
2058 0, sData->total_points, &data, dynamic_paint_apply_surface_wave_cb, &settings);
2059 result->tag_positions_changed();
2060 }
2061
2062 /* displace */
2063 if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE) {
2065 result->tag_positions_changed();
2066 }
2067 }
2068 }
2069 }
2070 }
2071 /* make a copy of mesh to use as brush data */
2072 else if (pmd->brush && pmd->type == MOD_DYNAMICPAINT_TYPE_BRUSH) {
2074 BLI_assert(runtime_data != nullptr);
2075 std::lock_guard lock(runtime_data->brush_mutex);
2076 if (runtime_data->brush_mesh != nullptr) {
2077 BKE_id_free(nullptr, runtime_data->brush_mesh);
2078 }
2079 runtime_data->brush_mesh = BKE_mesh_copy_for_eval(*result);
2080 }
2081
2082 return result;
2083}
2084
2086{
2087 if (surface->pointcache) {
2088 surface->pointcache->startframe = surface->start_frame;
2089 surface->pointcache->endframe = surface->end_frame;
2090 }
2091}
2092
2094{
2096 if (runtime->canvas_mesh != nullptr) {
2097 BKE_id_free(nullptr, runtime->canvas_mesh);
2098 }
2099
2101}
2102
2103/*
2104 * Updates evaluated-mesh copy and processes dynamic paint step / caches.
2105 */
2107 DynamicPaintModifierData *pmd, Depsgraph *depsgraph, Scene *scene, Object *ob, Mesh *mesh)
2108{
2109 if (pmd->canvas) {
2111 DynamicPaintSurface *surface = canvas->surfaces.first();
2112
2113 /* update evaluated-mesh copy */
2115
2116 /* in case image sequence baking, stop here */
2117 if (canvas->flags & MOD_DPAINT_BAKING) {
2118 return;
2119 }
2120
2121 /* loop through surfaces */
2122 for (; surface; surface = surface->next) {
2123 int current_frame = scene->r.cfra;
2124 bool no_surface_data;
2125
2126 /* free bake data if not required anymore */
2127 surface_freeUnusedData(surface);
2128
2129 /* image sequences are handled by bake operator */
2130 if ((surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) ||
2131 !(surface->flags & MOD_DPAINT_ACTIVE))
2132 {
2133 continue;
2134 }
2135
2136 /* make sure surface is valid */
2137 no_surface_data = surface->data == nullptr;
2138 if (!dynamicPaint_checkSurfaceData(scene, surface)) {
2139 continue;
2140 }
2141
2142 /* limit frame range */
2143 CLAMP(current_frame, surface->start_frame, surface->end_frame);
2144
2145 if (no_surface_data || current_frame != surface->current_frame ||
2146 scene->r.cfra == surface->start_frame)
2147 {
2148 PointCache *cache = surface->pointcache;
2149 PTCacheID pid;
2150 surface->current_frame = current_frame;
2151
2152 /* read point cache */
2153 BKE_ptcache_id_from_dynamicpaint(&pid, ob, surface);
2154 pid.cache->startframe = surface->start_frame;
2155 pid.cache->endframe = surface->end_frame;
2156 BKE_ptcache_id_time(&pid, scene, float(scene->r.cfra), nullptr, nullptr, nullptr);
2157
2158 /* reset non-baked cache at first frame */
2159 if (scene->r.cfra == surface->start_frame && !(cache->flag & PTCACHE_BAKED)) {
2160 cache->flag |= PTCACHE_REDO_NEEDED;
2162 cache->flag &= ~PTCACHE_REDO_NEEDED;
2163 }
2164
2165 /* try to read from cache */
2166 bool can_simulate = (scene->r.cfra == current_frame) && !(cache->flag & PTCACHE_BAKED);
2167
2168 if (BKE_ptcache_read(&pid, float(scene->r.cfra), can_simulate)) {
2169 BKE_ptcache_validate(cache, scene->r.cfra);
2170 }
2171 /* if read failed and we're on surface range do recalculate */
2172 else if (can_simulate) {
2173 /* calculate surface frame */
2174 canvas->flags |= MOD_DPAINT_BAKING;
2175 dynamicPaint_calculateFrame(surface, depsgraph, scene, ob, current_frame);
2176 canvas->flags &= ~MOD_DPAINT_BAKING;
2177
2178 /* restore canvas mesh if required */
2179 if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE &&
2180 surface->flags & MOD_DPAINT_DISP_INCREMENTAL && surface->next)
2181 {
2183 }
2184
2185 BKE_ptcache_validate(cache, surface->current_frame);
2186 BKE_ptcache_write(&pid, surface->current_frame);
2187 }
2188 }
2189 }
2190 }
2191}
2192
2194 DynamicPaintModifierData *pmd, Depsgraph *depsgraph, Scene *scene, Object *ob, Mesh *mesh)
2195{
2196 /* Update canvas data for a new frame */
2197 dynamicPaint_frameUpdate(pmd, depsgraph, scene, ob, mesh);
2198
2199 /* Return output mesh */
2200 return dynamicPaint_Modifier_apply(pmd, ob, mesh);
2201}
2202
2203/* -------------------------------------------------------------------- */
2206
2207/* Create a surface for uv image sequence format. */
2208#define JITTER_SAMPLES \
2209 { \
2210 0.0f, \
2211 0.0f, \
2212 -0.2f, \
2213 -0.4f, \
2214 0.2f, \
2215 0.4f, \
2216 0.4f, \
2217 -0.2f, \
2218 -0.4f, \
2219 0.3f, \
2220 }
2221
2235
2236static void dynamic_paint_create_uv_surface_direct_cb(void *__restrict userdata,
2237 const int ty,
2238 const TaskParallelTLS *__restrict /*tls*/)
2239{
2241 static_cast<const DynamicPaintCreateUVSurfaceData *>(userdata);
2242
2243 const DynamicPaintSurface *surface = data->surface;
2244 PaintUVPoint *tempPoints = data->tempPoints;
2245 Vec3f *tempWeights = data->tempWeights;
2246
2247 const Span<int3> corner_tris = data->corner_tris;
2248 const Span<float2> uv_map = data->uv_map;
2249 const Span<int> corner_verts = data->corner_verts;
2250
2251 const Bounds2D *faceBB = data->faceBB;
2252
2253 const float jitter5sample[10] = JITTER_SAMPLES;
2254 const int aa_samples = (surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
2255 const int w = surface->image_resolution;
2256 const int h = w;
2257
2258 for (int tx = 0; tx < w; tx++) {
2259 const int index = tx + w * ty;
2260 PaintUVPoint *tPoint = &tempPoints[index];
2261 float point[5][2];
2262
2263 /* Init per pixel settings */
2264 tPoint->tri_index = -1;
2265 tPoint->neighbor_pixel = -1;
2266 tPoint->pixel_index = index;
2267
2268 /* Actual pixel center, used when collision is found */
2269 point[0][0] = (float(tx) + 0.5f) / w;
2270 point[0][1] = (float(ty) + 0.5f) / h;
2271
2272 /*
2273 * A pixel middle sample isn't enough to find very narrow polygons
2274 * So using 4 samples of each corner too
2275 */
2276 point[1][0] = float(tx) / w;
2277 point[1][1] = float(ty) / h;
2278
2279 point[2][0] = (float(tx) + 1) / w;
2280 point[2][1] = float(ty) / h;
2281
2282 point[3][0] = float(tx) / w;
2283 point[3][1] = (float(ty) + 1) / h;
2284
2285 point[4][0] = (float(tx) + 1) / w;
2286 point[4][1] = (float(ty) + 1) / h;
2287
2288 /* Loop through samples, starting from middle point */
2289 for (int sample = 0; sample < 5; sample++) {
2290 /* Loop through every face in the mesh */
2291 /* XXX TODO: This is *horrible* with big meshes, should use a 2D BVHTree over UV tris here!
2292 */
2293 for (const int i : corner_tris.index_range()) {
2294 /* Check uv bb */
2295 if ((faceBB[i].min[0] > point[sample][0]) || (faceBB[i].min[1] > point[sample][1]) ||
2296 (faceBB[i].max[0] < point[sample][0]) || (faceBB[i].max[1] < point[sample][1]))
2297 {
2298 continue;
2299 }
2300
2301 const float *uv1 = uv_map[corner_tris[i][0]];
2302 const float *uv2 = uv_map[corner_tris[i][1]];
2303 const float *uv3 = uv_map[corner_tris[i][2]];
2304
2305 /* If point is inside the face */
2306 if (isect_point_tri_v2(point[sample], uv1, uv2, uv3) != 0) {
2307 float uv[2];
2308
2309 /* Add b-weights per anti-aliasing sample */
2310 for (int j = 0; j < aa_samples; j++) {
2311 uv[0] = point[0][0] + jitter5sample[j * 2] / w;
2312 uv[1] = point[0][1] + jitter5sample[j * 2 + 1] / h;
2313
2314 barycentric_weights_v2(uv1, uv2, uv3, uv, tempWeights[index * aa_samples + j].v);
2315 }
2316
2317 /* Set surface point face values */
2318 tPoint->tri_index = i;
2319
2320 /* save vertex indexes */
2321 tPoint->v1 = corner_verts[corner_tris[i][0]];
2322 tPoint->v2 = corner_verts[corner_tris[i][1]];
2323 tPoint->v3 = corner_verts[corner_tris[i][2]];
2324
2325 sample = 5; /* make sure we exit sample loop as well */
2326 break;
2327 }
2328 }
2329 }
2330 }
2331}
2332
2333static void dynamic_paint_create_uv_surface_neighbor_cb(void *__restrict userdata,
2334 const int ty,
2335 const TaskParallelTLS *__restrict /*tls*/)
2336{
2338 static_cast<const DynamicPaintCreateUVSurfaceData *>(userdata);
2339
2340 const DynamicPaintSurface *surface = data->surface;
2341 PaintUVPoint *tempPoints = data->tempPoints;
2342 Vec3f *tempWeights = data->tempWeights;
2343
2344 const Span<int3> corner_tris = data->corner_tris;
2345 const Span<float2> uv_map = data->uv_map;
2346 const Span<int> corner_verts = data->corner_verts;
2347
2348 uint32_t *active_points = data->active_points;
2349
2350 const float jitter5sample[10] = JITTER_SAMPLES;
2351 const int aa_samples = (surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
2352 const int w = surface->image_resolution;
2353 const int h = w;
2354
2355 for (int tx = 0; tx < w; tx++) {
2356 const int index = tx + w * ty;
2357 PaintUVPoint *tPoint = &tempPoints[index];
2358
2359 /* If point isn't on canvas mesh */
2360 if (tPoint->tri_index == -1) {
2361 float point[2];
2362
2363 /* get loop area */
2364 const int u_min = (tx > 0) ? -1 : 0;
2365 const int u_max = (tx < (w - 1)) ? 1 : 0;
2366 const int v_min = (ty > 0) ? -1 : 0;
2367 const int v_max = (ty < (h - 1)) ? 1 : 0;
2368
2369 point[0] = (float(tx) + 0.5f) / w;
2370 point[1] = (float(ty) + 0.5f) / h;
2371
2372 /* search through defined area for neighbor, checking grid directions first */
2373 for (int ni = 0; ni < 8; ni++) {
2374 int u = neighStraightX[ni];
2375 int v = neighStraightY[ni];
2376
2377 if (u >= u_min && u <= u_max && v >= v_min && v <= v_max) {
2378 /* if not this pixel itself */
2379 if (u != 0 || v != 0) {
2380 const int ind = (tx + u) + w * (ty + v);
2381
2382 /* if neighbor has index */
2383 if (tempPoints[ind].neighbor_pixel == -1 && tempPoints[ind].tri_index != -1) {
2384 float uv[2];
2385 const int i = tempPoints[ind].tri_index;
2386 const float *uv1 = uv_map[corner_tris[i][0]];
2387 const float *uv2 = uv_map[corner_tris[i][1]];
2388 const float *uv3 = uv_map[corner_tris[i][2]];
2389
2390 /* tri index */
2391 /* There is a low possibility of actually having a neighbor point which tri is
2392 * already set from another neighbor in a separate thread here.
2393 * Checking for both tri_index and neighbor_pixel above reduces that probability
2394 * but it remains possible.
2395 * That atomic op (and its memory fence) ensures tPoint->neighbor_pixel is set
2396 * to non--1 *before* its tri_index is set (i.e. that it cannot be used a neighbor).
2397 */
2398 tPoint->neighbor_pixel = ind - 1;
2400 tPoint->tri_index = i;
2401
2402 /* Now calculate pixel data for this pixel as it was on face surface */
2403 /* Add b-weights per anti-aliasing sample */
2404 for (int j = 0; j < aa_samples; j++) {
2405 uv[0] = point[0] + jitter5sample[j * 2] / w;
2406 uv[1] = point[1] + jitter5sample[j * 2 + 1] / h;
2407 barycentric_weights_v2(uv1, uv2, uv3, uv, tempWeights[index * aa_samples + j].v);
2408 }
2409
2410 /* save vertex indexes */
2411 tPoint->v1 = corner_verts[corner_tris[i][0]];
2412 tPoint->v2 = corner_verts[corner_tris[i][1]];
2413 tPoint->v3 = corner_verts[corner_tris[i][2]];
2414
2415 break;
2416 }
2417 }
2418 }
2419 }
2420 }
2421
2422 /* Increase the final number of active surface points if relevant. */
2423 if (tPoint->tri_index != -1) {
2424 atomic_add_and_fetch_uint32(active_points, 1);
2425 }
2426 }
2427}
2428
2429#undef JITTER_SAMPLES
2430
2432 const Span<float2> uv_map,
2433 int tri_index,
2434 const float point[2])
2435{
2436 BLI_assert(tri_index >= 0);
2437
2438 float min_distance = FLT_MAX;
2439
2440 for (int i = 0; i < 3; i++) {
2441 const float dist_squared = dist_squared_to_line_segment_v2(
2442 point,
2443 uv_map[corner_tris[tri_index][(i + 0)]],
2444 uv_map[corner_tris[tri_index][(i + 1) % 3]]);
2445
2446 min_distance = std::min(dist_squared, min_distance);
2447 }
2448
2449 return min_distance;
2450}
2451
2459
2462 int tri_index,
2463 const float pixel[2],
2464 int in_edge,
2465 int depth);
2466
2467/* Tries to find the neighboring pixel in given (uv space) direction.
2468 * Result is used by effect system to move paint on the surface.
2469 *
2470 * px, py : origin pixel x and y
2471 * n_index : lookup direction index (use neighX, neighY to get final index)
2472 */
2474 const MeshElemMap *vert_to_tri_map,
2475 const int w,
2476 const int h,
2477 const int px,
2478 const int py,
2479 const int n_index)
2480{
2481 /* NOTE: Current method only uses face edges to detect neighboring pixels.
2482 * -> It doesn't always lead to the optimum pixel but is accurate enough
2483 * and faster/simpler than including possible face tip point links.
2484 */
2485
2486 /* shift position by given n_index */
2487 const int x = px + neighX[n_index];
2488 const int y = py + neighY[n_index];
2489
2490 if (x < 0 || x >= w || y < 0 || y >= h) {
2491 return OUT_OF_TEXTURE;
2492 }
2493
2494 const PaintUVPoint *tempPoints = data->tempPoints;
2495 const PaintUVPoint *tPoint = &tempPoints[x + w * y]; /* UV neighbor */
2496 const PaintUVPoint *cPoint = &tempPoints[px + w * py]; /* Origin point */
2497
2498 /* Check if shifted point is on same face -> it's a correct neighbor
2499 * (and if it isn't marked as an "edge pixel") */
2500 if ((tPoint->tri_index == cPoint->tri_index) && (tPoint->neighbor_pixel == -1)) {
2501 return (x + w * y);
2502 }
2503
2504 /* Even if shifted point is on another face
2505 * -> use this point.
2506 *
2507 * !! Replace with "is uv faces linked" check !!
2508 * This should work fine as long as uv island margin is > 1 pixel.
2509 */
2510 if ((tPoint->tri_index != -1) && (tPoint->neighbor_pixel == -1)) {
2511 return (x + w * y);
2512 }
2513
2514 /* If we get here, the actual neighboring pixel is located on a non-linked uv face,
2515 * and we have to find its "real" position.
2516 *
2517 * Simple neighboring face finding algorithm:
2518 * - find closest uv edge to shifted pixel and get the another face that shares that edge
2519 * - find corresponding position of that new face edge in uv space
2520 *
2521 * TODO: Implement something more accurate / optimized?
2522 */
2523 {
2525 bdata.vert_to_tri_map = vert_to_tri_map;
2526 bdata.w = w;
2527 bdata.h = h;
2528 bdata.px = px;
2529 bdata.py = py;
2530 bdata.best_index = NOT_FOUND;
2531 bdata.best_weight = 1.0f;
2532
2533 float pixel[2];
2534
2535 pixel[0] = (float(px + neighX[n_index]) + 0.5f) / float(w);
2536 pixel[1] = (float(py + neighY[n_index]) + 0.5f) / float(h);
2537
2538 /* Do a small recursive search for the best island edge. */
2539 dynamic_paint_find_island_border(data, &bdata, cPoint->tri_index, pixel, -1, 5);
2540
2541 return bdata.best_index;
2542 }
2543}
2544
2547 int tri_index,
2548 const float pixel[2],
2549 int in_edge,
2550 int depth)
2551{
2552 const Span<int> corner_verts = data->corner_verts;
2553 const Span<int3> corner_tris = data->corner_tris;
2554 const Span<float2> uv_map = data->uv_map;
2555
2556 const int3 loop_idx = corner_tris[tri_index];
2557
2558 /* Enumerate all edges of the triangle, rotating the vertex list accordingly. */
2559 for (int edge_idx = 0; edge_idx < 3; edge_idx++) {
2560 /* but not the edge we have just recursed through */
2561 if (edge_idx == in_edge) {
2562 continue;
2563 }
2564
2565 float uv0[2], uv1[2], uv2[2];
2566
2567 copy_v2_v2(uv0, uv_map[loop_idx[(edge_idx + 0)]]);
2568 copy_v2_v2(uv1, uv_map[loop_idx[(edge_idx + 1) % 3]]);
2569 copy_v2_v2(uv2, uv_map[loop_idx[(edge_idx + 2) % 3]]);
2570
2571 /* Verify the target point is on the opposite side of the edge from the third triangle
2572 * vertex, to ensure that we always move closer to the goal point. */
2573 const float sidep = line_point_side_v2(uv0, uv1, pixel);
2574 const float side2 = line_point_side_v2(uv0, uv1, uv2);
2575
2576 if (side2 == 0.0f) {
2577 continue;
2578 }
2579
2580 /* Hack: allow all edges of the original triangle */
2581 const bool correct_side = (in_edge == -1) || (sidep < 0 && side2 > 0) ||
2582 (sidep > 0 && side2 < 0);
2583
2584 /* Allow exactly on edge for the non-recursive case */
2585 if (!correct_side && sidep != 0.0f) {
2586 continue;
2587 }
2588
2589 /* Now find another face that is linked to that edge. */
2590 const int vert0 = corner_verts[loop_idx[(edge_idx + 0)]];
2591 const int vert1 = corner_verts[loop_idx[(edge_idx + 1) % 3]];
2592
2593 /* Use a pre-computed vert-to-corner_tri mapping,
2594 * speeds up things a lot compared to looping over all corner_tris. */
2595 const MeshElemMap *map = &bdata->vert_to_tri_map[vert0];
2596
2597 bool found_other = false;
2598 int target_tri = -1;
2599 int target_edge = -1;
2600
2601 float ouv0[2], ouv1[2];
2602
2603 for (int i = 0; i < map->count && !found_other; i++) {
2604 const int tri_other_index = map->indices[i];
2605
2606 if (tri_other_index == tri_index) {
2607 continue;
2608 }
2609
2610 const int3 other_tri = corner_tris[tri_other_index];
2611
2612 /* Check edges for match, looping in the same order as the outer loop. */
2613 for (int j = 0; j < 3; j++) {
2614 const int overt0 = corner_verts[other_tri[(j + 0)]];
2615 const int overt1 = corner_verts[other_tri[(j + 1) % 3]];
2616
2617 /* Allow for swapped vertex order */
2618 if (overt0 == vert0 && overt1 == vert1) {
2619 found_other = true;
2620 copy_v2_v2(ouv0, uv_map[other_tri[(j + 0)]]);
2621 copy_v2_v2(ouv1, uv_map[other_tri[(j + 1) % 3]]);
2622 }
2623 else if (overt0 == vert1 && overt1 == vert0) {
2624 found_other = true;
2625 copy_v2_v2(ouv1, uv_map[other_tri[(j + 0)]]);
2626 copy_v2_v2(ouv0, uv_map[other_tri[(j + 1) % 3]]);
2627 }
2628
2629 if (found_other) {
2630 target_tri = tri_other_index;
2631 target_edge = j;
2632 break;
2633 }
2634 }
2635 }
2636
2637 if (!found_other) {
2638 if (bdata->best_index < 0) {
2639 bdata->best_index = ON_MESH_EDGE;
2640 }
2641
2642 continue;
2643 }
2644
2645 /* If this edge is connected in UV space too, recurse */
2646 if (equals_v2v2(uv0, ouv0) && equals_v2v2(uv1, ouv1)) {
2647 if (depth > 0 && correct_side) {
2648 dynamic_paint_find_island_border(data, bdata, target_tri, pixel, target_edge, depth - 1);
2649 }
2650
2651 continue;
2652 }
2653
2654 /* Otherwise try to map to the other side of the edge.
2655 * First check if there already is a better solution. */
2656 const float dist_squared = dist_squared_to_line_segment_v2(pixel, uv0, uv1);
2657
2658 if (bdata->best_index >= 0 && dist_squared >= bdata->best_weight) {
2659 continue;
2660 }
2661
2662 /*
2663 * Find a point that is relatively at same edge position
2664 * on this other face UV
2665 */
2666 float closest_point[2], dir_vec[2], tgt_pixel[2];
2667
2668 float lambda = closest_to_line_v2(closest_point, pixel, uv0, uv1);
2669 CLAMP(lambda, 0.0f, 1.0f);
2670
2671 sub_v2_v2v2(dir_vec, ouv1, ouv0);
2672 madd_v2_v2v2fl(tgt_pixel, ouv0, dir_vec, lambda);
2673
2674 int w = bdata->w, h = bdata->h, px = bdata->px, py = bdata->py;
2675
2676 const int final_pixel[2] = {int(floorf(tgt_pixel[0] * w)), int(floorf(tgt_pixel[1] * h))};
2677
2678 /* If current pixel uv is outside of texture */
2679 if (final_pixel[0] < 0 || final_pixel[0] >= w || final_pixel[1] < 0 || final_pixel[1] >= h) {
2680 if (bdata->best_index == NOT_FOUND) {
2681 bdata->best_index = OUT_OF_TEXTURE;
2682 }
2683
2684 continue;
2685 }
2686
2687 const PaintUVPoint *tempPoints = data->tempPoints;
2688 int final_index = final_pixel[0] + w * final_pixel[1];
2689
2690 /* If we ended up to our origin point ( mesh has smaller than pixel sized faces) */
2691 if (final_index == (px + w * py)) {
2692 continue;
2693 }
2694
2695 /* If final point is an "edge pixel", use its "real" neighbor instead */
2696 if (tempPoints[final_index].neighbor_pixel != -1) {
2697 final_index = tempPoints[final_index].neighbor_pixel;
2698
2699 /* If we ended up to our origin point */
2700 if (final_index == (px + w * py)) {
2701 continue;
2702 }
2703 }
2704
2705 const int final_tri_index = tempPoints[final_index].tri_index;
2706 /* If found pixel still lies on wrong face ( mesh has smaller than pixel sized faces) */
2707 if (!ELEM(final_tri_index, target_tri, -1)) {
2708 /* Check if it's close enough to likely touch the intended triangle. Any triangle
2709 * becomes thinner than a pixel at its vertices, so robustness requires some margin. */
2710 const float final_pt[2] = {((final_index % w) + 0.5f) / w, ((final_index / w) + 0.5f) / h};
2711 const float threshold = square_f(0.7f) / (w * h);
2712
2713 if (dist_squared_to_corner_tris_uv_edges(corner_tris, uv_map, final_tri_index, final_pt) >
2714 threshold)
2715 {
2716 continue;
2717 }
2718 }
2719
2720 bdata->best_index = final_index;
2721 bdata->best_weight = dist_squared;
2722 }
2723}
2724
2725static bool dynamicPaint_pointHasNeighbor(PaintAdjData *ed, int index, int neighbor)
2726{
2727 const int idx = ed->n_index[index];
2728
2729 for (int i = 0; i < ed->n_num[index]; i++) {
2730 if (ed->n_target[idx + i] == neighbor) {
2731 return true;
2732 }
2733 }
2734
2735 return false;
2736}
2737
2738/* Makes the adjacency data symmetric, except for border pixels.
2739 * I.e. if A is neighbor of B, B is neighbor of A. */
2740static bool dynamicPaint_symmetrizeAdjData(PaintAdjData *ed, int active_points)
2741{
2742 int *new_n_index = MEM_new_array_zeroed<int>(active_points, "Surface Adj Index");
2743 int *new_n_num = MEM_new_array_zeroed<int>(active_points, "Surface Adj Counts");
2744
2745 if (new_n_num && new_n_index) {
2746 /* Count symmetrized neighbors */
2747 int total_targets = 0;
2748
2749 for (int index = 0; index < active_points; index++) {
2750 total_targets += ed->n_num[index];
2751 new_n_num[index] = ed->n_num[index];
2752 }
2753
2754 for (int index = 0; index < active_points; index++) {
2755 if (ed->flags[index] & ADJ_BORDER_PIXEL) {
2756 continue;
2757 }
2758
2759 for (int i = 0, idx = ed->n_index[index]; i < ed->n_num[index]; i++) {
2760 const int target = ed->n_target[idx + i];
2761
2762 BLI_assert(!(ed->flags[target] & ADJ_BORDER_PIXEL));
2763
2764 if (!dynamicPaint_pointHasNeighbor(ed, target, index)) {
2765 new_n_num[target]++;
2766 total_targets++;
2767 }
2768 }
2769 }
2770
2771 /* Allocate a new target map */
2772 int *new_n_target = MEM_new_array_zeroed<int>(total_targets, "Surface Adj Targets");
2773
2774 if (new_n_target) {
2775 /* Copy existing neighbors to the new map */
2776 int n_pos = 0;
2777
2778 for (int index = 0; index < active_points; index++) {
2779 new_n_index[index] = n_pos;
2780 memcpy(&new_n_target[n_pos],
2781 &ed->n_target[ed->n_index[index]],
2782 sizeof(int) * ed->n_num[index]);
2783
2784 /* Reset count to old, but advance position by new, leaving a gap to fill below. */
2785 n_pos += new_n_num[index];
2786 new_n_num[index] = ed->n_num[index];
2787 }
2788
2789 BLI_assert(n_pos == total_targets);
2790
2791 /* Add symmetrized - this loop behavior must exactly match the count pass above */
2792 for (int index = 0; index < active_points; index++) {
2793 if (ed->flags[index] & ADJ_BORDER_PIXEL) {
2794 continue;
2795 }
2796
2797 for (int i = 0, idx = ed->n_index[index]; i < ed->n_num[index]; i++) {
2798 const int target = ed->n_target[idx + i];
2799
2800 if (!dynamicPaint_pointHasNeighbor(ed, target, index)) {
2801 const int num = new_n_num[target]++;
2802 new_n_target[new_n_index[target] + num] = index;
2803 }
2804 }
2805 }
2806
2807 /* Swap maps */
2808 MEM_delete(ed->n_target);
2809 ed->n_target = new_n_target;
2810
2811 MEM_delete(ed->n_index);
2812 ed->n_index = new_n_index;
2813
2814 MEM_delete(ed->n_num);
2815 ed->n_num = new_n_num;
2816
2817 ed->total_targets = total_targets;
2818 return true;
2819 }
2820 }
2821
2822 if (new_n_index) {
2823 MEM_delete(new_n_index);
2824 }
2825 if (new_n_num) {
2826 MEM_delete(new_n_num);
2827 }
2828
2829 return false;
2830}
2831
2833 DynamicPaintSurface *surface,
2834 float *progress,
2835 bool *do_update)
2836{
2837 /* Anti-alias jitter point relative coords. */
2838 const int aa_samples = (surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
2839 uint32_t active_points = 0;
2840 bool error = false;
2841
2842 PaintSurfaceData *sData;
2845
2846 PaintUVPoint *tempPoints = nullptr;
2847 Vec3f *tempWeights = nullptr;
2848 VArraySpan<float2> uv_map;
2849
2850 Bounds2D *faceBB = nullptr;
2851 int *final_index;
2852
2853 *progress = 0.0f;
2854 *do_update = true;
2855
2856 if (!mesh) {
2857 return setError(canvas, N_("Canvas mesh not updated"));
2858 }
2859 if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ) {
2860 return setError(canvas, N_("Cannot bake non-'image sequence' formats"));
2861 }
2862
2863 const Span<int> corner_verts = mesh->corner_verts();
2864 const Span<int3> corner_tris = mesh->corner_tris();
2865
2866 /* get uv map */
2867 const VectorSet<StringRefNull> uv_map_names = mesh->uv_map_names();
2868 if (!uv_map_names.is_empty()) {
2869 const StringRef uvname = uv_map_names.contains(surface->uvlayer_name) ?
2870 surface->uvlayer_name :
2871 mesh->active_uv_map_name();
2872 const bke::AttributeAccessor attributes = mesh->attributes();
2873 uv_map = *attributes.lookup<float2>(uvname, bke::AttrDomain::Corner);
2874 }
2875
2876 /* Check for validity */
2877 if (uv_map.is_empty()) {
2878 return setError(canvas, N_("No UV data on canvas"));
2879 }
2880 if (surface->image_resolution < 16 || surface->image_resolution > 8192) {
2881 return setError(canvas, N_("Invalid resolution"));
2882 }
2883
2884 const int w = surface->image_resolution;
2885 const int h = w;
2886
2887 /*
2888 * Start generating the surface
2889 */
2890 CLOG_DEBUG(
2891 &LOG, "Preparing UV surface of %ix%i pixels and %i tris.", w, h, int(corner_tris.size()));
2892
2893 /* Init data struct */
2894 if (surface->data) {
2896 }
2897 sData = surface->data = MEM_new_zeroed<PaintSurfaceData>(__func__);
2898 if (!surface->data) {
2899 return setError(canvas, N_("Not enough free memory"));
2900 }
2901
2902 tempPoints = MEM_new_array_zeroed<PaintUVPoint>(size_t(w) * size_t(h), "Temp PaintUVPoint");
2903 if (!tempPoints) {
2904 error = true;
2905 }
2906
2907 final_index = MEM_new_array_zeroed<int>(size_t(w) * size_t(h), "Temp UV Final Indexes");
2908 if (!final_index) {
2909 error = true;
2910 }
2911
2912 tempWeights = MEM_new_array_uninitialized<Vec3f>(size_t(w) * size_t(h) * size_t(aa_samples),
2913 "Temp bWeights");
2914 if (!tempWeights) {
2915 error = true;
2916 }
2917
2918 /*
2919 * Generate a temporary bounding box array for UV faces to optimize
2920 * the pixel-inside-a-face search.
2921 */
2922 if (!error) {
2923 faceBB = MEM_new_array_uninitialized<Bounds2D>(size_t(corner_tris.size()), "MPCanvasFaceBB");
2924 if (!faceBB) {
2925 error = true;
2926 }
2927 }
2928
2929 *progress = 0.01f;
2930 *do_update = true;
2931
2932 if (!error) {
2933 for (const int i : corner_tris.index_range()) {
2934 copy_v2_v2(faceBB[i].min, uv_map[corner_tris[i][0]]);
2935 copy_v2_v2(faceBB[i].max, uv_map[corner_tris[i][0]]);
2936
2937 for (int j = 1; j < 3; j++) {
2938 minmax_v2v2_v2(faceBB[i].min, faceBB[i].max, uv_map[corner_tris[i][j]]);
2939 }
2940 }
2941
2942 *progress = 0.02f;
2943 *do_update = true;
2944
2945 /* Loop through every pixel and check if pixel is uv-mapped on a canvas face. */
2947 data.surface = surface;
2948 data.tempPoints = tempPoints;
2949 data.tempWeights = tempWeights;
2950 data.corner_tris = corner_tris;
2951 data.uv_map = uv_map;
2952 data.corner_verts = corner_verts;
2953 data.faceBB = faceBB;
2954
2955 {
2956 TaskParallelSettings settings;
2958 settings.use_threading = (h > 64 || corner_tris.size() > 1000);
2960 }
2961
2962 *progress = 0.04f;
2963 *do_update = true;
2964
2965 /*
2966 * Now loop through every pixel that was left without index
2967 * and find if they have neighboring pixels that have an index.
2968 * If so use that face as pixel surface.
2969 * (To avoid seams on uv island edges)
2970 */
2971 data.active_points = &active_points;
2972 {
2973 TaskParallelSettings settings;
2975 settings.use_threading = (h > 64);
2977 }
2978
2979 *progress = 0.06f;
2980 *do_update = true;
2981
2982 /* Generate surface adjacency data. */
2983 {
2984 int cursor = 0;
2985
2986 /* Create a temporary array of final indexes (before unassigned
2987 * pixels have been dropped) */
2988 for (int i = 0; i < w * h; i++) {
2989 if (tempPoints[i].tri_index != -1) {
2990 final_index[i] = cursor;
2991 cursor++;
2992 }
2993 }
2994 /* allocate memory */
2995 sData->total_points = w * h;
2996 dynamicPaint_initAdjacencyData(surface, true);
2997
2998 if (sData->adj_data) {
2999 PaintAdjData *ed = sData->adj_data;
3000 int n_pos = 0;
3001
3002 MeshElemMap *vert_to_tri_map;
3003 int *vert_to_tri_map_mem;
3004
3005 BKE_mesh_vert_corner_tri_map_create(&vert_to_tri_map,
3006 &vert_to_tri_map_mem,
3007 mesh->verts_num,
3008 corner_tris.data(),
3009 corner_tris.size(),
3010 corner_verts.data(),
3011 mesh->corners_num);
3012
3013 int total_border = 0;
3014
3015 for (int ty = 0; ty < h; ty++) {
3016 for (int tx = 0; tx < w; tx++) {
3017 const int index = tx + w * ty;
3018
3019 if (tempPoints[index].tri_index != -1) {
3020 ed->n_index[final_index[index]] = n_pos;
3021 ed->n_num[final_index[index]] = 0;
3022
3023 if (tempPoints[index].neighbor_pixel != -1) {
3024 ed->flags[final_index[index]] |= ADJ_BORDER_PIXEL;
3025 total_border++;
3026 }
3027
3028 for (int i = 0; i < 8; i++) {
3029 /* Try to find a neighboring pixel in defined direction.
3030 * If not found, -1 is returned */
3031 const int n_target = dynamic_paint_find_neighbor_pixel(
3032 &data, vert_to_tri_map, w, h, tx, ty, i);
3033
3034 if (n_target >= 0 && n_target != index) {
3036 ed, final_index[index], final_index[n_target]))
3037 {
3038 ed->n_target[n_pos] = final_index[n_target];
3039 ed->n_num[final_index[index]]++;
3040 n_pos++;
3041 }
3042 }
3043 else if (ELEM(n_target, ON_MESH_EDGE, OUT_OF_TEXTURE)) {
3044 ed->flags[final_index[index]] |= ADJ_ON_MESH_EDGE;
3045 }
3046 }
3047 }
3048 }
3049 }
3050
3051 MEM_delete(vert_to_tri_map);
3052 MEM_delete(vert_to_tri_map_mem);
3053
3054 /* Make neighbors symmetric */
3055 if (!dynamicPaint_symmetrizeAdjData(ed, active_points)) {
3056 error = true;
3057 }
3058
3059 /* Create a list of border pixels */
3060 ed->border = MEM_new_array_zeroed<int>(total_border, "Border Pixel Index");
3061
3062 if (ed->border) {
3063 ed->total_border = total_border;
3064
3065 for (int i = 0, next = 0; i < active_points; i++) {
3066 if (ed->flags[i] & ADJ_BORDER_PIXEL) {
3067 ed->border[next++] = i;
3068 }
3069 }
3070 }
3071
3072#if 0
3073 /* -----------------------------------------------------------------
3074 * For debug, write a dump of adjacency data to a file.
3075 * ----------------------------------------------------------------- */
3076 FILE *dump_file = fopen("dynpaint-adj-data.txt", "w");
3077 int *tmp = MEM_new_array_zeroed<int>(active_points, "tmp");
3078 for (int ty = 0; ty < h; ty++) {
3079 for (int tx = 0; tx < w; tx++) {
3080 const int index = tx + w * ty;
3081 if (tempPoints[index].tri_index != -1) {
3082 tmp[final_index[index]] = index;
3083 }
3084 }
3085 }
3086 for (int ty = 0; ty < h; ty++) {
3087 for (int tx = 0; tx < w; tx++) {
3088 const int index = tx + w * ty;
3089 const int fidx = final_index[index];
3090
3091 if (tempPoints[index].tri_index != -1) {
3092 int nidx = tempPoints[index].neighbor_pixel;
3093 fprintf(dump_file,
3094 "%d\t%d,%d\t%u\t%d,%d\t%d\t",
3095 fidx,
3096 tx,
3097 h - 1 - ty,
3098 tempPoints[index].tri_index,
3099 nidx < 0 ? -1 : (nidx % w),
3100 nidx < 0 ? -1 : h - 1 - (nidx / w),
3101 ed->flags[fidx]);
3102 for (int i = 0; i < ed->n_num[fidx]; i++) {
3103 int tgt = tmp[ed->n_target[ed->n_index[fidx] + i]];
3104 fprintf(dump_file, "%s%d,%d", i ? " " : "", tgt % w, h - 1 - tgt / w);
3105 }
3106 fprintf(dump_file, "\n");
3107 }
3108 }
3109 }
3110 MEM_delete(tmp);
3111 fclose(dump_file);
3112#endif
3113 }
3114 }
3115
3116 *progress = 0.08f;
3117 *do_update = true;
3118
3119 /* Create final surface data without inactive points */
3121 if (f_data) {
3122 f_data->uv_p = MEM_new_array_zeroed<PaintUVPoint>(active_points, "PaintUVPoint");
3123 f_data->barycentricWeights = MEM_new_array_zeroed<Vec3f>(active_points * size_t(aa_samples),
3124 "PaintUVPoint");
3125
3126 if (!f_data->uv_p || !f_data->barycentricWeights) {
3127 error = true;
3128 }
3129 }
3130 else {
3131 error = true;
3132 }
3133
3134 /* in case of allocation error, free everything */
3135 if (error) {
3136 if (f_data) {
3137 if (f_data->uv_p) {
3138 MEM_delete(f_data->uv_p);
3139 }
3140 if (f_data->barycentricWeights) {
3141 MEM_delete(f_data->barycentricWeights);
3142 }
3143 MEM_delete(f_data);
3144 }
3145 sData->total_points = 0;
3146 }
3147 else {
3148 sData->total_points = int(active_points);
3149 sData->format_data = f_data;
3150
3151 for (int index = 0, cursor = 0; index < (w * h); index++) {
3152 if (tempPoints[index].tri_index != -1) {
3153 memcpy(&f_data->uv_p[cursor], &tempPoints[index], sizeof(PaintUVPoint));
3154 memcpy(&f_data->barycentricWeights[cursor * aa_samples],
3155 &tempWeights[index * aa_samples],
3156 sizeof(*tempWeights) * aa_samples);
3157 cursor++;
3158 }
3159 }
3160 }
3161 }
3162 if (error == 1) {
3163 setError(canvas, N_("Not enough free memory"));
3164 }
3165
3166 if (faceBB) {
3167 MEM_delete(faceBB);
3168 }
3169 if (tempPoints) {
3170 MEM_delete(tempPoints);
3171 }
3172 if (tempWeights) {
3173 MEM_delete(tempWeights);
3174 }
3175 if (final_index) {
3176 MEM_delete(final_index);
3177 }
3178
3179 /* Init surface type data */
3180 if (!error) {
3182
3183#if 0
3184 /* -----------------------------------------------------------------
3185 * For debug, output pixel statuses to the color map
3186 * ----------------------------------------------------------------- */
3187 for (index = 0; index < sData->total_points; index++) {
3188 ImgSeqFormatData *f_data = sData->format_data;
3189 PaintUVPoint *uvPoint = &((PaintUVPoint *)f_data->uv_p)[index];
3190 PaintPoint *pPoint = &((PaintPoint *)sData->type_data)[index];
3191 pPoint->alpha = 1.0f;
3192
3193 /* Every pixel that is assigned as "edge pixel" gets blue color */
3194 if (uvPoint->neighbor_pixel != -1) {
3195 pPoint->color[2] = 1.0f;
3196 }
3197 /* and every pixel that finally got an face gets red color */
3198 /* green color shows pixel face index hash */
3199 if (uvPoint->tri_index != -1) {
3200 pPoint->color[0] = 1.0f;
3201 pPoint->color[1] = float(uvPoint->tri_index % 255) / 256.0f;
3202 }
3203 }
3204#endif
3205
3206 dynamicPaint_setInitialColor(scene, surface);
3207 }
3208
3209 *progress = 0.09f;
3210 *do_update = true;
3211
3212 return (error == 0);
3213}
3214
3215/*
3216 * Outputs an image file from uv surface data.
3217 */
3222
3223static void dynamic_paint_output_surface_image_paint_cb(void *__restrict userdata,
3224 const int index,
3225 const TaskParallelTLS *__restrict /*tls*/)
3226{
3228 static_cast<const DynamicPaintOutputSurfaceImageData *>(userdata);
3229
3230 const DynamicPaintSurface *surface = data->surface;
3231 const PaintPoint *point = &(static_cast<PaintPoint *>(surface->data->type_data))[index];
3232
3233 /* image buffer position */
3234 const int pos = surface->data->format_data->uv_p[index].pixel_index * 4;
3235
3236 /* blend wet and dry layers */
3237 blendColors(point->color,
3238 point->color[3],
3239 point->e_color,
3240 point->e_color[3],
3241 &data->ibuf_float_data[pos]);
3242
3243 /* Multiply color by alpha if enabled */
3244 if (surface->flags & MOD_DPAINT_MULALPHA) {
3245 mul_v3_fl(&data->ibuf_float_data[pos], data->ibuf_float_data[pos + 3]);
3246 }
3247}
3248
3250 void *__restrict userdata, const int index, const TaskParallelTLS *__restrict /*tls*/)
3251{
3253 static_cast<const DynamicPaintOutputSurfaceImageData *>(userdata);
3254
3255 const DynamicPaintSurface *surface = data->surface;
3256 float depth = (static_cast<float *>(surface->data->type_data))[index];
3257
3258 /* image buffer position */
3259 const int pos = surface->data->format_data->uv_p[index].pixel_index * 4;
3260
3261 if (surface->depth_clamp) {
3262 depth /= surface->depth_clamp;
3263 }
3264
3265 if (surface->disp_type == MOD_DPAINT_DISP_DISPLACE) {
3266 depth = (0.5f - depth / 2.0f);
3267 }
3268
3269 CLAMP(depth, 0.0f, 1.0f);
3270
3271 copy_v3_fl(&data->ibuf_float_data[pos], depth);
3272 data->ibuf_float_data[pos + 3] = 1.0f;
3273}
3274
3275static void dynamic_paint_output_surface_image_wave_cb(void *__restrict userdata,
3276 const int index,
3277 const TaskParallelTLS *__restrict /*tls*/)
3278{
3280 static_cast<const DynamicPaintOutputSurfaceImageData *>(userdata);
3281
3282 const DynamicPaintSurface *surface = data->surface;
3283 const PaintWavePoint *wPoint = &(static_cast<PaintWavePoint *>(surface->data->type_data))[index];
3284 float depth = wPoint->height;
3285
3286 /* image buffer position */
3287 const int pos = surface->data->format_data->uv_p[index].pixel_index * 4;
3288
3289 if (surface->depth_clamp) {
3290 depth /= surface->depth_clamp;
3291 }
3292
3293 depth = (0.5f + depth / 2.0f);
3294 CLAMP(depth, 0.0f, 1.0f);
3295
3296 copy_v3_fl(&data->ibuf_float_data[pos], depth);
3297 data->ibuf_float_data[pos + 3] = 1.0f;
3298}
3299
3300static void dynamic_paint_output_surface_image_wetmap_cb(void *__restrict userdata,
3301 const int index,
3302 const TaskParallelTLS *__restrict /*tls*/)
3303{
3305 static_cast<const DynamicPaintOutputSurfaceImageData *>(userdata);
3306
3307 const DynamicPaintSurface *surface = data->surface;
3308 const PaintPoint *point = &(static_cast<PaintPoint *>(surface->data->type_data))[index];
3309
3310 /* image buffer position */
3311 const int pos = surface->data->format_data->uv_p[index].pixel_index * 4;
3312
3313 copy_v3_fl(&data->ibuf_float_data[pos], (point->wetness > 1.0f) ? 1.0f : point->wetness);
3314 data->ibuf_float_data[pos + 3] = 1.0f;
3315}
3316
3318 const char *filepath,
3319 short output_layer)
3320{
3321 ImBuf *ibuf = nullptr;
3322 PaintSurfaceData *sData = surface->data;
3323 /* OpenEXR or PNG */
3326 char output_file[FILE_MAX];
3327
3328 if (!sData->type_data) {
3329 setError(surface->canvas, N_("Image save failed: invalid surface"));
3330 return;
3331 }
3332 STRNCPY(output_file, filepath);
3333 BKE_image_path_ext_from_imtype_ensure(output_file, sizeof(output_file), format);
3334
3335 /* Validate output file path */
3338
3339 /* Init image buffer */
3340 ibuf = IMB_allocImBuf(
3342 if (ibuf == nullptr) {
3343 setError(surface->canvas, N_("Image save failed: not enough free memory"));
3344 return;
3345 }
3346
3348 data.surface = surface;
3349 data.ibuf_float_data = ibuf->float_data_for_write();
3350
3351 switch (surface->type) {
3353 switch (output_layer) {
3354 case 0: {
3355 TaskParallelSettings settings;
3357 settings.use_threading = (sData->total_points > 10000);
3359 sData->total_points,
3360 &data,
3362 &settings);
3363 break;
3364 }
3365 case 1: {
3366 TaskParallelSettings settings;
3368 settings.use_threading = (sData->total_points > 10000);
3370 sData->total_points,
3371 &data,
3373 &settings);
3374 break;
3375 }
3376 default:
3377 BLI_assert(0);
3378 break;
3379 }
3380 break;
3382 switch (output_layer) {
3383 case 0: {
3384 TaskParallelSettings settings;
3386 settings.use_threading = (sData->total_points > 10000);
3388 sData->total_points,
3389 &data,
3391 &settings);
3392 break;
3393 }
3394 case 1:
3395 break;
3396 default:
3397 BLI_assert(0);
3398 break;
3399 }
3400 break;
3402 switch (output_layer) {
3403 case 0: {
3404 TaskParallelSettings settings;
3406 settings.use_threading = (sData->total_points > 10000);
3408 sData->total_points,
3409 &data,
3411 &settings);
3412 break;
3413 }
3414 case 1:
3415 break;
3416 default:
3417 BLI_assert(0);
3418 break;
3419 }
3420 break;
3421 default:
3422 BLI_assert(0);
3423 break;
3424 }
3425
3426 /* Set output format, PNG in case EXR isn't supported. */
3427 if (format == R_IMF_IMTYPE_OPENEXR) { /* OpenEXR 32-bit float */
3428 ibuf->ftype = IMB_FTYPE_OPENEXR;
3430 }
3431 else {
3432 ibuf->ftype = IMB_FTYPE_PNG;
3433 }
3434
3435 /* Save image */
3436 IMB_save_image(ibuf, output_file, ImBufFlags::FloatData);
3437 IMB_freeImBuf(ibuf);
3438}
3439
3441
3442/***************************** Ray / Nearest Point Utils ******************************/
3443
3444/***************************** Brush Painting Calls ******************************/
3445
3457 const int index,
3458 const int paintFlags,
3459 const float paintColor[3],
3460 const float paintAlpha,
3461 const float paintWetness,
3462 const float timescale)
3463{
3464 PaintPoint *pPoint = &(static_cast<PaintPoint *>(surface->data->type_data))[index];
3465
3466 /* Add paint */
3467 if (!(paintFlags & MOD_DPAINT_ERASE)) {
3468 float mix[4];
3469 float temp_alpha = paintAlpha * ((paintFlags & MOD_DPAINT_ABS_ALPHA) ? 1.0f : timescale);
3470
3471 /* mix brush color with wet layer color */
3472 blendColors(pPoint->e_color, pPoint->e_color[3], paintColor, temp_alpha, mix);
3473 copy_v3_v3(pPoint->e_color, mix);
3474
3475 /* mix wetness and alpha depending on selected alpha mode */
3476 if (paintFlags & MOD_DPAINT_ABS_ALPHA) {
3477 /* update values to the brush level unless they're higher already */
3478 CLAMP_MIN(pPoint->e_color[3], paintAlpha);
3479 CLAMP_MIN(pPoint->wetness, paintWetness);
3480 }
3481 else {
3482 float wetness = paintWetness;
3483 CLAMP(wetness, 0.0f, 1.0f);
3484 pPoint->e_color[3] = mix[3];
3485 pPoint->wetness = pPoint->wetness * (1.0f - wetness) + wetness;
3486 }
3487
3488 CLAMP_MIN(pPoint->wetness, MIN_WETNESS);
3489
3490 pPoint->state = DPAINT_PAINT_NEW;
3491 }
3492 /* Erase paint */
3493 else {
3494 float a_ratio, a_highest;
3495 float wetness;
3496 float invFact = 1.0f - paintAlpha;
3497
3498 /*
3499 * Make highest alpha to match erased value
3500 * but maintain alpha ratio
3501 */
3502 if (paintFlags & MOD_DPAINT_ABS_ALPHA) {
3503 a_highest = max_ff(pPoint->color[3], pPoint->e_color[3]);
3504 if (a_highest > invFact) {
3505 a_ratio = invFact / a_highest;
3506
3507 pPoint->e_color[3] *= a_ratio;
3508 pPoint->color[3] *= a_ratio;
3509 }
3510 }
3511 else {
3512 pPoint->e_color[3] -= paintAlpha * timescale;
3513 CLAMP_MIN(pPoint->e_color[3], 0.0f);
3514 pPoint->color[3] -= paintAlpha * timescale;
3515 CLAMP_MIN(pPoint->color[3], 0.0f);
3516 }
3517
3518 wetness = (1.0f - paintWetness) * pPoint->e_color[3];
3519 CLAMP_MAX(pPoint->wetness, wetness);
3520 }
3521}
3522
3523/* applies given brush intersection value for wave surface */
3526 float isect_height)
3527{
3528 const float isect_change = isect_height - wPoint->brush_isect;
3529 const float wave_factor = brush->wave_factor;
3530 bool hit = false;
3531
3532 /* intersection marked regardless of brush type or hit */
3533 wPoint->brush_isect = isect_height;
3535
3536 isect_height *= wave_factor;
3537
3538 /* determine hit depending on wave_factor */
3539 if (wave_factor > 0.0f && wPoint->height > isect_height) {
3540 hit = true;
3541 }
3542 else if (wave_factor < 0.0f && wPoint->height < isect_height) {
3543 hit = true;
3544 }
3545
3546 if (hit) {
3547 switch (brush->wave_type) {
3549 wPoint->height = isect_height;
3550 wPoint->state = DPAINT_WAVE_OBSTACLE;
3551 wPoint->velocity = 0.0f;
3552 break;
3554 wPoint->velocity = isect_height;
3555 break;
3558 break;
3560 if (isect_change < 0.0f) {
3561 wPoint->height += isect_change * wave_factor;
3562 }
3563 break;
3564 default:
3565 BLI_assert(0);
3566 break;
3567 }
3568 }
3569}
3570
3571/*
3572 * add brush results to the surface data depending on surface type
3573 */
3575 const int index,
3577 float paint[3],
3578 float influence,
3579 float depth,
3580 float vel_factor,
3581 const float timescale)
3582{
3583 PaintSurfaceData *sData = surface->data;
3584 float strength;
3585
3586 /* apply influence scale */
3587 influence *= surface->influence_scale;
3588 depth *= surface->influence_scale;
3589
3590 strength = influence * brush->alpha;
3591 CLAMP(strength, 0.0f, 1.0f);
3592
3593 /* Sample velocity colorband if required */
3594 if (brush->flags &
3596 {
3597 float coba_res[4];
3598 vel_factor /= brush->max_velocity;
3599 CLAMP(vel_factor, 0.0f, 1.0f);
3600
3601 if (BKE_colorband_evaluate(brush->vel_ramp, vel_factor, coba_res)) {
3602 if (brush->flags & MOD_DPAINT_VELOCITY_COLOR) {
3603 copy_v3_v3(paint, coba_res);
3604 }
3605 if (brush->flags & MOD_DPAINT_VELOCITY_ALPHA) {
3606 strength *= coba_res[3];
3607 }
3608 if (brush->flags & MOD_DPAINT_VELOCITY_DEPTH) {
3609 depth *= coba_res[3];
3610 }
3611 }
3612 }
3613
3614 /* mix paint surface */
3615 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
3616 float paintWetness = brush->wetness * strength;
3617 float paintAlpha = strength;
3618
3620 surface, index, brush->flags, paint, paintAlpha, paintWetness, timescale);
3621 }
3622 /* displace surface */
3623 else if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE) {
3624 float *value = static_cast<float *>(sData->type_data);
3625
3626 if (surface->flags & MOD_DPAINT_DISP_INCREMENTAL) {
3627 depth = value[index] + depth;
3628 }
3629
3630 if (surface->depth_clamp) {
3631 CLAMP(depth, 0.0f - surface->depth_clamp, surface->depth_clamp);
3632 }
3633
3634 if (brush->flags & MOD_DPAINT_ERASE) {
3635 value[index] *= (1.0f - strength);
3636 CLAMP_MIN(value[index], 0.0f);
3637 }
3638 else {
3639 CLAMP_MIN(value[index], depth);
3640 }
3641 }
3642 /* vertex weight group surface */
3643 else if (surface->type == MOD_DPAINT_SURFACE_T_WEIGHT) {
3644 float *value = static_cast<float *>(sData->type_data);
3645
3646 if (brush->flags & MOD_DPAINT_ERASE) {
3647 value[index] *= (1.0f - strength);
3648 CLAMP_MIN(value[index], 0.0f);
3649 }
3650 else {
3651 CLAMP_MIN(value[index], strength);
3652 }
3653 }
3654 /* wave surface */
3655 else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) {
3656 if (brush->wave_clamp) {
3657 CLAMP(depth, 0.0f - brush->wave_clamp, brush->wave_clamp);
3658 }
3659
3661 &(static_cast<PaintWavePoint *>(sData->type_data))[index], brush, 0.0f - depth);
3662 }
3663
3664 /* doing velocity based painting */
3665 if (sData->bData->brush_velocity) {
3666 sData->bData->brush_velocity[index * 4 + 3] *= influence;
3667 }
3668}
3669
3670/* checks whether surface and brush bounds intersect depending on brush type */
3672 Bounds3D *b2,
3674 float brush_radius)
3675{
3676 if (brush->collision == MOD_DPAINT_COL_VOLUME) {
3677 return boundsIntersect(b1, b2);
3678 }
3680 return boundsIntersectDist(b1, b2, brush_radius);
3681 }
3682 return true;
3683}
3684
3685/* calculate velocity for mesh vertices */
3688
3689 const float (*positions_p)[3];
3690 const float (*positions_c)[3];
3691
3692 const float (*obmat)[4];
3694
3696};
3697
3698static void dynamic_paint_brush_velocity_compute_cb(void *__restrict userdata,
3699 const int i,
3700 const TaskParallelTLS *__restrict /*tls*/)
3701{
3703 userdata);
3704
3705 Vec3f *brush_vel = data->brush_vel;
3706
3707 const float (*positions_p)[3] = data->positions_p;
3708 const float (*positions_c)[3] = data->positions_c;
3709
3710 const float (*obmat)[4] = data->obmat;
3711 float (*prev_obmat)[4] = data->prev_obmat;
3712
3713 const float timescale = data->timescale;
3714
3715 float p1[3], p2[3];
3716
3717 copy_v3_v3(p1, positions_p[i]);
3718 mul_m4_v3(prev_obmat, p1);
3719
3720 copy_v3_v3(p2, positions_c[i]);
3721 mul_m4_v3(obmat, p2);
3722
3723 sub_v3_v3v3(brush_vel[i].v, p2, p1);
3724 mul_v3_fl(brush_vel[i].v, 1.0f / timescale);
3725}
3726
3727static void dynamicPaint_brushMeshCalculateVelocity(Depsgraph *depsgraph,
3728 Scene *scene,
3729 Object *ob,
3731 Vec3f **brushVel,
3732 float timescale)
3733{
3734 float prev_obmat[4][4];
3735 Mesh *mesh_p, *mesh_c;
3736 int numOfVerts_p, numOfVerts_c;
3737
3738 float cur_sfra = scene->r.subframe;
3739 int cur_fra = scene->r.cfra;
3740 float prev_sfra = cur_sfra - timescale;
3741 int prev_fra = cur_fra;
3742
3743 if (prev_sfra < 0.0f) {
3744 prev_sfra += 1.0f;
3745 prev_fra = cur_fra - 1;
3746 }
3747
3748 /* previous frame mesh */
3749 scene->r.cfra = prev_fra;
3750 scene->r.subframe = prev_sfra;
3751
3753 scene,
3754 ob,
3755 true,
3757 BKE_scene_ctime_get(scene),
3759
3760 {
3761 auto *runtime_data = static_cast<DynamicPaintRuntime *>(brush->pmd->modifier.runtime);
3762 if (!runtime_data) {
3763 return;
3764 }
3765 std::lock_guard lock(runtime_data->brush_mutex);
3766 mesh_p = BKE_mesh_copy_for_eval(*runtime_data->brush_mesh);
3767 }
3768 numOfVerts_p = mesh_p->verts_num;
3769
3770 float (*positions_p)[3] = reinterpret_cast<float (*)[3]>(
3771 mesh_p->vert_positions_for_write().data());
3772 copy_m4_m4(prev_obmat, ob->object_to_world().ptr());
3773
3774 /* current frame mesh */
3775 scene->r.cfra = cur_fra;
3776 scene->r.subframe = cur_sfra;
3777
3779 scene,
3780 ob,
3781 true,
3783 BKE_scene_ctime_get(scene),
3785 auto *runtime_data = static_cast<DynamicPaintRuntime *>(brush->pmd->modifier.runtime);
3786 if (!runtime_data) {
3787 return;
3788 }
3789 std::lock_guard lock(runtime_data->brush_mutex);
3790 mesh_c = runtime_data->brush_mesh;
3791
3792 numOfVerts_c = mesh_c->verts_num;
3793 float (*positions_c)[3] = reinterpret_cast<float (*)[3]>(
3794 mesh_c->vert_positions_for_write().data());
3795
3796 (*brushVel) = MEM_new_array_uninitialized<Vec3f>(size_t(numOfVerts_c),
3797 "Dynamic Paint brush velocity");
3798 if (!(*brushVel)) {
3799 return;
3800 }
3801
3802 /* If mesh is constructive -> num of verts has changed,
3803 * only use current frame evaluated-mesh. */
3804 if (numOfVerts_p != numOfVerts_c) {
3805 positions_p = positions_c;
3806 }
3807
3808 /* calculate speed */
3810 data.brush_vel = *brushVel;
3811 data.positions_p = positions_p;
3812 data.positions_c = positions_c;
3813 data.obmat = ob->object_to_world().ptr();
3814 data.prev_obmat = prev_obmat;
3815 data.timescale = timescale;
3816
3817 TaskParallelSettings settings;
3819 settings.use_threading = (numOfVerts_c > 10000);
3821 0, numOfVerts_c, &data, dynamic_paint_brush_velocity_compute_cb, &settings);
3822
3823 BKE_id_free(nullptr, mesh_p);
3824}
3825
3826/* calculate velocity for object center point */
3828 Depsgraph *depsgraph, Scene *scene, Object *ob, Vec3f *brushVel, float timescale)
3829{
3830 float prev_obmat[4][4];
3831 float cur_loc[3] = {0.0f}, prev_loc[3] = {0.0f};
3832
3833 float cur_sfra = scene->r.subframe;
3834 int cur_fra = scene->r.cfra;
3835 float prev_sfra = cur_sfra - timescale;
3836 int prev_fra = cur_fra;
3837
3838 if (prev_sfra < 0.0f) {
3839 prev_sfra += 1.0f;
3840 prev_fra = cur_fra - 1;
3841 }
3842
3843 /* previous frame mesh */
3844 scene->r.cfra = prev_fra;
3845 scene->r.subframe = prev_sfra;
3847 scene,
3848 ob,
3849 false,
3851 BKE_scene_ctime_get(scene),
3853 copy_m4_m4(prev_obmat, ob->object_to_world().ptr());
3854
3855 /* current frame mesh */
3856 scene->r.cfra = cur_fra;
3857 scene->r.subframe = cur_sfra;
3859 scene,
3860 ob,
3861 false,
3863 BKE_scene_ctime_get(scene),
3865
3866 /* calculate speed */
3867 mul_m4_v3(prev_obmat, prev_loc);
3868 mul_m4_v3(ob->object_to_world().ptr(), cur_loc);
3869
3870 sub_v3_v3v3(brushVel->v, cur_loc, prev_loc);
3871 mul_v3_fl(brushVel->v, 1.0f / timescale);
3872}
3873
3897
3898/*
3899 * Paint a brush object mesh to the surface
3900 */
3901static void dynamic_paint_paint_mesh_cell_point_cb_ex(void *__restrict userdata,
3902 const int id,
3903 const TaskParallelTLS *__restrict /*tls*/)
3904{
3905 const DynamicPaintPaintData *data = static_cast<const DynamicPaintPaintData *>(userdata);
3906
3907 const DynamicPaintSurface *surface = data->surface;
3908 const PaintSurfaceData *sData = surface->data;
3909 const PaintBakeData *bData = sData->bData;
3910 DynamicPaintVolumeGrid *grid = bData->grid;
3911
3912 const DynamicPaintBrushSettings *brush = data->brush;
3913
3914 const float timescale = data->timescale;
3915 const int c_index = data->c_index;
3916
3917 const Span<float3> positions = data->positions;
3918 const Span<int> corner_verts = data->corner_verts;
3919 const Span<int3> corner_tris = data->corner_tris;
3920 const float brush_radius = data->brush_radius;
3921 const float *avg_brushNor = data->avg_brushNor;
3922 const Vec3f *brushVelocity = data->brushVelocity;
3923
3924 const auto &treeData = *static_cast<bke::bvh::Tree *>(data->treeData);
3925
3926 const int index = grid->t_index[grid->s_pos[c_index] + id];
3927 const int samples = bData->s_num[index];
3928 int ss;
3929 float total_sample = float(samples);
3930 float brushStrength = 0.0f; /* brush influence factor */
3931 float depth = 0.0f; /* brush intersection depth */
3932 float velocity_val = 0.0f;
3933
3934 float paintColor[3] = {0.0f};
3935 int numOfHits = 0;
3936
3937 /* for image sequence anti-aliasing, use gaussian factors */
3938 if (samples > 1 && surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
3939 total_sample = gaussianTotal;
3940 }
3941
3942 /* Super-sampling */
3943 for (ss = 0; ss < samples; ss++) {
3944 float3 ray_start, ray_dir;
3945 float sample_factor = 0.0f;
3946 float sampleStrength = 0.0f;
3947 short hit_found = 0;
3948
3949 /* volume sample */
3950 float volume_factor = 0.0f;
3951 /* proximity sample */
3952 float proximity_factor = 0.0f;
3953 float prox_colorband[4] = {0.0f};
3954 const bool inner_proximity = (brush->flags & MOD_DPAINT_INVERSE_PROX &&
3955 brush->collision == MOD_DPAINT_COL_VOLDIST);
3956
3957 /* hit data */
3958 float hitCoord[3];
3959 int hitTri = -1;
3960
3961 /* Super-sampling factor. */
3962 if (samples > 1 && surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
3963 sample_factor = gaussianFactors[ss];
3964 }
3965 else {
3966 sample_factor = 1.0f;
3967 }
3968
3969 /* Get current sample position in world coordinates */
3970 copy_v3_v3(ray_start, bData->realCoord[bData->s_pos[index] + ss].v);
3971 copy_v3_v3(ray_dir, bData->bNormal[index].invNorm);
3972
3973 /* a simple hack to minimize chance of ray leaks at identical ray <-> edge locations */
3974 add_v3_fl(ray_start, 0.001f);
3975
3976 /* Check volume collision */
3978 const bke::bvh::Ray ray(ray_start, ray_dir);
3979 if (const std::optional<bke::bvh::RayHit> hit = treeData.ray_intersect(ray)) {
3980 /* We hit a triangle, now check if collision point normal is facing the point */
3981 float dot = dot_v3v3(ray_dir, math::normalize(hit->normal));
3982
3983 /* If ray and hit face normal are facing same direction
3984 * hit point is inside a closed mesh. */
3985 if (dot >= 0.0f) {
3986 const float dist = hit->distance;
3987 const int f_index = hit->index;
3988
3989 /* Also cast a ray in opposite direction to make sure
3990 * point is at least surrounded by two brush faces */
3991 negate_v3(ray_dir);
3992 const bke::bvh::Ray other_ray(ray_start, ray_dir);
3993 if (const std::optional<bke::bvh::RayHit> hit_other = treeData.ray_intersect(other_ray))
3994 {
3995 /* Add factor on super-sample filter. */
3996 volume_factor = 1.0f;
3997 hit_found = HIT_VOLUME;
3998
3999 /* Mark hit info */
4000
4001 /* Calculate final hit coordinates */
4002 madd_v3_v3v3fl(hitCoord, ray_start, ray_dir, hit_other->distance);
4003
4004 depth += dist * sample_factor;
4005 hitTri = f_index;
4006 }
4007 }
4008 }
4009 }
4010
4011 /* Check proximity collision */
4013 (!hit_found || (brush->flags & MOD_DPAINT_INVERSE_PROX)))
4014 {
4015 float proxDist = -1.0f;
4016 float hitCo[3] = {0.0f, 0.0f, 0.0f};
4017 int tri = 0;
4018
4019 /* if inverse prox and no hit found, skip this sample */
4020 if (inner_proximity && !hit_found) {
4021 continue;
4022 }
4023
4024 /* If pure distance proximity, find the nearest point on the mesh */
4025 if (!(brush->flags & MOD_DPAINT_PROX_PROJECT)) {
4026 if (const std::optional<bke::bvh::ClosestPointResult> nearest = treeData.closest_point(
4027 ray_start, brush_radius))
4028 {
4029 proxDist = math::distance(nearest->position, ray_start);
4030 copy_v3_v3(hitCo, nearest->position);
4031 tri = nearest->index;
4032 }
4033 }
4034 else { /* else cast a ray in defined projection direction */
4035 float proj_ray[3] = {0.0f};
4036
4037 if (brush->ray_dir == MOD_DPAINT_RAY_CANVAS) {
4038 copy_v3_v3(proj_ray, bData->bNormal[index].invNorm);
4039 negate_v3(proj_ray);
4040 }
4041 else if (brush->ray_dir == MOD_DPAINT_RAY_BRUSH_AVG) {
4042 copy_v3_v3(proj_ray, avg_brushNor);
4043 }
4044 else { /* MOD_DPAINT_RAY_ZPLUS */
4045 proj_ray[2] = 1.0f;
4046 }
4047
4048 /* Do a face normal directional ray-cast, and use that distance. */
4049 const bke::bvh::Ray ray(ray_start, proj_ray, brush_radius);
4050 if (const std::optional<bke::bvh::RayHit> hit = treeData.ray_intersect(ray)) {
4051 proxDist = hit->distance;
4052
4053 /* Calculate final hit coordinates */
4054 madd_v3_v3v3fl(hitCo, ray_start, proj_ray, hit->distance);
4055
4056 tri = hit->index;
4057 }
4058 }
4059
4060 /* If a hit was found, calculate required values */
4061 if (proxDist >= 0.0f && proxDist <= brush_radius) {
4062 proximity_factor = proxDist / brush_radius;
4063 CLAMP(proximity_factor, 0.0f, 1.0f);
4064 if (!inner_proximity) {
4065 proximity_factor = 1.0f - proximity_factor;
4066 }
4067
4068 hit_found = HIT_PROXIMITY;
4069
4070 /* if no volume hit, use prox point face info */
4071 if (hitTri == -1) {
4072 copy_v3_v3(hitCoord, hitCo);
4073 hitTri = tri;
4074 }
4075 }
4076 }
4077
4078 /* mix final sample strength depending on brush settings */
4079 if (hit_found) {
4080 /* If "negate volume" enabled, negate all factors within volume. */
4081 if (brush->collision == MOD_DPAINT_COL_VOLDIST && brush->flags & MOD_DPAINT_NEGATE_VOLUME) {
4082 volume_factor = 1.0f - volume_factor;
4083 if (inner_proximity) {
4084 proximity_factor = 1.0f - proximity_factor;
4085 }
4086 }
4087
4088 /* apply final sample depending on final hit type */
4089 if (hit_found == HIT_VOLUME) {
4090 sampleStrength = volume_factor;
4091 }
4092 else if (hit_found == HIT_PROXIMITY) {
4093 /* apply falloff curve to the proximity_factor */
4094 if (brush->proximity_falloff == MOD_DPAINT_PRFALL_RAMP &&
4095 BKE_colorband_evaluate(brush->paint_ramp, (1.0f - proximity_factor), prox_colorband))
4096 {
4097 proximity_factor = prox_colorband[3];
4098 }
4099 else if (brush->proximity_falloff == MOD_DPAINT_PRFALL_CONSTANT) {
4100 proximity_factor = (!inner_proximity || brush->flags & MOD_DPAINT_NEGATE_VOLUME) ? 1.0f :
4101 0.0f;
4102 }
4103 /* apply sample */
4104 sampleStrength = proximity_factor;
4105 }
4106
4107 sampleStrength *= sample_factor;
4108 }
4109 else {
4110 continue;
4111 }
4112
4113 /* velocity brush, only do on main sample */
4114 if (brush->flags & MOD_DPAINT_USES_VELOCITY && ss == 0 && brushVelocity) {
4115 float weights[3];
4116 float brushPointVelocity[3];
4117 float velocity[3];
4118
4119 const int v1 = corner_verts[corner_tris[hitTri][0]];
4120 const int v2 = corner_verts[corner_tris[hitTri][1]];
4121 const int v3 = corner_verts[corner_tris[hitTri][2]];
4122
4123 /* calculate barycentric weights for hit point */
4124 interp_weights_tri_v3(weights, positions[v1], positions[v2], positions[v3], hitCoord);
4125
4126 /* Simple check based on brush surface velocity,
4127 * TODO: perhaps implement something that handles volume movement as well. */
4128
4129 /* interpolate vertex speed vectors to get hit point velocity */
4130 interp_v3_v3v3v3(brushPointVelocity,
4131 brushVelocity[v1].v,
4132 brushVelocity[v2].v,
4133 brushVelocity[v3].v,
4134 weights);
4135
4136 /* subtract canvas point velocity */
4137 if (bData->velocity) {
4138 sub_v3_v3v3(velocity, brushPointVelocity, bData->velocity[index].v);
4139 }
4140 else {
4141 copy_v3_v3(velocity, brushPointVelocity);
4142 }
4143 velocity_val = normalize_v3(velocity);
4144
4145 /* if brush has smudge enabled store brush velocity */
4146 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT && brush->flags & MOD_DPAINT_DO_SMUDGE &&
4147 bData->brush_velocity)
4148 {
4149 copy_v3_v3(&bData->brush_velocity[index * 4], velocity);
4150 bData->brush_velocity[index * 4 + 3] = velocity_val;
4151 }
4152 }
4153
4154 /*
4155 * Process hit color and alpha
4156 */
4157 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
4158 float sampleColor[3];
4159 float alpha_factor = 1.0f;
4160
4161 sampleColor[0] = brush->r;
4162 sampleColor[1] = brush->g;
4163 sampleColor[2] = brush->b;
4164
4165 /* Sample proximity colorband if required */
4166 if ((hit_found == HIT_PROXIMITY) && (brush->proximity_falloff == MOD_DPAINT_PRFALL_RAMP)) {
4167 if (!(brush->flags & MOD_DPAINT_RAMP_ALPHA)) {
4168 sampleColor[0] = prox_colorband[0];
4169 sampleColor[1] = prox_colorband[1];
4170 sampleColor[2] = prox_colorband[2];
4171 }
4172 }
4173
4174 /* Add AA sample */
4175 paintColor[0] += sampleColor[0];
4176 paintColor[1] += sampleColor[1];
4177 paintColor[2] += sampleColor[2];
4178 sampleStrength *= alpha_factor;
4179 numOfHits++;
4180 }
4181
4182 /* Apply sample strength. */
4183 brushStrength += sampleStrength;
4184 } /* End super-sampling. */
4185
4186 /* If any sample was inside paint range. */
4187 if (brushStrength > 0.0f || depth > 0.0f) {
4188 /* Apply super-sampling results. */
4189 if (samples > 1) {
4190 brushStrength /= total_sample;
4191 }
4192 CLAMP(brushStrength, 0.0f, 1.0f);
4193
4194 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
4195 /* Get final pixel color and alpha. */
4196 paintColor[0] /= numOfHits;
4197 paintColor[1] /= numOfHits;
4198 paintColor[2] /= numOfHits;
4199 }
4200 /* Get final object space depth. */
4202 depth /= bData->bNormal[index].normal_scale * total_sample;
4203 }
4204
4206 surface, index, brush, paintColor, brushStrength, depth, velocity_val, timescale);
4207 }
4208}
4209
4210static bool dynamicPaint_paintMesh(Depsgraph *depsgraph,
4211 DynamicPaintSurface *surface,
4213 Object *brushOb,
4214 Scene *scene,
4215 float timescale)
4216{
4217 PaintSurfaceData *sData = surface->data;
4218 PaintBakeData *bData = sData->bData;
4219 Mesh *mesh = nullptr;
4220 Vec3f *brushVelocity = nullptr;
4221
4222 if (brush->flags & MOD_DPAINT_USES_VELOCITY) {
4224 depsgraph, scene, brushOb, brush, &brushVelocity, timescale);
4225 }
4226
4227 auto *runtime_data = static_cast<DynamicPaintRuntime *>(brush->pmd->modifier.runtime);
4228 if (!runtime_data) {
4229 return false;
4230 }
4231 std::lock_guard lock(runtime_data->brush_mutex);
4232 const Mesh *brush_mesh = runtime_data->brush_mesh;
4233 if (brush_mesh == nullptr) {
4234 return false;
4235 }
4236
4237 {
4238 float avg_brushNor[3] = {0.0f};
4239 const float brush_radius = brush->paint_distance * surface->radius_scale;
4240 int numOfVerts;
4241 int ii;
4242 Bounds3D mesh_bb = {{0}};
4243 DynamicPaintVolumeGrid *grid = bData->grid;
4244
4245 mesh = BKE_mesh_copy_for_eval(*brush_mesh);
4246 MutableSpan<float3> positions = mesh->vert_positions_for_write();
4247 const Span<float3> vert_normals = mesh->vert_normals();
4248 const Span<int> corner_verts = mesh->corner_verts();
4249 const Span<int3> corner_tris = mesh->corner_tris();
4250 numOfVerts = mesh->verts_num;
4251
4252 /* Transform collider vertices to global space
4253 * (Faster than transforming per surface point
4254 * coordinates and normals to object space) */
4255 for (ii = 0; ii < numOfVerts; ii++) {
4256 mul_m4_v3(brushOb->object_to_world().ptr(), positions[ii]);
4257 boundInsert(&mesh_bb, positions[ii]);
4258
4259 /* for proximity project calculate average normal */
4260 if (brush->flags & MOD_DPAINT_PROX_PROJECT && brush->collision != MOD_DPAINT_COL_VOLUME) {
4261 float nor[3];
4262 copy_v3_v3(nor, vert_normals[ii]);
4263 mul_mat3_m4_v3(brushOb->object_to_world().ptr(), nor);
4264 normalize_v3(nor);
4265
4266 add_v3_v3(avg_brushNor, nor);
4267 }
4268 }
4269
4270 mesh->tag_positions_changed();
4271
4272 if (brush->flags & MOD_DPAINT_PROX_PROJECT && brush->collision != MOD_DPAINT_COL_VOLUME) {
4273 mul_v3_fl(avg_brushNor, 1.0f / float(numOfVerts));
4274 /* instead of null vector use positive z */
4275 if (normalize_v3(avg_brushNor) == 0.0f) [[unlikely]] {
4276 avg_brushNor[2] = 1.0f;
4277 }
4278 }
4279
4280 /* check bounding box collision */
4281 if (grid && meshBrush_boundsIntersect(&grid->grid_bounds, &mesh_bb, brush, brush_radius)) {
4282 /* Build a bvh tree from transformed vertices */
4283 if (mesh->faces_num != 0) {
4284 const bke::bvh::Tree &tree = mesh->bvh_tris();
4285
4286 int c_index;
4287 int total_cells = grid->dim[0] * grid->dim[1] * grid->dim[2];
4288
4289 /* loop through space partitioning grid */
4290 for (c_index = 0; c_index < total_cells; c_index++) {
4291 /* check grid cell bounding box */
4292 if (!grid->s_num[c_index] ||
4293 !meshBrush_boundsIntersect(&grid->bounds[c_index], &mesh_bb, brush, brush_radius))
4294 {
4295 continue;
4296 }
4297
4298 /* loop through cell points and process brush */
4300 data.surface = surface;
4301 data.brush = brush;
4302 data.brushOb = brushOb;
4303 data.scene = scene;
4304 data.timescale = timescale;
4305 data.c_index = c_index;
4306 data.mesh = mesh;
4307 data.positions = positions;
4308 data.corner_verts = corner_verts;
4309 data.corner_tris = corner_tris;
4310 data.brush_radius = brush_radius;
4311 data.avg_brushNor = avg_brushNor;
4312 data.brushVelocity = brushVelocity;
4313 data.treeData = &const_cast<bke::bvh::Tree &>(tree);
4314
4315 TaskParallelSettings settings;
4317 settings.use_threading = (grid->s_num[c_index] > 250);
4319 grid->s_num[c_index],
4320 &data,
4322 &settings);
4323 }
4324 }
4325 }
4326 BKE_id_free(nullptr, mesh);
4327 }
4328
4329 /* free brush velocity data */
4330 if (brushVelocity) {
4331 MEM_delete(brushVelocity);
4332 }
4333
4334 return true;
4335}
4336
4337/*
4338 * Paint a particle system to the surface
4339 */
4341 void *__restrict userdata, const int id, const TaskParallelTLS *__restrict /*tls*/)
4342{
4343 const DynamicPaintPaintData *data = static_cast<const DynamicPaintPaintData *>(userdata);
4344
4345 const DynamicPaintSurface *surface = data->surface;
4346 const PaintSurfaceData *sData = surface->data;
4347 const PaintBakeData *bData = sData->bData;
4348 DynamicPaintVolumeGrid *grid = bData->grid;
4349
4350 const DynamicPaintBrushSettings *brush = data->brush;
4351
4352 const ParticleSystem *psys = data->psys;
4353
4354 const float timescale = data->timescale;
4355 const int c_index = data->c_index;
4356
4357 KDTree<float3> *tree = static_cast<KDTree<float3> *>(data->treeData);
4358
4359 const float solidradius = data->solidradius;
4360 const float smooth = brush->particle_smooth * surface->radius_scale;
4361 const float range = solidradius + smooth;
4362 const float particle_timestep = 0.04f * psys->part->timetweak;
4363
4364 const int index = grid->t_index[grid->s_pos[c_index] + id];
4365 float disp_intersect = 0.0f;
4366 float radius = 0.0f;
4367 float strength = 0.0f;
4368 int part_index = -1;
4369
4370 /*
4371 * With predefined radius, there is no variation between particles.
4372 * It's enough to just find the nearest one.
4373 */
4374 {
4375 KDTreeNearest<float3> nearest;
4376 float smooth_range, part_solidradius;
4377
4378 /* Find nearest particle and get distance to it */
4379 kdtree_find_nearest<float3>(tree, bData->realCoord[bData->s_pos[index]].v, &nearest);
4380 /* if outside maximum range, no other particle can influence either */
4381 if (nearest.dist > range) {
4382 return;
4383 }
4384
4385 if (brush->flags & MOD_DPAINT_PART_RAD) {
4386 /* use particles individual size */
4387 ParticleData *pa = psys->particles + nearest.index;
4388 part_solidradius = pa->size;
4389 }
4390 else {
4391 part_solidradius = solidradius;
4392 }
4393 radius = part_solidradius + smooth;
4394 if (nearest.dist < radius) {
4395 /* distances inside solid radius has maximum influence -> dist = 0 */
4396 smooth_range = max_ff(0.0f, (nearest.dist - part_solidradius));
4397 /* do smoothness if enabled */
4398 if (smooth) {
4399 smooth_range /= smooth;
4400 }
4401
4402 strength = 1.0f - smooth_range;
4403 disp_intersect = radius - nearest.dist;
4404 part_index = nearest.index;
4405 }
4406 }
4407 /* If using random per particle radius and closest particle didn't give max influence */
4408 if (brush->flags & MOD_DPAINT_PART_RAD && strength < 1.0f && psys->part->randsize > 0.0f) {
4409 /*
4410 * If we use per particle radius, we have to sample all particles
4411 * within max radius range
4412 */
4413 KDTreeNearest<float3> *nearest;
4414
4415 float smooth_range = smooth * (1.0f - strength), dist;
4416 /* calculate max range that can have particles with higher influence than the nearest one */
4417 const float max_range = smooth - strength * smooth + solidradius;
4418 /* Make gcc happy! */
4419 dist = max_range;
4420
4421 const int particles = kdtree_range_search<float3>(
4422 tree, bData->realCoord[bData->s_pos[index]].v, &nearest, max_range);
4423
4424 /* Find particle that produces highest influence */
4425 for (int n = 0; n < particles; n++) {
4426 ParticleData *pa = &psys->particles[nearest[n].index];
4427
4428 /* skip if out of range */
4429 if (nearest[n].dist > (pa->size + smooth)) {
4430 continue;
4431 }
4432
4433 /* update hit data */
4434 const float s_range = nearest[n].dist - pa->size;
4435 /* skip if higher influence is already found */
4436 if (smooth_range < s_range) {
4437 continue;
4438 }
4439
4440 /* update hit data */
4441 smooth_range = s_range;
4442 dist = nearest[n].dist;
4443 part_index = nearest[n].index;
4444
4445 /* If inside solid range and no disp depth required, no need to seek further */
4446 if ((s_range < 0.0f) &&
4448 {
4449 break;
4450 }
4451 }
4452
4453 if (nearest) {
4454 MEM_delete(nearest);
4455 }
4456
4457 /* now calculate influence for this particle */
4458 const float rad = radius + smooth;
4459 if ((rad - dist) > disp_intersect) {
4460 disp_intersect = radius - dist;
4461 radius = rad;
4462 }
4463
4464 /* do smoothness if enabled */
4465 CLAMP_MIN(smooth_range, 0.0f);
4466 if (smooth) {
4467 smooth_range /= smooth;
4468 }
4469
4470 const float str = 1.0f - smooth_range;
4471 /* if influence is greater, use this one */
4472 strength = std::max(str, strength);
4473 }
4474
4475 if (strength > 0.001f) {
4476 float paintColor[4] = {0.0f};
4477 float depth = 0.0f;
4478 float velocity_val = 0.0f;
4479
4480 /* apply velocity */
4481 if ((brush->flags & MOD_DPAINT_USES_VELOCITY) && (part_index != -1)) {
4482 float velocity[3];
4483 ParticleData *pa = psys->particles + part_index;
4484 mul_v3_v3fl(velocity, pa->state.vel, particle_timestep);
4485
4486 /* subtract canvas point velocity */
4487 if (bData->velocity) {
4488 sub_v3_v3(velocity, bData->velocity[index].v);
4489 }
4490 velocity_val = normalize_v3(velocity);
4491
4492 /* store brush velocity for smudge */
4493 if ((surface->type == MOD_DPAINT_SURFACE_T_PAINT) &&
4494 (brush->flags & MOD_DPAINT_DO_SMUDGE && bData->brush_velocity))
4495 {
4496 copy_v3_v3(&bData->brush_velocity[index * 4], velocity);
4497 bData->brush_velocity[index * 4 + 3] = velocity_val;
4498 }
4499 }
4500
4501 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
4502 copy_v3_v3(paintColor, &brush->r);
4503 }
4505 /* get displace depth */
4506 disp_intersect = (1.0f - sqrtf(disp_intersect / radius)) * radius;
4507 depth = max_ff(0.0f, (radius - disp_intersect) / bData->bNormal[index].normal_scale);
4508 }
4509
4511 surface, index, brush, paintColor, strength, depth, velocity_val, timescale);
4512 }
4513}
4514
4516 ParticleSystem *psys,
4518 float timescale)
4519{
4520 ParticleSettings *part = psys->part;
4521 PaintSurfaceData *sData = surface->data;
4522 PaintBakeData *bData = sData->bData;
4523 DynamicPaintVolumeGrid *grid = bData->grid;
4524
4525 KDTree<float3> *tree;
4526 int particlesAdded = 0;
4527 int invalidParticles = 0;
4528 int p = 0;
4529
4530 const float solidradius = surface->radius_scale * ((brush->flags & MOD_DPAINT_PART_RAD) ?
4531 part->size :
4532 brush->particle_radius);
4533 const float smooth = brush->particle_smooth * surface->radius_scale;
4534
4535 const float range = solidradius + smooth;
4536
4537 Bounds3D part_bb = {{0}};
4538
4539 if (psys->totpart < 1) {
4540 return true;
4541 }
4542
4543 /*
4544 * Build a KD-tree to optimize distance search
4545 */
4546 tree = kdtree_new<float3>(psys->totpart);
4547
4548 /* loop through particles and insert valid ones to the tree */
4549 p = 0;
4550 for (ParticleData *pa = psys->particles; p < psys->totpart; p++, pa++) {
4551 /* Proceed only if particle is active */
4552 if ((pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN) == 0) ||
4553 (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) || (pa->flag & PARS_UNEXIST))
4554 {
4555 continue;
4556 }
4557
4558 /* for debug purposes check if any NAN particle proceeds
4559 * For some reason they get past activity check, this should rule most of them out */
4560 if (isnan(pa->state.co[0]) || isnan(pa->state.co[1]) || isnan(pa->state.co[2])) {
4561 invalidParticles++;
4562 continue;
4563 }
4564
4565 /* make sure particle is close enough to canvas */
4566 if (!boundIntersectPoint(&grid->grid_bounds, pa->state.co, range)) {
4567 continue;
4568 }
4569
4570 kdtree_insert<float3>(tree, p, pa->state.co);
4571
4572 /* calc particle system bounds */
4573 boundInsert(&part_bb, pa->state.co);
4574
4575 particlesAdded++;
4576 }
4577 if (invalidParticles) {
4578 CLOG_WARN(&LOG, "Invalid particle(s) found!");
4579 }
4580
4581 /* If no suitable particles were found, exit */
4582 if (particlesAdded < 1) {
4583 kdtree_free<float3>(tree);
4584 return true;
4585 }
4586
4587 /* only continue if particle bb is close enough to canvas bb */
4588 if (boundsIntersectDist(&grid->grid_bounds, &part_bb, range)) {
4589 int c_index;
4590 int total_cells = grid->dim[0] * grid->dim[1] * grid->dim[2];
4591
4592 /* balance tree */
4594
4595 /* loop through space partitioning grid */
4596 for (c_index = 0; c_index < total_cells; c_index++) {
4597 /* check cell bounding box */
4598 if (!grid->s_num[c_index] || !boundsIntersectDist(&grid->bounds[c_index], &part_bb, range)) {
4599 continue;
4600 }
4601
4602 /* loop through cell points */
4604 data.surface = surface;
4605 data.brush = brush;
4606 data.psys = psys;
4607 data.solidradius = solidradius;
4608 data.timescale = timescale;
4609 data.c_index = c_index;
4610 data.treeData = tree;
4611
4612 TaskParallelSettings settings;
4614 settings.use_threading = (grid->s_num[c_index] > 250);
4616 grid->s_num[c_index],
4617 &data,
4619 &settings);
4620 }
4621 }
4622 kdtree_free<float3>(tree);
4623
4624 return true;
4625}
4626
4627/* paint a single point of defined proximity radius to the surface */
4628static void dynamic_paint_paint_single_point_cb_ex(void *__restrict userdata,
4629 const int index,
4630 const TaskParallelTLS *__restrict /*tls*/)
4631{
4632 const DynamicPaintPaintData *data = static_cast<const DynamicPaintPaintData *>(userdata);
4633
4634 const DynamicPaintSurface *surface = data->surface;
4635 const PaintSurfaceData *sData = surface->data;
4636 const PaintBakeData *bData = sData->bData;
4637
4638 const DynamicPaintBrushSettings *brush = data->brush;
4639
4640 const float timescale = data->timescale;
4641
4642 const float brush_radius = data->brush_radius;
4643 const Vec3f *brushVelocity = data->brushVelocity;
4644
4645 float *pointCoord = data->pointCoord;
4646
4647 const float distance = len_v3v3(pointCoord, bData->realCoord[bData->s_pos[index]].v);
4648 float colorband[4] = {0.0f};
4649 float strength;
4650
4651 if (distance > brush_radius) {
4652 return;
4653 }
4654
4655 /* Smooth range or color ramp */
4656 if (ELEM(brush->proximity_falloff, MOD_DPAINT_PRFALL_SMOOTH, MOD_DPAINT_PRFALL_RAMP)) {
4657 strength = 1.0f - distance / brush_radius;
4658 CLAMP(strength, 0.0f, 1.0f);
4659 }
4660 else {
4661 strength = 1.0f;
4662 }
4663
4664 if (strength >= 0.001f) {
4665 float paintColor[3] = {0.0f};
4666 float depth = 0.0f;
4667 float velocity_val = 0.0f;
4668
4669 /* color ramp */
4670 if (brush->proximity_falloff == MOD_DPAINT_PRFALL_RAMP &&
4671 BKE_colorband_evaluate(brush->paint_ramp, (1.0f - strength), colorband))
4672 {
4673 strength = colorband[3];
4674 }
4675
4676 if (brush->flags & MOD_DPAINT_USES_VELOCITY) {
4677 float velocity[3];
4678
4679 /* subtract canvas point velocity */
4680 if (bData->velocity) {
4681 sub_v3_v3v3(velocity, brushVelocity->v, bData->velocity[index].v);
4682 }
4683 else {
4684 copy_v3_v3(velocity, brushVelocity->v);
4685 }
4686 velocity_val = len_v3(velocity);
4687
4688 /* store brush velocity for smudge */
4689 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT && brush->flags & MOD_DPAINT_DO_SMUDGE &&
4690 bData->brush_velocity)
4691 {
4692 mul_v3_v3fl(&bData->brush_velocity[index * 4], velocity, 1.0f / velocity_val);
4693 bData->brush_velocity[index * 4 + 3] = velocity_val;
4694 }
4695 }
4696
4697 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
4698 if (brush->proximity_falloff == MOD_DPAINT_PRFALL_RAMP &&
4699 !(brush->flags & MOD_DPAINT_RAMP_ALPHA))
4700 {
4701 paintColor[0] = colorband[0];
4702 paintColor[1] = colorband[1];
4703 paintColor[2] = colorband[2];
4704 }
4705 else {
4706 paintColor[0] = brush->r;
4707 paintColor[1] = brush->g;
4708 paintColor[2] = brush->b;
4709 }
4710 }
4712 /* get displace depth */
4713 const float disp_intersect = (1.0f - sqrtf((brush_radius - distance) / brush_radius)) *
4714 brush_radius;
4715 depth = max_ff(0.0f, (brush_radius - disp_intersect) / bData->bNormal[index].normal_scale);
4716 }
4718 surface, index, brush, paintColor, strength, depth, velocity_val, timescale);
4719 }
4720}
4721
4723 Depsgraph *depsgraph,
4724 DynamicPaintSurface *surface,
4725 /* Cannot be const, because it is assigned to non-const variable.
4726 * NOLINTNEXTLINE: readability-non-const-parameter. */
4727 float *pointCoord,
4729 Object *brushOb,
4730 Scene *scene,
4731 float timescale)
4732{
4733 PaintSurfaceData *sData = surface->data;
4734 float brush_radius = brush->paint_distance * surface->radius_scale;
4735 Vec3f brushVel;
4736
4737 if (brush->flags & MOD_DPAINT_USES_VELOCITY) {
4738 dynamicPaint_brushObjectCalculateVelocity(depsgraph, scene, brushOb, &brushVel, timescale);
4739 }
4740
4741 auto *runtime_data = static_cast<DynamicPaintRuntime *>(brush->pmd->modifier.runtime);
4742 std::lock_guard lock(runtime_data->brush_mutex);
4743 const Mesh *brush_mesh = runtime_data->brush_mesh;
4744
4745 /*
4746 * Loop through every surface point
4747 */
4749 data.surface = surface;
4750 data.brush = brush;
4751 data.brushOb = brushOb;
4752 data.scene = scene;
4753 data.timescale = timescale;
4754 data.positions = brush_mesh->vert_positions();
4755 data.brush_radius = brush_radius;
4756 data.brushVelocity = &brushVel;
4757 data.pointCoord = pointCoord;
4758
4759 TaskParallelSettings settings;
4761 settings.use_threading = (sData->total_points > 1000);
4764
4765 return true;
4766}
4767
4768/***************************** Dynamic Paint Step / Baking ******************************/
4769
4770/*
4771 * Calculate current frame distances and directions for adjacency data
4772 */
4773
4774static void dynamic_paint_prepare_adjacency_cb(void *__restrict userdata,
4775 const int index,
4776 const TaskParallelTLS *__restrict /*tls*/)
4777{
4778 PaintSurfaceData *sData = static_cast<PaintSurfaceData *>(userdata);
4779 PaintBakeData *bData = sData->bData;
4780 BakeAdjPoint *bNeighs = bData->bNeighs;
4781 PaintAdjData *adj_data = sData->adj_data;
4782 Vec3f *realCoord = bData->realCoord;
4783
4784 const int num_neighs = adj_data->n_num[index];
4785
4786 for (int i = 0; i < num_neighs; i++) {
4787 const int n_index = adj_data->n_index[index] + i;
4788 const int t_index = adj_data->n_target[n_index];
4789
4790 /* dir vec */
4791 sub_v3_v3v3(bNeighs[n_index].dir,
4792 realCoord[bData->s_pos[t_index]].v,
4793 realCoord[bData->s_pos[index]].v);
4794 /* dist */
4795 bNeighs[n_index].dist = normalize_v3(bNeighs[n_index].dir);
4796 }
4797}
4798
4799static void dynamicPaint_prepareAdjacencyData(DynamicPaintSurface *surface, const bool force_init)
4800{
4801 PaintSurfaceData *sData = surface->data;
4802 PaintBakeData *bData = sData->bData;
4803 BakeAdjPoint *bNeighs;
4804 PaintAdjData *adj_data = sData->adj_data;
4805
4806 int index;
4807
4808 if ((!surface_usesAdjDistance(surface) && !force_init) || !sData->adj_data) {
4809 return;
4810 }
4811
4812 if (bData->bNeighs) {
4813 MEM_delete(bData->bNeighs);
4814 }
4816 size_t(sData->adj_data->total_targets), "PaintEffectBake");
4817 if (!bNeighs) {
4818 return;
4819 }
4820
4821 TaskParallelSettings settings;
4823 settings.use_threading = (sData->total_points > 1000);
4825 0, sData->total_points, sData, dynamic_paint_prepare_adjacency_cb, &settings);
4826
4827 /* calculate average values (single thread).
4828 * NOTE: tried to put this in threaded callback (using _reduce feature),
4829 * but gave ~30% slower result! */
4830 bData->average_dist = 0.0;
4831 for (index = 0; index < sData->total_points; index++) {
4832 int numOfNeighs = adj_data->n_num[index];
4833
4834 for (int i = 0; i < numOfNeighs; i++) {
4835 bData->average_dist += double(bNeighs[adj_data->n_index[index] + i].dist);
4836 }
4837 }
4838 bData->average_dist /= adj_data->total_targets;
4839}
4840
4841/* Find two adjacency points (closest_id) and influence (closest_d)
4842 * to move paint towards when affected by a force. */
4844 const int index,
4845 const float force[3],
4846 float closest_d[2],
4847 int closest_id[2])
4848{
4849 BakeAdjPoint *bNeighs = sData->bData->bNeighs;
4850 const int numOfNeighs = sData->adj_data->n_num[index];
4851
4852 closest_id[0] = closest_id[1] = -1;
4853 closest_d[0] = closest_d[1] = -1.0f;
4854
4855 /* find closest neigh */
4856 for (int i = 0; i < numOfNeighs; i++) {
4857 const int n_index = sData->adj_data->n_index[index] + i;
4858 const float dir_dot = dot_v3v3(bNeighs[n_index].dir, force);
4859
4860 if (dir_dot > closest_d[0] && dir_dot > 0.0f) {
4861 closest_d[0] = dir_dot;
4862 closest_id[0] = n_index;
4863 }
4864 }
4865
4866 if (closest_d[0] < 0.0f) {
4867 return;
4868 }
4869
4870 /* find second closest neigh */
4871 for (int i = 0; i < numOfNeighs; i++) {
4872 const int n_index = sData->adj_data->n_index[index] + i;
4873
4874 if (n_index == closest_id[0]) {
4875 continue;
4876 }
4877
4878 const float dir_dot = dot_v3v3(bNeighs[n_index].dir, force);
4879 const float closest_dot = dot_v3v3(bNeighs[n_index].dir, bNeighs[closest_id[0]].dir);
4880
4881 /* only accept neighbor at "other side" of the first one in relation to force dir
4882 * so make sure angle between this and closest neigh is greater than first angle. */
4883 if (dir_dot > closest_d[1] && closest_dot < closest_d[0] && dir_dot > 0.0f) {
4884 closest_d[1] = dir_dot;
4885 closest_id[1] = n_index;
4886 }
4887 }
4888
4889 /* if two valid neighs found, calculate how force effect is divided evenly between them
4890 * (so that d[0] + d[1] = 1.0) */
4891 if (closest_id[1] != -1) {
4892 float force_proj[3];
4893 float tangent[3];
4894 const float neigh_diff = acosf(
4895 dot_v3v3(bNeighs[closest_id[0]].dir, bNeighs[closest_id[1]].dir));
4896 float force_intersect;
4897 float temp;
4898
4899 /* project force vector on the plane determined by these two neighbor points
4900 * and calculate relative force angle from it. */
4901 cross_v3_v3v3(tangent, bNeighs[closest_id[0]].dir, bNeighs[closest_id[1]].dir);
4902 normalize_v3(tangent);
4903 force_intersect = dot_v3v3(force, tangent);
4904 madd_v3_v3v3fl(force_proj, force, tangent, (-1.0f) * force_intersect);
4905 normalize_v3(force_proj);
4906
4907 /* get drip factor based on force dir in relation to angle between those neighbors */
4908 temp = dot_v3v3(bNeighs[closest_id[0]].dir, force_proj);
4909 CLAMP(temp, -1.0f, 1.0f); /* float precision might cause values > 1.0f that return infinite */
4910 closest_d[1] = acosf(temp) / neigh_diff;
4911 closest_d[0] = 1.0f - closest_d[1];
4912
4913 /* and multiply depending on how deeply force intersects surface */
4914 temp = fabsf(force_intersect);
4915 CLAMP(temp, 0.0f, 1.0f);
4916 mul_v2_fl(closest_d, acosf(temp) / float(M_PI_2));
4917 }
4918 else {
4919 /* if only single neighbor, still linearize force intersection effect */
4920 closest_d[0] = 1.0f - acosf(closest_d[0]) / float(M_PI_2);
4921 }
4922}
4923
4926 float timescale)
4927{
4928 PaintSurfaceData *sData = surface->data;
4929 PaintBakeData *bData = sData->bData;
4930 BakeAdjPoint *bNeighs = sData->bData->bNeighs;
4931 float max_velocity = 0.0f;
4932
4933 if (!sData->adj_data) {
4934 return;
4935 }
4936
4937 /* find max velocity */
4938 for (int index = 0; index < sData->total_points; index++) {
4939 float vel = bData->brush_velocity[index * 4 + 3];
4940 CLAMP_MIN(max_velocity, vel);
4941 }
4942
4943 int steps = int(ceil(double(max_velocity) / bData->average_dist * double(timescale)));
4944 CLAMP(steps, 0, 12);
4945 float eff_scale = brush->smudge_strength / float(steps) * timescale;
4946
4947 for (int step = 0; step < steps; step++) {
4948 for (int index = 0; index < sData->total_points; index++) {
4949
4950 if (sData->adj_data->flags[index] & ADJ_BORDER_PIXEL) {
4951 continue;
4952 }
4953
4954 PaintPoint *pPoint = &(static_cast<PaintPoint *>(sData->type_data))[index];
4955 float smudge_str = bData->brush_velocity[index * 4 + 3];
4956
4957 /* force targets */
4958 int closest_id[2];
4959 float closest_d[2];
4960
4961 if (!smudge_str) {
4962 continue;
4963 }
4964
4965 /* get force affect points */
4967 sData, index, &bData->brush_velocity[index * 4], closest_d, closest_id);
4968
4969 /* Apply movement towards those two points */
4970 for (int i = 0; i < 2; i++) {
4971 int n_index = closest_id[i];
4972 if (n_index != -1 && closest_d[i] > 0.0f) {
4973 float dir_dot = closest_d[i], dir_factor;
4974 float speed_scale = eff_scale * smudge_str / bNeighs[n_index].dist;
4975 PaintPoint *ePoint = &(
4976 static_cast<PaintPoint *>(sData->type_data))[sData->adj_data->n_target[n_index]];
4977
4978 /* just skip if angle is too extreme */
4979 if (dir_dot <= 0.0f) {
4980 continue;
4981 }
4982
4983 dir_factor = dir_dot * speed_scale;
4984 CLAMP_MAX(dir_factor, brush->smudge_strength);
4985
4986 /* mix new color and alpha */
4987 mixColors(ePoint->color, ePoint->color[3], pPoint->color, pPoint->color[3], dir_factor);
4988 ePoint->color[3] = ePoint->color[3] * (1.0f - dir_factor) +
4989 pPoint->color[3] * dir_factor;
4990
4991 /* smudge "wet layer" */
4992 mixColors(ePoint->e_color,
4993 ePoint->e_color[3],
4994 pPoint->e_color,
4995 pPoint->e_color[3],
4996 dir_factor);
4997 ePoint->e_color[3] = ePoint->e_color[3] * (1.0f - dir_factor) +
4998 pPoint->e_color[3] * dir_factor;
4999 pPoint->wetness *= (1.0f - dir_factor);
5000 }
5001 }
5002 }
5003 }
5004}
5005
5009
5010 float *force;
5011 ListBaseT<EffectorCache> *effectors;
5012 const void *prevPoint;
5014
5016
5020
5021 float dt;
5025};
5026
5027/*
5028 * Prepare data required by effects for current frame.
5029 * Returns number of steps required
5030 */
5031static void dynamic_paint_prepare_effect_cb(void *__restrict userdata,
5032 const int index,
5033 const TaskParallelTLS *__restrict /*tls*/)
5034{
5035 const DynamicPaintEffectData *data = static_cast<const DynamicPaintEffectData *>(userdata);
5036
5037 const DynamicPaintSurface *surface = data->surface;
5038 const PaintSurfaceData *sData = surface->data;
5039 const PaintBakeData *bData = sData->bData;
5040 Vec3f *realCoord = bData->realCoord;
5041
5042 Scene *scene = data->scene;
5043
5044 float *force = data->force;
5045 ListBaseT<EffectorCache> *effectors = data->effectors;
5046
5047 float forc[3] = {0};
5048 float vel[3] = {0};
5049
5050 /* apply force fields */
5051 if (effectors) {
5052 EffectedPoint epoint;
5053 pd_point_from_loc(scene, realCoord[bData->s_pos[index]].v, vel, index, &epoint);
5054 epoint.vel_to_sec = 1.0f;
5056 effectors, nullptr, surface->effector_weights, &epoint, forc, nullptr, nullptr);
5057 }
5058
5059 /* if global gravity is enabled, add it too */
5061 /* also divide by 10 to about match default gravity
5062 * with default force strength (1.0). */
5063 madd_v3_v3fl(forc,
5065 surface->effector_weights->global_gravity * surface->effector_weights->weight[0] /
5066 10.0f);
5067 }
5068
5069 /* add surface point velocity and acceleration if enabled */
5070 if (bData->velocity) {
5071 if (surface->drip_vel) {
5072 madd_v3_v3fl(forc, bData->velocity[index].v, surface->drip_vel * (-1.0f));
5073 }
5074
5075 /* acceleration */
5076 if (bData->prev_velocity && surface->drip_acc) {
5077 float acc[3];
5078 copy_v3_v3(acc, bData->velocity[index].v);
5079 sub_v3_v3(acc, bData->prev_velocity[index].v);
5080 madd_v3_v3fl(forc, acc, surface->drip_acc * (-1.0f));
5081 }
5082 }
5083
5084 /* force strength, and normalize force vec */
5085 force[index * 4 + 3] = normalize_v3_v3(&force[index * 4], forc);
5086}
5087
5088static int dynamicPaint_prepareEffectStep(Depsgraph *depsgraph,
5089 DynamicPaintSurface *surface,
5090 Scene *scene,
5091 Object *ob,
5092 float **force,
5093 float timescale)
5094{
5095 double average_force = 0.0f;
5096 float shrink_speed = 0.0f, spread_speed = 0.0f;
5097 float fastest_effect, avg_dist;
5098 int steps;
5099 PaintSurfaceData *sData = surface->data;
5100 PaintBakeData *bData = sData->bData;
5101
5102 /* Init force data if required */
5103 if (surface->effect & MOD_DPAINT_EFFECT_DO_DRIP) {
5104 ListBaseT<EffectorCache> *effectors = BKE_effectors_create(
5105 depsgraph, ob, nullptr, surface->effector_weights, false);
5106
5107 /* allocate memory for force data (dir vector + strength) */
5108 *force = MEM_new_array_uninitialized<float>(4 * size_t(sData->total_points),
5109 "PaintEffectForces");
5110
5111 if (*force) {
5113 data.surface = surface;
5114 data.scene = scene;
5115 data.force = *force;
5116 data.effectors = effectors;
5117
5118 TaskParallelSettings settings;
5120 settings.use_threading = (sData->total_points > 1000);
5122 0, sData->total_points, &data, dynamic_paint_prepare_effect_cb, &settings);
5123
5124 /* calculate average values (single thread) */
5125 for (int index = 0; index < sData->total_points; index++) {
5126 average_force += double((*force)[index * 4 + 3]);
5127 }
5128 average_force /= sData->total_points;
5129 }
5130 BKE_effectors_free(effectors);
5131 }
5132
5133 /* Get number of required steps using average point distance
5134 * so that just a few ultra close pixels won't increase sub-steps to max. */
5135
5136 /* Adjust number of required sub-step by fastest active effect. */
5137 if (surface->effect & MOD_DPAINT_EFFECT_DO_SPREAD) {
5138 spread_speed = surface->spread_speed;
5139 }
5140 if (surface->effect & MOD_DPAINT_EFFECT_DO_SHRINK) {
5141 shrink_speed = surface->shrink_speed;
5142 }
5143
5144 fastest_effect = std::max({spread_speed, shrink_speed, float(average_force)});
5145 avg_dist = bData->average_dist * double(CANVAS_REL_SIZE) / double(getSurfaceDimension(sData));
5146
5147 steps = int(ceilf(1.5f * EFF_MOVEMENT_PER_FRAME * fastest_effect / avg_dist * timescale));
5148 CLAMP(steps, 1, 20);
5149
5150 return steps;
5151}
5152
5156static void dynamic_paint_effect_spread_cb(void *__restrict userdata,
5157 const int index,
5158 const TaskParallelTLS *__restrict /*tls*/)
5159{
5160 const DynamicPaintEffectData *data = static_cast<const DynamicPaintEffectData *>(userdata);
5161
5162 const DynamicPaintSurface *surface = data->surface;
5163 const PaintSurfaceData *sData = surface->data;
5164
5165 if (sData->adj_data->flags[index] & ADJ_BORDER_PIXEL) {
5166 return;
5167 }
5168
5169 const int numOfNeighs = sData->adj_data->n_num[index];
5170 BakeAdjPoint *bNeighs = sData->bData->bNeighs;
5171 PaintPoint *pPoint = &(static_cast<PaintPoint *>(sData->type_data))[index];
5172 const PaintPoint *prevPoint = static_cast<const PaintPoint *>(data->prevPoint);
5173 const float eff_scale = data->eff_scale;
5174
5175 const int *n_index = sData->adj_data->n_index;
5176 const int *n_target = sData->adj_data->n_target;
5177
5178 /* Loop through neighboring points */
5179 for (int i = 0; i < numOfNeighs; i++) {
5180 const int n_idx = n_index[index] + i;
5181 float w_factor;
5182 const PaintPoint *pPoint_prev = &prevPoint[n_target[n_idx]];
5183 const float speed_scale = (bNeighs[n_idx].dist < eff_scale) ? 1.0f :
5184 eff_scale / bNeighs[n_idx].dist;
5185 const float color_mix = std::min({pPoint_prev->wetness, pPoint->wetness, 1.0f}) * 0.25f *
5186 surface->color_spread_speed;
5187
5188 /* do color mixing */
5189 if (color_mix) {
5190 mixColors(pPoint->e_color,
5191 pPoint->e_color[3],
5192 pPoint_prev->e_color,
5193 pPoint_prev->e_color[3],
5194 color_mix);
5195 }
5196
5197 /* Only continue if surrounding point has higher wetness */
5198 if (pPoint_prev->wetness < pPoint->wetness || pPoint_prev->wetness < MIN_WETNESS) {
5199 continue;
5200 }
5201
5202 w_factor = 1.0f / numOfNeighs * min_ff(pPoint_prev->wetness, 1.0f) * speed_scale;
5203 CLAMP(w_factor, 0.0f, 1.0f);
5204
5205 /* mix new wetness and color */
5206 pPoint->wetness = pPoint->wetness + w_factor * (pPoint_prev->wetness - pPoint->wetness);
5207 pPoint->e_color[3] = mixColors(pPoint->e_color,
5208 pPoint->e_color[3],
5209 pPoint_prev->e_color,
5210 pPoint_prev->e_color[3],
5211 w_factor);
5212 }
5213}
5214
5215static void dynamic_paint_effect_shrink_cb(void *__restrict userdata,
5216 const int index,
5217 const TaskParallelTLS *__restrict /*tls*/)
5218{
5219 const DynamicPaintEffectData *data = static_cast<const DynamicPaintEffectData *>(userdata);
5220
5221 const DynamicPaintSurface *surface = data->surface;
5222 const PaintSurfaceData *sData = surface->data;
5223
5224 if (sData->adj_data->flags[index] & ADJ_BORDER_PIXEL) {
5225 return;
5226 }
5227
5228 const int numOfNeighs = sData->adj_data->n_num[index];
5229 BakeAdjPoint *bNeighs = sData->bData->bNeighs;
5230 PaintPoint *pPoint = &(static_cast<PaintPoint *>(sData->type_data))[index];
5231 const PaintPoint *prevPoint = static_cast<const PaintPoint *>(data->prevPoint);
5232 const float eff_scale = data->eff_scale;
5233
5234 const int *n_index = sData->adj_data->n_index;
5235 const int *n_target = sData->adj_data->n_target;
5236
5237 /* Loop through neighboring points */
5238 for (int i = 0; i < numOfNeighs; i++) {
5239 const int n_idx = n_index[index] + i;
5240 const float speed_scale = (bNeighs[n_idx].dist < eff_scale) ? 1.0f :
5241 eff_scale / bNeighs[n_idx].dist;
5242 const PaintPoint *pPoint_prev = &prevPoint[n_target[n_idx]];
5243 float a_factor, ea_factor, w_factor;
5244
5245 /* Check if neighboring point has lower alpha,
5246 * if so, decrease this point's alpha as well. */
5247 if (pPoint->color[3] <= 0.0f && pPoint->e_color[3] <= 0.0f && pPoint->wetness <= 0.0f) {
5248 continue;
5249 }
5250
5251 /* decrease factor for dry paint alpha */
5252 a_factor = max_ff((1.0f - pPoint_prev->color[3]) / numOfNeighs *
5253 (pPoint->color[3] - pPoint_prev->color[3]) * speed_scale,
5254 0.0f);
5255 /* decrease factor for wet paint alpha */
5256 ea_factor = max_ff((1.0f - pPoint_prev->e_color[3]) / 8 *
5257 (pPoint->e_color[3] - pPoint_prev->e_color[3]) * speed_scale,
5258 0.0f);
5259 /* decrease factor for paint wetness */
5260 w_factor = max_ff((1.0f - pPoint_prev->wetness) / 8 *
5261 (pPoint->wetness - pPoint_prev->wetness) * speed_scale,
5262 0.0f);
5263
5264 pPoint->color[3] -= a_factor;
5265 CLAMP_MIN(pPoint->color[3], 0.0f);
5266 pPoint->e_color[3] -= ea_factor;
5267 CLAMP_MIN(pPoint->e_color[3], 0.0f);
5268 pPoint->wetness -= w_factor;
5269 CLAMP_MIN(pPoint->wetness, 0.0f);
5270 }
5271}
5272
5273static void dynamic_paint_effect_drip_cb(void *__restrict userdata,
5274 const int index,
5275 const TaskParallelTLS *__restrict /*tls*/)
5276{
5277 const DynamicPaintEffectData *data = static_cast<const DynamicPaintEffectData *>(userdata);
5278
5279 const DynamicPaintSurface *surface = data->surface;
5280 const PaintSurfaceData *sData = surface->data;
5281
5282 if (sData->adj_data->flags[index] & ADJ_BORDER_PIXEL) {
5283 return;
5284 }
5285
5286 BakeAdjPoint *bNeighs = sData->bData->bNeighs;
5287 PaintPoint *pPoint = &(static_cast<PaintPoint *>(sData->type_data))[index];
5288 const PaintPoint *prevPoint = static_cast<const PaintPoint *>(data->prevPoint);
5289 const PaintPoint *pPoint_prev = &prevPoint[index];
5290 const float *force = data->force;
5291 const float eff_scale = data->eff_scale;
5292
5293 const int *n_target = sData->adj_data->n_target;
5294
5295 uint8_t *point_locks = data->point_locks;
5296
5297 int closest_id[2];
5298 float closest_d[2];
5299
5300 /* adjust drip speed depending on wetness */
5301 float w_factor = pPoint_prev->wetness - 0.025f;
5302 if (w_factor <= 0) {
5303 return;
5304 }
5305 CLAMP(w_factor, 0.0f, 1.0f);
5306
5307 float ppoint_wetness_diff = 0.0f;
5308
5309 /* get force affect points */
5310 surface_determineForceTargetPoints(sData, index, &force[index * 4], closest_d, closest_id);
5311
5312 /* Apply movement towards those two points */
5313 for (int i = 0; i < 2; i++) {
5314 const int n_idx = closest_id[i];
5315 if (n_idx != -1 && closest_d[i] > 0.0f) {
5316 const float dir_dot = closest_d[i];
5317
5318 /* just skip if angle is too extreme */
5319 if (dir_dot <= 0.0f) {
5320 continue;
5321 }
5322
5323 float dir_factor, a_factor;
5324 const float speed_scale = eff_scale * force[index * 4 + 3] / bNeighs[n_idx].dist;
5325
5326 const uint n_trgt = uint(n_target[n_idx]);
5327
5328 /* Sort of spin-lock, but only for given ePoint.
5329 * Since the odds a same ePoint is modified at the same time by several threads is very low,
5330 * this is much more efficient than a global spin lock. */
5331 const uint epointlock_idx = n_trgt / 8;
5332 const uint8_t epointlock_bitmask = 1 << (n_trgt & 7); /* 7 == 0b111 */
5333 while (atomic_fetch_and_or_uint8(&point_locks[epointlock_idx], epointlock_bitmask) &
5334 epointlock_bitmask)
5335 {
5336 /* pass */
5337 }
5338
5339 PaintPoint *ePoint = &(static_cast<PaintPoint *>(sData->type_data))[n_trgt];
5340 const float e_wet = ePoint->wetness;
5341
5342 dir_factor = min_ff(0.5f, dir_dot * min_ff(speed_scale, 1.0f) * w_factor);
5343
5344 /* mix new wetness */
5345 ePoint->wetness += dir_factor;
5346 CLAMP(ePoint->wetness, 0.0f, MAX_WETNESS);
5347
5348 /* mix new color */
5349 a_factor = dir_factor / pPoint_prev->wetness;
5350 CLAMP(a_factor, 0.0f, 1.0f);
5351 mixColors(ePoint->e_color,
5352 ePoint->e_color[3],
5353 pPoint_prev->e_color,
5354 pPoint_prev->e_color[3],
5355 a_factor);
5356 /* dripping is supposed to preserve alpha level */
5357 if (pPoint_prev->e_color[3] > ePoint->e_color[3]) {
5358 ePoint->e_color[3] += a_factor * pPoint_prev->e_color[3];
5359 CLAMP_MAX(ePoint->e_color[3], pPoint_prev->e_color[3]);
5360 }
5361
5362 /* Decrease paint wetness on current point (just store diff here,
5363 * that way we can only lock current point once at the end to apply it). */
5364 ppoint_wetness_diff += (ePoint->wetness - e_wet);
5365
5366#ifndef NDEBUG
5367 {
5368 uint8_t ret = atomic_fetch_and_and_uint8(&point_locks[epointlock_idx],
5369 ~epointlock_bitmask);
5370 BLI_assert(ret & epointlock_bitmask);
5371 }
5372#else
5373 atomic_fetch_and_and_uint8(&point_locks[epointlock_idx], ~epointlock_bitmask);
5374#endif
5375 }
5376 }
5377
5378 {
5379 const uint ppointlock_idx = index / 8;
5380 const uint8_t ppointlock_bitmask = 1 << (index & 7); /* 7 == 0b111 */
5381 while (atomic_fetch_and_or_uint8(&point_locks[ppointlock_idx], ppointlock_bitmask) &
5382 ppointlock_bitmask)
5383 {
5384 /* pass */
5385 }
5386
5387 pPoint->wetness -= ppoint_wetness_diff;
5388 CLAMP(pPoint->wetness, 0.0f, MAX_WETNESS);
5389
5390#ifndef NDEBUG
5391 {
5392 uint8_t ret = atomic_fetch_and_and_uint8(&point_locks[ppointlock_idx], ~ppointlock_bitmask);
5393 BLI_assert(ret & ppointlock_bitmask);
5394 }
5395#else
5396 atomic_fetch_and_and_uint8(&point_locks[ppointlock_idx], ~ppointlock_bitmask);
5397#endif
5398 }
5399}
5400
5402 DynamicPaintSurface *surface,
5403 /* Cannot be const, because it is assigned to non-const variable.
5404 * NOLINTNEXTLINE: readability-non-const-parameter. */
5405 float *force,
5406 PaintPoint *prevPoint,
5407 float timescale,
5408 float steps)
5409{
5410 PaintSurfaceData *sData = surface->data;
5411
5412 const float distance_scale = getSurfaceDimension(sData) / CANVAS_REL_SIZE;
5413 timescale /= steps;
5414
5415 if (!sData->adj_data) {
5416 return;
5417 }
5418
5419 /*
5420 * Spread Effect
5421 */
5422 if (surface->effect & MOD_DPAINT_EFFECT_DO_SPREAD) {
5423 const float eff_scale = distance_scale * EFF_MOVEMENT_PER_FRAME * surface->spread_speed *
5424 timescale;
5425
5426 /* Copy current surface to the previous points array to read unmodified values */
5427 memcpy(prevPoint, sData->type_data, sData->total_points * sizeof(PaintPoint));
5428
5430 data.surface = surface;
5431 data.prevPoint = prevPoint;
5432 data.eff_scale = eff_scale;
5433
5434 TaskParallelSettings settings;
5436 settings.use_threading = (sData->total_points > 1000);
5438 0, sData->total_points, &data, dynamic_paint_effect_spread_cb, &settings);
5439 }
5440
5441 /*
5442 * Shrink Effect
5443 */
5444 if (surface->effect & MOD_DPAINT_EFFECT_DO_SHRINK) {
5445 const float eff_scale = distance_scale * EFF_MOVEMENT_PER_FRAME * surface->shrink_speed *
5446 timescale;
5447
5448 /* Copy current surface to the previous points array to read unmodified values */
5449 memcpy(prevPoint, sData->type_data, sData->total_points * sizeof(PaintPoint));
5450
5452 data.surface = surface;
5453 data.prevPoint = prevPoint;
5454 data.eff_scale = eff_scale;
5455
5456 TaskParallelSettings settings;
5458 settings.use_threading = (sData->total_points > 1000);
5460 0, sData->total_points, &data, dynamic_paint_effect_shrink_cb, &settings);
5461 }
5462
5463 /*
5464 * Drip Effect
5465 */
5466 if (surface->effect & MOD_DPAINT_EFFECT_DO_DRIP && force) {
5467 const float eff_scale = distance_scale * EFF_MOVEMENT_PER_FRAME * timescale / 2.0f;
5468
5469 /* Same as #BLI_bitmask, but handled atomically as 'ePoint' locks. */
5470 const size_t point_locks_size = (sData->total_points / 8) + 1;
5471 uint8_t *point_locks = MEM_new_array_zeroed<uint8_t>(point_locks_size, __func__);
5472
5473 /* Copy current surface to the previous points array to read unmodified values */
5474 memcpy(prevPoint, sData->type_data, sData->total_points * sizeof(PaintPoint));
5475
5477 data.surface = surface;
5478 data.prevPoint = prevPoint;
5479 data.eff_scale = eff_scale;
5480 data.force = force;
5481 data.point_locks = point_locks;
5482
5483 TaskParallelSettings settings;
5485 settings.use_threading = (sData->total_points > 1000);
5487 0, sData->total_points, &data, dynamic_paint_effect_drip_cb, &settings);
5488
5489 MEM_delete(point_locks);
5490 }
5491}
5492
5493static void dynamic_paint_border_cb(void *__restrict userdata,
5494 const int b_index,
5495 const TaskParallelTLS *__restrict /*tls*/)
5496{
5497 const DynamicPaintEffectData *data = static_cast<const DynamicPaintEffectData *>(userdata);
5498
5499 const DynamicPaintSurface *surface = data->surface;
5500 const PaintSurfaceData *sData = surface->data;
5501
5502 const int index = sData->adj_data->border[b_index];
5503
5504 const int numOfNeighs = sData->adj_data->n_num[index];
5505 PaintPoint *pPoint = &(static_cast<PaintPoint *>(sData->type_data))[index];
5506
5507 const int *n_index = sData->adj_data->n_index;
5508 const int *n_target = sData->adj_data->n_target;
5509
5510 /* Average neighboring points. Intermediaries use premultiplied alpha. */
5511 float mix_color[4] = {0.0f, 0.0f, 0.0f, 0.0f};
5512 float mix_e_color[4] = {0.0f, 0.0f, 0.0f, 0.0f};
5513 float mix_wetness = 0.0f;
5514
5515 for (int i = 0; i < numOfNeighs; i++) {
5516 const int n_idx = n_index[index] + i;
5517 const int target = n_target[n_idx];
5518
5519 PaintPoint *pPoint2 = &(static_cast<PaintPoint *>(sData->type_data))[target];
5520
5521 BLI_assert(!(sData->adj_data->flags[target] & ADJ_BORDER_PIXEL));
5522
5523 madd_v3_v3fl(mix_color, pPoint2->color, pPoint2->color[3]);
5524 mix_color[3] += pPoint2->color[3];
5525
5526 madd_v3_v3fl(mix_e_color, pPoint2->e_color, pPoint2->e_color[3]);
5527 mix_e_color[3] += pPoint2->e_color[3];
5528
5529 mix_wetness += pPoint2->wetness;
5530 }
5531
5532 const float divisor = 1.0f / numOfNeighs;
5533
5534 if (mix_color[3]) {
5535 pPoint->color[3] = mix_color[3] * divisor;
5536 mul_v3_v3fl(pPoint->color, mix_color, divisor / pPoint->color[3]);
5537 }
5538 else {
5539 pPoint->color[3] = 0.0f;
5540 }
5541
5542 if (mix_e_color[3]) {
5543 pPoint->e_color[3] = mix_e_color[3] * divisor;
5544 mul_v3_v3fl(pPoint->e_color, mix_e_color, divisor / pPoint->e_color[3]);
5545 }
5546 else {
5547 pPoint->e_color[3] = 0.0f;
5548 }
5549
5550 pPoint->wetness = mix_wetness / numOfNeighs;
5551}
5552
5554{
5555 PaintSurfaceData *sData = surface->data;
5556
5557 if (!sData->adj_data || !sData->adj_data->border) {
5558 return;
5559 }
5560
5561 /* Don't use prevPoint, relying on the condition that neighbors are never border pixels. */
5563 data.surface = surface;
5564
5565 TaskParallelSettings settings;
5567 settings.use_threading = (sData->adj_data->total_border > 1000);
5569 0, sData->adj_data->total_border, &data, dynamic_paint_border_cb, &settings);
5570}
5571
5572static void dynamic_paint_wave_step_cb(void *__restrict userdata,
5573 const int index,
5574 const TaskParallelTLS *__restrict /*tls*/)
5575{
5576 const DynamicPaintEffectData *data = static_cast<const DynamicPaintEffectData *>(userdata);
5577
5578 const DynamicPaintSurface *surface = data->surface;
5579 const PaintSurfaceData *sData = surface->data;
5580 BakeAdjPoint *bNeighs = sData->bData->bNeighs;
5581 const PaintWavePoint *prevPoint = static_cast<const PaintWavePoint *>(data->prevPoint);
5582
5583 const float wave_speed = data->wave_speed;
5584 const float wave_scale = data->wave_scale;
5585 const float wave_max_slope = data->wave_max_slope;
5586
5587 const float dt = data->dt;
5588 const float min_dist = data->min_dist;
5589 const float damp_factor = data->damp_factor;
5590
5591 PaintWavePoint *wPoint = &(static_cast<PaintWavePoint *>(sData->type_data))[index];
5592 const int numOfNeighs = sData->adj_data->n_num[index];
5593 float force = 0.0f, avg_dist = 0.0f, avg_height = 0.0f, avg_n_height = 0.0f;
5594 int numOfN = 0, numOfRN = 0;
5595
5596 if (wPoint->state > 0) {
5597 return;
5598 }
5599
5600 const int *n_index = sData->adj_data->n_index;
5601 const int *n_target = sData->adj_data->n_target;
5602 const int *adj_flags = sData->adj_data->flags;
5603
5604 /* calculate force from surrounding points */
5605 for (int i = 0; i < numOfNeighs; i++) {
5606 const int n_idx = n_index[index] + i;
5607 float dist = bNeighs[n_idx].dist * wave_scale;
5608 const PaintWavePoint *tPoint = &prevPoint[n_target[n_idx]];
5609
5610 if (!dist || tPoint->state > 0) {
5611 continue;
5612 }
5613
5614 CLAMP_MIN(dist, min_dist);
5615 avg_dist += dist;
5616 numOfN++;
5617
5618 /* count average height for edge points for open borders */
5619 if (!(adj_flags[n_target[n_idx]] & ADJ_ON_MESH_EDGE)) {
5620 avg_n_height += tPoint->height;
5621 numOfRN++;
5622 }
5623
5624 force += (tPoint->height - wPoint->height) / (dist * dist);
5625 avg_height += tPoint->height;
5626 }
5627 avg_dist = (numOfN) ? avg_dist / numOfN : 0.0f;
5628
5629 if (surface->flags & MOD_DPAINT_WAVE_OPEN_BORDERS && adj_flags[index] & ADJ_ON_MESH_EDGE) {
5630 /* if open borders, apply a fake height to keep waves going on */
5631 avg_n_height = (numOfRN) ? avg_n_height / numOfRN : 0.0f;
5632 wPoint->height = (dt * wave_speed * avg_n_height + wPoint->height * avg_dist) /
5633 (avg_dist + dt * wave_speed);
5634 }
5635 /* Else do wave equation. */
5636 else {
5637 /* add force towards zero height based on average dist */
5638 if (avg_dist) {
5639 force += (0.0f - wPoint->height) * surface->wave_spring / (avg_dist * avg_dist) / 2.0f;
5640 }
5641
5642 /* change point velocity */
5643 wPoint->velocity += force * dt * wave_speed * wave_speed;
5644 /* damping */
5645 wPoint->velocity *= damp_factor;
5646 /* and new height */
5647 wPoint->height += wPoint->velocity * dt;
5648
5649 /* limit wave slope steepness */
5650 if (wave_max_slope && avg_dist) {
5651 const float max_offset = wave_max_slope * avg_dist;
5652 const float offset = (numOfN) ? (avg_height / numOfN - wPoint->height) : 0.0f;
5653 if (offset > max_offset) {
5654 wPoint->height += offset - max_offset;
5655 }
5656 else if (offset < -max_offset) {
5657 wPoint->height += offset + max_offset;
5658 }
5659 }
5660 }
5661
5662 if (data->reset_wave) {
5663 /* if there wasn't any brush intersection, clear isect height */
5664 if (wPoint->state == DPAINT_WAVE_NONE) {
5665 wPoint->brush_isect = 0.0f;
5666 }
5667 wPoint->state = DPAINT_WAVE_NONE;
5668 }
5669}
5670
5671static void dynamicPaint_doWaveStep(DynamicPaintSurface *surface, float timescale)
5672{
5673 PaintSurfaceData *sData = surface->data;
5674 BakeAdjPoint *bNeighs = sData->bData->bNeighs;
5675 int index;
5676 int steps, ss;
5677 float dt, min_dist, damp_factor;
5678 const float wave_speed = surface->wave_speed;
5679 const float wave_max_slope = (surface->wave_smoothness >= 0.01f) ?
5680 (0.5f / surface->wave_smoothness) :
5681 0.0f;
5682 double average_dist = 0.0f;
5683 const float canvas_size = getSurfaceDimension(sData);
5684 const float wave_scale = CANVAS_REL_SIZE / canvas_size;
5685
5686 /* allocate memory */
5688 size_t(sData->total_points), __func__);
5689 if (!prevPoint) {
5690 return;
5691 }
5692
5693 /* calculate average neigh distance (single thread) */
5694 for (index = 0; index < sData->total_points; index++) {
5695 int numOfNeighs = sData->adj_data->n_num[index];
5696
5697 for (int i = 0; i < numOfNeighs; i++) {
5698 average_dist += double(bNeighs[sData->adj_data->n_index[index] + i].dist);
5699 }
5700 }
5701 average_dist *= double(wave_scale) / sData->adj_data->total_targets;
5702
5703 /* determine number of required steps */
5704 steps = int(ceil(double(WAVE_TIME_FAC * timescale * surface->wave_timescale) /
5705 (average_dist / double(wave_speed) / 3)));
5706 CLAMP(steps, 1, 20);
5707 timescale /= steps;
5708
5709 /* apply simulation values for final timescale */
5710 dt = WAVE_TIME_FAC * timescale * surface->wave_timescale;
5711 min_dist = wave_speed * dt * 1.5f;
5712 damp_factor = pow((1.0f - surface->wave_damping), timescale * surface->wave_timescale);
5713
5714 for (ss = 0; ss < steps; ss++) {
5715 /* copy previous frame data */
5716 memcpy(prevPoint, sData->type_data, sData->total_points * sizeof(PaintWavePoint));
5717
5719 data.surface = surface;
5720 data.prevPoint = prevPoint;
5721 data.wave_speed = wave_speed;
5722 data.wave_scale = wave_scale;
5723 data.wave_max_slope = wave_max_slope;
5724 data.dt = dt;
5725 data.min_dist = min_dist;
5726 data.damp_factor = damp_factor;
5727 data.reset_wave = (ss == steps - 1);
5728
5729 TaskParallelSettings settings;
5731 settings.use_threading = (sData->total_points > 1000);
5733 }
5734
5735 MEM_delete(prevPoint);
5736}
5737
5738/* Do dissolve and fading effects */
5746
5751
5752static void dynamic_paint_surface_pre_step_cb(void *__restrict userdata,
5753 const int index,
5754 const TaskParallelTLS *__restrict /*tls*/)
5755{
5756 const DynamicPaintDissolveDryData *data = static_cast<const DynamicPaintDissolveDryData *>(
5757 userdata);
5758
5759 const DynamicPaintSurface *surface = data->surface;
5760 const PaintSurfaceData *sData = surface->data;
5761 const float timescale = data->timescale;
5762
5763 /* Do drying dissolve effects */
5764 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
5765 PaintPoint *pPoint = &(static_cast<PaintPoint *>(sData->type_data))[index];
5766 /* drying */
5767 if (surface->flags & MOD_DPAINT_USE_DRYING) {
5768 if (pPoint->wetness >= MIN_WETNESS) {
5769 float f_color[4];
5770 float p_wetness = pPoint->wetness;
5771
5772 value_dissolve(&pPoint->wetness,
5773 surface->dry_speed,
5774 timescale,
5775 (surface->flags & MOD_DPAINT_DRY_LOG) != 0);
5776 CLAMP_MIN(pPoint->wetness, 0.0f);
5777
5778 if (pPoint->wetness < surface->color_dry_threshold) {
5779 float dry_ratio = pPoint->wetness / p_wetness;
5780
5781 /*
5782 * Slowly "shift" paint from wet layer to dry layer as it drys:
5783 */
5784 /* make sure alpha values are within proper range */
5785 CLAMP(pPoint->color[3], 0.0f, 1.0f);
5786 CLAMP(pPoint->e_color[3], 0.0f, 1.0f);
5787
5788 /* get current final blended color of these layers */
5790 pPoint->color, pPoint->color[3], pPoint->e_color, pPoint->e_color[3], f_color);
5791 /* reduce wet layer alpha by dry factor */
5792 pPoint->e_color[3] *= dry_ratio;
5793
5794 /* Now calculate new alpha for dry layer that keeps final blended color unchanged. */
5795 pPoint->color[3] = (f_color[3] - pPoint->e_color[3]) / (1.0f - pPoint->e_color[3]);
5796 /* For each rgb component, calculate a new dry layer color that keeps the final blend
5797 * color with these new alpha values. (wet layer color doesn't change). */
5798 if (pPoint->color[3]) {
5799 for (int i = 0; i < 3; i++) {
5800 pPoint->color[i] = (f_color[i] * f_color[3] -
5801 pPoint->e_color[i] * pPoint->e_color[3]) /
5802 (pPoint->color[3] * (1.0f - pPoint->e_color[3]));
5803 }
5804 }
5805 }
5806
5807 pPoint->state = DPAINT_PAINT_WET;
5808 }
5809 /* In case of just dried paint, just mix it to the dry layer and mark it empty. */
5810 else if (pPoint->state > 0) {
5811 float f_color[4];
5812 blendColors(pPoint->color, pPoint->color[3], pPoint->e_color, pPoint->e_color[3], f_color);
5813 copy_v4_v4(pPoint->color, f_color);
5814 /* clear wet layer */
5815 pPoint->wetness = 0.0f;
5816 pPoint->e_color[3] = 0.0f;
5817 pPoint->state = DPAINT_PAINT_DRY;
5818 }
5819 }
5820
5821 if (surface->flags & MOD_DPAINT_DISSOLVE) {
5822 value_dissolve(&pPoint->color[3],
5823 surface->diss_speed,
5824 timescale,
5825 (surface->flags & MOD_DPAINT_DISSOLVE_LOG) != 0);
5826 CLAMP_MIN(pPoint->color[3], 0.0f);
5827
5828 value_dissolve(&pPoint->e_color[3],
5829 surface->diss_speed,
5830 timescale,
5831 (surface->flags & MOD_DPAINT_DISSOLVE_LOG) != 0);
5832 CLAMP_MIN(pPoint->e_color[3], 0.0f);
5833 }
5834 }
5835 /* dissolve for float types */
5836 else if (surface->flags & MOD_DPAINT_DISSOLVE &&
5838 {
5839 float *point = &(static_cast<float *>(sData->type_data))[index];
5840 /* log or linear */
5842 point, surface->diss_speed, timescale, (surface->flags & MOD_DPAINT_DISSOLVE_LOG) != 0);
5843 CLAMP_MIN(*point, 0.0f);
5844 }
5845}
5846
5848{
5849 PaintSurfaceData *sData = surface->data;
5850 PaintBakeData *bData = sData->bData;
5852 const Span<float3> positions = mesh->vert_positions();
5853
5854 int numOfVerts = mesh->verts_num;
5855
5856 if (!bData->prev_positions) {
5857 return true;
5858 }
5859
5860 /* matrix comparison */
5861 if (!equals_m4m4(bData->prev_obmat, ob->object_to_world().ptr())) {
5862 return true;
5863 }
5864
5865 /* vertices */
5866 for (int i = 0; i < numOfVerts; i++) {
5867 if (!equals_v3v3(bData->prev_positions[i], positions[i])) {
5868 return true;
5869 }
5870 }
5871
5872 return false;
5873}
5874
5875/* Prepare for surface step by creating PaintBakeNormal data */
5887
5888static void dynamic_paint_generate_bake_data_cb(void *__restrict userdata,
5889 const int index,
5890 const TaskParallelTLS *__restrict /*tls*/)
5891{
5893 userdata);
5894
5895 const DynamicPaintSurface *surface = data->surface;
5896 const PaintSurfaceData *sData = surface->data;
5897 const PaintAdjData *adj_data = sData->adj_data;
5898 const PaintBakeData *bData = sData->bData;
5899
5900 Object *ob = data->ob;
5901
5902 const Vec3f *canvas_verts = data->canvas_verts;
5903
5904 const bool do_velocity_data = data->do_velocity_data;
5905 const bool new_bdata = data->new_bdata;
5906
5907 float prev_point[3] = {0.0f, 0.0f, 0.0f};
5908 float temp_nor[3];
5909
5910 if (do_velocity_data && !new_bdata) {
5911 copy_v3_v3(prev_point, bData->realCoord[bData->s_pos[index]].v);
5912 }
5913
5914 /*
5915 * Calculate current 3D-position and normal of each surface point
5916 */
5917 if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
5918 float n1[3], n2[3], n3[3];
5919 const ImgSeqFormatData *f_data = sData->format_data;
5920 const PaintUVPoint *tPoint = &(static_cast<PaintUVPoint *>(f_data->uv_p))[index];
5921
5922 bData->s_num[index] = (surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1;
5923 bData->s_pos[index] = index * bData->s_num[index];
5924
5925 /* per sample coordinates */
5926 for (int ss = 0; ss < bData->s_num[index]; ss++) {
5927 interp_v3_v3v3v3(bData->realCoord[bData->s_pos[index] + ss].v,
5928 canvas_verts[tPoint->v1].v,
5929 canvas_verts[tPoint->v2].v,
5930 canvas_verts[tPoint->v3].v,
5931 f_data->barycentricWeights[index * bData->s_num[index] + ss].v);
5932 }
5933
5934 /* Calculate current pixel surface normal */
5935 copy_v3_v3(n1, data->vert_normals[tPoint->v1]);
5936 copy_v3_v3(n2, data->vert_normals[tPoint->v2]);
5937 copy_v3_v3(n3, data->vert_normals[tPoint->v3]);
5938
5940 temp_nor, n1, n2, n3, f_data->barycentricWeights[index * bData->s_num[index]].v);
5941 normalize_v3(temp_nor);
5943 /* Prepare surface normal directional scale to easily convert
5944 * brush intersection amount between global and local space */
5945 float scaled_nor[3];
5946 mul_v3_v3v3(scaled_nor, temp_nor, ob->scale);
5947 bData->bNormal[index].normal_scale = len_v3(scaled_nor);
5948 }
5949 mul_mat3_m4_v3(ob->object_to_world().ptr(), temp_nor);
5950 normalize_v3(temp_nor);
5951 negate_v3_v3(bData->bNormal[index].invNorm, temp_nor);
5952 }
5953 else if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) {
5954 int ss;
5955 if (surface->flags & MOD_DPAINT_ANTIALIAS && adj_data) {
5956 bData->s_num[index] = adj_data->n_num[index] + 1;
5957 bData->s_pos[index] = adj_data->n_index[index] + index;
5958 }
5959 else {
5960 bData->s_num[index] = 1;
5961 bData->s_pos[index] = index;
5962 }
5963
5964 /* calculate position for each sample */
5965 for (ss = 0; ss < bData->s_num[index]; ss++) {
5966 /* first sample is always point center */
5967 copy_v3_v3(bData->realCoord[bData->s_pos[index] + ss].v, canvas_verts[index].v);
5968 if (ss > 0) {
5969 int t_index = adj_data->n_index[index] + (ss - 1);
5970 /* get vertex position at 1/3 of each neigh edge */
5971 mul_v3_fl(bData->realCoord[bData->s_pos[index] + ss].v, 2.0f / 3.0f);
5972 madd_v3_v3fl(bData->realCoord[bData->s_pos[index] + ss].v,
5973 canvas_verts[adj_data->n_target[t_index]].v,
5974 1.0f / 3.0f);
5975 }
5976 }
5977
5978 /* normal */
5979 copy_v3_v3(temp_nor, data->vert_normals[index]);
5981 /* Prepare surface normal directional scale to easily convert
5982 * brush intersection amount between global and local space */
5983 float scaled_nor[3];
5984 mul_v3_v3v3(scaled_nor, temp_nor, ob->scale);
5985 bData->bNormal[index].normal_scale = len_v3(scaled_nor);
5986 }
5987 mul_mat3_m4_v3(ob->object_to_world().ptr(), temp_nor);
5988 normalize_v3(temp_nor);
5989 negate_v3_v3(bData->bNormal[index].invNorm, temp_nor);
5990 }
5991
5992 /* calculate speed vector */
5993 if (do_velocity_data && !new_bdata && !bData->clear) {
5994 sub_v3_v3v3(bData->velocity[index].v, bData->realCoord[bData->s_pos[index]].v, prev_point);
5995 }
5996}
5997
5999 Depsgraph *depsgraph,
6000 Object *ob)
6001{
6002 PaintSurfaceData *sData = surface->data;
6003 PaintBakeData *bData = sData->bData;
6005 int index;
6006 bool new_bdata = false;
6007 const bool do_velocity_data = ((surface->effect & MOD_DPAINT_EFFECT_DO_DRIP) ||
6008 (surface_getBrushFlags(surface, depsgraph) &
6010 const bool do_accel_data = (surface->effect & MOD_DPAINT_EFFECT_DO_DRIP) != 0;
6011
6012 int canvasNumOfVerts = mesh->verts_num;
6013 const Span<float3> positions = mesh->vert_positions();
6014 Vec3f *canvas_verts;
6015
6016 if (bData) {
6017 const bool surface_moved = dynamicPaint_surfaceHasMoved(surface, ob);
6018
6019 /* Get previous speed for acceleration. */
6020 if (do_accel_data && bData->prev_velocity && bData->velocity) {
6021 memcpy(bData->prev_velocity, bData->velocity, sData->total_points * sizeof(Vec3f));
6022 }
6023
6024 /* reset speed vectors */
6025 if (do_velocity_data && bData->velocity && (bData->clear || !surface_moved)) {
6026 memset(bData->velocity, 0, sData->total_points * sizeof(Vec3f));
6027 }
6028
6029 /* if previous data exists and mesh hasn't moved, no need to recalc */
6030 if (!surface_moved) {
6031 return true;
6032 }
6033 }
6034
6035 canvas_verts = MEM_new_array_uninitialized<Vec3f>(size_t(canvasNumOfVerts),
6036 "Dynamic Paint transformed canvas verts");
6037 if (!canvas_verts) {
6038 return false;
6039 }
6040
6041 /* allocate memory if required */
6042 if (!bData) {
6043 sData->bData = bData = MEM_new_zeroed<PaintBakeData>("Dynamic Paint bake data");
6044 if (!bData) {
6045 if (canvas_verts) {
6046 MEM_delete(canvas_verts);
6047 }
6048 return false;
6049 }
6050
6051 /* Init bdata */
6053 "Dynamic Paint step data");
6054 bData->s_pos = MEM_new_array_uninitialized<int>(size_t(sData->total_points),
6055 "Dynamic Paint bData s_pos");
6056 bData->s_num = MEM_new_array_uninitialized<int>(size_t(sData->total_points),
6057 "Dynamic Paint bData s_num");
6059 "Dynamic Paint point coords");
6061 size_t(canvasNumOfVerts), "Dynamic Paint bData prev_positions");
6062
6063 /* if any allocation failed, free everything */
6064 if (!bData->bNormal || !bData->s_pos || !bData->s_num || !bData->realCoord || !canvas_verts) {
6065 if (bData->bNormal) {
6066 MEM_delete(bData->bNormal);
6067 }
6068 if (bData->s_pos) {
6069 MEM_delete(bData->s_pos);
6070 }
6071 if (bData->s_num) {
6072 MEM_delete(bData->s_num);
6073 }
6074 if (bData->realCoord) {
6075 MEM_delete(bData->realCoord);
6076 }
6077 if (canvas_verts) {
6078 MEM_delete(canvas_verts);
6079 }
6080
6081 return setError(surface->canvas, N_("Not enough free memory"));
6082 }
6083
6084 new_bdata = true;
6085 }
6086
6087 if (do_velocity_data && !bData->velocity) {
6088 bData->velocity = MEM_new_array_zeroed<Vec3f>(sData->total_points, "Dynamic Paint velocity");
6089 }
6090 if (do_accel_data && !bData->prev_velocity) {
6092 "Dynamic Paint prev velocity");
6093 /* copy previous vel */
6094 if (bData->prev_velocity && bData->velocity) {
6095 memcpy(bData->prev_velocity, bData->velocity, sData->total_points * sizeof(Vec3f));
6096 }
6097 }
6098
6099 /*
6100 * Make a transformed copy of canvas evaluated-mesh vertices to avoid recalculation.
6101 */
6102 bData->mesh_bounds.valid = false;
6103 for (index = 0; index < canvasNumOfVerts; index++) {
6104 copy_v3_v3(canvas_verts[index].v, positions[index]);
6105 mul_m4_v3(ob->object_to_world().ptr(), canvas_verts[index].v);
6106 boundInsert(&bData->mesh_bounds, canvas_verts[index].v);
6107 }
6108
6109 /*
6110 * Prepare each surface point for a new step
6111 */
6113 data.surface = surface;
6114 data.ob = ob;
6115 data.positions = positions;
6116 data.vert_normals = mesh->vert_normals();
6117 data.canvas_verts = canvas_verts;
6118 data.do_velocity_data = do_velocity_data;
6119 data.new_bdata = new_bdata;
6120
6121 TaskParallelSettings settings;
6123 settings.use_threading = (sData->total_points > 1000);
6125 0, sData->total_points, &data, dynamic_paint_generate_bake_data_cb, &settings);
6126
6127 MEM_delete(canvas_verts);
6128
6129 /* generate surface space partitioning grid */
6130 surfaceGenerateGrid(surface);
6131 /* Calculate current frame adjacency point distances and global directions. */
6132 dynamicPaint_prepareAdjacencyData(surface, false);
6133
6134 /* Copy current frame vertices to check against in next frame */
6135 copy_m4_m4(bData->prev_obmat, ob->object_to_world().ptr());
6136 memcpy(bData->prev_positions, positions.data(), canvasNumOfVerts * sizeof(float[3]));
6137
6138 bData->clear = 0;
6139
6140 return true;
6141}
6142
6143/*
6144 * Do Dynamic Paint step. Paints scene brush objects of current state/frame to the surface.
6145 */
6146static int dynamicPaint_doStep(Depsgraph *depsgraph,
6147 Scene *scene,
6148 Object *ob,
6149 DynamicPaintSurface *surface,
6150 float timescale,
6151 float subframe)
6152{
6153 PaintSurfaceData *sData = surface->data;
6154 PaintBakeData *bData = sData->bData;
6156 const bool for_render = (DEG_get_mode(depsgraph) == DAG_EVAL_RENDER);
6157 int ret = 1;
6158
6159 if (sData->total_points < 1) {
6160 return 0;
6161 }
6162
6165 data.surface = surface;
6166 data.timescale = timescale;
6167
6168 TaskParallelSettings settings;
6170 settings.use_threading = (sData->total_points > 1000);
6172 0, sData->total_points, &data, dynamic_paint_surface_pre_step_cb, &settings);
6173 }
6174
6175 /*
6176 * Loop through surface's target paint objects and do painting
6177 */
6178 {
6179 uint numobjects;
6181 depsgraph, nullptr, surface->brush_group, &numobjects, eModifierType_DynamicPaint);
6182
6183 /* backup current scene frame */
6184 int scene_frame = scene->r.cfra;
6185 float scene_subframe = scene->r.subframe;
6186
6187 for (int i = 0; i < numobjects; i++) {
6188 Object *brushObj = objects[i];
6189
6190 /* check if target has an active dp modifier */
6192 if (md && md->mode & (eModifierMode_Realtime | eModifierMode_Render)) {
6193 DynamicPaintModifierData *pmd2 = reinterpret_cast<DynamicPaintModifierData *>(md);
6194 /* make sure we're dealing with a brush */
6195 if (pmd2->brush && pmd2->type == MOD_DYNAMICPAINT_TYPE_BRUSH) {
6197
6198 /* calculate brush speed vectors if required */
6199 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT && brush->flags & MOD_DPAINT_DO_SMUDGE) {
6200 bData->brush_velocity = MEM_new_array_zeroed<float>(4 * size_t(sData->total_points),
6201 "Dynamic Paint brush velocity");
6202 /* init adjacency data if not already */
6203 if (!sData->adj_data) {
6204 dynamicPaint_initAdjacencyData(surface, true);
6205 }
6206 if (!bData->bNeighs) {
6207 dynamicPaint_prepareAdjacencyData(surface, true);
6208 }
6209 }
6210
6211 /* update object data on this subframe */
6212 if (subframe) {
6213 scene_setSubframe(scene, subframe);
6215 scene,
6216 brushObj,
6217 true,
6219 BKE_scene_ctime_get(scene),
6221 }
6222
6223 /* Apply brush on the surface depending on its collision type */
6224 if (brush->psys && brush->psys->part &&
6225 ELEM(brush->psys->part->type,
6227 PART_FLUID,
6237 psys_check_enabled(brushObj, brush->psys, for_render))
6238 {
6239 /* Paint a particle system */
6240 dynamicPaint_paintParticles(surface, brush->psys, brush, timescale);
6241 }
6242 /* Object center distance: */
6243 if (brush->collision == MOD_DPAINT_COL_POINT && brushObj != ob) {
6245 depsgraph, surface, brushObj->loc, brush, brushObj, scene, timescale);
6246 }
6247 /* Mesh volume/proximity: */
6248 else if (brushObj != ob) {
6249 dynamicPaint_paintMesh(depsgraph, surface, brush, brushObj, scene, timescale);
6250 }
6251
6252 /* reset object to its original state */
6253 if (subframe) {
6254 scene->r.cfra = scene_frame;
6255 scene->r.subframe = scene_subframe;
6257 scene,
6258 brushObj,
6259 true,
6261 BKE_scene_ctime_get(scene),
6263 }
6264
6265 /* process special brush effects, like smudge */
6266 if (bData->brush_velocity) {
6267 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT && brush->flags & MOD_DPAINT_DO_SMUDGE)
6268 {
6269 dynamicPaint_doSmudge(surface, brush, timescale);
6270 }
6271 MEM_delete(bData->brush_velocity);
6272 bData->brush_velocity = nullptr;
6273 }
6274 }
6275 }
6276 }
6277
6279 }
6280
6281 /* surfaces operations that use adjacency data */
6282 if (sData->adj_data && bData->bNeighs) {
6283 /* wave type surface simulation step */
6284 if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) {
6285 dynamicPaint_doWaveStep(surface, timescale);
6286 }
6287
6288 /* paint surface effects */
6289 if (surface->effect && surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
6290 int steps = 1, s;
6291 PaintPoint *prevPoint;
6292 float *force = nullptr;
6293
6294 /* Allocate memory for surface previous points to read unchanged values from */
6295 prevPoint = MEM_new_array_uninitialized<PaintPoint>(size_t(sData->total_points),
6296 "PaintSurfaceDataCopy");
6297 if (!prevPoint) {
6298 return setError(canvas, N_("Not enough free memory"));
6299 }
6300
6301 /* Prepare effects and get number of required steps */
6302 steps = dynamicPaint_prepareEffectStep(depsgraph, surface, scene, ob, &force, timescale);
6303 for (s = 0; s < steps; s++) {
6304 dynamicPaint_doEffectStep(surface, force, prevPoint, timescale, float(steps));
6305 }
6306
6307 /* Free temporary effect data */
6308 if (prevPoint) {
6309 MEM_delete(prevPoint);
6310 }
6311 if (force) {
6312 MEM_delete(force);
6313 }
6314 }
6315
6316 /* paint island border pixels */
6317 if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) {
6319 }
6320 }
6321
6322 return ret;
6323}
6324
6326 DynamicPaintSurface *surface, Depsgraph *depsgraph, Scene *scene, Object *cObject, int frame)
6327{
6328 float timescale = 1.0f;
6329
6330 /* Apply previous displace on evaluated-mesh if incremental surface. */
6331 if (surface->flags & MOD_DPAINT_DISP_INCREMENTAL) {
6333 }
6334
6335 /* update bake data */
6336 dynamicPaint_generateBakeData(surface, depsgraph, cObject);
6337
6338 /* don't do substeps for first frame */
6339 if (surface->substeps && (frame != surface->start_frame)) {
6340 int st;
6341 timescale = 1.0f / (surface->substeps + 1);
6342
6343 for (st = 1; st <= surface->substeps; st++) {
6344 float subframe = float(st) / (surface->substeps + 1);
6345 if (!dynamicPaint_doStep(depsgraph, scene, cObject, surface, timescale, subframe)) {
6346 return 0;
6347 }
6348 }
6349 }
6350
6351 return dynamicPaint_doStep(depsgraph, scene, cObject, surface, timescale, 0.0f);
6352}
6353
6354} // namespace blender
CustomData interface, see also DNA_customdata_types.h.
support for deformation groups and hooks.
#define DPAINT_PAINT_NEW
#define DPAINT_PAINT_DRY
#define DPAINT_WAVE_ISECT_CHANGED
#define DPAINT_WAVE_REFLECT_ONLY
#define DPAINT_PAINT_WET
#define DPAINT_WAVE_NONE
#define DPAINT_WAVE_OBSTACLE
General operations, lookup, etc. for materials.
General operations, lookup, etc. for blender objects.
#define PTCACHE_RESET_OUTDATED
File and directory operations.
A KD-tree for nearest neighbor search.
#define M_PI_2
#define FILE_MAX
#define BLI_path_cmp
#define SNPRINTF(dst, format,...)
#define STRNCPY_UTF8(dst, src)
#define BLT_I18NCONTEXT_ID_BRUSH
#define CTX_DATA_(context, msgid)
#define CLOG_DEBUG(clg_ref,...)
Definition CLG_log.h:191
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
#define CLOG_STR_ERROR(clg_ref, str)
Definition CLG_log.h:196
Object is a sort of wrapper for general info.
Read Blender memory allocation and freeing.
Provides wrapper around system-specific atomic primitives, and some extensions (faked-atomic operatio...
ATOMIC_INLINE uint8_t atomic_fetch_and_and_uint8(uint8_t *p, uint8_t b)
ATOMIC_INLINE uint8_t atomic_fetch_and_or_uint8(uint8_t *p, uint8_t b)
ATOMIC_INLINE uint32_t atomic_add_and_fetch_uint32(uint32_t *p, uint32_t x)
volatile int lock
#define CLAMP(a, b, c)
#define CLAMP_MAX(a, c)
#define BLI_INLINE
#define UNPACK3(a)
#define ELEM(...)
#define STREQ(a, b)
#define CLAMP_MIN(a, b)
btScalar max
#define output
SIMD_FORCE_INLINE const btScalar & z() const
Return the z value.
Definition btQuadWord.h:117
SIMD_FORCE_INLINE const btScalar & w() const
Return the w value.
Definition btQuadWord.h:119
constexpr bool is_empty() const
Definition BLI_span.hh:515
constexpr Span slice(int64_t start, int64_t size) const
Definition BLI_span.hh:141
constexpr const T * data() const
Definition BLI_span.hh:219
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
constexpr const char * c_str() const
bool contains(const Key &key) const
std::optional< AttributeMetaData > lookup_meta_data(StringRef name) const
GAttributeReader lookup(const StringRef name) const
GSpanAttributeWriter lookup_or_add_for_write_span(StringRef name, AttrDomain domain, AttrType data_type, const AttributeInit &initializer=AttributeInitDefaultValue())
GSpanAttributeWriter lookup_for_write_span(StringRef name)
constexpr bool is_empty() const
#define powf(x, y)
#define acosf(x)
#define NOT_FOUND
#define HIT_VOLUME
#define EFF_MOVEMENT_PER_FRAME
#define WAVE_TIME_FAC
#define CANVAS_REL_SIZE
#define MAX_WETNESS
#define HIT_PROXIMITY
#define JITTER_SAMPLES
#define ADJ_ON_MESH_EDGE
#define SUBFRAME_RECURSION
#define MIN_WETNESS
#define ADJ_BORDER_PIXEL
#define BRUSH_USES_VELOCITY
#define ON_MESH_EDGE
#define OUT_OF_TEXTURE
#define str(s)
void mix_color(float fac, float4 col1, float4 col2, float4 &outcol)
#define FLT_MAX
#define isnan
#define pow
float dot(VecOp< float, D >, VecOp< float, D >) RET
#define floor
float distance(float, float) RET
#define ceil
VecBase< float, D > step(VecOp< float, D >, VecOp< float, D >) RET
float3x3 scale(float3x3 mat, float2 scale)
T distance(const T &a, const T &b)
MatBase< T, NumCol, NumRow > normalize(const MatBase< T, NumCol, NumRow > &a)
BMesh Iterators.
MINLINE float min_ff(float a, float b)
MINLINE void madd_v3_v3v3fl(float r[3], const float a[3], const float b[3], float f)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
static void dynamicPaint_brushMeshCalculateVelocity(Depsgraph *depsgraph, Scene *scene, Object *ob, DynamicPaintBrushSettings *brush, Vec3f **brushVel, float timescale)
int BKE_ptcache_read(PTCacheID *pid, float cfra, bool no_extrapolate_old)
static int dynamicPaint_surfaceNumOfPoints(DynamicPaintSurface *surface)
MINLINE void negate_v3_v3(float r[3], const float a[3])
bool dynamicPaint_resetSurface(const struct Scene *scene, struct DynamicPaintSurface *surface)
void kdtree_balance(KDTree< CoordT > *tree)
MINLINE void rgba_uchar_to_float(float r_col[4], const unsigned char col_ub[4])
static void dynamicPaint_allocateSurfaceType(DynamicPaintSurface *surface)
void dynamicPaint_freeSurface(const struct DynamicPaintModifierData *pmd, struct DynamicPaintSurface *surface)
static int dynamicPaint_doStep(Depsgraph *depsgraph, Scene *scene, Object *ob, DynamicPaintSurface *surface, float timescale, float subframe)
char * STRNCPY(char(&dst)[N], const char *src)
static int surface_getBrushFlags(DynamicPaintSurface *surface, Depsgraph *depsgraph)
void dynamicPaint_outputSurfaceImage(struct DynamicPaintSurface *surface, const char *filepath, short output_layer)
static int neighStraightY[8]
MINLINE unsigned char unit_float_to_uchar_clamp(float val)
static void dynamicPaint_applySurfaceDisplace(DynamicPaintSurface *surface, Mesh *result)
void interp_v4_v4v4v4(float p[4], const float v1[4], const float v2[4], const float v3[4], const float w[3])
void dynamicPaint_Modifier_copy(const struct DynamicPaintModifierData *pmd, struct DynamicPaintModifierData *tpmd, int flag)
BLI_INLINE void BLI_parallel_range_settings_defaults(TaskParallelSettings *settings)
static void grid_bound_insert_cb_ex(void *__restrict userdata, const int i, const TaskParallelTLS *__restrict tls)
MINLINE void copy_v3_v3(float r[3], const float a[3])
unsigned int uint
Definition BKE_text.h:55
struct DynamicPaintSurface * dynamicPaint_createNewSurface(struct DynamicPaintCanvasSettings *canvas, struct Scene *scene)
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
static void dynamicPaint_brushObjectCalculateVelocity(Depsgraph *depsgraph, Scene *scene, Object *ob, Vec3f *brushVel, float timescale)
bool BLI_path_abs(char path[FILE_MAX], const char *basepath) ATTR_NONNULL(1
static void dynamic_paint_apply_surface_vpaint_blend_cb(void *__restrict userdata, const int i, const TaskParallelTLS *__restrict)
static void dynamic_paint_create_uv_surface_direct_cb(void *__restrict userdata, const int ty, const TaskParallelTLS *__restrict)
static void dynamic_paint_apply_surface_vpaint_cb(void *__restrict userdata, const int p_index, const TaskParallelTLS *__restrict)
void dynamicPaint_clearSurface(const struct Scene *scene, struct DynamicPaintSurface *surface)
static void free_bakeData(PaintSurfaceData *data)
void minmax_v3v3_v3(float min[3], float max[3], const float vec[3])
static void dynamic_paint_output_surface_image_wetmap_cb(void *__restrict userdata, const int index, const TaskParallelTLS *__restrict)
static bool dynamicPaint_paintMesh(Depsgraph *depsgraph, DynamicPaintSurface *surface, DynamicPaintBrushSettings *brush, Object *brushOb, Scene *scene, float timescale)
static void dynamic_paint_surface_pre_step_cb(void *__restrict userdata, const int index, const TaskParallelTLS *__restrict)
static bool boundsIntersectDist(Bounds3D *b1, Bounds3D *b2, const float dist)
static void dynamic_paint_prepare_adjacency_cb(void *__restrict userdata, const int index, const TaskParallelTLS *__restrict)
static void dynamic_paint_effect_spread_cb(void *__restrict userdata, const int index, const TaskParallelTLS *__restrict)
MINLINE void mul_v2_fl(float r[2], float f)
Mesh * BKE_mesh_copy_for_eval(const Mesh &source)
bool dynamicPaint_outputLayerExists(struct DynamicPaintSurface *surface, struct Object *ob, int output)
MINLINE void copy_v2_v2(float r[2], const float a[2])
void dynamicPaint_Modifier_free_runtime(struct DynamicPaintRuntime *runtime)
void dynamicPaint_freeSurfaceData(struct DynamicPaintSurface *surface)
static void dynamicPaint_mixWaveHeight(PaintWavePoint *wPoint, const DynamicPaintBrushSettings *brush, float isect_height)
void dynamicPaint_freeBrush(struct DynamicPaintModifierData *pmd)
int BKE_ptcache_id_reset(struct Scene *scene, PTCacheID *pid, int mode)
static void dynamic_paint_wave_step_cb(void *__restrict userdata, const int index, const TaskParallelTLS *__restrict)
static bool meshBrush_boundsIntersect(Bounds3D *b1, Bounds3D *b2, DynamicPaintBrushSettings *brush, float brush_radius)
static DynamicPaintRuntime * dynamicPaint_Modifier_runtime_ensure(DynamicPaintModifierData *pmd)
static void dynamic_paint_brush_velocity_compute_cb(void *__restrict userdata, const int i, const TaskParallelTLS *__restrict)
@ eModifierType_DynamicPaint
static void dynamicPaint_frameUpdate(DynamicPaintModifierData *pmd, Depsgraph *depsgraph, Scene *scene, Object *ob, Mesh *mesh)
static void dynamicPaint_prepareAdjacencyData(DynamicPaintSurface *surface, const bool force_init)
static const float gaussianFactors[5]
static void dynamicPaint_doWaveStep(DynamicPaintSurface *surface, float timescale)
static void dynamic_paint_set_init_color_tex_to_imseq_cb(void *__restrict userdata, const int i, const TaskParallelTLS *__restrict)
static void dynamicPaint_setInitialColor(const Scene *, DynamicPaintSurface *surface)
static void dynamicPaint_updatePointData(const DynamicPaintSurface *surface, const int index, const DynamicPaintBrushSettings *brush, float paint[3], float influence, float depth, float vel_factor, const float timescale)
static bool surface_usesAdjDistance(DynamicPaintSurface *surface)
MINLINE void add_v3_fl(float r[3], float f)
MINLINE void sub_v2_v2v2(float r[2], const float a[2], const float b[2])
void BKE_effectors_apply(ListBaseT< EffectorCache > *effectors, ListBaseT< ColliderCache > *colliders, struct EffectorWeights *weights, struct EffectedPoint *point, float *force, float *wind_force, float *impulse)
Definition effect.cc:1134
ColorBand * BKE_colorband_add(bool rangetype)
Definition colorband.cc:301
const char * BKE_main_blendfile_path_from_global()
Definition main.cc:1063
bool BKE_colorband_evaluate(const ColorBand *coba, float in, float out[4])
Definition colorband.cc:399
void BLI_task_parallel_range(int start, int stop, void *userdata, TaskParallelRangeFunc func, const TaskParallelSettings *settings)
ATTR_WARN_UNUSED_RESULT const BMVert * v
@ PART_FLUID_SPRAYFOAMBUBBLE
int isect_point_tri_v2(const float pt[2], const float v1[2], const float v2[2], const float v3[2])
static void dynamic_paint_set_init_color_tex_to_vcol_cb(void *__restrict userdata, const int i, const TaskParallelTLS *__restrict)
static Mesh * dynamicPaint_Modifier_apply(DynamicPaintModifierData *pmd, Object *ob, Mesh *mesh)
static void surface_determineForceTargetPoints(const PaintSurfaceData *sData, const int index, const float force[3], float closest_d[2], int closest_id[2])
static void freeGrid(PaintSurfaceData *data)
@ LIB_ID_COPY_SET_COPIED_ON_WRITE
bool dynamicPaint_createType(struct DynamicPaintModifierData *pmd, int type, struct Scene *scene)
MINLINE void mul_v3_fl(float r[3], float f)
static bool boundIntersectPoint(Bounds3D *b, const float point[3], const float radius)
static Mesh * dynamicPaint_canvas_mesh_get(DynamicPaintCanvasSettings *canvas)
float dist_squared_to_line_segment_v2(const float p[2], const float l1[2], const float l2[2])
Definition math_geom.cc:307
static bool dynamic_paint_surface_needs_dry_dissolve(DynamicPaintSurface *surface)
struct DynamicPaintSurface * get_activeSurface(struct DynamicPaintCanvasSettings *canvas)
MINLINE void sub_v3_v3(float r[3], const float a[3])
static bool setError(DynamicPaintCanvasSettings *canvas, const char *string)
KDTree< CoordT > * kdtree_new(uint nodes_len_capacity)
Definition BLI_kdtree.hh:65
static void dynamic_paint_effect_shrink_cb(void *__restrict userdata, const int index, const TaskParallelTLS *__restrict)
void mul_m4_v3(const float M[4][4], float r[3])
size_t void BLI_uniquename_cb(FunctionRef< bool(StringRefNull)> unique_check, const char *defname, char delim, char *name, size_t name_maxncpy) ATTR_NONNULL(2
bool IMB_save_image(ImBuf *ibuf, const char *filepath, ImBufFlags flags)
Definition writeimage.cc:40
MINLINE void madd_v3_v3fl(float r[3], const float a[3], float f)
MINLINE bool equals_v3v3(const float v1[3], const float v2[3]) ATTR_WARN_UNUSED_RESULT
void * BLI_findlink(const ListBase *listbase, int number) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:541
static int dynamic_paint_find_neighbor_pixel(const DynamicPaintCreateUVSurfaceData *data, const MeshElemMap *vert_to_tri_map, const int w, const int h, const int px, const int py, const int n_index)
unsigned int uint32_t
Definition BKE_text.h:81
static void dynamic_paint_apply_surface_displace_cb(void *__restrict userdata, const int i, const TaskParallelTLS *__restrict)
static void grid_bound_insert_reduce(const void *__restrict, void *__restrict chunk_join, void *__restrict chunk)
void IMB_freeImBuf(ImBuf *ibuf)
VecBase< float, 2 > float2
static void grid_cell_points_reduce(const void *__restrict userdata, void *__restrict chunk_join, void *__restrict chunk)
VecBase< int32_t, 3 > int3
void * MEM_new_zeroed(size_t len, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2)
static float getSurfaceDimension(PaintSurfaceData *sData)
unsigned char uchar
Definition BKE_text.h:58
MINLINE void cross_v3_v3v3(float r[3], const float a[3], const float b[3])
void dynamicPaint_freeCanvas(struct DynamicPaintModifierData *pmd)
int BKE_ptcache_write(PTCacheID *pid, unsigned int cfra)
static void dynamic_paint_set_init_color_vcol_to_imseq_cb(void *__restrict userdata, const int i, const TaskParallelTLS *__restrict)
void minmax_v2v2_v2(float min[2], float max[2], const float vec[2])
BLI_INLINE void value_dissolve(float *r_value, const float time, const float scale, const bool is_log)
void BLI_remlink(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:138
static void dynamic_paint_create_uv_surface_neighbor_cb(void *__restrict userdata, const int ty, const TaskParallelTLS *__restrict)
BMesh const char void * data
static void boundInsert(Bounds3D *b, const float point[3])
static void dynamicPaint_mixPaintColors(const DynamicPaintSurface *surface, const int index, const int paintFlags, const float paintColor[3], const float paintAlpha, const float paintWetness, const float timescale)
static void dynamic_paint_output_surface_image_paint_cb(void *__restrict userdata, const int index, const TaskParallelTLS *__restrict)
static bool dynamicPaint_paintSinglePoint(Depsgraph *depsgraph, DynamicPaintSurface *surface, float *pointCoord, DynamicPaintBrushSettings *brush, Object *brushOb, Scene *scene, float timescale)
void interp_weights_tri_v3(float w[3], const float v1[3], const float v2[3], const float v3[3], const float co[3])
static void dynamicPaint_doEffectStep(DynamicPaintSurface *surface, float *force, PaintPoint *prevPoint, float timescale, float steps)
void kdtree_insert(KDTree< CoordT > *tree, int index, const CoordT &co)
Definition BLI_kdtree.hh:96
unsigned char uint8_t
Definition BKE_text.h:79
void dynamicPaint_cacheUpdateFrames(struct DynamicPaintSurface *surface)
int kdtree_find_nearest(const KDTree< CoordT > *tree, const CoordT &co, KDTreeNearest< CoordT > *r_nearest)
MDeformWeight * BKE_defvert_ensure_index(MDeformVert *dv, int defgroup)
Definition deform.cc:830
int BKE_object_defgroup_name_index(const Object *ob, StringRef name)
Definition deform.cc:597
MINLINE void negate_v3(float r[3])
bool equals_m4m4(const float mat1[4][4], const float mat2[4][4])
void BKE_ptcache_id_time(PTCacheID *pid, struct Scene *scene, float cfra, int *startframe, int *endframe, float *timescale)
void interp_v3_v3v3(float r[3], const float a[3], const float b[3], float t)
struct Mesh * dynamicPaint_Modifier_do(struct DynamicPaintModifierData *pmd, struct Depsgraph *depsgraph, struct Scene *scene, struct Object *ob, struct Mesh *mesh)
static void surface_freeUnusedData(DynamicPaintSurface *surface)
static bool dynamicPaint_checkSurfaceData(const Scene *scene, DynamicPaintSurface *surface)
static bool dynamicPaint_pointHasNeighbor(PaintAdjData *ed, int index, int neighbor)
ATTR_WARN_UNUSED_RESULT const size_t num
MINLINE float len_v3(const float a[3]) ATTR_WARN_UNUSED_RESULT
void BKE_object_modifier_update_subframe(Depsgraph *depsgraph, Scene *scene, Object *ob, bool update_mesh, int parent_recursion_limit, float frame, int modifier_type)
Definition object.cc:5624
void BKE_ptcache_id_from_dynamicpaint(PTCacheID *pid, struct Object *ob, struct DynamicPaintSurface *surface)
void BKE_image_pool_free(ImagePool *pool)
void BKE_id_free(Main *bmain, void *idv)
eEvaluationMode DEG_get_mode(const Depsgraph *graph)
bool psys_check_enabled(struct Object *ob, struct ParticleSystem *psys, bool use_render_params)
Definition particle.cc:739
void BKE_mesh_vert_corner_tri_map_create(MeshElemMap **r_map, int **r_mem, int totvert, const int3 *corner_tris, int tris_num, const int *corner_verts, int corners_num)
MINLINE bool equals_v2v2(const float v1[2], const float v2[2]) ATTR_WARN_UNUSED_RESULT
static void dynamic_paint_generate_bake_data_cb(void *__restrict userdata, const int index, const TaskParallelTLS *__restrict)
static bool surface_duplicateNameExists(DynamicPaintSurface *t_surface, const StringRefNull name)
static int dynamicPaint_prepareEffectStep(Depsgraph *depsgraph, DynamicPaintSurface *surface, Scene *scene, Object *ob, float **force, float timescale)
void mul_mat3_m4_v3(const float mat[4][4], float r[3])
static int neighStraightX[8]
static float mixColors(float a_color[3], float a_weight, const float b_color[3], float b_weight, float ratio)
MINLINE float normalize_v3_v3(float r[3], const float a[3])
ImBuf * IMB_allocImBuf(unsigned int x, unsigned int y, ImBufFlags flags)
static void dynamic_paint_apply_surface_wave_cb(void *__restrict userdata, const int i, const TaskParallelTLS *__restrict)
void BKE_ptcache_validate(struct PointCache *cache, int framenr)
MINLINE void mul_v3_v3fl(float r[3], const float a[3], float f)
MINLINE float normalize_v3(float n[3])
static bool surface_duplicateOutputExists(DynamicPaintSurface *t_surface, const StringRefNull name)
static bool boundsIntersect(Bounds3D *b1, Bounds3D *b2)
ModifierData * BKE_modifiers_findby_type(const Object *ob, ModifierType type)
MINLINE void add_v3_v3(float r[3], const float a[3])
void kdtree_free(KDTree< CoordT > *tree)
Definition BLI_kdtree.hh:84
static int neighY[8]
MINLINE void sub_v3_v3v3(float r[3], const float a[3], const float b[3])
void pd_point_from_loc(struct Scene *scene, float *loc, float *vel, int index, struct EffectedPoint *point)
Definition effect.cc:424
static void dynamic_paint_effect_drip_cb(void *__restrict userdata, const int index, const TaskParallelTLS *__restrict)
void BKE_ptcache_free_list(ListBaseT< PointCache > *ptcaches)
static bool dynamicPaint_paintParticles(DynamicPaintSurface *surface, ParticleSystem *psys, DynamicPaintBrushSettings *brush, float timescale)
void BLI_addtail(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:118
static void dynamic_paint_prepare_effect_cb(void *__restrict userdata, const int index, const TaskParallelTLS *__restrict)
static const float gaussianTotal
ATTR_WARN_UNUSED_RESULT const BMVert * v2
float BKE_scene_ctime_get(const Scene *scene)
Definition scene.cc:2581
MINLINE void copy_v3_fl(float r[3], float f)
struct Object ** BKE_collision_objects_create(struct Depsgraph *depsgraph, struct Object *self, struct Collection *collection, unsigned int *numcollobj, unsigned int modifier_type)
static void surface_setUniqueOutputName(DynamicPaintSurface *surface, char *basename, int output)
static void dynamicPaint_freeAdjData(PaintSurfaceData *data)
int multitex_ext_safe(Tex *tex, const float texvec[3], TexResult *texres, ImagePool *pool, bool scene_color_manage, const bool skip_load_image)
static void scene_setSubframe(Scene *scene, float subframe)
static int surface_totalSamples(DynamicPaintSurface *surface)
MINLINE float max_ff(float a, float b)
std::mutex Mutex
Definition BLI_mutex.hh:51
static void blendColors(const float t_color[3], const float t_alpha, const float s_color[3], const float s_alpha, float result[4])
static void dynamic_paint_output_surface_image_displace_cb(void *__restrict userdata, const int index, const TaskParallelTLS *__restrict)
static void dynamic_paint_find_island_border(const DynamicPaintCreateUVSurfaceData *data, DynamicPaintFindIslandBorderData *bdata, int tri_index, const float pixel[2], int in_edge, int depth)
ListBaseT< EffectorCache > * BKE_effectors_create(struct Depsgraph *depsgraph, struct Object *ob_src, struct ParticleSystem *psys_src, struct EffectorWeights *weights, bool use_rotation)
Definition effect.cc:316
static bool dynamicPaint_generateBakeData(DynamicPaintSurface *surface, Depsgraph *depsgraph, Object *ob)
static void surfaceGenerateGrid(DynamicPaintSurface *surface)
int dynamicPaint_calculateFrame(struct DynamicPaintSurface *surface, struct Depsgraph *depsgraph, struct Scene *scene, struct Object *cObject, int frame)
float closest_to_line_v2(float r_close[2], const float p[2], const float l1[2], const float l2[2])
static void canvas_copyMesh(DynamicPaintCanvasSettings *canvas, Mesh *mesh)
struct PointCache * BKE_ptcache_add(ListBaseT< PointCache > *ptcaches)
static void dynamic_paint_output_surface_image_wave_cb(void *__restrict userdata, const int index, const TaskParallelTLS *__restrict)
static void dynamicPaint_doSmudge(DynamicPaintSurface *surface, DynamicPaintBrushSettings *brush, float timescale)
MINLINE float square_f(float a)
int kdtree_range_search(const KDTree< CoordT > *tree, const CoordT &co, KDTreeNearest< CoordT > **r_nearest, typename KDTree< CoordT >::ValueType range)
MINLINE float line_point_side_v2(const float l1[2], const float l2[2], const float pt[2]) ATTR_WARN_UNUSED_RESULT
static CLG_LogRef LOG
Definition logging.cpp:12
static void dynamicPaint_doBorderStep(DynamicPaintSurface *surface)
MINLINE void copy_v4_v4(float r[4], const float a[4])
static void dynamic_paint_border_cb(void *__restrict userdata, const int b_index, const TaskParallelTLS *__restrict)
void copy_m4_m4(float m1[4][4], const float m2[4][4])
VecBase< float, 3 > float3
void dynamicPaintSurface_setUniqueName(struct DynamicPaintSurface *surface, const char *basename)
void interp_v3_v3v3v3(float p[3], const float v1[3], const float v2[3], const float v3[3], const float w[3])
static void dynamic_paint_paint_single_point_cb_ex(void *__restrict userdata, const int index, const TaskParallelTLS *__restrict)
static bool dynamicPaint_symmetrizeAdjData(PaintAdjData *ed, int active_points)
static void dynamic_paint_paint_mesh_cell_point_cb_ex(void *__restrict userdata, const int id, const TaskParallelTLS *__restrict)
static bool surface_usesAdjData(DynamicPaintSurface *surface)
MINLINE float len_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
static void dynamicPaint_initAdjacencyData(DynamicPaintSurface *surface, const bool force_init)
MINLINE void mul_v3_v3v3(float r[3], const float v1[3], const float v2[3])
static float dist_squared_to_corner_tris_uv_edges(const Span< int3 > corner_tris, const Span< float2 > uv_map, int tri_index, const float point[2])
void barycentric_weights_v2(const float v1[2], const float v2[2], const float v3[2], const float co[2], float w[3])
static void dynamic_paint_paint_particle_cell_point_cb_ex(void *__restrict userdata, const int id, const TaskParallelTLS *__restrict)
int BKE_image_path_ext_from_imtype_ensure(char *filepath, size_t filepath_maxncpy, char imtype)
struct EffectorWeights * BKE_effector_add_weights(struct Collection *collection)
Definition effect.cc:63
MINLINE float dot_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
void dynamicPaint_Modifier_free(struct DynamicPaintModifierData *pmd)
static void grid_cell_bounds_cb(void *__restrict userdata, const int x, const TaskParallelTLS *__restrict)
void BKE_modifier_path_init(char *path, int path_maxncpy, const char *name)
bool BLI_file_ensure_parent_dir_exists(const char *filepath) ATTR_NONNULL(1)
Definition fileops_c.cc:454
int dynamicPaint_createUVSurface(struct Scene *scene, struct DynamicPaintSurface *surface, float *progress, bool *do_update)
void BKE_collision_objects_free(struct Object **objects)
static int neighX[8]
ColorSceneLinearByteEncoded4b< eAlpha::Premultiplied > ColorGeometry4b
MINLINE void rgba_float_to_uchar(unsigned char r_col[4], const float col_f[4])
void BKE_effectors_free(ListBaseT< EffectorCache > *lb)
Definition effect.cc:371
MDeformWeight * BKE_defvert_find_index(const MDeformVert *dv, int defgroup)
Definition deform.cc:811
static bool dynamicPaint_surfaceHasMoved(DynamicPaintSurface *surface, Object *ob)
static void grid_cell_points_cb_ex(void *__restrict userdata, const int i, const TaskParallelTLS *__restrict tls)
void * MEM_new_array_zeroed(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
MINLINE void madd_v2_v2v2fl(float r[2], const float a[2], const float b[2], float f)
void dynamicPaintSurface_updateType(struct DynamicPaintSurface *surface)
#define mix
#define floorf
#define fabsf
#define sqrtf
#define ceilf
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
#define min(a, b)
Definition sort.cc:38
struct DynamicPaintModifierData * pmd
ListBaseT< DynamicPaintSurface > surfaces
struct DynamicPaintModifierData * pmd
const DynamicPaintSurface * surface
const DynamicPaintSurface * surface
const DynamicPaintSurface * surface
ListBaseT< EffectorCache > * effectors
const DynamicPaintSurface * surface
const DynamicPaintSurface * surface
MutableSpan< ColorGeometry4b > mloopcol_wet
MutableSpan< ColorGeometry4b > mloopcol
struct DynamicPaintBrushSettings * brush
struct DynamicPaintCanvasSettings * canvas
const DynamicPaintSurface * surface
const ParticleSystem * psys
const DynamicPaintBrushSettings * brush
const DynamicPaintSurface * surface
struct DynamicPaintCanvasSettings * canvas
eDynamicPaint_EffectFlags effect
eDynamicPaint_SurfaceFormat format
eDynamicPaint_ImageFormat image_fileformat
struct EffectorWeights * effector_weights
eDynamicPaint_SurfaceFlags flags
eDynamicPaint_InitColorType init_color_type
struct DynamicPaintSurface * next
ImbFormatOptions foptions
eImbFileType ftype
float * float_data_for_write()
Definition allocimbuf.cc:79
struct PointCache * cache
DynamicPaintVolumeGrid * grid
PaintBakeNormal * bNormal
ImgSeqFormatData * format_data
struct PaintBakeData * bData
struct PhysicsSettings physics_settings
struct RenderData r
TaskParallelReduceFunc func_reduce
#define N_(msgid)