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