Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / physics / particle_object.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) 2009 Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/physics/particle_object.c
27  *  \ingroup edphys
28  */
29
30
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_mesh_types.h"
37 #include "DNA_meshdata_types.h"
38 #include "DNA_modifier_types.h"
39 #include "DNA_scene_types.h"
40
41 #include "BLI_math.h"
42 #include "BLI_listbase.h"
43 #include "BLI_utildefines.h"
44 #include "BLI_string.h"
45
46 #include "BKE_context.h"
47 #include "BKE_DerivedMesh.h"
48 #include "BKE_cdderivedmesh.h"
49 #include "BKE_global.h"
50 #include "BKE_library.h"
51 #include "BKE_main.h"
52 #include "BKE_mesh.h"
53 #include "BKE_modifier.h"
54 #include "BKE_object.h"
55 #include "BKE_particle.h"
56 #include "BKE_pointcache.h"
57 #include "BKE_report.h"
58
59 #include "DEG_depsgraph.h"
60 #include "DEG_depsgraph_build.h"
61
62 #include "RNA_access.h"
63 #include "RNA_define.h"
64
65 #include "WM_api.h"
66 #include "WM_types.h"
67
68 #include "ED_particle.h"
69 #include "ED_screen.h"
70 #include "ED_object.h"
71
72 #include "UI_resources.h"
73
74 #include "particle_edit_utildefines.h"
75
76 #include "physics_intern.h"
77
78 static float I[4][4] = {{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f}};
79
80 /********************** particle system slot operators *********************/
81
82 static int particle_system_add_exec(bContext *C, wmOperator *UNUSED(op))
83 {
84         Object *ob= ED_object_context(C);
85         Scene *scene = CTX_data_scene(C);
86
87         if (!scene || !ob)
88                 return OPERATOR_CANCELLED;
89
90         object_add_particle_system(scene, ob, NULL);
91
92         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
93         WM_event_add_notifier(C, NC_OBJECT|ND_POINTCACHE, ob);
94
95         return OPERATOR_FINISHED;
96 }
97
98 void OBJECT_OT_particle_system_add(wmOperatorType *ot)
99 {
100         /* identifiers */
101         ot->name = "Add Particle System Slot";
102         ot->idname = "OBJECT_OT_particle_system_add";
103         ot->description = "Add a particle system";
104
105         /* api callbacks */
106         ot->poll = ED_operator_object_active_editable;
107         ot->exec = particle_system_add_exec;
108
109         /* flags */
110         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
111 }
112
113 static int particle_system_remove_exec(bContext *C, wmOperator *UNUSED(op))
114 {
115         Object *ob = ED_object_context(C);
116         Scene *scene = CTX_data_scene(C);
117         ViewLayer *view_layer = CTX_data_view_layer(C);
118         int mode_orig;
119
120         if (!scene || !ob)
121                 return OPERATOR_CANCELLED;
122
123         mode_orig = ob->mode;
124         object_remove_particle_system(scene, ob);
125
126         /* possible this isn't the active object
127          * object_remove_particle_system() clears the mode on the last psys
128          */
129         if (mode_orig & OB_MODE_PARTICLE_EDIT) {
130                 if ((ob->mode & OB_MODE_PARTICLE_EDIT) == 0) {
131                         if (view_layer->basact && view_layer->basact->object == ob) {
132                                 WM_event_add_notifier(C, NC_SCENE|ND_MODE|NS_MODE_OBJECT, NULL);
133                         }
134                 }
135         }
136
137         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
138         WM_event_add_notifier(C, NC_OBJECT|ND_POINTCACHE, ob);
139
140         return OPERATOR_FINISHED;
141 }
142
143 void OBJECT_OT_particle_system_remove(wmOperatorType *ot)
144 {
145         /* identifiers */
146         ot->name = "Remove Particle System Slot";
147         ot->idname = "OBJECT_OT_particle_system_remove";
148         ot->description = "Remove the selected particle system";
149
150         /* api callbacks */
151         ot->poll = ED_operator_object_active_editable;
152         ot->exec = particle_system_remove_exec;
153
154         /* flags */
155         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
156 }
157
158 /********************** new particle settings operator *********************/
159
160 static int psys_poll(bContext *C)
161 {
162         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
163         return (ptr.data != NULL);
164 }
165
166 static int new_particle_settings_exec(bContext *C, wmOperator *UNUSED(op))
167 {
168         Main *bmain= CTX_data_main(C);
169         ParticleSystem *psys;
170         ParticleSettings *part = NULL;
171         Object *ob;
172         PointerRNA ptr;
173
174         ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
175
176         psys = ptr.data;
177
178         /* add or copy particle setting */
179         if (psys->part)
180                 part= BKE_particlesettings_copy(bmain, psys->part);
181         else
182                 part= BKE_particlesettings_add(bmain, "ParticleSettings");
183
184         ob= ptr.id.data;
185
186         if (psys->part)
187                 id_us_min(&psys->part->id);
188
189         psys->part = part;
190
191         psys_check_boid_data(psys);
192
193         DEG_relations_tag_update(bmain);
194         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
195
196         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
197
198         return OPERATOR_FINISHED;
199 }
200
201 void PARTICLE_OT_new(wmOperatorType *ot)
202 {
203         /* identifiers */
204         ot->name = "New Particle Settings";
205         ot->idname = "PARTICLE_OT_new";
206         ot->description = "Add new particle settings";
207
208         /* api callbacks */
209         ot->exec = new_particle_settings_exec;
210         ot->poll = psys_poll;
211
212         /* flags */
213         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
214 }
215
216 /********************** keyed particle target operators *********************/
217
218 static int new_particle_target_exec(bContext *C, wmOperator *UNUSED(op))
219 {
220         Main *bmain = CTX_data_main(C);
221         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
222         ParticleSystem *psys= ptr.data;
223         Object *ob = ptr.id.data;
224
225         ParticleTarget *pt;
226
227         if (!psys)
228                 return OPERATOR_CANCELLED;
229
230         pt = psys->targets.first;
231         for (; pt; pt=pt->next)
232                 pt->flag &= ~PTARGET_CURRENT;
233
234         pt = MEM_callocN(sizeof(ParticleTarget), "keyed particle target");
235
236         pt->flag |= PTARGET_CURRENT;
237         pt->psys = 1;
238
239         BLI_addtail(&psys->targets, pt);
240
241         DEG_relations_tag_update(bmain);
242         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
243
244         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
245
246         return OPERATOR_FINISHED;
247 }
248
249 void PARTICLE_OT_new_target(wmOperatorType *ot)
250 {
251         /* identifiers */
252         ot->name = "New Particle Target";
253         ot->idname = "PARTICLE_OT_new_target";
254         ot->description = "Add a new particle target";
255
256         /* api callbacks */
257         ot->exec = new_particle_target_exec;
258
259         /* flags */
260         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
261 }
262
263 static int remove_particle_target_exec(bContext *C, wmOperator *UNUSED(op))
264 {
265         Main *bmain = CTX_data_main(C);
266         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
267         ParticleSystem *psys= ptr.data;
268         Object *ob = ptr.id.data;
269
270         ParticleTarget *pt;
271
272         if (!psys)
273                 return OPERATOR_CANCELLED;
274
275         pt = psys->targets.first;
276         for (; pt; pt=pt->next) {
277                 if (pt->flag & PTARGET_CURRENT) {
278                         BLI_remlink(&psys->targets, pt);
279                         MEM_freeN(pt);
280                         break;
281                 }
282
283         }
284         pt = psys->targets.last;
285
286         if (pt)
287                 pt->flag |= PTARGET_CURRENT;
288
289         DEG_relations_tag_update(bmain);
290         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
291
292         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
293
294         return OPERATOR_FINISHED;
295 }
296
297 void PARTICLE_OT_target_remove(wmOperatorType *ot)
298 {
299         /* identifiers */
300         ot->name = "Remove Particle Target";
301         ot->idname = "PARTICLE_OT_target_remove";
302         ot->description = "Remove the selected particle target";
303
304         /* api callbacks */
305         ot->exec = remove_particle_target_exec;
306
307         /* flags */
308         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
309 }
310
311 /************************ move up particle target operator *********************/
312
313 static int target_move_up_exec(bContext *C, wmOperator *UNUSED(op))
314 {
315         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
316         ParticleSystem *psys= ptr.data;
317         Object *ob = ptr.id.data;
318         ParticleTarget *pt;
319
320         if (!psys)
321                 return OPERATOR_CANCELLED;
322
323         pt = psys->targets.first;
324         for (; pt; pt=pt->next) {
325                 if (pt->flag & PTARGET_CURRENT && pt->prev) {
326                         BLI_remlink(&psys->targets, pt);
327                         BLI_insertlinkbefore(&psys->targets, pt->prev, pt);
328
329                         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
330                         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
331                         break;
332                 }
333         }
334
335         return OPERATOR_FINISHED;
336 }
337
338 void PARTICLE_OT_target_move_up(wmOperatorType *ot)
339 {
340         ot->name = "Move Up Target";
341         ot->idname = "PARTICLE_OT_target_move_up";
342         ot->description = "Move particle target up in the list";
343
344         ot->exec = target_move_up_exec;
345
346         /* flags */
347         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
348 }
349
350 /************************ move down particle target operator *********************/
351
352 static int target_move_down_exec(bContext *C, wmOperator *UNUSED(op))
353 {
354         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
355         ParticleSystem *psys= ptr.data;
356         Object *ob = ptr.id.data;
357         ParticleTarget *pt;
358
359         if (!psys)
360                 return OPERATOR_CANCELLED;
361         pt = psys->targets.first;
362         for (; pt; pt=pt->next) {
363                 if (pt->flag & PTARGET_CURRENT && pt->next) {
364                         BLI_remlink(&psys->targets, pt);
365                         BLI_insertlinkafter(&psys->targets, pt->next, pt);
366
367                         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
368                         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
369                         break;
370                 }
371         }
372
373         return OPERATOR_FINISHED;
374 }
375
376 void PARTICLE_OT_target_move_down(wmOperatorType *ot)
377 {
378         ot->name = "Move Down Target";
379         ot->idname = "PARTICLE_OT_target_move_down";
380         ot->description = "Move particle target down in the list";
381
382         ot->exec = target_move_down_exec;
383
384         /* flags */
385         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
386 }
387
388 /************************ move up particle dupliweight operator *********************/
389
390 static int dupliob_move_up_exec(bContext *C, wmOperator *UNUSED(op))
391 {
392         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
393         ParticleSystem *psys= ptr.data;
394         ParticleSettings *part;
395         ParticleDupliWeight *dw;
396
397         if (!psys)
398                 return OPERATOR_CANCELLED;
399
400         part = psys->part;
401         for (dw=part->dupliweights.first; dw; dw=dw->next) {
402                 if (dw->flag & PART_DUPLIW_CURRENT && dw->prev) {
403                         BLI_remlink(&part->dupliweights, dw);
404                         BLI_insertlinkbefore(&part->dupliweights, dw->prev, dw);
405
406                         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, NULL);
407                         break;
408                 }
409         }
410
411         return OPERATOR_FINISHED;
412 }
413
414 void PARTICLE_OT_dupliob_move_up(wmOperatorType *ot)
415 {
416         ot->name = "Move Up Dupli Object";
417         ot->idname = "PARTICLE_OT_dupliob_move_up";
418         ot->description = "Move dupli object up in the list";
419
420         ot->exec = dupliob_move_up_exec;
421
422         /* flags */
423         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
424 }
425
426 /********************** particle dupliweight operators *********************/
427
428 static int copy_particle_dupliob_exec(bContext *C, wmOperator *UNUSED(op))
429 {
430         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
431         ParticleSystem *psys= ptr.data;
432         ParticleSettings *part;
433         ParticleDupliWeight *dw;
434
435         if (!psys)
436                 return OPERATOR_CANCELLED;
437         part = psys->part;
438         for (dw=part->dupliweights.first; dw; dw=dw->next) {
439                 if (dw->flag & PART_DUPLIW_CURRENT) {
440                         dw->flag &= ~PART_DUPLIW_CURRENT;
441                         dw = MEM_dupallocN(dw);
442                         dw->flag |= PART_DUPLIW_CURRENT;
443                         BLI_addhead(&part->dupliweights, dw);
444
445                         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, NULL);
446                         break;
447                 }
448         }
449
450         return OPERATOR_FINISHED;
451 }
452
453 void PARTICLE_OT_dupliob_copy(wmOperatorType *ot)
454 {
455         /* identifiers */
456         ot->name = "Copy Particle Dupliob";
457         ot->idname = "PARTICLE_OT_dupliob_copy";
458         ot->description = "Duplicate the current dupliobject";
459
460         /* api callbacks */
461         ot->exec = copy_particle_dupliob_exec;
462
463         /* flags */
464         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
465 }
466
467 static int remove_particle_dupliob_exec(bContext *C, wmOperator *UNUSED(op))
468 {
469         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
470         ParticleSystem *psys= ptr.data;
471         ParticleSettings *part;
472         ParticleDupliWeight *dw;
473
474         if (!psys)
475                 return OPERATOR_CANCELLED;
476
477         part = psys->part;
478         for (dw=part->dupliweights.first; dw; dw=dw->next) {
479                 if (dw->flag & PART_DUPLIW_CURRENT) {
480                         BLI_remlink(&part->dupliweights, dw);
481                         MEM_freeN(dw);
482                         break;
483                 }
484
485         }
486         dw = part->dupliweights.last;
487
488         if (dw)
489                 dw->flag |= PART_DUPLIW_CURRENT;
490
491         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, NULL);
492
493         return OPERATOR_FINISHED;
494 }
495
496 void PARTICLE_OT_dupliob_remove(wmOperatorType *ot)
497 {
498         /* identifiers */
499         ot->name = "Remove Particle Dupliobject";
500         ot->idname = "PARTICLE_OT_dupliob_remove";
501         ot->description = "Remove the selected dupliobject";
502
503         /* api callbacks */
504         ot->exec = remove_particle_dupliob_exec;
505
506         /* flags */
507         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
508 }
509
510 /************************ move down particle dupliweight operator *********************/
511
512 static int dupliob_move_down_exec(bContext *C, wmOperator *UNUSED(op))
513 {
514         PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem);
515         ParticleSystem *psys= ptr.data;
516         ParticleSettings *part;
517         ParticleDupliWeight *dw;
518
519         if (!psys)
520                 return OPERATOR_CANCELLED;
521
522         part = psys->part;
523         for (dw=part->dupliweights.first; dw; dw=dw->next) {
524                 if (dw->flag & PART_DUPLIW_CURRENT && dw->next) {
525                         BLI_remlink(&part->dupliweights, dw);
526                         BLI_insertlinkafter(&part->dupliweights, dw->next, dw);
527
528                         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, NULL);
529                         break;
530                 }
531         }
532
533         return OPERATOR_FINISHED;
534 }
535
536 void PARTICLE_OT_dupliob_move_down(wmOperatorType *ot)
537 {
538         ot->name = "Move Down Dupli Object";
539         ot->idname = "PARTICLE_OT_dupliob_move_down";
540         ot->description = "Move dupli object down in the list";
541
542         ot->exec = dupliob_move_down_exec;
543
544         /* flags */
545         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
546 }
547
548 /************************ connect/disconnect hair operators *********************/
549
550 static void disconnect_hair(
551         Depsgraph *depsgraph, Scene *scene,
552         Object *ob, ParticleSystem *psys)
553 {
554         ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
555         ParticleEditSettings *pset= PE_settings(scene);
556         ParticleData *pa;
557         PTCacheEdit *edit;
558         PTCacheEditPoint *point;
559         PTCacheEditKey *ekey = NULL;
560         HairKey *key;
561         int i, k;
562         float hairmat[4][4];
563
564         if (!ob || !psys || psys->flag & PSYS_GLOBAL_HAIR)
565                 return;
566
567         if (!psys->part || psys->part->type != PART_HAIR)
568                 return;
569
570         edit = psys->edit;
571         point= edit ? edit->points : NULL;
572
573         for (i=0, pa=psys->particles; i<psys->totpart; i++, pa++) {
574                 if (point) {
575                         ekey = point->keys;
576                         point++;
577                 }
578
579                 psys_mat_hair_to_global(ob, psmd->mesh_final, psys->part->from, pa, hairmat);
580
581                 for (k=0, key=pa->hair; k<pa->totkey; k++, key++) {
582                         mul_m4_v3(hairmat, key->co);
583
584                         if (ekey) {
585                                 ekey->flag &= ~PEK_USE_WCO;
586                                 ekey++;
587                         }
588                 }
589         }
590
591         psys_free_path_cache(psys, psys->edit);
592
593         psys->flag |= PSYS_GLOBAL_HAIR;
594
595         if (ELEM(pset->brushtype, PE_BRUSH_ADD, PE_BRUSH_PUFF))
596                 pset->brushtype = PE_BRUSH_NONE;
597
598         PE_update_object(depsgraph, scene, ob, 0);
599 }
600
601 static int disconnect_hair_exec(bContext *C, wmOperator *op)
602 {
603         Depsgraph *depsgraph = CTX_data_depsgraph(C);
604         Scene *scene= CTX_data_scene(C);
605         Object *ob= ED_object_context(C);
606         ParticleSystem *psys= NULL;
607         const bool all = RNA_boolean_get(op->ptr, "all");
608
609         if (!ob)
610                 return OPERATOR_CANCELLED;
611
612         if (all) {
613                 for (psys=ob->particlesystem.first; psys; psys=psys->next) {
614                         disconnect_hair(depsgraph, scene, ob, psys);
615                 }
616         }
617         else {
618                 psys = psys_get_current(ob);
619                 disconnect_hair(depsgraph, scene, ob, psys);
620         }
621
622         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
623         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
624
625         return OPERATOR_FINISHED;
626 }
627
628 void PARTICLE_OT_disconnect_hair(wmOperatorType *ot)
629 {
630         ot->name = "Disconnect Hair";
631         ot->description = "Disconnect hair from the emitter mesh";
632         ot->idname = "PARTICLE_OT_disconnect_hair";
633
634         ot->exec = disconnect_hair_exec;
635
636         /* flags */
637         ot->flag = OPTYPE_UNDO;  /* No REGISTER, redo does not work due to missing update, see T47750. */
638
639         RNA_def_boolean(ot->srna, "all", 0, "All hair", "Disconnect all hair systems from the emitter mesh");
640 }
641
642 /* from/to_world_space : whether from/to particles are in world or hair space
643  * from/to_mat : additional transform for from/to particles (e.g. for using object space copying)
644  */
645 static bool remap_hair_emitter(
646         Depsgraph *depsgraph, Scene *scene, Object *ob, ParticleSystem *psys,
647         Object *target_ob, ParticleSystem *target_psys, PTCacheEdit *target_edit,
648         float from_mat[4][4], float to_mat[4][4], bool from_global, bool to_global)
649 {
650         ParticleSystemModifierData *target_psmd = psys_get_modifier(target_ob, target_psys);
651         ParticleData *pa, *tpa;
652         PTCacheEditPoint *edit_point;
653         PTCacheEditKey *ekey;
654         BVHTreeFromMesh bvhtree= {NULL};
655         MFace *mface = NULL, *mf;
656         MEdge *medge = NULL, *me;
657         MVert *mvert;
658         Mesh *mesh, *target_mesh;
659         int numverts;
660         int i, k;
661         float from_ob_imat[4][4], to_ob_imat[4][4];
662         float from_imat[4][4], to_imat[4][4];
663
664         if (!target_psmd->mesh_final)
665                 return false;
666         if (!psys->part || psys->part->type != PART_HAIR)
667                 return false;
668         if (!target_psys->part || target_psys->part->type != PART_HAIR)
669                 return false;
670
671         edit_point = target_edit ? target_edit->points : NULL;
672
673         invert_m4_m4(from_ob_imat, ob->obmat);
674         invert_m4_m4(to_ob_imat, target_ob->obmat);
675         invert_m4_m4(from_imat, from_mat);
676         invert_m4_m4(to_imat, to_mat);
677
678         if (target_psmd->mesh_final->runtime.deformed_only) {
679                 /* we don't want to mess up target_psmd->dm when converting to global coordinates below */
680                 mesh = target_psmd->mesh_final;
681         }
682         else {
683                 mesh = target_psmd->mesh_original;
684         }
685         target_mesh = target_psmd->mesh_final;
686         if (mesh == NULL) {
687                 return false;
688         }
689         /* don't modify the original vertices */
690         BKE_id_copy_ex(
691                     NULL, &mesh->id, (ID **)&mesh,
692                     LIB_ID_CREATE_NO_MAIN |
693                     LIB_ID_CREATE_NO_USER_REFCOUNT |
694                     LIB_ID_CREATE_NO_DEG_TAG |
695                     LIB_ID_COPY_NO_PREVIEW,
696                     false);
697
698         /* BMESH_ONLY, deform dm may not have tessface */
699         BKE_mesh_tessface_ensure(mesh);
700
701         numverts = mesh->totvert;
702         mvert = mesh->mvert;
703
704         /* convert to global coordinates */
705         for (i=0; i<numverts; i++)
706                 mul_m4_v3(to_mat, mvert[i].co);
707
708         if (mesh->totface != 0) {
709                 mface = mesh->mface;
710                 BKE_bvhtree_from_mesh_get(&bvhtree, mesh, BVHTREE_FROM_FACES, 2);
711         }
712         else if (mesh->totedge != 0) {
713                 medge = mesh->medge;
714                 BKE_bvhtree_from_mesh_get(&bvhtree, mesh, BVHTREE_FROM_EDGES, 2);
715         }
716         else {
717                 BKE_id_free(NULL, mesh);
718                 return false;
719         }
720
721         for (i = 0, tpa = target_psys->particles, pa = psys->particles;
722              i < target_psys->totpart;
723              i++, tpa++, pa++)
724         {
725                 float from_co[3];
726                 BVHTreeNearest nearest;
727
728                 if (from_global)
729                         mul_v3_m4v3(from_co, from_ob_imat, pa->hair[0].co);
730                 else
731                         mul_v3_m4v3(from_co, from_ob_imat, pa->hair[0].world_co);
732                 mul_m4_v3(from_mat, from_co);
733
734                 nearest.index = -1;
735                 nearest.dist_sq = FLT_MAX;
736
737                 BLI_bvhtree_find_nearest(bvhtree.tree, from_co, &nearest, bvhtree.nearest_callback, &bvhtree);
738
739                 if (nearest.index == -1) {
740                         if (G.debug & G_DEBUG)
741                                 printf("No nearest point found for hair root!");
742                         continue;
743                 }
744
745                 if (mface) {
746                         float v[4][3];
747
748                         mf = &mface[nearest.index];
749
750                         copy_v3_v3(v[0], mvert[mf->v1].co);
751                         copy_v3_v3(v[1], mvert[mf->v2].co);
752                         copy_v3_v3(v[2], mvert[mf->v3].co);
753                         if (mf->v4) {
754                                 copy_v3_v3(v[3], mvert[mf->v4].co);
755                                 interp_weights_poly_v3(tpa->fuv, v, 4, nearest.co);
756                         }
757                         else
758                                 interp_weights_poly_v3(tpa->fuv, v, 3, nearest.co);
759                         tpa->foffset = 0.0f;
760
761                         tpa->num = nearest.index;
762                         tpa->num_dmcache = psys_particle_dm_face_lookup(target_mesh, mesh, tpa->num, tpa->fuv, NULL);
763                 }
764                 else {
765                         me = &medge[nearest.index];
766
767                         tpa->fuv[1] = line_point_factor_v3(nearest.co,
768                                                            mvert[me->v1].co,
769                                                            mvert[me->v2].co);
770                         tpa->fuv[0] = 1.0f - tpa->fuv[1];
771                         tpa->fuv[2] = tpa->fuv[3] = 0.0f;
772                         tpa->foffset = 0.0f;
773
774                         tpa->num = nearest.index;
775                         tpa->num_dmcache = -1;
776                 }
777
778                 /* translate hair keys */
779                 {
780                         HairKey *key, *tkey;
781                         float hairmat[4][4], imat[4][4];
782                         float offset[3];
783
784                         if (to_global)
785                                 copy_m4_m4(imat, target_ob->obmat);
786                         else {
787                                 /* note: using target_dm here, which is in target_ob object space and has full modifiers */
788                                 psys_mat_hair_to_object(target_ob, target_mesh, target_psys->part->from, tpa, hairmat);
789                                 invert_m4_m4(imat, hairmat);
790                         }
791                         mul_m4_m4m4(imat, imat, to_imat);
792
793                         /* offset in world space */
794                         sub_v3_v3v3(offset, nearest.co, from_co);
795
796                         if (edit_point) {
797                                 for (k=0, key=pa->hair, tkey=tpa->hair, ekey = edit_point->keys; k<tpa->totkey; k++, key++, tkey++, ekey++) {
798                                         float co_orig[3];
799
800                                         if (from_global)
801                                                 mul_v3_m4v3(co_orig, from_ob_imat, key->co);
802                                         else
803                                                 mul_v3_m4v3(co_orig, from_ob_imat, key->world_co);
804                                         mul_m4_v3(from_mat, co_orig);
805
806                                         add_v3_v3v3(tkey->co, co_orig, offset);
807
808                                         mul_m4_v3(imat, tkey->co);
809
810                                         ekey->flag |= PEK_USE_WCO;
811                                 }
812
813                                 edit_point++;
814                         }
815                         else {
816                                 for (k=0, key=pa->hair, tkey=tpa->hair; k<tpa->totkey; k++, key++, tkey++) {
817                                         float co_orig[3];
818
819                                         if (from_global)
820                                                 mul_v3_m4v3(co_orig, from_ob_imat, key->co);
821                                         else
822                                                 mul_v3_m4v3(co_orig, from_ob_imat, key->world_co);
823                                         mul_m4_v3(from_mat, co_orig);
824
825                                         add_v3_v3v3(tkey->co, co_orig, offset);
826
827                                         mul_m4_v3(imat, tkey->co);
828                                 }
829                         }
830                 }
831         }
832
833         free_bvhtree_from_mesh(&bvhtree);
834         BKE_id_free(NULL, mesh);
835
836         psys_free_path_cache(target_psys, target_edit);
837
838         PE_update_object(depsgraph, scene, target_ob, 0);
839
840         return true;
841 }
842
843 static bool connect_hair(
844         Depsgraph *depsgraph, Scene *scene,
845         Object *ob, ParticleSystem *psys)
846 {
847         bool ok;
848
849         if (!psys)
850                 return false;
851
852         ok = remap_hair_emitter(
853                  depsgraph, scene, ob, psys, ob, psys, psys->edit,
854                  ob->obmat, ob->obmat, psys->flag & PSYS_GLOBAL_HAIR, false);
855         psys->flag &= ~PSYS_GLOBAL_HAIR;
856
857         return ok;
858 }
859
860 static int connect_hair_exec(bContext *C, wmOperator *op)
861 {
862         Depsgraph *depsgraph = CTX_data_depsgraph(C);
863         Scene *scene= CTX_data_scene(C);
864         Object *ob= ED_object_context(C);
865         ParticleSystem *psys= NULL;
866         const bool all = RNA_boolean_get(op->ptr, "all");
867         bool any_connected = false;
868
869         if (!ob)
870                 return OPERATOR_CANCELLED;
871
872         if (all) {
873                 for (psys=ob->particlesystem.first; psys; psys=psys->next) {
874                         any_connected |= connect_hair(depsgraph, scene, ob, psys);
875                 }
876         }
877         else {
878                 psys = psys_get_current(ob);
879                 any_connected |= connect_hair(depsgraph, scene, ob, psys);
880         }
881
882         if (!any_connected) {
883                 BKE_report(op->reports, RPT_WARNING,
884                            "No hair connected (can't connect hair if particle system modifier is disabled)");
885                 return OPERATOR_CANCELLED;
886         }
887
888         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
889         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE, ob);
890
891         return OPERATOR_FINISHED;
892 }
893
894 void PARTICLE_OT_connect_hair(wmOperatorType *ot)
895 {
896         ot->name = "Connect Hair";
897         ot->description = "Connect hair to the emitter mesh";
898         ot->idname = "PARTICLE_OT_connect_hair";
899
900         ot->exec = connect_hair_exec;
901
902         /* flags */
903         ot->flag = OPTYPE_UNDO;  /* No REGISTER, redo does not work due to missing update, see T47750. */
904
905         RNA_def_boolean(ot->srna, "all", 0, "All hair", "Connect all hair systems to the emitter mesh");
906 }
907
908 /************************ particle system copy operator *********************/
909
910 typedef enum eCopyParticlesSpace {
911         PAR_COPY_SPACE_OBJECT   = 0,
912         PAR_COPY_SPACE_WORLD    = 1,
913 } eCopyParticlesSpace;
914
915 static void copy_particle_edit(
916         Depsgraph *depsgraph, Scene *scene,
917         Object *ob, ParticleSystem *psys, ParticleSystem *psys_from)
918 {
919         PTCacheEdit *edit_from = psys_from->edit, *edit;
920         ParticleData *pa;
921         KEY_K;
922         POINT_P;
923
924         if (!edit_from)
925                 return;
926
927         edit = MEM_dupallocN(edit_from);
928         edit->psys = psys;
929         psys->edit = edit;
930
931         edit->pathcache = NULL;
932         BLI_listbase_clear(&edit->pathcachebufs);
933
934         edit->emitter_field = NULL;
935         edit->emitter_cosnos = NULL;
936
937         edit->points = MEM_dupallocN(edit_from->points);
938         pa = psys->particles;
939         LOOP_POINTS {
940                 HairKey *hkey = pa->hair;
941
942                 point->keys= MEM_dupallocN(point->keys);
943                 LOOP_KEYS {
944                         key->co = hkey->co;
945                         key->time = &hkey->time;
946                         key->flag = hkey->editflag;
947                         if (!(psys->flag & PSYS_GLOBAL_HAIR)) {
948                                 key->flag |= PEK_USE_WCO;
949                                 hkey->editflag |= PEK_USE_WCO;
950                         }
951
952                         hkey++;
953                 }
954
955                 pa++;
956         }
957         update_world_cos(depsgraph, ob, edit);
958
959         UI_GetThemeColor3ubv(TH_EDGE_SELECT, edit->sel_col);
960         UI_GetThemeColor3ubv(TH_WIRE, edit->nosel_col);
961
962         recalc_lengths(edit);
963         recalc_emitter_field(depsgraph, ob, psys);
964         PE_update_object(depsgraph, scene, ob, true);
965 }
966
967 static void remove_particle_systems_from_object(Object *ob_to)
968 {
969         ModifierData *md, *md_next;
970
971         if (ob_to->type != OB_MESH)
972                 return;
973         if (!ob_to->data || ID_IS_LINKED(ob_to->data))
974                 return;
975
976         for (md = ob_to->modifiers.first; md; md = md_next) {
977                 md_next = md->next;
978
979                 /* remove all particle system modifiers as well,
980                  * these need to sync to the particle system list
981                  */
982                 if (ELEM(md->type, eModifierType_ParticleSystem, eModifierType_DynamicPaint, eModifierType_Smoke)) {
983                         BLI_remlink(&ob_to->modifiers, md);
984                         modifier_free(md);
985                 }
986         }
987
988         BKE_object_free_particlesystems(ob_to);
989 }
990
991 /* single_psys_from is optional, if NULL all psys of ob_from are copied */
992 static bool copy_particle_systems_to_object(const bContext *C,
993                                             Scene *scene,
994                                             Object *ob_from,
995                                             ParticleSystem *single_psys_from,
996                                             Object *ob_to,
997                                             int space,
998                                             bool duplicate_settings)
999 {
1000         Main *bmain = CTX_data_main(C);
1001         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1002         ModifierData *md;
1003         ParticleSystem *psys_start = NULL, *psys, *psys_from;
1004         ParticleSystem **tmp_psys;
1005         Mesh *final_mesh;
1006         CustomDataMask cdmask;
1007         int i, totpsys;
1008
1009         if (ob_to->type != OB_MESH)
1010                 return false;
1011         if (!ob_to->data || ID_IS_LINKED(ob_to->data))
1012                 return false;
1013
1014         /* For remapping we need a valid DM.
1015          * Because the modifiers are appended at the end it's safe to use
1016          * the final DM of the object without particles.
1017          * However, when evaluating the DM all the particle modifiers must be valid,
1018          * i.e. have the psys assigned already.
1019          * To break this hen/egg problem we create all psys separately first (to collect required customdata masks),
1020          * then create the DM, then add them to the object and make the psys modifiers ...
1021          */
1022         #define PSYS_FROM_FIRST (single_psys_from ? single_psys_from : ob_from->particlesystem.first)
1023         #define PSYS_FROM_NEXT(cur) (single_psys_from ? NULL : (cur)->next)
1024         totpsys = single_psys_from ? 1 : BLI_listbase_count(&ob_from->particlesystem);
1025
1026         tmp_psys = MEM_mallocN(sizeof(ParticleSystem*) * totpsys, "temporary particle system array");
1027
1028         cdmask = 0;
1029         for (psys_from = PSYS_FROM_FIRST, i = 0;
1030              psys_from;
1031              psys_from = PSYS_FROM_NEXT(psys_from), ++i)
1032         {
1033                 psys = BKE_object_copy_particlesystem(psys_from, 0);
1034                 tmp_psys[i] = psys;
1035
1036                 if (psys_start == NULL)
1037                         psys_start = psys;
1038
1039                 cdmask |= psys_emitter_customdata_mask(psys);
1040         }
1041         /* to iterate source and target psys in sync,
1042          * we need to know where the newly added psys start
1043          */
1044         psys_start = totpsys > 0 ? tmp_psys[0] : NULL;
1045
1046         /* get the DM (psys and their modifiers have not been appended yet) */
1047         /* TODO(Sybren): use mesh_eval instead */
1048         DerivedMesh *final_dm = mesh_get_derived_final(depsgraph, scene, ob_to, cdmask);
1049         final_mesh = BKE_id_new_nomain(ID_ME, NULL);
1050         DM_to_mesh(final_dm, final_mesh, ob_to, CD_MASK_EVERYTHING, false);
1051
1052         /* now append psys to the object and make modifiers */
1053         for (i = 0, psys_from = PSYS_FROM_FIRST;
1054              i < totpsys;
1055              ++i, psys_from = PSYS_FROM_NEXT(psys_from))
1056         {
1057                 ParticleSystemModifierData *psmd;
1058
1059                 psys = tmp_psys[i];
1060
1061                 /* append to the object */
1062                 BLI_addtail(&ob_to->particlesystem, psys);
1063
1064                 /* add a particle system modifier for each system */
1065                 md = modifier_new(eModifierType_ParticleSystem);
1066                 psmd = (ParticleSystemModifierData *)md;
1067                 /* push on top of the stack, no use trying to reproduce old stack order */
1068                 BLI_addtail(&ob_to->modifiers, md);
1069
1070                 BLI_snprintf(md->name, sizeof(md->name), "ParticleSystem %i", i);
1071                 modifier_unique_name(&ob_to->modifiers, (ModifierData *)psmd);
1072
1073                 psmd->psys = psys;
1074                 BKE_id_copy_ex(
1075                             NULL, &final_mesh->id, (ID **)&psmd->mesh_final,
1076                             LIB_ID_CREATE_NO_MAIN |
1077                             LIB_ID_CREATE_NO_USER_REFCOUNT |
1078                             LIB_ID_CREATE_NO_DEG_TAG |
1079                             LIB_ID_COPY_NO_PREVIEW,
1080                             false);
1081
1082                 BKE_mesh_calc_normals(psmd->mesh_final);
1083                 BKE_mesh_tessface_ensure(psmd->mesh_final);
1084
1085                 if (psys_from->edit) {
1086                         copy_particle_edit(depsgraph, scene, ob_to, psys, psys_from);
1087                 }
1088
1089                 if (duplicate_settings) {
1090                         id_us_min(&psys->part->id);
1091                         psys->part = BKE_particlesettings_copy(bmain, psys->part);
1092                 }
1093         }
1094         MEM_freeN(tmp_psys);
1095
1096         /* note: do this after creating DM copies for all the particle system modifiers,
1097          * the remapping otherwise makes final_dm invalid!
1098          */
1099         for (psys = psys_start, psys_from = PSYS_FROM_FIRST, i = 0;
1100              psys;
1101              psys = psys->next, psys_from = PSYS_FROM_NEXT(psys_from), ++i)
1102         {
1103                 float (*from_mat)[4], (*to_mat)[4];
1104
1105                 switch (space) {
1106                         case PAR_COPY_SPACE_OBJECT:
1107                                 from_mat = I;
1108                                 to_mat = I;
1109                                 break;
1110                         case PAR_COPY_SPACE_WORLD:
1111                                 from_mat = ob_from->obmat;
1112                                 to_mat = ob_to->obmat;
1113                                 break;
1114                         default:
1115                                 /* should not happen */
1116                                 from_mat = to_mat = NULL;
1117                                 BLI_assert(false);
1118                                 break;
1119                 }
1120                 if (ob_from != ob_to) {
1121                         remap_hair_emitter(
1122                                 depsgraph, scene, ob_from, psys_from, ob_to, psys, psys->edit,
1123                                 from_mat, to_mat, psys_from->flag & PSYS_GLOBAL_HAIR, psys->flag & PSYS_GLOBAL_HAIR);
1124                 }
1125
1126                 /* tag for recalc */
1127 //              psys->recalc |= PSYS_RECALC_RESET;
1128         }
1129
1130         #undef PSYS_FROM_FIRST
1131         #undef PSYS_FROM_NEXT
1132
1133         DEG_id_tag_update(&ob_to->id, OB_RECALC_DATA);
1134         WM_main_add_notifier(NC_OBJECT | ND_PARTICLE | NA_EDITED, ob_to);
1135         return true;
1136 }
1137
1138 static int copy_particle_systems_poll(bContext *C)
1139 {
1140         Object *ob;
1141         if (!ED_operator_object_active_editable(C))
1142                 return false;
1143
1144         ob = ED_object_active_context(C);
1145         if (BLI_listbase_is_empty(&ob->particlesystem))
1146                 return false;
1147
1148         return true;
1149 }
1150
1151 static int copy_particle_systems_exec(bContext *C, wmOperator *op)
1152 {
1153         const int space = RNA_enum_get(op->ptr, "space");
1154         const bool remove_target_particles = RNA_boolean_get(op->ptr, "remove_target_particles");
1155         const bool use_active = RNA_boolean_get(op->ptr, "use_active");
1156         Scene *scene = CTX_data_scene(C);
1157         Object *ob_from = ED_object_active_context(C);
1158         ParticleSystem *psys_from = use_active ? CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem).data : NULL;
1159
1160         int changed_tot = 0;
1161         int fail = 0;
1162
1163         CTX_DATA_BEGIN (C, Object *, ob_to, selected_editable_objects)
1164         {
1165                 if (ob_from != ob_to) {
1166                         bool changed = false;
1167                         if (remove_target_particles) {
1168                                 remove_particle_systems_from_object(ob_to);
1169                                 changed = true;
1170                         }
1171                         if (copy_particle_systems_to_object(C, scene, ob_from, psys_from, ob_to, space, false))
1172                                 changed = true;
1173                         else
1174                                 fail++;
1175
1176                         if (changed)
1177                                 changed_tot++;
1178                 }
1179         }
1180         CTX_DATA_END;
1181
1182         if ((changed_tot == 0 && fail == 0) || fail) {
1183                 BKE_reportf(op->reports, RPT_ERROR,
1184                             "Copy particle systems to selected: %d done, %d failed",
1185                             changed_tot, fail);
1186         }
1187
1188         return OPERATOR_FINISHED;
1189 }
1190
1191 void PARTICLE_OT_copy_particle_systems(wmOperatorType *ot)
1192 {
1193         static const EnumPropertyItem space_items[] = {
1194                 {PAR_COPY_SPACE_OBJECT, "OBJECT", 0, "Object", "Copy inside each object's local space"},
1195                 {PAR_COPY_SPACE_WORLD, "WORLD", 0, "World", "Copy in world space"},
1196                 {0, NULL, 0, NULL, NULL}
1197         };
1198
1199         ot->name = "Copy Particle Systems";
1200         ot->description = "Copy particle systems from the active object to selected objects";
1201         ot->idname = "PARTICLE_OT_copy_particle_systems";
1202
1203         ot->poll = copy_particle_systems_poll;
1204         ot->exec = copy_particle_systems_exec;
1205
1206         /* flags */
1207         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1208
1209         RNA_def_enum(ot->srna, "space", space_items, PAR_COPY_SPACE_OBJECT, "Space", "Space transform for copying from one object to another");
1210         RNA_def_boolean(ot->srna, "remove_target_particles", true, "Remove Target Particles", "Remove particle systems on the target objects");
1211         RNA_def_boolean(ot->srna, "use_active", false, "Use Active", "Use the active particle system from the context");
1212 }
1213
1214 static int duplicate_particle_systems_poll(bContext *C)
1215 {
1216         if (!ED_operator_object_active_editable(C)) {
1217                 return false;
1218         }
1219         Object *ob = ED_object_active_context(C);
1220         if (BLI_listbase_is_empty(&ob->particlesystem)) {
1221                 return false;
1222         }
1223         return true;
1224 }
1225
1226 static int duplicate_particle_systems_exec(bContext *C, wmOperator *op)
1227 {
1228         const bool duplicate_settings = RNA_boolean_get(op->ptr, "use_duplicate_settings");
1229         Scene *scene = CTX_data_scene(C);
1230         Object *ob = ED_object_active_context(C);
1231         ParticleSystem *psys = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem).data;
1232         copy_particle_systems_to_object(C, scene, ob, psys, ob,
1233                                         PAR_COPY_SPACE_OBJECT, duplicate_settings);
1234         return OPERATOR_FINISHED;
1235 }
1236
1237 void PARTICLE_OT_duplicate_particle_system(wmOperatorType *ot)
1238 {
1239         ot->name = "Duplicate Particle Systems";
1240         ot->description = "Duplicate particle system within the active object";
1241         ot->idname = "PARTICLE_OT_duplicate_particle_system";
1242
1243         ot->poll = duplicate_particle_systems_poll;
1244         ot->exec = duplicate_particle_systems_exec;
1245
1246         /* flags */
1247         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1248
1249         RNA_def_boolean(ot->srna, "use_duplicate_settings", false, "Duplicate Settings",
1250                         "Duplicate settings as well, so new particle system uses own settings");
1251 }