Cleanup: style
[blender.git] / source / blender / modifiers / intern / MOD_particleinstance.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software  Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2005 by the Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Daniel Dunbar
22  *                 Ton Roosendaal,
23  *                 Ben Batt,
24  *                 Brecht Van Lommel,
25  *                 Campbell Barton
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  *
29  */
30
31 /** \file blender/modifiers/intern/MOD_particleinstance.c
32  *  \ingroup modifiers
33  */
34
35
36 #include "DNA_mesh_types.h"
37 #include "DNA_meshdata_types.h"
38
39 #include "MEM_guardedalloc.h"
40
41 #include "BLI_math.h"
42 #include "BLI_listbase.h"
43 #include "BLI_rand.h"
44 #include "BLI_string.h"
45 #include "BLI_utildefines.h"
46
47 #include "BKE_effect.h"
48 #include "BKE_global.h"
49 #include "BKE_lattice.h"
50 #include "BKE_library_query.h"
51 #include "BKE_mesh.h"
52 #include "BKE_modifier.h"
53 #include "BKE_particle.h"
54 #include "BKE_pointcache.h"
55
56 #include "DEG_depsgraph_build.h"
57
58 static void initData(ModifierData *md)
59 {
60         ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *) md;
61
62         pimd->flag = eParticleInstanceFlag_Parents | eParticleInstanceFlag_Unborn |
63                      eParticleInstanceFlag_Alive | eParticleInstanceFlag_Dead;
64         pimd->psys = 1;
65         pimd->position = 1.0f;
66         pimd->axis = 2;
67         pimd->space = eParticleInstanceSpace_World;
68         pimd->particle_amount = 1.0f;
69         pimd->particle_offset = 0.0f;
70
71         STRNCPY(pimd->index_layer_name, "");
72         STRNCPY(pimd->value_layer_name, "");
73 }
74
75 static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md)
76 {
77         ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *)md;
78         CustomDataMask dataMask = 0;
79
80         if (pimd->index_layer_name[0] != '\0' ||
81             pimd->value_layer_name[0] != '\0')
82         {
83                 dataMask |= CD_MASK_MLOOPCOL;
84         }
85
86         return dataMask;
87
88 }
89
90 static bool isDisabled(ModifierData *md, int useRenderParams)
91 {
92         ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *)md;
93         ParticleSystem *psys;
94         ModifierData *ob_md;
95
96         if (!pimd->ob)
97                 return true;
98
99         psys = BLI_findlink(&pimd->ob->particlesystem, pimd->psys - 1);
100         if (psys == NULL)
101                 return true;
102
103         /* If the psys modifier is disabled we cannot use its data.
104          * First look up the psys modifier from the object, then check if it is enabled.
105          */
106         for (ob_md = pimd->ob->modifiers.first; ob_md; ob_md = ob_md->next) {
107                 if (ob_md->type == eModifierType_ParticleSystem) {
108                         ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)ob_md;
109                         if (psmd->psys == psys) {
110                                 int required_mode;
111
112                                 if (useRenderParams) required_mode = eModifierMode_Render;
113                                 else required_mode = eModifierMode_Realtime;
114
115                                 if (!modifier_isEnabled(md->scene, ob_md, required_mode))
116                                         return true;
117
118                                 break;
119                         }
120                 }
121         }
122
123         return false;
124 }
125
126 static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
127 {
128         ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *) md;
129         if (pimd->ob != NULL) {
130                 DEG_add_object_relation(ctx->node, pimd->ob, DEG_OB_COMP_TRANSFORM, "Particle Instance Modifier");
131                 DEG_add_object_relation(ctx->node, pimd->ob, DEG_OB_COMP_GEOMETRY, "Particle Instance Modifier");
132         }
133 }
134
135 static void foreachObjectLink(
136         ModifierData *md, Object *ob,
137         ObjectWalkFunc walk, void *userData)
138 {
139         ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *) md;
140
141         walk(userData, ob, &pimd->ob, IDWALK_CB_NOP);
142 }
143
144 static bool particle_skip(ParticleInstanceModifierData *pimd, ParticleSystem *psys, int p)
145 {
146         const bool between = (psys->part->childtype == PART_CHILD_FACES);
147         ParticleData *pa;
148         int totpart, randp, minp, maxp;
149
150         if (p >= psys->totpart) {
151                 ChildParticle *cpa = psys->child + (p - psys->totpart);
152                 pa = psys->particles + (between ? cpa->pa[0] : cpa->parent);
153         }
154         else {
155                 pa = psys->particles + p;
156         }
157
158         if (pa) {
159                 if (pa->alive == PARS_UNBORN && (pimd->flag & eParticleInstanceFlag_Unborn) == 0) return true;
160                 if (pa->alive == PARS_ALIVE && (pimd->flag & eParticleInstanceFlag_Alive) == 0) return true;
161                 if (pa->alive == PARS_DEAD && (pimd->flag & eParticleInstanceFlag_Dead) == 0) return true;
162         }
163
164         if (pimd->particle_amount == 1.0f) {
165                 /* Early output, all particles are to be instanced. */
166                 return false;
167         }
168
169         /* Randomly skip particles based on desired amount of visible particles. */
170
171         totpart = psys->totpart + psys->totchild;
172
173         /* TODO make randomization optional? */
174         randp = (int)(psys_frand(psys, 3578 + p) * totpart) % totpart;
175
176         minp = (int)(totpart * pimd->particle_offset) % (totpart + 1);
177         maxp = (int)(totpart * (pimd->particle_offset + pimd->particle_amount)) % (totpart + 1);
178
179         if (maxp > minp) {
180                 return randp < minp || randp >= maxp;
181         }
182         else if (maxp < minp) {
183                 return randp < minp && randp >= maxp;
184         }
185         else {
186                 return true;
187         }
188
189         return false;
190 }
191
192 static void store_float_in_vcol(MLoopCol *vcol, float float_value)
193 {
194         const uchar value = unit_float_to_uchar_clamp(float_value);
195         vcol->r = vcol->g = vcol->b = value;
196         vcol->a = 1.0f;
197 }
198
199 static Mesh *applyModifier(
200         ModifierData *md, const ModifierEvalContext *ctx,
201         Mesh *mesh)
202 {
203         Mesh *result;
204         ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *) md;
205         ParticleSimulationData sim;
206         ParticleSystem *psys = NULL;
207         ParticleData *pa = NULL;
208         MPoly *mpoly, *orig_mpoly;
209         MLoop *mloop, *orig_mloop;
210         MVert *mvert, *orig_mvert;
211         int totvert, totpoly, totloop, totedge;
212         int maxvert, maxpoly, maxloop, maxedge, part_end = 0, part_start;
213         int k, p, p_skip;
214         short track = ctx->object->trackflag % 3, trackneg, axis = pimd->axis;
215         float max_co = 0.0, min_co = 0.0, temp_co[3];
216         float *size = NULL;
217         float spacemat[4][4];
218         const bool use_parents = pimd->flag & eParticleInstanceFlag_Parents;
219         const bool use_children = pimd->flag & eParticleInstanceFlag_Children;
220         bool between;
221
222         trackneg = ((ctx->object->trackflag > 2) ? 1 : 0);
223
224         if (pimd->ob == ctx->object) {
225                 pimd->ob = NULL;
226                 return mesh;
227         }
228
229         if (pimd->ob) {
230                 psys = BLI_findlink(&pimd->ob->particlesystem, pimd->psys - 1);
231                 if (psys == NULL || psys->totpart == 0)
232                         return mesh;
233         }
234         else {
235                 return mesh;
236         }
237
238         part_start = use_parents ? 0 : psys->totpart;
239
240         part_end = 0;
241         if (use_parents)
242                 part_end += psys->totpart;
243         if (use_children)
244                 part_end += psys->totchild;
245
246         if (part_end == 0)
247                 return mesh;
248
249         sim.depsgraph = ctx->depsgraph;
250         sim.scene = md->scene;
251         sim.ob = pimd->ob;
252         sim.psys = psys;
253         sim.psmd = psys_get_modifier(pimd->ob, psys);
254         between = (psys->part->childtype == PART_CHILD_FACES);
255
256         if (pimd->flag & eParticleInstanceFlag_UseSize) {
257                 float *si;
258                 si = size = MEM_calloc_arrayN(part_end, sizeof(float), "particle size array");
259
260                 if (pimd->flag & eParticleInstanceFlag_Parents) {
261                         for (p = 0, pa = psys->particles; p < psys->totpart; p++, pa++, si++)
262                                 *si = pa->size;
263                 }
264
265                 if (pimd->flag & eParticleInstanceFlag_Children) {
266                         ChildParticle *cpa = psys->child;
267
268                         for (p = 0; p < psys->totchild; p++, cpa++, si++) {
269                                 *si = psys_get_child_size(psys, cpa, 0.0f, NULL);
270                         }
271                 }
272         }
273
274         switch (pimd->space) {
275                 case eParticleInstanceSpace_World:
276                         /* particle states are in world space already */
277                         unit_m4(spacemat);
278                         break;
279                 case eParticleInstanceSpace_Local:
280                         /* get particle states in the particle object's local space */
281                         invert_m4_m4(spacemat, pimd->ob->obmat);
282                         break;
283                 default:
284                         /* should not happen */
285                         BLI_assert(false);
286                         break;
287         }
288
289         totvert = mesh->totvert;
290         totpoly = mesh->totpoly;
291         totloop = mesh->totloop;
292         totedge = mesh->totedge;
293
294         /* count particles */
295         maxvert = 0;
296         maxpoly = 0;
297         maxloop = 0;
298         maxedge = 0;
299
300         for (p = part_start; p < part_end; p++) {
301                 if (particle_skip(pimd, psys, p))
302                         continue;
303
304                 maxvert += totvert;
305                 maxpoly += totpoly;
306                 maxloop += totloop;
307                 maxedge += totedge;
308         }
309
310         psys->lattice_deform_data = psys_create_lattice_deform_data(&sim);
311
312         if (psys->flag & (PSYS_HAIR_DONE | PSYS_KEYED) || psys->pointcache->flag & PTCACHE_BAKED) {
313                 float min[3], max[3];
314                 INIT_MINMAX(min, max);
315                 BKE_mesh_minmax(mesh, min, max);
316                 min_co = min[track];
317                 max_co = max[track];
318         }
319
320         result = BKE_mesh_new_nomain_from_template(mesh, maxvert, maxedge, 0, maxloop, maxpoly);
321
322         mvert = result->mvert;
323         orig_mvert = mesh->mvert;
324         mpoly = result->mpoly;
325         orig_mpoly = mesh->mpoly;
326         mloop = result->mloop;
327         orig_mloop = mesh->mloop;
328
329         MLoopCol *mloopcols_index = CustomData_get_layer_named(&result->ldata, CD_MLOOPCOL, pimd->index_layer_name);
330         MLoopCol *mloopcols_value = CustomData_get_layer_named(&result->ldata, CD_MLOOPCOL, pimd->value_layer_name);
331         int *vert_part_index = NULL;
332         float *vert_part_value = NULL;
333         if (mloopcols_index != NULL) {
334                 vert_part_index = MEM_calloc_arrayN(maxvert, sizeof(int), "vertex part index array");
335         }
336         if (mloopcols_value) {
337                 vert_part_value = MEM_calloc_arrayN(maxvert, sizeof(float), "vertex part value array");
338         }
339
340         for (p = part_start, p_skip = 0; p < part_end; p++) {
341                 float prev_dir[3];
342                 float frame[4]; /* frame orientation quaternion */
343                 float p_random = psys_frand(psys, 77091 + 283 * p);
344
345                 /* skip particle? */
346                 if (particle_skip(pimd, psys, p))
347                         continue;
348
349                 /* set vertices coordinates */
350                 for (k = 0; k < totvert; k++) {
351                         ParticleKey state;
352                         MVert *inMV;
353                         int vindex = p_skip * totvert + k;
354                         MVert *mv = mvert + vindex;
355
356                         inMV = orig_mvert + k;
357                         CustomData_copy_data(&mesh->vdata, &result->vdata, k, p_skip * totvert + k, 1);
358                         *mv = *inMV;
359
360                         if (vert_part_index != NULL) {
361                                 vert_part_index[vindex] = p;
362                         }
363                         if (vert_part_value != NULL) {
364                                 vert_part_value[vindex] = p_random;
365                         }
366
367                         /*change orientation based on object trackflag*/
368                         copy_v3_v3(temp_co, mv->co);
369                         mv->co[axis] = temp_co[track];
370                         mv->co[(axis + 1) % 3] = temp_co[(track + 1) % 3];
371                         mv->co[(axis + 2) % 3] = temp_co[(track + 2) % 3];
372
373                         /* get particle state */
374                         if ((psys->flag & (PSYS_HAIR_DONE | PSYS_KEYED) || psys->pointcache->flag & PTCACHE_BAKED) &&
375                             (pimd->flag & eParticleInstanceFlag_Path))
376                         {
377                                 float ran = 0.0f;
378                                 if (pimd->random_position != 0.0f) {
379                                         ran = pimd->random_position * BLI_hash_frand(psys->seed + p);
380                                 }
381
382                                 if (pimd->flag & eParticleInstanceFlag_KeepShape) {
383                                         state.time = pimd->position * (1.0f - ran);
384                                 }
385                                 else {
386                                         state.time = (mv->co[axis] - min_co) / (max_co - min_co) * pimd->position * (1.0f - ran);
387
388                                         if (trackneg)
389                                                 state.time = 1.0f - state.time;
390
391                                         mv->co[axis] = 0.0;
392                                 }
393
394                                 psys_get_particle_on_path(&sim, p, &state, 1);
395
396                                 normalize_v3(state.vel);
397
398                                 /* Incrementally Rotating Frame (Bishop Frame) */
399                                 if (k == 0) {
400                                         float hairmat[4][4];
401                                         float mat[3][3];
402
403                                         if (p < psys->totpart)
404                                                 pa = psys->particles + p;
405                                         else {
406                                                 ChildParticle *cpa = psys->child + (p - psys->totpart);
407                                                 pa = psys->particles + (between ? cpa->pa[0] : cpa->parent);
408                                         }
409                                         psys_mat_hair_to_global(sim.ob, sim.psmd->mesh_final, sim.psys->part->from, pa, hairmat);
410                                         copy_m3_m4(mat, hairmat);
411                                         /* to quaternion */
412                                         mat3_to_quat(frame, mat);
413
414                                         if (pimd->rotation > 0.0f || pimd->random_rotation > 0.0f) {
415                                                 float angle = 2.0f * M_PI * (pimd->rotation + pimd->random_rotation * (psys_frand(psys, 19957323 + p) - 0.5f));
416                                                 float eul[3] = { 0.0f, 0.0f, angle };
417                                                 float rot[4];
418
419                                                 eul_to_quat(rot, eul);
420                                                 mul_qt_qtqt(frame, frame, rot);
421                                         }
422
423                                         /* note: direction is same as normal vector currently,
424                                          * but best to keep this separate so the frame can be
425                                          * rotated later if necessary
426                                          */
427                                         copy_v3_v3(prev_dir, state.vel);
428                                 }
429                                 else {
430                                         float rot[4];
431
432                                         /* incrementally rotate along bend direction */
433                                         rotation_between_vecs_to_quat(rot, prev_dir, state.vel);
434                                         mul_qt_qtqt(frame, rot, frame);
435
436                                         copy_v3_v3(prev_dir, state.vel);
437                                 }
438
439                                 copy_qt_qt(state.rot, frame);
440 #if 0
441                                 /* Absolute Frame (Frenet Frame) */
442                                 if (state.vel[axis] < -0.9999f || state.vel[axis] > 0.9999f) {
443                                         unit_qt(state.rot);
444                                 }
445                                 else {
446                                         float cross[3];
447                                         float temp[3] = {0.0f, 0.0f, 0.0f};
448                                         temp[axis] = 1.0f;
449
450                                         cross_v3_v3v3(cross, temp, state.vel);
451
452                                         /* state.vel[axis] is the only component surviving from a dot product with the axis */
453                                         axis_angle_to_quat(state.rot, cross, saacos(state.vel[axis]));
454                                 }
455 #endif
456                         }
457                         else {
458                                 state.time = -1.0;
459                                 psys_get_particle_state(&sim, p, &state, 1);
460                         }
461
462                         mul_qt_v3(state.rot, mv->co);
463                         if (pimd->flag & eParticleInstanceFlag_UseSize)
464                                 mul_v3_fl(mv->co, size[p]);
465                         add_v3_v3(mv->co, state.co);
466
467                         mul_m4_v3(spacemat, mv->co);
468                 }
469
470                 /* create edges and adjust edge vertex indices*/
471                 CustomData_copy_data(&mesh->edata, &result->edata, 0, p_skip * totedge, totedge);
472                 MEdge *me = &result->medge[p_skip * totedge];
473                 for (k = 0; k < totedge; k++, me++) {
474                         me->v1 += p_skip * totvert;
475                         me->v2 += p_skip * totvert;
476                 }
477
478                 /* create polys and loops */
479                 for (k = 0; k < totpoly; k++) {
480
481                         MPoly *inMP = orig_mpoly + k;
482                         MPoly *mp = mpoly + p_skip * totpoly + k;
483
484                         CustomData_copy_data(&mesh->pdata, &result->pdata, k, p_skip * totpoly + k, 1);
485                         *mp = *inMP;
486                         mp->loopstart += p_skip * totloop;
487
488                         {
489                                 MLoop *inML = orig_mloop + inMP->loopstart;
490                                 MLoop *ml = mloop + mp->loopstart;
491                                 int j = mp->totloop;
492
493                                 CustomData_copy_data(&mesh->ldata, &result->ldata, inMP->loopstart, mp->loopstart, j);
494                                 for (; j; j--, ml++, inML++) {
495                                         ml->v = inML->v + (p_skip * totvert);
496                                         ml->e = inML->e + (p_skip * totedge);
497                                         const int ml_index = (ml - mloop);
498                                         if (mloopcols_index != NULL) {
499                                                 const int part_index = vert_part_index[ml->v];
500                                                 store_float_in_vcol(&mloopcols_index[ml_index], (float)part_index / psys->totpart);
501                                         }
502                                         if (mloopcols_value != NULL) {
503                                                 const float part_value = vert_part_value[ml->v];
504                                                 store_float_in_vcol(&mloopcols_value[ml_index], part_value);
505                                         }
506                                 }
507                         }
508                 }
509                 p_skip++;
510         }
511
512         if (psys->lattice_deform_data) {
513                 end_latt_deform(psys->lattice_deform_data);
514                 psys->lattice_deform_data = NULL;
515         }
516
517         if (size)
518                 MEM_freeN(size);
519
520         MEM_SAFE_FREE(vert_part_index);
521         MEM_SAFE_FREE(vert_part_value);
522
523         result->runtime.cd_dirty_vert |= CD_MASK_NORMAL;
524
525         return result;
526 }
527 ModifierTypeInfo modifierType_ParticleInstance = {
528         /* name */              "ParticleInstance",
529         /* structName */        "ParticleInstanceModifierData",
530         /* structSize */        sizeof(ParticleInstanceModifierData),
531         /* type */              eModifierTypeType_Constructive,
532         /* flags */             eModifierTypeFlag_AcceptsMesh |
533                                 eModifierTypeFlag_SupportsMapping |
534                                 eModifierTypeFlag_SupportsEditmode |
535                                 eModifierTypeFlag_EnableInEditmode,
536
537         /* copyData */          modifier_copyData_generic,
538
539         /* deformVerts_DM */    NULL,
540         /* deformMatrices_DM */ NULL,
541         /* deformVertsEM_DM */  NULL,
542         /* deformMatricesEM_DM*/NULL,
543         /* applyModifier_DM */  NULL,
544         /* applyModifierEM_DM */NULL,
545
546         /* deformVerts */       NULL,
547         /* deformMatrices */    NULL,
548         /* deformVertsEM */     NULL,
549         /* deformMatricesEM */  NULL,
550         /* applyModifier */     applyModifier,
551         /* applyModifierEM */   NULL,
552
553         /* initData */          initData,
554         /* requiredDataMask */  requiredDataMask,
555         /* freeData */          NULL,
556         /* isDisabled */        isDisabled,
557         /* updateDepsgraph */   updateDepsgraph,
558         /* dependsOnTime */     NULL,
559         /* dependsOnNormals */  NULL,
560         /* foreachObjectLink */ foreachObjectLink,
561         /* foreachIDLink */     NULL,
562         /* foreachTexLink */    NULL,
563 };