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