Blender V5.3
draw_cache_impl_particles.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2017 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
10
11#include "BLI_color_types.hh"
13#include "DNA_curves_types.h"
14#include "DNA_scene_types.h"
15#include "DRW_render.hh"
16
17#include "MEM_guardedalloc.h"
18
19#include "BLI_alloca.hh"
20#include "BLI_math_color_c.hh"
21#include "BLI_math_vector_c.hh"
22#include "BLI_offset_indices.hh"
23#include "BLI_string_utf8.hh"
24#include "BLI_utildefines.hh"
25
27#include "DNA_mesh_types.h"
28#include "DNA_meshdata_types.h"
29#include "DNA_modifier_types.h"
30#include "DNA_particle_types.h"
31
32#include "BKE_customdata.hh"
33#include "BKE_mesh.hh"
35#include "BKE_particle.h"
36#include "BKE_pointcache.h"
37
38#include "ED_particle.hh"
39
40#include "GPU_batch.hh"
41#include "GPU_capabilities.hh"
42#include "GPU_material.hh"
43
45
47
48#include "draw_attributes.hh"
49#include "draw_cache_impl.hh" /* own include */
50#include "draw_hair_private.hh"
51
52namespace blender::draw {
53
54static void particle_batch_cache_clear(ParticleSystem *psys);
55
56/* ---------------------------------------------------------------------- */
57/* Particle gpu::Batch Cache */
58
60 /* Output of the subdivision stage: vertex buff sized to subdiv level. */
62
63 /* Just contains a huge index buffer used to draw the final hair. */
65
66 int strands_res; /* points per hair, at least 2 */
67};
68
72 gpu::Batch *hairs;
76
77 /* Equivalent to the new Curves data structure.
78 * Allows to create the eval cache. */
81
83};
84
91
93 /* Object mode strands for hair and points for particle,
94 * strands for paths when in edit mode.
95 */
96 ParticleHairCache hair; /* Used for hair strands */
97 ParticlePointCache point; /* Used for particle points. */
98
99 /* Control points when in edit mode. */
101
103 gpu::Batch *edit_strands;
104
106 gpu::Batch *edit_inner_points;
108
110 gpu::Batch *edit_tip_points;
112
113 /* Settings to determine if cache is invalid. */
116};
117
118/* gpu::Batch cache management. */
119
125
127 float pos[3];
129};
130
131static const GPUVertFormat *edit_points_vert_format_get(uint *r_pos_id, uint *r_selection_id)
132{
133 static uint pos_id, selection_id;
134 static const GPUVertFormat edit_point_format = [&]() {
135 GPUVertFormat format{};
136 pos_id = GPU_vertformat_attr_add(&format, "pos", gpu::VertAttrType::SFLOAT_32_32_32);
137 selection_id = GPU_vertformat_attr_add(&format, "selection", gpu::VertAttrType::SFLOAT_32);
138 return format;
139 }();
140 *r_pos_id = pos_id;
141 *r_selection_id = selection_id;
142 return &edit_point_format;
143}
144
146{
147 ParticleBatchCache *cache = psys->batch_cache;
148
149 if (cache == nullptr) {
150 return false;
151 }
152
153 if (cache->is_dirty == false) {
154 return true;
155 }
156
157 return false;
158
159 return true;
160}
161
163{
164 ParticleBatchCache *cache = psys->batch_cache;
165
166 if (!cache) {
167 cache = MEM_new<ParticleBatchCache>(__func__);
168 psys->batch_cache = cache;
169 }
170 else {
171 cache->edit_hair.eval_cache = {};
172 cache->hair.eval_cache = {};
173 }
174
175 cache->is_dirty = false;
176}
177
186
188{
189 ParticleBatchCache *cache = psys->batch_cache;
190 if (cache == nullptr) {
191 return;
192 }
193 switch (mode) {
195 cache->is_dirty = true;
196 break;
197 default:
198 BLI_assert(0);
199 }
200}
201
203{
204 GPU_BATCH_DISCARD_SAFE(point_cache->points);
205 GPU_VERTBUF_DISCARD_SAFE(point_cache->pos);
206}
207
209{
210 /* TODO: more granular update tagging. */
211
212 /* "Normal" legacy hairs */
213 GPU_BATCH_DISCARD_SAFE(hair_cache->hairs);
214 GPU_VERTBUF_DISCARD_SAFE(hair_cache->pos);
216
218 hair_cache->points_by_curve_storage.clear();
219
220 hair_cache->eval_cache.clear();
221}
222
224{
225 ParticleBatchCache *cache = psys->batch_cache;
226 if (!cache) {
227 return;
228 }
229
230 /* All memory allocated by `cache` must be freed. */
231
233
236
241}
242
244{
246 ParticleBatchCache *batch_cache = psys->batch_cache;
247 MEM_delete(batch_cache);
248 psys->batch_cache = nullptr;
249}
250
252{
253 for (const auto &particle : parent) {
254 callback(Span<ParticleCacheKey>(particle, particle->segments + 1));
255 }
256 for (const auto &particle : children) {
257 callback(Span<ParticleCacheKey>(particle, particle->segments + 1));
258 }
259}
260
262{
263 if (edit && edit->pathcache) {
264 /* Edit particles only display their parent. */
265 return {{edit->pathcache, edit->totcached}, {}};
266 }
267
268 ParticleSpans spans;
269 const bool display_parent = !psys->childcache || (psys->part->draw & PART_DRAW_PARENT);
270 if (psys->pathcache && display_parent) {
271 spans.parent = {psys->pathcache, psys->totpart};
272 }
273
274 if (psys->childcache) {
275 spans.children = {psys->childcache, psys->totchild * psys->part->disp / 100};
276 }
277 return spans;
278}
279
281{
282 if (!points_by_curve_storage_.is_empty()) {
283 return points_by_curve_storage_.as_span();
284 }
285
286 int total = 0;
287 points_by_curve_storage_.append(total);
289 total += strand.size();
290 points_by_curve_storage_.append(total);
291 });
292 return points_by_curve_storage_.as_span();
293}
294
296{
297 if (additional_subdivision_ == 0) {
298 return points_by_curve();
299 }
300
301 if (!evaluated_points_by_curve_storage_.is_empty()) {
302 return evaluated_points_by_curve_storage_.as_span();
303 }
304 int segment_multiplier = this->resolution();
305
306 int total = 0;
307 evaluated_points_by_curve_storage_.append(total);
309 int size = strand.size();
310 total += (size > 1) ? size * segment_multiplier : 1;
311 evaluated_points_by_curve_storage_.append(total);
312 });
313 return evaluated_points_by_curve_storage_.as_span();
314}
315
317 const int num_path_cache_keys,
318 ParticleHairCache *hair_cache)
319{
320 for (int i = 0; i < num_path_cache_keys; i++) {
321 ParticleCacheKey *path = pathcache[i];
322 if (path->segments > 0) {
323 hair_cache->strands_len++;
324 hair_cache->elems_len += path->segments + 2;
325 hair_cache->point_len += path->segments + 1;
326 }
327 }
328}
329
331 ParticleSystem *psys,
332 ParticleHairCache *hair_cache)
333{
334 if (hair_cache->pos != nullptr && hair_cache->indices != nullptr) {
335 return;
336 }
337
338 hair_cache->strands_len = 0;
339 hair_cache->elems_len = 0;
340 hair_cache->point_len = 0;
341
342 if (edit != nullptr && edit->pathcache != nullptr) {
343 count_cache_segment_keys(edit->pathcache, edit->totcached, hair_cache);
344 }
345 else {
346 if (psys->pathcache && (!psys->childcache || (psys->part->draw & PART_DRAW_PARENT))) {
347 count_cache_segment_keys(psys->pathcache, psys->totpart, hair_cache);
348 }
349 if (psys->childcache) {
350 const int child_count = psys->totchild * psys->part->disp / 100;
351 count_cache_segment_keys(psys->childcache, child_count, hair_cache);
352 }
353 }
354}
355
356static void particle_pack_mcol(MCol *mcol, ushort r_scol[3])
357{
358 /* Convert to linear ushort and swizzle */
359 float3 col = {BLI_color_from_srgb_table[mcol->r],
363 r_scol[0] = unit_float_to_ushort_clamp(col[2]);
364 r_scol[1] = unit_float_to_ushort_clamp(col[1]);
365 r_scol[2] = unit_float_to_ushort_clamp(col[0]);
366}
367
368/* Used by parent particles and simple children. */
371 const int num_uv_layers,
372 const int parent_index,
373 const MTFace **mtfaces,
374 float (*r_uv)[2])
375{
376 if (psmd == nullptr) {
377 return;
378 }
379 const int emit_from = psmd->psys->part->from;
380 if (!ELEM(emit_from, PART_FROM_FACE, PART_FROM_VOLUME)) {
381 return;
382 }
383 ParticleData *particle = &psys->particles[parent_index];
384 int num = particle->num_dmcache;
386 if (particle->num < psmd->mesh_final->totface_legacy) {
387 num = particle->num;
388 }
389 }
391 const MFace *mfaces = static_cast<const MFace *>(
393 if (mfaces == nullptr) [[unlikely]] {
395 "A mesh with polygons should always have a generated 'CD_MFACE' layer!");
396 return;
397 }
398 const MFace *mface = &mfaces[num];
399 for (int j = 0; j < num_uv_layers; j++) {
400 psys_interpolate_uvs(mtfaces[j] + num, mface->v4, particle->fuv, r_uv[j]);
401 }
402 }
403}
404
407 const int num_col_layers,
408 const int parent_index,
409 const MCol **mcols,
410 MCol *r_mcol)
411{
412 if (psmd == nullptr) {
413 return;
414 }
415 const int emit_from = psmd->psys->part->from;
416 if (!ELEM(emit_from, PART_FROM_FACE, PART_FROM_VOLUME)) {
417 return;
418 }
419 ParticleData *particle = &psys->particles[parent_index];
420 int num = particle->num_dmcache;
422 if (particle->num < psmd->mesh_final->totface_legacy) {
423 num = particle->num;
424 }
425 }
427 const MFace *mfaces = static_cast<const MFace *>(
429 if (mfaces == nullptr) [[unlikely]] {
431 "A mesh with polygons should always have a generated 'CD_MFACE' layer!");
432 return;
433 }
434 const MFace *mface = &mfaces[num];
435 for (int j = 0; j < num_col_layers; j++) {
436 /* CustomDataLayer CD_MCOL has 4 structs per face. */
437 psys_interpolate_mcol(mcols[j] + num * 4, mface->v4, particle->fuv, &r_mcol[j]);
438 }
439 }
440}
441
442/* Used by interpolated children. */
445 const int num_uv_layers,
446 const int child_index,
447 const MTFace **mtfaces,
448 float (*r_uv)[2])
449{
450 if (psmd == nullptr) {
451 return;
452 }
453 const int emit_from = psmd->psys->part->from;
454 if (!ELEM(emit_from, PART_FROM_FACE, PART_FROM_VOLUME)) {
455 return;
456 }
457 ChildParticle *particle = &psys->child[child_index];
458 int num = particle->num;
459 if (num != DMCACHE_NOTFOUND) {
460 const MFace *mfaces = static_cast<const MFace *>(
462 const MFace *mface = &mfaces[num];
463 for (int j = 0; j < num_uv_layers; j++) {
464 psys_interpolate_uvs(mtfaces[j] + num, mface->v4, particle->fuv, r_uv[j]);
465 }
466 }
467}
468
471 const int num_col_layers,
472 const int child_index,
473 const MCol **mcols,
474 MCol *r_mcol)
475{
476 if (psmd == nullptr) {
477 return;
478 }
479 const int emit_from = psmd->psys->part->from;
480 if (!ELEM(emit_from, PART_FROM_FACE, PART_FROM_VOLUME)) {
481 return;
482 }
483 ChildParticle *particle = &psys->child[child_index];
484 int num = particle->num;
485 if (num != DMCACHE_NOTFOUND) {
486 const MFace *mfaces = static_cast<const MFace *>(
488 const MFace *mface = &mfaces[num];
489 for (int j = 0; j < num_col_layers; j++) {
490 /* CustomDataLayer CD_MCOL has 4 structs per face. */
491 psys_interpolate_mcol(mcols[j] + num * 4, mface->v4, particle->fuv, &r_mcol[j]);
492 }
493 }
494}
495
498 const bool is_simple,
499 const int num_uv_layers,
500 const int parent_index,
501 const int child_index,
502 const MTFace **mtfaces,
503 float (**r_parent_uvs)[2],
504 float (**r_uv)[2])
505{
506 if (psmd == nullptr) {
507 return;
508 }
509 if (is_simple) {
510 if (r_parent_uvs[parent_index] != nullptr) {
511 *r_uv = r_parent_uvs[parent_index];
512 }
513 else {
514 *r_uv = MEM_new_array_zeroed<float[2]>(num_uv_layers, "Particle UVs");
515 }
516 }
517 else {
518 *r_uv = MEM_new_array_zeroed<float[2]>(num_uv_layers, "Particle UVs");
519 }
520 if (child_index == -1) {
521 /* Calculate UVs for parent particles. */
522 if (is_simple) {
523 r_parent_uvs[parent_index] = *r_uv;
524 }
525 particle_calculate_parent_uvs(psys, psmd, num_uv_layers, parent_index, mtfaces, *r_uv);
526 }
527 else {
528 /* Calculate UVs for child particles. */
529 if (!is_simple) {
530 particle_interpolate_children_uvs(psys, psmd, num_uv_layers, child_index, mtfaces, *r_uv);
531 }
532 else if (!r_parent_uvs[psys->child[child_index].parent]) {
533 r_parent_uvs[psys->child[child_index].parent] = *r_uv;
534 particle_calculate_parent_uvs(psys, psmd, num_uv_layers, parent_index, mtfaces, *r_uv);
535 }
536 }
537}
538
541 const bool is_simple,
542 const int num_col_layers,
543 const int parent_index,
544 const int child_index,
545 const MCol **mcols,
546 MCol **r_parent_mcol,
547 MCol **r_mcol)
548{
549 if (psmd == nullptr) {
550 return;
551 }
552 if (is_simple) {
553 if (r_parent_mcol[parent_index] != nullptr) {
554 *r_mcol = r_parent_mcol[parent_index];
555 }
556 else {
557 *r_mcol = MEM_new_array_zeroed<MCol>(num_col_layers, "Particle MCol");
558 }
559 }
560 else {
561 *r_mcol = MEM_new_array_zeroed<MCol>(num_col_layers, "Particle MCol");
562 }
563 if (child_index == -1) {
564 /* Calculate MCols for parent particles. */
565 if (is_simple) {
566 r_parent_mcol[parent_index] = *r_mcol;
567 }
568 particle_calculate_parent_mcol(psys, psmd, num_col_layers, parent_index, mcols, *r_mcol);
569 }
570 else {
571 /* Calculate MCols for child particles. */
572 if (!is_simple) {
573 particle_interpolate_children_mcol(psys, psmd, num_col_layers, child_index, mcols, *r_mcol);
574 }
575 else if (!r_parent_mcol[psys->child[child_index].parent]) {
576 r_parent_mcol[psys->child[child_index].parent] = *r_mcol;
577 particle_calculate_parent_mcol(psys, psmd, num_col_layers, parent_index, mcols, *r_mcol);
578 }
579 }
580}
581
582/* Will return last filled index. */
589 ParticleCacheKey **path_cache,
590 const ParticleSource particle_source,
591 const int global_offset,
592 const int start_index,
593 const int num_path_keys,
594 const int num_uv_layers,
595 const int num_col_layers,
596 const MTFace **mtfaces,
597 const MCol **mcols,
598 uint *uv_id,
599 uint *col_id,
600 float (***r_parent_uvs)[2],
601 MCol ***r_parent_mcol,
603 HairAttributeID *attr_id,
604 ParticleHairCache *hair_cache)
605{
606 const bool is_simple = (psys->part->childtype == PART_CHILD_PARTICLES);
607 const bool is_child = (particle_source == PARTICLE_SOURCE_CHILDREN);
608 if (is_simple && *r_parent_uvs == nullptr) {
609 /* TODO(sergey): For edit mode it should be edit->totcached. */
610 *r_parent_uvs = MEM_new_array_zeroed<float (*)[2]>(psys->totpart, "Parent particle UVs");
611 }
612 if (is_simple && *r_parent_mcol == nullptr) {
613 *r_parent_mcol = MEM_new_array_zeroed<MCol *>(psys->totpart, "Parent particle MCol");
614 }
615 int curr_point = start_index;
616 for (int i = 0; i < num_path_keys; i++) {
617 ParticleCacheKey *path = path_cache[i];
618 if (path->segments <= 0) {
619 continue;
620 }
621 float tangent[3];
622 float (*uv)[2] = nullptr;
623 MCol *mcol = nullptr;
625 psmd,
626 is_simple,
627 num_col_layers,
628 is_child ? psys->child[i].parent : i,
629 is_child ? i : -1,
630 mcols,
631 *r_parent_mcol,
632 &mcol);
634 psmd,
635 is_simple,
636 num_uv_layers,
637 is_child ? psys->child[i].parent : i,
638 is_child ? i : -1,
639 mtfaces,
640 *r_parent_uvs,
641 &uv);
642 for (int j = 0; j < path->segments; j++) {
643 if (j == 0) {
644 sub_v3_v3v3(tangent, path[j + 1].co, path[j].co);
645 }
646 else {
647 sub_v3_v3v3(tangent, path[j + 1].co, path[j - 1].co);
648 }
649 GPU_vertbuf_attr_set(hair_cache->pos, attr_id->pos, curr_point, path[j].co);
650 GPU_vertbuf_attr_set(hair_cache->pos, attr_id->tan, curr_point, tangent);
651 GPU_vertbuf_attr_set(hair_cache->pos, attr_id->ind, curr_point, &i);
652 if (psmd != nullptr) {
653 for (int k = 0; k < num_uv_layers; k++) {
655 hair_cache->pos,
656 uv_id[k],
657 curr_point,
658 (is_simple && is_child) ? (*r_parent_uvs)[psys->child[i].parent][k] : uv[k]);
659 }
660 for (int k = 0; k < num_col_layers; k++) {
661 /* TODO: Put the conversion outside the loop. */
662 ushort scol[4];
664 (is_simple && is_child) ? &(*r_parent_mcol)[psys->child[i].parent][k] : &mcol[k],
665 scol);
666 GPU_vertbuf_attr_set(hair_cache->pos, col_id[k], curr_point, scol);
667 }
668 }
669 GPU_indexbuf_add_generic_vert(elb, curr_point);
670 curr_point++;
671 }
672 sub_v3_v3v3(tangent, path[path->segments].co, path[path->segments - 1].co);
673
674 int global_index = i + global_offset;
675 GPU_vertbuf_attr_set(hair_cache->pos, attr_id->pos, curr_point, path[path->segments].co);
676 GPU_vertbuf_attr_set(hair_cache->pos, attr_id->tan, curr_point, tangent);
677 GPU_vertbuf_attr_set(hair_cache->pos, attr_id->ind, curr_point, &global_index);
678
679 if (psmd != nullptr) {
680 for (int k = 0; k < num_uv_layers; k++) {
681 GPU_vertbuf_attr_set(hair_cache->pos,
682 uv_id[k],
683 curr_point,
684 (is_simple && is_child) ? (*r_parent_uvs)[psys->child[i].parent][k] :
685 uv[k]);
686 }
687 for (int k = 0; k < num_col_layers; k++) {
688 /* TODO: Put the conversion outside the loop. */
689 ushort scol[4];
690 particle_pack_mcol((is_simple && is_child) ? &(*r_parent_mcol)[psys->child[i].parent][k] :
691 &mcol[k],
692 scol);
693 GPU_vertbuf_attr_set(hair_cache->pos, col_id[k], curr_point, scol);
694 }
695 if (!is_simple) {
696 MEM_delete(uv);
697 MEM_delete(mcol);
698 }
699 }
700 /* Finish the segment and add restart primitive. */
701 GPU_indexbuf_add_generic_vert(elb, curr_point);
703 curr_point++;
704 }
705 return curr_point;
706}
707
708static float particle_key_weight(const ParticleData *particle, int strand, float t)
709{
710 const ParticleData *part = particle + strand;
711 const HairKey *hkeys = part->hair;
712 float edit_key_seg_t = 1.0f / (part->totkey - 1);
713 if (t == 1.0) {
714 return hkeys[part->totkey - 1].weight;
715 }
716
717 float interp = t / edit_key_seg_t;
718 int index = int(interp);
719 interp -= floorf(interp); /* Time between 2 edit key */
720 float s1 = hkeys[index].weight;
721 float s2 = hkeys[index + 1].weight;
722 return s1 + interp * (s2 - s1);
723}
724
726 const PTCacheEdit * /*edit*/, /* nullptr for weight data */
727 const ParticleData *particle, /* nullptr for select data */
728 ParticleCacheKey **path_cache,
729 const int start_index,
730 const int num_path_keys,
732 GPUVertBufRaw *attr_step)
733{
734 int curr_point = start_index;
735 for (int i = 0; i < num_path_keys; i++) {
736 ParticleCacheKey *path = path_cache[i];
737 if (path->segments <= 0) {
738 continue;
739 }
740 for (int j = 0; j <= path->segments; j++) {
741 EditStrandData *seg_data = static_cast<EditStrandData *>(GPU_vertbuf_raw_step(attr_step));
742 copy_v3_v3(seg_data->pos, path[j].co);
743 float strand_t = float(j) / path->segments;
744 if (particle) {
745 float weight = particle_key_weight(particle, i, strand_t);
746 /* NaN or unclamped become 1.0f */
747 seg_data->selection = (weight < 1.0f) ? weight : 1.0f;
748 }
749 else {
750 /* Computed in psys_cache_edit_paths_iter(). */
751 seg_data->selection = path[j].col[0];
752 }
753 GPU_indexbuf_add_generic_vert(elb, curr_point);
754 curr_point++;
755 }
756 /* Finish the segment and add restart primitive. */
758 }
759 return curr_point;
760}
761
763 ParticleSystem *psys,
764 ModifierData *md,
765 ParticleHairCache *hair_cache)
766{
767 if (hair_cache->pos != nullptr && hair_cache->indices != nullptr) {
768 return;
769 }
770
771 int curr_point = 0;
772 ParticleSystemModifierData *psmd = reinterpret_cast<ParticleSystemModifierData *>(md);
773
774 GPU_VERTBUF_DISCARD_SAFE(hair_cache->pos);
776
777 GPUVertFormat format = {0};
778 HairAttributeID attr_id;
779 uint *uv_id = nullptr;
780 uint *col_id = nullptr;
781 Vector<StringRef> color_attribute_names;
782 int num_col_layers = 0;
783 const MTFace **mtfaces = nullptr;
784 const MCol **mcols = nullptr;
785 float (**parent_uvs)[2] = nullptr;
786 MCol **parent_mcol = nullptr;
787
788 VectorSet<StringRefNull> uv_map_names;
789 if (psmd != nullptr) {
790 psmd->mesh_final->uv_map_names();
791 psmd->mesh_final->attributes().foreach_attribute([&](const bke::AttributeIter &iter) {
793 color_attribute_names.append(iter.name);
794 }
795 });
796 num_col_layers = color_attribute_names.size();
797 }
798 int num_uv_layers = uv_map_names.size();
799
800 attr_id.pos = GPU_vertformat_attr_add(&format, "pos", gpu::VertAttrType::SFLOAT_32_32_32);
801 attr_id.tan = GPU_vertformat_attr_add(&format, "nor", gpu::VertAttrType::SFLOAT_32_32_32);
802 attr_id.ind = GPU_vertformat_attr_add(&format, "ind", gpu::VertAttrType::SINT_32);
803
804 if (psmd) {
805 const StringRef active_uv = psmd->mesh_final->default_uv_map_name();
806 const char *active_col = psmd->mesh_final->active_color_attribute;
807 uv_id = MEM_new_array_uninitialized<uint>(num_uv_layers, "UV attr format");
808 col_id = MEM_new_array_uninitialized<uint>(color_attribute_names.size(), "Col attr format");
809
810 for (int i = 0; i < num_uv_layers; i++) {
811
812 char uuid[32], attr_safe_name[GPU_MAX_SAFE_ATTR_NAME];
813 const StringRef name = uv_map_names[i];
814 GPU_vertformat_safe_attr_name(name, attr_safe_name, GPU_MAX_SAFE_ATTR_NAME);
815
816 SNPRINTF_UTF8(uuid, "a%s", attr_safe_name);
817 uv_id[i] = GPU_vertformat_attr_add(&format, uuid, gpu::VertAttrType::SFLOAT_32_32);
818
819 if (name == active_uv) {
820 GPU_vertformat_alias_add(&format, "a");
821 }
822 }
823
824 for (int i = 0; i < num_col_layers; i++) {
825 const StringRef name = color_attribute_names[i];
826 char uuid[32], attr_safe_name[GPU_MAX_SAFE_ATTR_NAME];
827 GPU_vertformat_safe_attr_name(name, attr_safe_name, GPU_MAX_SAFE_ATTR_NAME);
828
829 SNPRINTF_UTF8(uuid, "a%s", attr_safe_name);
830 col_id[i] = GPU_vertformat_attr_add(&format, uuid, gpu::VertAttrType::UNORM_16_16_16_16);
831
832 if (name == active_col) {
833 GPU_vertformat_alias_add(&format, "c");
834 }
835 }
836 }
837
838 hair_cache->pos = GPU_vertbuf_create_with_format(format);
839 GPU_vertbuf_data_alloc(*hair_cache->pos, hair_cache->point_len);
840
842 GPU_indexbuf_init_ex(&elb, GPU_PRIM_LINE_STRIP, hair_cache->elems_len, hair_cache->point_len);
843
844 if (num_uv_layers || num_col_layers) {
846 if (num_uv_layers) {
847 mtfaces = MEM_new_array_uninitialized<const MTFace *>(num_uv_layers, "Faces UV layers");
848 for (int i = 0; i < num_uv_layers; i++) {
849 mtfaces[i] = static_cast<const MTFace *>(
851 }
852 }
853 if (num_col_layers) {
854 mcols = MEM_new_array_uninitialized<const MCol *>(num_col_layers, "Color layers");
855 for (int i = 0; i < num_col_layers; i++) {
856 mcols[i] = static_cast<const MCol *>(
858 }
859 }
860 }
861
862 if (edit != nullptr && edit->pathcache != nullptr) {
863 curr_point = particle_batch_cache_fill_segments(psys,
864 psmd,
865 edit->pathcache,
867 0,
868 0,
869 edit->totcached,
870 num_uv_layers,
871 num_col_layers,
872 mtfaces,
873 mcols,
874 uv_id,
875 col_id,
876 &parent_uvs,
877 &parent_mcol,
878 &elb,
879 &attr_id,
880 hair_cache);
881 }
882 else {
883 if ((psys->pathcache != nullptr) &&
884 (!psys->childcache || (psys->part->draw & PART_DRAW_PARENT)))
885 {
886 curr_point = particle_batch_cache_fill_segments(psys,
887 psmd,
888 psys->pathcache,
890 0,
891 0,
892 psys->totpart,
893 num_uv_layers,
894 num_col_layers,
895 mtfaces,
896 mcols,
897 uv_id,
898 col_id,
899 &parent_uvs,
900 &parent_mcol,
901 &elb,
902 &attr_id,
903 hair_cache);
904 }
905 if (psys->childcache != nullptr) {
906 const int child_count = psys->totchild * psys->part->disp / 100;
907 curr_point = particle_batch_cache_fill_segments(psys,
908 psmd,
909 psys->childcache,
911 psys->totpart,
912 curr_point,
913 child_count,
914 num_uv_layers,
915 num_col_layers,
916 mtfaces,
917 mcols,
918 uv_id,
919 col_id,
920 &parent_uvs,
921 &parent_mcol,
922 &elb,
923 &attr_id,
924 hair_cache);
925 }
926 }
927 /* Cleanup. */
928 if (parent_uvs != nullptr) {
929 /* TODO(sergey): For edit mode it should be edit->totcached. */
930 for (int i = 0; i < psys->totpart; i++) {
931 MEM_SAFE_DELETE(parent_uvs[i]);
932 }
933 MEM_delete(parent_uvs);
934 }
935 if (parent_mcol != nullptr) {
936 for (int i = 0; i < psys->totpart; i++) {
937 MEM_SAFE_DELETE(parent_mcol[i]);
938 }
939 MEM_delete(parent_mcol);
940 }
941 if (num_uv_layers) {
942 MEM_delete(mtfaces);
943 }
944 if (num_col_layers) {
945 MEM_delete(mcols);
946 }
947 if (psmd != nullptr) {
948 MEM_delete(uv_id);
949 }
950 hair_cache->indices = GPU_indexbuf_build(&elb);
951}
952
954 ParticleSystem *psys,
955 ParticlePointCache *point_cache)
956{
957 if (point_cache->pos != nullptr) {
958 return;
959 }
960
961 int i, curr_point;
962 ParticleData *pa;
964 ParticleSimulationData sim = {nullptr};
965 const DRWContext *draw_ctx = DRW_context_get();
966
967 sim.depsgraph = draw_ctx->depsgraph;
968 sim.scene = draw_ctx->scene;
969 sim.ob = object;
970 sim.psys = psys;
971 sim.psmd = psys_get_modifier(object, psys);
972 psys_sim_data_init(&sim);
973
974 GPU_VERTBUF_DISCARD_SAFE(point_cache->pos);
975
976 static uint pos_id, rot_id, val_id;
977 static const GPUVertFormat format = [&]() {
978 GPUVertFormat format{};
979 pos_id = GPU_vertformat_attr_add(&format, "part_pos", gpu::VertAttrType::SFLOAT_32_32_32);
980 val_id = GPU_vertformat_attr_add(&format, "part_val", gpu::VertAttrType::SFLOAT_32);
981 rot_id = GPU_vertformat_attr_add(&format, "part_rot", gpu::VertAttrType::SFLOAT_32_32_32_32);
982 return format;
983 }();
984
985 point_cache->pos = GPU_vertbuf_create_with_format(format);
986 GPU_vertbuf_data_alloc(*point_cache->pos, psys->totpart);
987
988 for (curr_point = 0, i = 0, pa = psys->particles; i < psys->totpart; i++, pa++) {
989 state.time = DEG_get_ctime(draw_ctx->depsgraph);
990 if (!psys_get_particle_state(&sim, i, &state, false)) {
991 continue;
992 }
993
994 float val;
995
996 GPU_vertbuf_attr_set(point_cache->pos, pos_id, curr_point, state.co);
997 GPU_vertbuf_attr_set(point_cache->pos, rot_id, curr_point, state.rot);
998
999 switch (psys->part->draw_col) {
1000 case PART_DRAW_COL_VEL:
1001 val = len_v3(state.vel) / psys->part->color_vec_max;
1002 break;
1003 case PART_DRAW_COL_ACC:
1004 val = len_v3v3(state.vel, pa->prev_state.vel) /
1005 ((state.time - pa->prev_state.time) * psys->part->color_vec_max);
1006 break;
1007 default:
1008 val = -1.0f;
1009 break;
1010 }
1011
1012 GPU_vertbuf_attr_set(point_cache->pos, val_id, curr_point, &val);
1013
1014 curr_point++;
1015 }
1016
1017 if (curr_point != psys->totpart) {
1018 GPU_vertbuf_data_resize(*point_cache->pos, curr_point);
1019 }
1020
1021 psys_sim_data_free(&sim);
1022}
1023
1025 ParticleSystem *psys,
1026 PTCacheEdit *edit)
1027{
1028 if (edit->psys == nullptr) {
1029 return;
1030 }
1031 /* NOTE: Get flag from particle system coming from drawing object.
1032 * this is where depsgraph will be setting flags to.
1033 */
1034 const DRWContext *draw_ctx = DRW_context_get();
1035 Scene *scene_orig = DEG_get_original(draw_ctx->scene);
1036 Object *object_orig = DEG_get_original(object_eval);
1037 if (psys->flag & PSYS_HAIR_UPDATED) {
1038 PE_update_object(draw_ctx->depsgraph, scene_orig, object_orig, 0);
1039 psys->flag &= ~PSYS_HAIR_UPDATED;
1040 }
1041 if (edit->pathcache == nullptr) {
1042 Depsgraph *depsgraph = draw_ctx->depsgraph;
1043 psys_cache_edit_paths(depsgraph,
1044 scene_orig,
1045 object_orig,
1046 edit,
1047 DEG_get_ctime(depsgraph),
1048 DEG_get_mode(depsgraph) == DAG_EVAL_RENDER);
1049 }
1050}
1051
1053{
1054 if ((object_eval->mode & OB_MODE_PARTICLE_EDIT) == 0) {
1055 return;
1056 }
1057 const DRWContext *draw_ctx = DRW_context_get();
1058 Scene *scene_orig = DEG_get_original(draw_ctx->scene);
1059 Object *object_orig = DEG_get_original(object_eval);
1060 PTCacheEdit *edit = PE_create_current(draw_ctx->depsgraph, scene_orig, object_orig);
1061 if (edit != nullptr) {
1062 drw_particle_update_ptcache_edit(object_eval, psys, edit);
1063 }
1064}
1065
1067 ParticleSystem *psys,
1068 ModifierData *md,
1069 PTCacheEdit *edit,
1070 const int additional_subdivision)
1071{
1072 const DRWContext *draw_ctx = DRW_context_get();
1073 if (psys_in_edit_mode(draw_ctx->depsgraph, psys)) {
1074 object = DEG_get_original(object);
1075 psys = psys_orig_get(psys);
1076 }
1078
1081 math::clamp(additional_subdivision, 0, 3));
1082 src.object = object;
1083 src.psys = psys;
1084 src.md = md;
1085 src.edit = edit;
1086 return src;
1087}
1088
1090 ParticleSystem *psys,
1091 ModifierData *md)
1092{
1094 if (cache->hair.hairs == nullptr) {
1095 drw_particle_update_ptcache(object, psys);
1096 ParticleDrawSource source = drw_particle_get_hair_source(object, psys, md, nullptr, 0);
1097 ensure_seg_pt_count(source.edit, source.psys, &cache->hair);
1098 particle_batch_cache_ensure_pos_and_seg(source.edit, source.psys, source.md, &cache->hair);
1099 cache->hair.hairs = GPU_batch_create(
1100 GPU_PRIM_LINE_STRIP, cache->hair.pos, cache->hair.indices);
1101 }
1102 return cache->hair.hairs;
1103}
1104
1106{
1108
1109 if (cache->point.points == nullptr) {
1110 particle_batch_cache_ensure_pos(object, psys, &cache->point);
1111 cache->point.points = GPU_batch_create(GPU_PRIM_POINTS, cache->point.pos, nullptr);
1112 }
1113
1114 return cache->point.points;
1115}
1116
1118 ParticleSystem *psys,
1119 ModifierData * /*md*/,
1120 ParticleHairCache *hair_cache,
1121 bool use_weight)
1122{
1123 if (hair_cache->pos != nullptr && hair_cache->indices != nullptr) {
1124 return;
1125 }
1126
1127 ParticleData *particle = (use_weight) ? psys->particles : nullptr;
1128
1129 GPU_VERTBUF_DISCARD_SAFE(hair_cache->pos);
1131
1132 GPUVertBufRaw data_step;
1134 uint pos_id, selection_id;
1135 const GPUVertFormat *edit_point_format = edit_points_vert_format_get(&pos_id, &selection_id);
1136
1137 hair_cache->pos = GPU_vertbuf_create_with_format(*edit_point_format);
1138 GPU_vertbuf_data_alloc(*hair_cache->pos, hair_cache->point_len);
1139 GPU_vertbuf_attr_get_raw_data(hair_cache->pos, pos_id, &data_step);
1140
1141 GPU_indexbuf_init_ex(&elb, GPU_PRIM_LINE_STRIP, hair_cache->elems_len, hair_cache->point_len);
1142
1143 if (edit != nullptr && edit->pathcache != nullptr) {
1145 edit, particle, edit->pathcache, 0, edit->totcached, &elb, &data_step);
1146 }
1147 hair_cache->indices = GPU_indexbuf_build(&elb);
1148}
1149
1151 ParticleSystem *psys,
1152 PTCacheEdit *edit,
1153 bool use_weight)
1154{
1156 if (cache->edit_is_weight != use_weight) {
1159 }
1160 if (cache->edit_hair.hairs != nullptr) {
1161 return cache->edit_hair.hairs;
1162 }
1163 drw_particle_update_ptcache_edit(object, psys, edit);
1164 ensure_seg_pt_count(edit, psys, &cache->edit_hair);
1165 particle_batch_cache_ensure_edit_pos_and_seg(edit, psys, nullptr, &cache->edit_hair, use_weight);
1168 cache->edit_is_weight = use_weight;
1169 return cache->edit_hair.hairs;
1170}
1171
1173{
1174 if (cache->edit_inner_pos != nullptr) {
1175 return;
1176 }
1177 cache->edit_inner_point_len = 0;
1178 for (int point_index = 0; point_index < edit->totpoint; point_index++) {
1179 const PTCacheEditPoint *point = &edit->points[point_index];
1180 if (point->flag & PEP_HIDE) {
1181 continue;
1182 }
1183 BLI_assert(point->totkey >= 1);
1184 cache->edit_inner_point_len += (point->totkey - 1);
1185 }
1186}
1187
1189 ParticleBatchCache *cache)
1190{
1191 if (cache->edit_inner_pos != nullptr) {
1192 return;
1193 }
1194
1195 uint pos_id, selection_id;
1196 const GPUVertFormat *edit_point_format = edit_points_vert_format_get(&pos_id, &selection_id);
1197
1198 cache->edit_inner_pos = GPU_vertbuf_create_with_format(*edit_point_format);
1200
1201 int global_key_index = 0;
1202 for (int point_index = 0; point_index < edit->totpoint; point_index++) {
1203 const PTCacheEditPoint *point = &edit->points[point_index];
1204 if (point->flag & PEP_HIDE) {
1205 continue;
1206 }
1207 for (int key_index = 0; key_index < point->totkey - 1; key_index++) {
1208 PTCacheEditKey *key = &point->keys[key_index];
1209 float selection = (key->flag & PEK_SELECT) ? 1.0f : 0.0f;
1210 GPU_vertbuf_attr_set(cache->edit_inner_pos, pos_id, global_key_index, key->world_co);
1211 GPU_vertbuf_attr_set(cache->edit_inner_pos, selection_id, global_key_index, &selection);
1212 global_key_index++;
1213 }
1214 }
1215}
1216
1218 ParticleSystem *psys,
1219 PTCacheEdit *edit)
1220{
1222 if (cache->edit_inner_points != nullptr) {
1223 return cache->edit_inner_points;
1224 }
1225 drw_particle_update_ptcache_edit(object, psys, edit);
1226 ensure_edit_inner_points_count(edit, cache);
1229 return cache->edit_inner_points;
1230}
1231
1233{
1234 if (cache->edit_tip_pos != nullptr) {
1235 return;
1236 }
1237 cache->edit_tip_point_len = 0;
1238 for (int point_index = 0; point_index < edit->totpoint; point_index++) {
1239 const PTCacheEditPoint *point = &edit->points[point_index];
1240 if (point->flag & PEP_HIDE) {
1241 continue;
1242 }
1243 cache->edit_tip_point_len += 1;
1244 }
1245}
1246
1248{
1249 if (cache->edit_tip_pos != nullptr) {
1250 return;
1251 }
1252
1253 uint pos_id, selection_id;
1254 const GPUVertFormat *edit_point_format = edit_points_vert_format_get(&pos_id, &selection_id);
1255
1256 cache->edit_tip_pos = GPU_vertbuf_create_with_format(*edit_point_format);
1258
1259 int global_point_index = 0;
1260 for (int point_index = 0; point_index < edit->totpoint; point_index++) {
1261 const PTCacheEditPoint *point = &edit->points[point_index];
1262 if (point->flag & PEP_HIDE) {
1263 continue;
1264 }
1265 PTCacheEditKey *key = &point->keys[point->totkey - 1];
1266 float selection = (key->flag & PEK_SELECT) ? 1.0f : 0.0f;
1267
1268 GPU_vertbuf_attr_set(cache->edit_tip_pos, pos_id, global_point_index, key->world_co);
1269 GPU_vertbuf_attr_set(cache->edit_tip_pos, selection_id, global_point_index, &selection);
1270 global_point_index++;
1271 }
1272}
1273
1275 ParticleSystem *psys,
1276 PTCacheEdit *edit)
1277{
1279 if (cache->edit_tip_points != nullptr) {
1280 return cache->edit_tip_points;
1281 }
1282 drw_particle_update_ptcache_edit(object, psys, edit);
1283 ensure_edit_tip_points_count(edit, cache);
1286 return cache->edit_tip_points;
1287}
1288
1289/* Can return DMCACHE_NOTFOUND in case of invalid mapping. */
1290static int particle_mface_index(const ParticleData &particle, int face_count_legacy)
1291{
1293 return particle.num_dmcache;
1294 }
1295 if (particle.num < face_count_legacy) {
1296 return (particle.num == DMCACHE_ISCHILD) ? DMCACHE_NOTFOUND : particle.num;
1297 }
1298 return DMCACHE_NOTFOUND;
1299}
1300static int particle_mface_index(const ChildParticle &particle, int /*face_count_legacy*/)
1301{
1302 return particle.num;
1303}
1304
1306{
1307 /* Convert to linear ushort and swizzle */
1308 float4 col = {BLI_color_from_srgb_table[mcol.r],
1311 mcol.a / 255.0f};
1313 std::swap(col[0], col[2]);
1314 return col;
1315}
1316
1317template<typename ParticleDataT>
1318static float4 interpolate(const ParticleDataT &particle, Span<MFace> mfaces, Span<MCol> mcols)
1319{
1320 int num = particle_mface_index(particle, mfaces.size());
1321 if (num == DMCACHE_NOTFOUND) {
1322 return float4(0, 0, 0, 1);
1323 }
1324 /* CustomDataLayer CD_MCOL has 4 structs per face. */
1325 MCol mcol;
1326 psys_interpolate_mcol(mcols.slice(num * 4, 4).data(), mfaces[num].v4, particle.fuv, &mcol);
1327 return particle_mcol_convert(mcol);
1328}
1329
1330template<typename ParticleDataT>
1331static float2 interpolate(const ParticleDataT &particle, Span<MFace> mfaces, Span<MTFace> mtfaces)
1332{
1333 int num = particle_mface_index(particle, mfaces.size());
1334 if (num == DMCACHE_NOTFOUND) {
1335 return float2(0);
1336 }
1337 float2 uv;
1338 psys_interpolate_uvs(&mtfaces[num], mfaces[num].v4, particle.fuv, uv);
1339 return uv;
1340}
1341
1342static std::optional<StringRef> get_first_uv_name(const bke::AttributeAccessor &attributes)
1343{
1344 std::optional<StringRef> name;
1345 attributes.foreach_attribute([&](const bke::AttributeIter &iter) {
1346 if (iter.data_type == bke::AttrType::Float2) {
1347 name = iter.name;
1348 iter.stop();
1349 }
1350 });
1351 return name;
1352}
1353
1354template<typename T>
1356 const eCustomDataType type,
1357 const StringRef name)
1358{
1359 int layer_id = CustomData_get_named_layer(&mesh.fdata_legacy, type, name);
1360 return {static_cast<const T *>(CustomData_get_layer_n(&mesh.fdata_legacy, type, layer_id)),
1361 /* There is 4 MCol per face. */
1362 mesh.totface_legacy * (std::is_same_v<T, MCol> ? 4 : 1)};
1363}
1364
1365template<typename T>
1367{
1368 return {static_cast<const T *>(CustomData_get_layer(&mesh.fdata_legacy, type)),
1369 mesh.totface_legacy};
1370}
1371
1372template<typename InputT, typename OutputT, eCustomDataType data_type>
1374 const StringRef name)
1375{
1376 ParticleSystemModifierData *psmd = reinterpret_cast<ParticleSystemModifierData *>(src.md);
1377 Mesh &mesh = *psmd->mesh_final;
1378
1379 /* TODO(fclem): Use normalized integer format. */
1383 vbo->allocate(src.curves_num());
1384 MutableSpan<OutputT> data = vbo->data<OutputT>();
1385
1386 const int emit_from = psmd->psys->part->from;
1387 /* True if no interpolation for child particle. */
1388 const bool is_simple = (src.psys->part->childtype == PART_CHILD_PARTICLES) ||
1389 !ELEM(emit_from, PART_FROM_FACE, PART_FROM_VOLUME);
1390
1392 Span<InputT> attr = span_from_custom_data_layer<InputT>(mesh, data_type, name);
1394 Span<ChildParticle> children(src.psys->child, src.psys->totchild);
1395 Span<ParticleData> particles(src.psys->particles, src.psys->totpart);
1396
1397 /* Index of the particle/hair curve. Note that the order of the loops matter. */
1398 int curve_index = 0;
1399
1400 ParticleSpans part_spans = src.particles_get();
1401 for (const int particle_index : part_spans.parent.index_range()) {
1402 data[curve_index++] = interpolate(particles[particle_index], mfaces, attr);
1403 }
1404
1405 if (is_simple) {
1406 /* Fallback array if parent particles are not displayed. */
1407 Vector<OutputT> parent_data;
1408 if (part_spans.parent.is_empty()) {
1409 parent_data.reserve(src.psys->totpart);
1410 for (int particle_index : IndexRange(src.psys->totpart)) {
1411 parent_data.append(interpolate(particles[particle_index], mfaces, attr));
1412 }
1413 }
1414
1415 Span<OutputT> data_parent(part_spans.parent.is_empty() ? parent_data.data() : data.data(),
1416 src.psys->totpart);
1417
1418 for (const int particle_index : part_spans.children.index_range()) {
1419 /* Simple copy of the parent data. */
1420 data[curve_index++] = data_parent[children[particle_index].parent];
1421 }
1422 }
1423 else {
1424 for (const int particle_index : part_spans.children.index_range()) {
1425 data[curve_index++] = interpolate(children[particle_index], mfaces, attr);
1426 }
1427 }
1428 return vbo;
1429}
1430
1432 const Mesh &mesh,
1433 const StringRef name,
1434 bool &r_is_point_domain)
1435{
1436 using namespace bke;
1437 /* Note: All legacy hair attributes come from the emitter mesh and are on per curve domain. */
1438 r_is_point_domain = false;
1439
1440 const AttributeAccessor attributes = mesh.attributes();
1441
1442 auto meta_data = attributes.lookup_meta_data(name);
1443 if (meta_data && meta_data->domain == bke::AttrDomain::Corner) {
1444 if (meta_data->data_type == AttrType::ColorByte) {
1446 }
1447 if (meta_data->data_type == AttrType::Float2) {
1449 }
1450 }
1451 /* Attribute doesn't exist or is of an incompatible type.
1452 * Replace it with a black curve domain attribute. */
1454}
1455
1457 ParticleDrawSource &src,
1458 const Mesh &mesh,
1459 const StringRef name,
1460 const int index)
1461{
1462 char sampler_name[32];
1463 drw_curves_get_attribute_sampler_name(name, sampler_name);
1464
1466 src, mesh, name, attributes_point_domain[index]);
1467
1468 /* Existing final data may have been for a different attribute (with a different name or domain),
1469 * free the data. */
1470 this->curve_attributes_buf[index].reset();
1471
1472 /* Ensure final data for points. */
1475 }
1476 else {
1477 this->curve_attributes_buf[index] = std::move(attr_buf);
1478 }
1479}
1480
1482 ParticleDrawSource &src,
1483 const GPUMaterial *gpu_material)
1484{
1485 ParticleSystemModifierData *psmd = reinterpret_cast<ParticleSystemModifierData *>(src.md);
1486 if (psmd == nullptr || psmd->mesh_final == nullptr || src.curves_num() == 0) {
1487 return;
1488 }
1489 const Mesh &mesh = *psmd->mesh_final;
1490 const bke::AttributeAccessor attributes = mesh.attributes();
1491
1492 if (gpu_material) {
1493 VectorSet<std::string> attrs_needed;
1494 ListBaseT<GPUMaterialAttribute> gpu_attrs = GPU_material_attributes(gpu_material);
1495 for (GPUMaterialAttribute &gpu_attr : gpu_attrs) {
1496 StringRef name = gpu_attr.name;
1497 if (name.is_empty()) {
1498 if (std::optional<StringRef> uv_name = get_first_uv_name(attributes)) {
1499 drw_attributes_add_request(&attrs_needed, *uv_name);
1500 }
1501 }
1502 if (!attributes.contains(name)) {
1503 continue;
1504 }
1505 drw_attributes_add_request(&attrs_needed, name);
1506 }
1507
1508 if (!drw_attributes_overlap(&attr_used, &attrs_needed)) {
1509 /* Some new attributes have been added, free all and start over. */
1510 for (const int i : IndexRange(GPU_MAX_ATTR)) {
1511 this->curve_attributes_buf[i].reset();
1512 }
1513 drw_attributes_merge(&attr_used, &attrs_needed);
1514 }
1516 }
1517
1518 for (const int i : attr_used.index_range()) {
1519 if (this->curve_attributes_buf[i]) {
1520 continue;
1521 }
1522 ensure_attribute(module, src, mesh, attr_used[i], i);
1523 }
1524}
1525
1527{
1528 if (points_by_curve_buf) {
1529 return;
1530 }
1531
1534 src.evaluated_points_by_curve().data());
1535
1536 /* Use the same type for all curves. */
1538 auto resolution_varray = VArray<int32_t>::from_single(src.resolution(), src.curves_num());
1539 /* Not used. */
1540 auto cyclic_offsets_varray = VArray<int32_t>::from_single(0, 2);
1541 /* TODO(fclem): Optimize shaders to avoid needing to upload this data if data is uniform.
1542 * This concerns all varray. */
1543 this->curves_type_buf = gpu::VertBuf::from_varray(type_varray);
1544 this->curves_resolution_buf = gpu::VertBuf::from_varray(resolution_varray);
1545 this->curves_cyclic_buf = gpu::VertBuf::from_varray(cyclic_offsets_varray);
1546}
1547
1548/* Copied from cycles. */
1549static float hair_shape_radius(float shape, float root, float tip, float time)
1550{
1551 BLI_assert(time >= 0.0f);
1552 BLI_assert(time <= 1.0f);
1553 float radius = 1.0f - time;
1554 if (shape < 0.0f) {
1555 radius = powf(radius, 1.0f + shape);
1556 }
1557 else {
1558 radius = powf(radius, 1.0f / (1.0f - shape));
1559 }
1560 return (radius * (root - tip)) + tip;
1561}
1562
1564{
1566 return;
1567 }
1568
1569 if (src.curves_num() == 0) {
1570 /* Garbage data. */
1574 return;
1575 }
1576
1577 ensure_common(src);
1578
1581
1582 MutableSpan<float3> points_pos = points_pos_buf->data<float3>();
1583 MutableSpan<float> points_rad = points_rad_buf->data<float>();
1584
1585 const ParticleSettings &part = *src.psys->part;
1586 const float hair_rad_shape = part.shape;
1587 const float hair_rad_root = part.rad_root * part.rad_scale * 0.5f;
1588 const float hair_rad_tip = part.rad_tip * part.rad_scale * 0.5f;
1589 const bool hair_close_tip = (part.shape_flag & PART_SHAPE_CLOSE_TIP) != 0;
1590
1591 int i = 0;
1593 int j = 0;
1594 for (const ParticleCacheKey &point : strand) {
1595 points_pos[i] = point.co;
1596 points_rad[i] = (hair_close_tip && (j == strand.index_range().last())) ?
1597 0.0f :
1599 hair_rad_shape, hair_rad_root, hair_rad_tip, point.time);
1600 i++, j++;
1601 }
1602 });
1603
1605
1607
1608 module.evaluate_positions(true,
1609 false,
1610 false,
1611 false,
1612 false,
1613 src.curves_num(),
1614 *this,
1615 std::move(points_pos_buf),
1616 std::move(points_rad_buf),
1617 evaluated_pos_rad_buf,
1618 transform);
1619
1620 /* TODO(fclem): Make time and length optional. */
1623
1624 module.evaluate_curve_length_intercept(false, src.curves_num(), *this);
1625}
1626
1628 ParticleDrawSource &src,
1629 int face_per_segment)
1630{
1631 const bool is_ribbon = face_per_segment < 2;
1632
1633 gpu::VertBufPtr &indirection_buf = is_ribbon ? this->indirection_ribbon_buf :
1635 if (indirection_buf) {
1636 return indirection_buf;
1637 }
1638
1639 if (src.curves_num() == 0) {
1640 /* Garbage data. */
1641 indirection_buf = gpu::VertBuf::device_only<int>(4);
1642 return indirection_buf;
1643 }
1644
1645 ensure_common(src);
1646
1647 indirection_buf = module.evaluate_topology_indirection(
1648 src.curves_num(), src.evaluated_points_num(), *this, is_ribbon, false);
1649
1650 return indirection_buf;
1651}
1652
1654{
1656 CurvesEvalCache &eval_cache = cache->hair.eval_cache;
1657 if (assign_if_different(eval_cache.resolution, src.resolution())) {
1659 }
1660 return eval_cache;
1661}
1662
1663} // namespace blender::draw
CustomData interface, see also DNA_customdata_types.h.
#define DMCACHE_NOTFOUND
#define DMCACHE_ISCHILD
#define PEP_HIDE
#define PEK_SELECT
#define SNPRINTF_UTF8(dst, format,...)
Object groups, one object can be in many groups at once.
#define GPU_batch_create(primitive_type, vertex_buf, index_buf)
Definition GPU_batch.hh:143
#define GPU_BATCH_DISCARD_SAFE(batch)
Definition GPU_batch.hh:199
#define GPU_INDEXBUF_DISCARD_SAFE(elem)
#define GPU_VERTBUF_DISCARD_SAFE(verts)
Read Blender memory allocation and freeing.
#define BLI_assert_unreachable()
#define ELEM(...)
#define BLI_assert_msg(a, msg)
constexpr IndexRange()=default
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
static VArray from_single(T value, const int64_t size)
int64_t size() const
IndexRange index_range() const
int64_t size() const
void append(const T &value)
void reserve(const int64_t min_capacity)
void foreach_attribute(const FunctionRef< void(const AttributeIter &)> fn) const
bool contains(StringRef name) const
std::optional< AttributeMetaData > lookup_meta_data(StringRef name) const
constexpr bool is_empty() const
static VertBufPtr device_only(uint size)
static VertBufPtr from_varray(const VArray< T > &array)
static VertBufPtr from_size(const int size, GPUUsageType usage=GPU_USAGE_STATIC)
static VertBufPtr from_span(const Span< T > data)
#define powf(x, y)
Utilities for rendering attributes.
#define MAX_THICKRES
const int state
ccl_device_inline uint particle_index(KernelGlobals kg, const int particle)
ccl_device_inline float interp(const float a, const float b, const float t)
Definition math_base.h:549
#define T
void drw_particle_update_ptcache(Object *object_eval, ParticleSystem *psys)
void drw_attributes_add_request(VectorSet< std::string > *attrs, const StringRef name)
static void count_cache_segment_keys(ParticleCacheKey **pathcache, const int num_path_cache_keys, ParticleHairCache *hair_cache)
static float4 particle_mcol_convert(const MCol &mcol)
void DRW_particle_batch_cache_free(ParticleSystem *psys)
CurvesEvalCache & hair_particle_get_eval_cache(ParticleDrawSource &src)
gpu::Batch * DRW_particles_batch_cache_get_edit_inner_points(Object *object, ParticleSystem *psys, PTCacheEdit *edit)
ParticleDrawSource drw_particle_get_hair_source(Object *object, ParticleSystem *psys, ModifierData *md, PTCacheEdit *edit, const int additional_subdivision)
gpu::Batch * DRW_particles_batch_cache_get_edit_tip_points(Object *object, ParticleSystem *psys, PTCacheEdit *edit)
static void drw_particle_update_ptcache_edit(Object *object_eval, ParticleSystem *psys, PTCacheEdit *edit)
static void particle_batch_cache_ensure_pos_and_seg(PTCacheEdit *edit, ParticleSystem *psys, ModifierData *md, ParticleHairCache *hair_cache)
static int particle_batch_cache_fill_segments_edit(const PTCacheEdit *, const ParticleData *particle, ParticleCacheKey **path_cache, const int start_index, const int num_path_keys, GPUIndexBufBuilder *elb, GPUVertBufRaw *attr_step)
static bool particle_batch_cache_valid(ParticleSystem *psys)
static void particle_batch_cache_ensure_edit_tip_pos(PTCacheEdit *edit, ParticleBatchCache *cache)
gpu::Batch * DRW_particles_batch_cache_get_edit_strands(Object *object, ParticleSystem *psys, PTCacheEdit *edit, bool use_weight)
static void particle_batch_cache_ensure_edit_pos_and_seg(PTCacheEdit *edit, ParticleSystem *psys, ModifierData *, ParticleHairCache *hair_cache, bool use_weight)
static void particle_calculate_uvs(ParticleSystem *psys, ParticleSystemModifierData *psmd, const bool is_simple, const int num_uv_layers, const int parent_index, const int child_index, const MTFace **mtfaces, float(**r_parent_uvs)[2], float(**r_uv)[2])
static void ensure_edit_inner_points_count(const PTCacheEdit *edit, ParticleBatchCache *cache)
gpu::Batch * DRW_particles_batch_cache_get_dots(Object *object, ParticleSystem *psys)
static std::optional< StringRef > get_first_uv_name(const bke::AttributeAccessor &attributes)
static void particle_batch_cache_clear(ParticleSystem *psys)
Span< T > span_from_custom_data_layer(const Mesh &mesh, const eCustomDataType type, const StringRef name)
static void particle_interpolate_children_uvs(ParticleSystem *psys, ParticleSystemModifierData *psmd, const int num_uv_layers, const int child_index, const MTFace **mtfaces, float(*r_uv)[2])
static void particle_pack_mcol(MCol *mcol, ushort r_scol[3])
static int particle_mface_index(const ParticleData &particle, int face_count_legacy)
static void particle_batch_cache_ensure_edit_inner_pos(PTCacheEdit *edit, ParticleBatchCache *cache)
void drw_curves_get_attribute_sampler_name(const StringRef layer_name, char r_sampler_name[32])
static void particle_batch_cache_clear_point(ParticlePointCache *point_cache)
static void particle_batch_cache_ensure_pos(Object *object, ParticleSystem *psys, ParticlePointCache *point_cache)
bool drw_attributes_overlap(const VectorSet< std::string > *a, const VectorSet< std::string > *b)
static float particle_key_weight(const ParticleData *particle, int strand, float t)
static void particle_calculate_parent_mcol(ParticleSystem *psys, ParticleSystemModifierData *psmd, const int num_col_layers, const int parent_index, const MCol **mcols, MCol *r_mcol)
static gpu::VertBufPtr ensure_curve_attribute(ParticleDrawSource &src, const Mesh &mesh, const StringRef name, bool &r_is_point_domain)
static void particle_calculate_mcol(ParticleSystem *psys, ParticleSystemModifierData *psmd, const bool is_simple, const int num_col_layers, const int parent_index, const int child_index, const MCol **mcols, MCol **r_parent_mcol, MCol **r_mcol)
static gpu::VertBufPtr interpolate_face_corner_attribute_to_curve(ParticleDrawSource &src, const StringRef name)
static void particle_batch_cache_init(ParticleSystem *psys)
void DRW_particle_batch_cache_dirty_tag(ParticleSystem *psys, int mode)
static float4 interpolate(const ParticleDataT &particle, Span< MFace > mfaces, Span< MCol > mcols)
static ParticleBatchCache * particle_batch_cache_get(ParticleSystem *psys)
static void particle_interpolate_children_mcol(ParticleSystem *psys, ParticleSystemModifierData *psmd, const int num_col_layers, const int child_index, const MCol **mcols, MCol *r_mcol)
static int particle_batch_cache_fill_segments(ParticleSystem *psys, ParticleSystemModifierData *psmd, ParticleCacheKey **path_cache, const ParticleSource particle_source, const int global_offset, const int start_index, const int num_path_keys, const int num_uv_layers, const int num_col_layers, const MTFace **mtfaces, const MCol **mcols, uint *uv_id, uint *col_id, float(***r_parent_uvs)[2], MCol ***r_parent_mcol, GPUIndexBufBuilder *elb, HairAttributeID *attr_id, ParticleHairCache *hair_cache)
void drw_attributes_merge(VectorSet< std::string > *dst, const VectorSet< std::string > *src)
gpu::Batch * DRW_particles_batch_cache_get_hair(Object *object, ParticleSystem *psys, ModifierData *md)
static float hair_shape_radius(float shape, float root, float tip, float time)
static void ensure_seg_pt_count(PTCacheEdit *edit, ParticleSystem *psys, ParticleHairCache *hair_cache)
static void ensure_edit_tip_points_count(const PTCacheEdit *edit, ParticleBatchCache *cache)
static const GPUVertFormat * edit_points_vert_format_get(uint *r_pos_id, uint *r_selection_id)
static void particle_batch_cache_clear_hair(ParticleHairCache *hair_cache)
static void particle_calculate_parent_uvs(ParticleSystem *psys, ParticleSystemModifierData *psmd, const int num_uv_layers, const int parent_index, const MTFace **mtfaces, float(*r_uv)[2])
std::unique_ptr< gpu::VertBuf, gpu::VertBufDeleter > VertBufPtr
T clamp(const T &a, const T &min, const T &max)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
void GPU_vertformat_alias_add(GPUVertFormat *, StringRef alias)
void GPU_indexbuf_init_ex(GPUIndexBufBuilder *, GPUPrimType, uint index_len, uint vertex_len)
MINLINE void copy_v3_v3(float r[3], const float a[3])
unsigned int uint
Definition BKE_text.h:55
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
bool assign_if_different(T &old_value, T &&new_value)
void psys_sim_data_init(struct ParticleSimulationData *sim)
Definition particle.cc:621
unsigned short ushort
Definition BKE_text.h:56
void GPU_indexbuf_add_primitive_restart(GPUIndexBufBuilder *)
@ GPU_PRIM_LINE_STRIP
struct ParticleSystem * psys_orig_get(struct ParticleSystem *psys)
Definition particle.cc:689
MatBase< float, 4, 4 > float4x4
struct ParticleSystemModifierData * psys_get_modifier(struct Object *ob, struct ParticleSystem *psys)
Definition particle.cc:2190
GPU_INLINE void * GPU_vertbuf_raw_step(GPUVertBufRaw *a)
void PE_update_object(Depsgraph *depsgraph, Scene *scene, Object *ob, int useflag)
VecBase< float, 4 > float4
float BLI_color_from_srgb_table[256]
bool psys_in_edit_mode(struct Depsgraph *depsgraph, const struct ParticleSystem *psys)
gpu::IndexBuf * GPU_indexbuf_build(GPUIndexBufBuilder *)
VecBase< float, 2 > float2
bool psys_get_particle_state(struct ParticleSimulationData *sim, int p, struct ParticleKey *state, bool always)
Definition particle.cc:4930
void GPU_vertformat_safe_attr_name(StringRef attr_name, char *r_safe_name, uint max_len)
BLI_INLINE void IMB_colormanagement_rec709_to_scene_linear(float scene_linear[3], const float rec709[3])
@ OB_MODE_PARTICLE_EDIT
BMesh const char void * data
void GPU_vertbuf_attr_set(gpu::VertBuf *, uint a_idx, uint v_idx, const void *data)
ListBaseT< GPUMaterialAttribute > GPU_material_attributes(const GPUMaterial *material)
const void * CustomData_get_layer(const CustomData *data, eCustomDataType type)
ATTR_WARN_UNUSED_RESULT const size_t num
MINLINE float len_v3(const float a[3]) ATTR_WARN_UNUSED_RESULT
gpu::VertBuf * GPU_vertbuf_create_with_format_ex(const GPUVertFormat &format, GPUUsageType usage)
void psys_interpolate_mcol(const struct MCol *mcol, int quad, const float w[4], struct MCol *mc)
void psys_interpolate_uvs(const struct MTFace *tface, int quad, const float w[4], float r_uv[2])
const DRWContext * DRW_context_get()
void GPU_vertbuf_attr_get_raw_data(gpu::VertBuf *, uint a_idx, GPUVertBufRaw *access)
eEvaluationMode DEG_get_mode(const Depsgraph *graph)
uint GPU_vertformat_attr_add(GPUVertFormat *format, StringRef name, gpu::VertAttrType type)
const void * CustomData_get_layer_n(const CustomData *data, eCustomDataType type, int n)
MINLINE void sub_v3_v3v3(float r[3], const float a[3], const float b[3])
T * DEG_get_original(T *id)
MINLINE unsigned short unit_float_to_ushort_clamp(float val)
@ CURVE_TYPE_CATMULL_ROM
void GPU_vertbuf_data_alloc(gpu::VertBuf &verts, uint v_len)
void GPU_vertbuf_data_resize(gpu::VertBuf &verts, uint v_len)
void BKE_mesh_tessface_ensure(Mesh *mesh)
void psys_cache_edit_paths(struct Depsgraph *depsgraph, struct Scene *scene, struct Object *ob, struct PTCacheEdit *edit, float cfra, bool use_render_params)
Definition particle.cc:3697
void GPU_indexbuf_add_generic_vert(GPUIndexBufBuilder *, uint v)
VecBase< float, 3 > float3
PTCacheEdit * PE_create_current(Depsgraph *depsgraph, Scene *scene, Object *ob)
MINLINE float len_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
int CustomData_get_named_layer(const CustomData *data, eCustomDataType type, StringRef name)
float DEG_get_ctime(const Depsgraph *graph)
@ GPU_USAGE_FLAG_BUFFER_TEXTURE_ONLY
void psys_sim_data_free(struct ParticleSimulationData *sim)
Definition particle.cc:662
@ BKE_PARTICLE_BATCH_DIRTY_ALL
void * MEM_new_array_zeroed(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
#define floorf
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
Depsgraph * depsgraph
char * active_color_attribute
CustomData fdata_legacy
struct PTCacheEditKey * keys
PTCacheEditPoint * points
struct ParticleSystem * psys
struct ParticleCacheKey ** pathcache
struct ParticleSystem * psys
struct ParticleSystemModifierData * psmd
draw::ParticleBatchCache * batch_cache
struct ParticleCacheKey ** childcache
struct ParticleCacheKey ** pathcache
eParticleSystem_Flag flag
std::array< bool, GPU_MAX_ATTR > attributes_point_domain
void ensure_common(const bke::CurvesGeometry &curves)
gpu::VertBufPtr & indirection_buf_get(CurvesModule &module, const bke::CurvesGeometry &curves, int face_per_segment)
void ensure_attributes(struct CurvesModule &module, const bke::CurvesGeometry &curves, const GPUMaterial *gpu_material)
void ensure_positions(CurvesModule &module, const bke::CurvesGeometry &curves)
gpu::VertBufPtr curve_attributes_buf[GPU_MAX_ATTR]
VectorSet< std::string > attr_used_over_time
VectorSet< std::string > attr_used
void ensure_attribute(struct CurvesModule &module, const bke::CurvesGeometry &curves, StringRef name, int index)
ParticleDrawSource(Vector< int > &points_by_curve_storage, Vector< int > &evaluated_points_by_curve_storage, int additional_subdivision)
void foreach_strand(FunctionRef< void(Span< ParticleCacheKey >)> callback)
Span< ParticleCacheKey * > parent
Span< ParticleCacheKey * > children