Welcome to mirror list, hosted at ThFree Co, Russian Federation.

simulate.cpp « bparticles « simulations « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bf96c971c2e800e41a5ba7480f1bb35e01929237 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493

#include "BLI_array_cxx.h"
#include "BLI_parallel.h"
#include "BLI_timeit.h"
#include "BLI_vector_adaptor.h"

#include "FN_cpp_type.h"

#include "simulate.hpp"

namespace BParticles {

using BLI::ScopedVector;
using BLI::VectorAdaptor;
using FN::CPPType;

BLI_NOINLINE static void find_next_event_per_particle(
    BlockStepData &step_data,
    IndexMask mask,
    ArrayRef<Event *> events,
    MutableArrayRef<int> r_next_event_indices,
    MutableArrayRef<float> r_time_factors_to_next_event,
    ScopedVector<uint> &r_pindices_with_event)
{
  r_next_event_indices.fill_indices(mask, -1);
  r_time_factors_to_next_event.fill_indices(mask, 1.0f);

  for (uint event_index : events.index_range()) {
    Vector<uint> triggered_pindices;
    Vector<float> triggered_time_factors;

    Event *event = events[event_index];
    EventFilterInterface interface(
        step_data, mask, r_time_factors_to_next_event, triggered_pindices, triggered_time_factors);
    event->filter(interface);

    for (uint i : triggered_pindices.index_range()) {
      uint pindex = triggered_pindices[i];
      float time_factor = triggered_time_factors[i];
      BLI_assert(time_factor <= r_time_factors_to_next_event[pindex]);

      r_next_event_indices[pindex] = event_index;
      r_time_factors_to_next_event[pindex] = time_factor;
    }
  }

  for (uint pindex : mask) {
    if (r_next_event_indices[pindex] != -1) {
      r_pindices_with_event.append(pindex);
    }
  }
}

BLI_NOINLINE static void forward_particles_to_next_event_or_end(
    BlockStepData &step_data,
    ParticleAllocator &particle_allocator,
    IndexMask mask,
    ArrayRef<float> time_factors_to_next_event,
    ArrayRef<OffsetHandler *> offset_handlers)
{
  OffsetHandlerInterface interface(
      step_data, mask, time_factors_to_next_event, particle_allocator);
  for (OffsetHandler *handler : offset_handlers) {
    handler->execute(interface);
  }

  auto attributes = step_data.attributes;
  auto attribute_offsets = step_data.attribute_offsets;
  for (uint attribute_index : attribute_offsets.info().indices()) {
    StringRef name = attribute_offsets.info().name_of(attribute_index);

    /* Only vectors can be integrated for now. */
    auto values = attributes.get<float3>(name);
    auto offsets = attribute_offsets.get<float3>(attribute_index);

    for (uint pindex : mask) {
      float time_factor = time_factors_to_next_event[pindex];
      values[pindex] += time_factor * offsets[pindex];
    }
  }
}

BLI_NOINLINE static void update_remaining_attribute_offsets(
    IndexMask mask,
    ArrayRef<float> time_factors_to_next_event,
    MutableAttributesRef attribute_offsets)
{
  for (uint attribute_index : attribute_offsets.info().indices()) {
    /* Only vectors can be integrated for now. */
    auto offsets = attribute_offsets.get<float3>(attribute_index);

    for (uint pindex : mask) {
      float factor = 1.0f - time_factors_to_next_event[pindex];
      offsets[pindex] *= factor;
    }
  }
}

BLI_NOINLINE static void update_remaining_durations(IndexMask mask,
                                                    ArrayRef<float> time_factors_to_next_event,
                                                    MutableArrayRef<float> remaining_durations)
{
  for (uint pindex : mask) {
    remaining_durations[pindex] *= (1.0f - time_factors_to_next_event[pindex]);
  }
}

BLI_NOINLINE static void find_pindices_per_event(
    IndexMask mask,
    ArrayRef<int> next_event_indices,
    MutableArrayRef<Vector<uint>> r_particles_per_event)
{
  for (uint pindex : mask) {
    int event_index = next_event_indices[pindex];
    BLI_assert(event_index >= 0);
    r_particles_per_event[event_index].append(pindex);
  }
}

BLI_NOINLINE static void compute_current_time_per_particle(IndexMask mask,
                                                           ArrayRef<float> remaining_durations,
                                                           float end_time,
                                                           MutableArrayRef<float> r_current_times)
{
  for (uint pindex : mask) {
    r_current_times[pindex] = end_time - remaining_durations[pindex];
  }
}

BLI_NOINLINE static void find_unfinished_particles(IndexMask mask,
                                                   ArrayRef<float> time_factors_to_next_event,
                                                   ArrayRef<bool> kill_states,
                                                   VectorAdaptor<uint> &r_unfinished_pindices)
{
  for (uint pindex : mask) {
    if (kill_states[pindex] == 0) {
      float time_factor = time_factors_to_next_event[pindex];

      if (time_factor < 1.0f) {
        r_unfinished_pindices.append(pindex);
      }
    }
  }
}

BLI_NOINLINE static void execute_events(BlockStepData &step_data,
                                        ParticleAllocator &particle_allocator,
                                        ArrayRef<Vector<uint>> pindices_per_event,
                                        ArrayRef<float> current_times,
                                        ArrayRef<Event *> events)
{
  BLI::assert_same_size(events, pindices_per_event);

  for (uint event_index : events.index_range()) {
    Event *event = events[event_index];
    ArrayRef<uint> pindices = pindices_per_event[event_index];

    if (pindices.size() == 0) {
      continue;
    }

    EventExecuteInterface interface(step_data, pindices, current_times, particle_allocator);
    event->execute(interface);
  }
}

BLI_NOINLINE static void simulate_to_next_event(BlockStepData &step_data,
                                                ParticleAllocator &particle_allocator,
                                                IndexMask mask,
                                                ParticleSystemInfo &system_info,
                                                VectorAdaptor<uint> &r_unfinished_pindices)
{
  uint amount = step_data.array_size();
  Array<int> next_event_indices(amount);
  Array<float> time_factors_to_next_event(amount);
  ScopedVector<uint> pindices_with_event;

  find_next_event_per_particle(step_data,
                               mask,
                               system_info.events,
                               next_event_indices,
                               time_factors_to_next_event,
                               pindices_with_event);

  forward_particles_to_next_event_or_end(step_data,
                                         particle_allocator,
                                         mask,
                                         time_factors_to_next_event,
                                         system_info.offset_handlers);

  update_remaining_attribute_offsets(
      pindices_with_event, time_factors_to_next_event, step_data.attribute_offsets);

  update_remaining_durations(
      pindices_with_event, time_factors_to_next_event, step_data.remaining_durations);

  Vector<Vector<uint>> particles_per_event(system_info.events.size());
  find_pindices_per_event(pindices_with_event, next_event_indices, particles_per_event);

  Array<float> current_times(amount);
  compute_current_time_per_particle(
      pindices_with_event, step_data.remaining_durations, step_data.step_end_time, current_times);

  execute_events(
      step_data, particle_allocator, particles_per_event, current_times, system_info.events);

  find_unfinished_particles(pindices_with_event,
                            time_factors_to_next_event,
                            step_data.attributes.get<bool>("Dead"),
                            r_unfinished_pindices);
}

BLI_NOINLINE static void simulate_with_max_n_events(BlockStepData &step_data,
                                                    ParticleAllocator &particle_allocator,
                                                    uint max_events,
                                                    ParticleSystemInfo &system_info,
                                                    ScopedVector<uint> &r_unfinished_pindices)
{
  Array<uint> pindices_A(step_data.array_size());
  Array<uint> pindices_B(step_data.array_size());

  uint amount_left = step_data.attributes.size();

  {
    /* Handle first event separately to be able to use the static number range. */
    VectorAdaptor<uint> pindices_output(pindices_A.begin(), amount_left);
    simulate_to_next_event(step_data,
                           particle_allocator,
                           IndexRange(amount_left).as_array_ref(),
                           system_info,
                           pindices_output);
    amount_left = pindices_output.size();
  }

  for (uint iteration = 0; iteration < max_events - 1 && amount_left > 0; iteration++) {
    VectorAdaptor<uint> pindices_input(pindices_A.begin(), amount_left, amount_left);
    VectorAdaptor<uint> pindices_output(pindices_B.begin(), amount_left, 0);

    simulate_to_next_event(
        step_data, particle_allocator, pindices_input, system_info, pindices_output);
    amount_left = pindices_output.size();
    std::swap(pindices_A, pindices_B);
  }

  for (uint i = 0; i < amount_left; i++) {
    r_unfinished_pindices.append(pindices_A[i]);
  }
}

BLI_NOINLINE static void apply_remaining_offsets(BlockStepData &step_data,
                                                 ParticleAllocator &particle_allocator,
                                                 ArrayRef<OffsetHandler *> offset_handlers,
                                                 IndexMask mask)
{
  if (offset_handlers.size() > 0) {
    Array<float> time_factors(step_data.array_size());
    time_factors.fill_indices(mask, 1.0f);

    OffsetHandlerInterface interface(step_data, mask, time_factors, particle_allocator);
    for (OffsetHandler *handler : offset_handlers) {
      handler->execute(interface);
    }
  }

  auto attributes = step_data.attributes;
  auto attribute_offsets = step_data.attribute_offsets;

  for (uint attribute_index : attribute_offsets.info().indices()) {
    StringRef name = attribute_offsets.info().name_of(attribute_index);

    /* Only vectors can be integrated for now. */
    auto values = attributes.get<float3>(name);
    auto offsets = attribute_offsets.get<float3>(attribute_index);

    for (uint pindex : mask) {
      values[pindex] += offsets[pindex];
    }
  }
}

BLI_NOINLINE static void simulate_particle_chunk(SimulationState &simulation_state,
                                                 ParticleAllocator &particle_allocator,
                                                 MutableAttributesRef attributes,
                                                 ParticleSystemInfo &system_info,
                                                 MutableArrayRef<float> remaining_durations,
                                                 float end_time)
{
  uint amount = attributes.size();
  BLI_assert(amount == remaining_durations.size());

  BufferCache buffer_cache;

  Integrator &integrator = *system_info.integrator;
  const AttributesInfo &offsets_info = integrator.offset_attributes_info();
  Vector<void *> offset_buffers;
  for (const CPPType *type : offsets_info.types()) {
    void *ptr = buffer_cache.allocate(type->size() * amount, type->alignment());
    offset_buffers.append(ptr);
  }
  MutableAttributesRef attribute_offsets(offsets_info, offset_buffers, amount);

  BlockStepData step_data = {simulation_state,
                             buffer_cache,
                             attributes,
                             attribute_offsets,
                             remaining_durations,
                             end_time};

  IntegratorInterface interface(step_data, IndexRange(amount).as_array_ref());
  integrator.integrate(interface);

  if (system_info.events.size() == 0) {
    apply_remaining_offsets(step_data,
                            particle_allocator,
                            system_info.offset_handlers,
                            IndexRange(amount).as_array_ref());
  }
  else {
    ScopedVector<uint> unfinished_pindices;
    simulate_with_max_n_events(
        step_data, particle_allocator, 10, system_info, unfinished_pindices);

    /* Not sure yet, if this really should be done. */
    if (unfinished_pindices.size() > 0) {
      apply_remaining_offsets(
          step_data, particle_allocator, system_info.offset_handlers, unfinished_pindices);
    }
  }

  for (void *buffer : offset_buffers) {
    buffer_cache.deallocate(buffer);
  }
}

BLI_NOINLINE static void delete_tagged_particles_and_reorder(ParticleSet &particles)
{
  auto kill_states = particles.attributes().get<bool>("Dead");
  ScopedVector<uint> indices_to_delete;

  for (uint i : kill_states.index_range()) {
    if (kill_states[i]) {
      indices_to_delete.append(i);
    }
  }

  particles.destruct_and_reorder(indices_to_delete.as_ref());
}

BLI_NOINLINE static void simulate_particles_for_time_span(SimulationState &simulation_state,
                                                          ParticleAllocator &particle_allocator,
                                                          ParticleSystemInfo &system_info,
                                                          FloatInterval time_span,
                                                          MutableAttributesRef particle_attributes)
{
  BLI::blocked_parallel_for(IndexRange(particle_attributes.size()), 1000, [&](IndexRange range) {
    Array<float> remaining_durations(range.size(), time_span.size());
    simulate_particle_chunk(simulation_state,
                            particle_allocator,
                            particle_attributes.slice(range),
                            system_info,
                            remaining_durations,
                            time_span.end());
  });
}

BLI_NOINLINE static void simulate_particles_from_birth_to_end_of_step(
    SimulationState &simulation_state,
    ParticleAllocator &particle_allocator,
    ParticleSystemInfo &system_info,
    float end_time,
    MutableAttributesRef particle_attributes)
{
  ArrayRef<float> all_birth_times = particle_attributes.get<float>("Birth Time");

  BLI::blocked_parallel_for(IndexRange(particle_attributes.size()), 1000, [&](IndexRange range) {
    ArrayRef<float> birth_times = all_birth_times.slice(range);

    Array<float> remaining_durations(range.size());
    for (uint i : remaining_durations.index_range()) {
      remaining_durations[i] = end_time - birth_times[i];
    }

    simulate_particle_chunk(simulation_state,
                            particle_allocator,
                            particle_attributes.slice(range),
                            system_info,
                            remaining_durations,
                            end_time);
  });
}

BLI_NOINLINE static void simulate_existing_particles(
    SimulationState &simulation_state,
    ParticleAllocator &particle_allocator,
    StringMap<ParticleSystemInfo> &systems_to_simulate)
{
  FloatInterval simulation_time_span = simulation_state.time().current_update_time();

  BLI::parallel_map_items(simulation_state.particles().particle_containers(),
                          [&](StringRef system_name, ParticleSet *particle_set) {
                            ParticleSystemInfo *system_info = systems_to_simulate.lookup_ptr(
                                system_name);
                            if (system_info == nullptr) {
                              return;
                            }

                            simulate_particles_for_time_span(simulation_state,
                                                             particle_allocator,
                                                             *system_info,
                                                             simulation_time_span,
                                                             particle_set->attributes());
                          });
}

BLI_NOINLINE static void create_particles_from_emitters(SimulationState &simulation_state,
                                                        ParticleAllocator &particle_allocator,
                                                        ArrayRef<Emitter *> emitters,
                                                        FloatInterval time_span)
{
  BLI::parallel_for(emitters.index_range(), [&](uint emitter_index) {
    Emitter &emitter = *emitters[emitter_index];
    EmitterInterface interface(simulation_state, particle_allocator, time_span);
    emitter.emit(interface);
  });
}

void simulate_particles(SimulationState &simulation_state,
                        ArrayRef<Emitter *> emitters,
                        StringMap<ParticleSystemInfo> &systems_to_simulate)
{
  SCOPED_TIMER(__func__);

  ParticlesState &particles_state = simulation_state.particles();
  FloatInterval simulation_time_span = simulation_state.time().current_update_time();

  StringMultiMap<ParticleSet *> all_newly_created_particles;
  StringMultiMap<ParticleSet *> newly_created_particles;
  {
    ParticleAllocator particle_allocator(particles_state);
    BLI::parallel_invoke(
        [&]() {
          simulate_existing_particles(simulation_state, particle_allocator, systems_to_simulate);
        },
        [&]() {
          create_particles_from_emitters(
              simulation_state, particle_allocator, emitters, simulation_time_span);
        });

    newly_created_particles = particle_allocator.allocated_particles();
    all_newly_created_particles = newly_created_particles;
  }

  while (newly_created_particles.key_amount() > 0) {
    ParticleAllocator particle_allocator(particles_state);

    BLI::parallel_map_items(
        newly_created_particles, [&](StringRef name, ArrayRef<ParticleSet *> new_particle_sets) {
          ParticleSystemInfo *system_info = systems_to_simulate.lookup_ptr(name);
          if (system_info == nullptr) {
            return;
          }

          BLI::parallel_for(new_particle_sets.index_range(), [&](uint index) {
            ParticleSet &particle_set = *new_particle_sets[index];
            simulate_particles_from_birth_to_end_of_step(simulation_state,
                                                         particle_allocator,
                                                         *system_info,
                                                         simulation_time_span.end(),
                                                         particle_set.attributes());
          });
        });

    newly_created_particles = particle_allocator.allocated_particles();
    all_newly_created_particles.add_multiple(newly_created_particles);
  }

  BLI::parallel_map_items(all_newly_created_particles,
                          [&](StringRef name, ArrayRef<ParticleSet *> new_particle_sets) {
                            ParticleSet &main_set = particles_state.particle_container(name);

                            for (ParticleSet *set : new_particle_sets) {
                              main_set.add_particles(*set);
                              delete set;
                            }
                          });

  BLI::parallel_map_keys(systems_to_simulate, [&](StringRef name) {
    ParticleSet &particles = particles_state.particle_container(name);
    delete_tagged_particles_and_reorder(particles);
  });
}

}  // namespace BParticles