fix for compiling with the c90 standard, support for non-static variable initializers...
[blender.git] / source / blender / editors / physics / particle_edit.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2007 by Janne Karhu.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <stdlib.h>
31 #include <math.h>
32 #include <string.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_scene_types.h"
37 #include "DNA_mesh_types.h"
38 #include "DNA_meshdata_types.h"
39 #include "DNA_view3d_types.h"
40 #include "DNA_screen_types.h"
41 #include "DNA_space_types.h"
42
43 #include "BKE_DerivedMesh.h"
44 #include "BKE_depsgraph.h"
45
46 #include "BKE_context.h"
47 #include "BKE_global.h"
48 #include "BKE_object.h"
49 #include "BKE_mesh.h"
50 #include "BKE_modifier.h"
51 #include "BKE_particle.h"
52 #include "BKE_report.h"
53 #include "BKE_scene.h"
54 #include "BKE_utildefines.h"
55 #include "BKE_pointcache.h"
56
57 #include "BLI_math.h"
58 #include "BLI_blenlib.h"
59 #include "BLI_dynstr.h"
60 #include "BLI_kdtree.h"
61 #include "BLI_rand.h"
62
63
64 #include "BIF_gl.h"
65 #include "BIF_glutil.h"
66
67 #include "ED_mesh.h"
68 #include "ED_particle.h"
69 #include "ED_view3d.h"
70
71 #include "UI_resources.h"
72
73 #include "WM_api.h"
74 #include "WM_types.h"
75
76 #include "RNA_access.h"
77 #include "RNA_define.h"
78
79 #include "physics_intern.h"
80
81 static void PE_create_particle_edit(Scene *scene, Object *ob, PointCache *cache, ParticleSystem *psys);
82 static void PTCacheUndo_clear(PTCacheEdit *edit);
83 static void recalc_emitter_field(Object *ob, ParticleSystem *psys);
84
85 #define KEY_K                                   PTCacheEditKey *key; int k
86 #define POINT_P                                 PTCacheEditPoint *point; int p
87 #define LOOP_POINTS                             for(p=0, point=edit->points; p<edit->totpoint; p++, point++)
88 #define LOOP_VISIBLE_POINTS             for(p=0, point=edit->points; p<edit->totpoint; p++, point++) if(!(point->flag & PEP_HIDE))
89 #define LOOP_SELECTED_POINTS    for(p=0, point=edit->points; p<edit->totpoint; p++, point++) if(point_is_selected(point))
90 #define LOOP_UNSELECTED_POINTS  for(p=0, point=edit->points; p<edit->totpoint; p++, point++) if(!point_is_selected(point))
91 #define LOOP_EDITED_POINTS              for(p=0, point=edit->points; p<edit->totpoint; p++, point++) if(point->flag & PEP_EDIT_RECALC)
92 #define LOOP_TAGGED_POINTS              for(p=0, point=edit->points; p<edit->totpoint; p++, point++) if(point->flag & PEP_TAG)
93 #define LOOP_KEYS                               for(k=0, key=point->keys; k<point->totkey; k++, key++)
94 #define LOOP_VISIBLE_KEYS               for(k=0, key=point->keys; k<point->totkey; k++, key++) if(!(key->flag & PEK_HIDE))
95 #define LOOP_SELECTED_KEYS              for(k=0, key=point->keys; k<point->totkey; k++, key++) if((key->flag & PEK_SELECT) && !(key->flag & PEK_HIDE))
96 #define LOOP_TAGGED_KEYS                for(k=0, key=point->keys; k<point->totkey; k++, key++) if(key->flag & PEK_TAG)
97
98 #define KEY_WCO                                 (key->flag & PEK_USE_WCO ? key->world_co : key->co)
99
100 /**************************** utilities *******************************/
101
102 int PE_poll(bContext *C)
103 {
104         Scene *scene= CTX_data_scene(C);
105         Object *ob= CTX_data_active_object(C);
106
107         if(!scene || !ob || !(ob->mode & OB_MODE_PARTICLE_EDIT))
108                 return 0;
109         
110         return (PE_get_current(scene, ob) != NULL);
111 }
112
113 int PE_hair_poll(bContext *C)
114 {
115         Scene *scene= CTX_data_scene(C);
116         Object *ob= CTX_data_active_object(C);
117         PTCacheEdit *edit;
118
119         if(!scene || !ob || !(ob->mode & OB_MODE_PARTICLE_EDIT))
120                 return 0;
121         
122         edit= PE_get_current(scene, ob);
123
124         return (edit && edit->psys);
125 }
126
127 int PE_poll_view3d(bContext *C)
128 {
129         return PE_poll(C) && CTX_wm_area(C)->spacetype == SPACE_VIEW3D &&
130                 CTX_wm_region(C)->regiontype == RGN_TYPE_WINDOW;
131 }
132
133 void PE_free_ptcache_edit(PTCacheEdit *edit)
134 {
135         POINT_P;
136
137         if(edit==0) return;
138
139         PTCacheUndo_clear(edit);
140
141         if(edit->points) {
142                 LOOP_POINTS {
143                         if(point->keys) 
144                                 MEM_freeN(point->keys);
145                 }
146
147                 MEM_freeN(edit->points);
148         }
149
150         if(edit->mirror_cache)
151                 MEM_freeN(edit->mirror_cache);
152
153         if(edit->emitter_cosnos) {
154                 MEM_freeN(edit->emitter_cosnos);
155                 edit->emitter_cosnos= 0;
156         }
157
158         if(edit->emitter_field) {
159                 BLI_kdtree_free(edit->emitter_field);
160                 edit->emitter_field= 0;
161         }
162
163         psys_free_path_cache(edit->psys, edit);
164
165         MEM_freeN(edit);
166 }
167
168 /************************************************/
169 /*                      Edit Mode Helpers                                       */
170 /************************************************/
171
172 int PE_start_edit(PTCacheEdit *edit)
173 {
174         if(edit) {
175                 edit->edited = 1;
176                 if(edit->psys)
177                         edit->psys->flag |= PSYS_EDITED;
178                 return 1;
179         }
180
181         return 0;
182 }
183
184 ParticleEditSettings *PE_settings(Scene *scene)
185 {
186         return scene->toolsettings ? &scene->toolsettings->particle : NULL;
187 }
188
189 /* always gets atleast the first particlesystem even if PSYS_CURRENT flag is not set
190  *
191  * note: this function runs on poll, therefor it can runs many times a second
192  * keep it fast! */
193 static PTCacheEdit *pe_get_current(Scene *scene, Object *ob, int create)
194 {
195         ParticleEditSettings *pset= PE_settings(scene);
196         PTCacheEdit *edit = NULL;
197         ListBase pidlist;
198         PTCacheID *pid;
199
200         if(pset==NULL || ob==NULL)
201                 return NULL;
202
203         pset->scene = scene;
204         pset->object = ob;
205
206         BKE_ptcache_ids_from_object(&pidlist, ob, NULL, 0);
207
208         /* in the case of only one editable thing, set pset->edittype accordingly */
209         if(pidlist.first && pidlist.first == pidlist.last) {
210                 pid = pidlist.first;
211                 switch(pid->type) {
212                         case PTCACHE_TYPE_PARTICLES:
213                                 pset->edittype = PE_TYPE_PARTICLES;
214                                 break;
215                         case PTCACHE_TYPE_SOFTBODY:
216                                 pset->edittype = PE_TYPE_SOFTBODY;
217                                 break;
218                         case PTCACHE_TYPE_CLOTH:
219                                 pset->edittype = PE_TYPE_CLOTH;
220                                 break;
221                 }
222         }
223
224         for(pid=pidlist.first; pid; pid=pid->next) {
225                 if(pset->edittype == PE_TYPE_PARTICLES && pid->type == PTCACHE_TYPE_PARTICLES) {
226                         ParticleSystem *psys = pid->calldata;
227
228                         if(psys->flag & PSYS_CURRENT) {
229                                 if(psys->part && psys->part->type == PART_HAIR) {
230                                         if(psys->flag & PSYS_HAIR_DYNAMICS && psys->pointcache->flag & PTCACHE_BAKED) {
231                                                 if(create && !psys->pointcache->edit)
232                                                         PE_create_particle_edit(scene, ob, pid->cache, NULL);
233                                                 edit = pid->cache->edit;
234                                         }
235                                         else {
236                                                 if(create && !psys->edit && psys->flag & PSYS_HAIR_DONE)
237                                                         PE_create_particle_edit(scene, ob, NULL, psys);
238                                                 edit = psys->edit;
239                                         }
240                                 }
241                                 else {
242                                         if(create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit)
243                                                 PE_create_particle_edit(scene, ob, pid->cache, psys);
244                                         edit = pid->cache->edit;
245                                 }
246
247                                 break;
248                         }
249                 }
250                 else if(pset->edittype == PE_TYPE_SOFTBODY && pid->type == PTCACHE_TYPE_SOFTBODY) {
251                         if(create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit)
252                                 PE_create_particle_edit(scene, ob, pid->cache, NULL);
253                         edit = pid->cache->edit;
254                         break;
255                 }
256                 else if(pset->edittype == PE_TYPE_CLOTH && pid->type == PTCACHE_TYPE_CLOTH) {
257                         if(create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit)
258                                 PE_create_particle_edit(scene, ob, pid->cache, NULL);
259                         edit = pid->cache->edit;
260                         break;
261                 }
262         }
263
264         if(edit)
265                 edit->pid = *pid;
266
267         BLI_freelistN(&pidlist);
268
269         return edit;
270 }
271
272 PTCacheEdit *PE_get_current(Scene *scene, Object *ob)
273 {
274         return pe_get_current(scene, ob, 0);
275 }
276
277 PTCacheEdit *PE_create_current(Scene *scene, Object *ob)
278 {
279         return pe_get_current(scene, ob, 1);
280 }
281
282 void PE_current_changed(Scene *scene, Object *ob)
283 {
284         if(ob->mode == OB_MODE_PARTICLE_EDIT)
285                 PE_create_current(scene, ob);
286 }
287
288 void PE_hide_keys_time(Scene *scene, PTCacheEdit *edit, float cfra)
289 {
290         ParticleEditSettings *pset=PE_settings(scene);
291         POINT_P; KEY_K;
292
293
294         if(pset->flag & PE_FADE_TIME && pset->selectmode==SCE_SELECT_POINT) {
295                 LOOP_POINTS {
296                         LOOP_KEYS {
297                                 if(fabs(cfra-*key->time) < pset->fade_frames)
298                                         key->flag &= ~PEK_HIDE;
299                                 else {
300                                         key->flag |= PEK_HIDE;
301                                         //key->flag &= ~PEK_SELECT;
302                                 }
303                         }
304                 }
305         }
306         else {
307                 LOOP_POINTS {
308                         LOOP_KEYS {
309                                 key->flag &= ~PEK_HIDE;
310                         }
311                 }
312         }
313 }
314
315 static int pe_x_mirror(Object *ob)
316 {
317         if(ob->type == OB_MESH)
318                 return (((Mesh*)ob->data)->editflag & ME_EDIT_MIRROR_X);
319         
320         return 0;
321 }
322
323 /****************** common struct passed to callbacks ******************/
324
325 typedef struct PEData {
326         ViewContext vc;
327         bglMats mats;
328         
329         Scene *scene;
330         Object *ob;
331         DerivedMesh *dm;
332         PTCacheEdit *edit;
333
334         short *mval;
335         rcti *rect;
336         float rad;
337         float dist;
338         float dval;
339         int select;
340
341         float *dvec;
342         float combfac;
343         float pufffac;
344         float cutfac;
345         float smoothfac;
346         float weightfac;
347         float growfac;
348         int totrekey;
349
350         int invert;
351         int tot;
352         float vec[3];
353 } PEData;
354
355 static void PE_set_data(bContext *C, PEData *data)
356 {
357         memset(data, 0, sizeof(*data));
358
359         data->scene= CTX_data_scene(C);
360         data->ob= CTX_data_active_object(C);
361         data->edit= PE_get_current(data->scene, data->ob);
362 }
363
364 static void PE_set_view3d_data(bContext *C, PEData *data)
365 {
366         PE_set_data(C, data);
367
368         view3d_set_viewcontext(C, &data->vc);
369         /* note, the object argument means the modelview matrix does not account for the objects matrix, use viewmat rather then (obmat * viewmat) */
370         view3d_get_transformation(data->vc.ar, data->vc.rv3d, NULL, &data->mats);
371
372         if((data->vc.v3d->drawtype>OB_WIRE) && (data->vc.v3d->flag & V3D_ZBUF_SELECT))
373                 view3d_validate_backbuf(&data->vc);
374 }
375
376 /*************************** selection utilities *******************************/
377
378 static int key_test_depth(PEData *data, float co[3])
379 {
380         View3D *v3d= data->vc.v3d;
381         double ux, uy, uz;
382         float depth;
383         short wco[3], x,y;
384
385         /* nothing to do */
386         if((v3d->drawtype<=OB_WIRE) || (v3d->flag & V3D_ZBUF_SELECT)==0)
387                 return 1;
388
389         project_short(data->vc.ar, co, wco);
390         
391         if(wco[0] == IS_CLIPPED)
392                 return 0;
393
394         gluProject(co[0],co[1],co[2], data->mats.modelview, data->mats.projection,
395                 (GLint *)data->mats.viewport, &ux, &uy, &uz);
396
397         x=wco[0];
398         y=wco[1];
399
400         x+= (short)data->vc.ar->winrct.xmin;
401         y+= (short)data->vc.ar->winrct.ymin;
402
403         /* PE_set_view3d_data calls this. no need to call here */
404         /* view3d_validate_backbuf(&data->vc); */
405         glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
406
407         if((float)uz - 0.0001 > depth)
408                 return 0;
409         else
410                 return 1;
411 }
412
413 static int key_inside_circle(PEData *data, float rad, float co[3], float *distance)
414 {
415         float dx, dy, dist;
416         short sco[2];
417
418         project_short(data->vc.ar, co, sco);
419         
420         if(sco[0] == IS_CLIPPED)
421                 return 0;
422         
423         dx= data->mval[0] - sco[0];
424         dy= data->mval[1] - sco[1];
425         dist= sqrt(dx*dx + dy*dy);
426
427         if(dist > rad)
428                 return 0;
429
430         if(key_test_depth(data, co)) {
431                 if(distance)
432                         *distance=dist;
433
434                 return 1;
435         }
436         
437         return 0;
438 }
439
440 static int key_inside_rect(PEData *data, float co[3])
441 {
442         short sco[2];
443
444         project_short(data->vc.ar, co,sco);
445
446         if(sco[0] == IS_CLIPPED)
447                 return 0;
448         
449         if(sco[0] > data->rect->xmin && sco[0] < data->rect->xmax &&
450            sco[1] > data->rect->ymin && sco[1] < data->rect->ymax)
451                 return key_test_depth(data, co);
452
453         return 0;
454 }
455
456 static int key_inside_test(PEData *data, float co[3])
457 {
458         if(data->mval)
459                 return key_inside_circle(data, data->rad, co, NULL);
460         else
461                 return key_inside_rect(data, co);
462 }
463
464 static int point_is_selected(PTCacheEditPoint *point)
465 {
466         KEY_K;
467         int sel;
468
469         if(point->flag & PEP_HIDE)
470                 return 0;
471
472         sel= 0;
473
474         LOOP_SELECTED_KEYS {
475                 return 1;
476         }
477         
478         return 0;
479 }
480
481 /*************************** iterators *******************************/
482
483 typedef void (*ForPointFunc)(PEData *data, int point_index);
484 typedef void (*ForKeyFunc)(PEData *data, int point_index, int key_index);
485 typedef void (*ForKeyMatFunc)(PEData *data, float mat[][4], float imat[][4], int point_index, int key_index, PTCacheEditKey *key);
486
487 static void for_mouse_hit_keys(PEData *data, ForKeyFunc func, int nearest)
488 {
489         ParticleEditSettings *pset= PE_settings(data->scene);
490         PTCacheEdit *edit= data->edit;
491         POINT_P; KEY_K;
492         int nearest_point, nearest_key;
493         float dist= data->rad;
494
495         /* in path select mode we have no keys */
496         if(pset->selectmode==SCE_SELECT_PATH)
497                 return;
498
499         nearest_point= -1;
500         nearest_key= -1;
501
502         LOOP_VISIBLE_POINTS {
503                 if(pset->selectmode == SCE_SELECT_END) {
504                         /* only do end keys */
505                         key= point->keys + point->totkey-1;
506
507                         if(nearest) {
508                                 if(key_inside_circle(data, dist, KEY_WCO, &dist)) {
509                                         nearest_point= p;
510                                         nearest_key= point->totkey-1;
511                                 }
512                         }
513                         else if(key_inside_test(data, KEY_WCO))
514                                 func(data, p, point->totkey-1);
515                 }
516                 else {
517                         /* do all keys */
518                         LOOP_VISIBLE_KEYS {
519                                 if(nearest) {
520                                         if(key_inside_circle(data, dist, KEY_WCO, &dist)) {
521                                                 nearest_point= p;
522                                                 nearest_key= k;
523                                         }
524                                 }
525                                 else if(key_inside_test(data, KEY_WCO))
526                                         func(data, p, k);
527                         }
528                 }
529         }
530
531         /* do nearest only */
532         if(nearest && nearest_point > -1)
533                 func(data, nearest_point, nearest_key);
534 }
535
536 static void foreach_mouse_hit_point(PEData *data, ForPointFunc func, int selected)
537 {
538         ParticleEditSettings *pset= PE_settings(data->scene);
539         PTCacheEdit *edit= data->edit;
540         POINT_P; KEY_K;
541
542         /* all is selected in path mode */
543         if(pset->selectmode==SCE_SELECT_PATH)
544                 selected=0;
545
546         LOOP_VISIBLE_POINTS {
547                 if(pset->selectmode==SCE_SELECT_END) {
548                         /* only do end keys */
549                         key= point->keys + point->totkey - 1;
550
551                         if(selected==0 || key->flag & PEK_SELECT)
552                                 if(key_inside_circle(data, data->rad, KEY_WCO, &data->dist))
553                                         func(data, p);
554                 }
555                 else {
556                         /* do all keys */
557                         LOOP_VISIBLE_KEYS {
558                                 if(selected==0 || key->flag & PEK_SELECT) {
559                                         if(key_inside_circle(data, data->rad, KEY_WCO, &data->dist)) {
560                                                 func(data, p);
561                                                 break;
562                                         }
563                                 }
564                         }
565                 }
566         }
567 }
568
569 static void foreach_mouse_hit_key(PEData *data, ForKeyMatFunc func, int selected)
570 {
571         PTCacheEdit *edit = data->edit;
572         ParticleSystem *psys = edit->psys;
573         ParticleSystemModifierData *psmd = NULL;
574         ParticleEditSettings *pset= PE_settings(data->scene);
575         POINT_P; KEY_K;
576         float mat[4][4], imat[4][4];
577
578         if(edit->psys)
579                 psmd= psys_get_modifier(data->ob, edit->psys);
580
581         /* all is selected in path mode */
582         if(pset->selectmode==SCE_SELECT_PATH)
583                 selected= 0;
584
585         unit_m4(imat);
586         unit_m4(mat);
587
588         LOOP_VISIBLE_POINTS {
589                 if(pset->selectmode==SCE_SELECT_END) {
590                         /* only do end keys */
591                         key= point->keys + point->totkey-1;
592
593                         if(selected==0 || key->flag & PEK_SELECT) {
594                                 if(key_inside_circle(data, data->rad, KEY_WCO, &data->dist)) {
595                                         if(edit->psys && !(edit->psys->flag & PSYS_GLOBAL_HAIR)) {
596                                                 psys_mat_hair_to_global(data->ob, psmd->dm, psys->part->from, psys->particles + p, mat);
597                                                 invert_m4_m4(imat,mat);
598                                         }
599
600                                         func(data, mat, imat, p, point->totkey-1, key);
601                                 }
602                         }
603                 }
604                 else {
605                         /* do all keys */
606                         LOOP_VISIBLE_KEYS {
607                                 if(selected==0 || key->flag & PEK_SELECT) {
608                                         if(key_inside_circle(data, data->rad, KEY_WCO, &data->dist)) {
609                                                 if(edit->psys && !(edit->psys->flag & PSYS_GLOBAL_HAIR)) {
610                                                         psys_mat_hair_to_global(data->ob, psmd->dm, psys->part->from, psys->particles + p, mat);
611                                                         invert_m4_m4(imat,mat);
612                                                 }
613
614                                                 func(data, mat, imat, p, k, key);
615                                         }
616                                 }
617                         }
618                 }
619         }
620 }
621
622 static void foreach_selected_point(PEData *data, ForPointFunc func)
623 {
624         PTCacheEdit *edit = data->edit;
625         POINT_P;
626
627         LOOP_SELECTED_POINTS {
628                 func(data, p);
629         }
630 }
631
632 static void foreach_selected_key(PEData *data, ForKeyFunc func)
633 {
634         PTCacheEdit *edit = data->edit;
635         POINT_P; KEY_K;
636
637         LOOP_VISIBLE_POINTS {
638                 LOOP_SELECTED_KEYS {
639                         func(data, p, k);
640                 }
641         }
642 }
643
644 static void foreach_point(PEData *data, ForPointFunc func)
645 {
646         PTCacheEdit *edit = data->edit;
647         POINT_P;
648
649         LOOP_POINTS { 
650                 func(data, p);
651         }
652 }
653
654 static int count_selected_keys(Scene *scene, PTCacheEdit *edit)
655 {
656         ParticleEditSettings *pset= PE_settings(scene);
657         POINT_P; KEY_K;
658         int sel= 0;
659
660         LOOP_VISIBLE_POINTS {
661                 if(pset->selectmode==SCE_SELECT_POINT) {
662                         LOOP_SELECTED_KEYS {
663                                 sel++;
664                         }
665                 }
666                 else if(pset->selectmode==SCE_SELECT_END) {
667                         key = point->keys + point->totkey - 1;
668                         if(key->flag & PEK_SELECT)
669                                 sel++;
670                 }
671         }
672
673         return sel;
674 }
675
676 /************************************************/
677 /*                      Particle Edit Mirroring                         */
678 /************************************************/
679
680 static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys)
681 {
682         PTCacheEdit *edit;
683         ParticleSystemModifierData *psmd;
684         KDTree *tree;
685         KDTreeNearest nearest;
686         HairKey *key;
687         PARTICLE_P;
688         float mat[4][4], co[3];
689         int index, totpart;
690
691         edit= psys->edit;
692         psmd= psys_get_modifier(ob, psys);
693         totpart= psys->totpart;
694
695         if(!psmd->dm)
696                 return;
697
698         tree= BLI_kdtree_new(totpart);
699
700         /* insert particles into kd tree */
701         LOOP_PARTICLES {
702                 key = pa->hair;
703                 psys_mat_hair_to_orco(ob, psmd->dm, psys->part->from, pa, mat);
704                 VECCOPY(co, key->co);
705                 mul_m4_v3(mat, co);
706                 BLI_kdtree_insert(tree, p, co, NULL);
707         }
708
709         BLI_kdtree_balance(tree);
710
711         /* lookup particles and set in mirror cache */
712         if(!edit->mirror_cache)
713                 edit->mirror_cache= MEM_callocN(sizeof(int)*totpart, "PE mirror cache");
714         
715         LOOP_PARTICLES {
716                 key = pa->hair;
717                 psys_mat_hair_to_orco(ob, psmd->dm, psys->part->from, pa, mat);
718                 VECCOPY(co, key->co);
719                 mul_m4_v3(mat, co);
720                 co[0]= -co[0];
721
722                 index= BLI_kdtree_find_nearest(tree, co, NULL, &nearest);
723
724                 /* this needs a custom threshold still, duplicated for editmode mirror */
725                 if(index != -1 && index != p && (nearest.dist <= 0.0002f))
726                         edit->mirror_cache[p]= index;
727                 else
728                         edit->mirror_cache[p]= -1;
729         }
730
731         /* make sure mirrors are in two directions */
732         LOOP_PARTICLES {
733                 if(edit->mirror_cache[p]) {
734                         index= edit->mirror_cache[p];
735                         if(edit->mirror_cache[index] != p)
736                                 edit->mirror_cache[p]= -1;
737                 }
738         }
739
740         BLI_kdtree_free(tree);
741 }
742
743 static void PE_mirror_particle(Object *ob, DerivedMesh *dm, ParticleSystem *psys, ParticleData *pa, ParticleData *mpa)
744 {
745         HairKey *hkey, *mhkey;
746         PTCacheEditPoint *point, *mpoint;
747         PTCacheEditKey *key, *mkey;
748         PTCacheEdit *edit;
749         float mat[4][4], mmat[4][4], immat[4][4];
750         int i, mi, k;
751
752         edit= psys->edit;
753         i= pa - psys->particles;
754
755         /* find mirrored particle if needed */
756         if(!mpa) {
757                 if(!edit->mirror_cache)
758                         PE_update_mirror_cache(ob, psys);
759
760                 mi= edit->mirror_cache[i];
761                 if(mi == -1)
762                         return;
763                 mpa= psys->particles + mi;
764         }
765         else
766                 mi= mpa - psys->particles;
767
768         point = edit->points + i;
769         mpoint = edit->points + mi;
770
771         /* make sure they have the same amount of keys */
772         if(pa->totkey != mpa->totkey) {
773                 if(mpa->hair) MEM_freeN(mpa->hair);
774                 if(mpoint->keys) MEM_freeN(mpoint->keys);
775
776                 mpa->hair= MEM_dupallocN(pa->hair);
777                 mpa->totkey= pa->totkey;
778                 mpoint->keys= MEM_dupallocN(point->keys);
779                 mpoint->totkey= point->totkey;
780
781                 mhkey= mpa->hair;
782                 mkey= mpoint->keys;
783                 for(k=0; k<mpa->totkey; k++, mkey++, mhkey++) {
784                         mkey->co= mhkey->co;
785                         mkey->time= &mhkey->time;
786                         mkey->flag &= ~PEK_SELECT;
787                 }
788         }
789
790         /* mirror positions and tags */
791         psys_mat_hair_to_orco(ob, dm, psys->part->from, pa, mat);
792         psys_mat_hair_to_orco(ob, dm, psys->part->from, mpa, mmat);
793         invert_m4_m4(immat, mmat);
794
795         hkey=pa->hair;
796         mhkey=mpa->hair;
797         key= point->keys;
798         mkey= mpoint->keys;
799         for(k=0; k<pa->totkey; k++, hkey++, mhkey++, key++, mkey++) {
800                 VECCOPY(mhkey->co, hkey->co);
801                 mul_m4_v3(mat, mhkey->co);
802                 mhkey->co[0]= -mhkey->co[0];
803                 mul_m4_v3(immat, mhkey->co);
804
805                 if(key->flag & PEK_TAG)
806                         mkey->flag |= PEK_TAG;
807         }
808
809         if(point->flag & PEP_TAG)
810                 mpoint->flag |= PEP_TAG;
811         if(point->flag & PEP_EDIT_RECALC)
812                 mpoint->flag |= PEP_EDIT_RECALC;
813 }
814
815 static void PE_apply_mirror(Object *ob, ParticleSystem *psys)
816 {
817         PTCacheEdit *edit;
818         ParticleSystemModifierData *psmd;
819         POINT_P;
820
821         if(!psys)
822                 return;
823
824         edit= psys->edit;
825         psmd= psys_get_modifier(ob, psys);
826
827         if(!psmd->dm)
828                 return;
829
830         if(!edit->mirror_cache)
831                 PE_update_mirror_cache(ob, psys);
832
833         /* we delay settings the PARS_EDIT_RECALC for mirrored particles
834          * to avoid doing mirror twice */
835         LOOP_POINTS {
836                 if(point->flag & PEP_EDIT_RECALC) {
837                         PE_mirror_particle(ob, psmd->dm, psys, psys->particles + p, NULL);
838
839                         if(edit->mirror_cache[p] != -1)
840                                 edit->points[edit->mirror_cache[p]].flag &= ~PEP_EDIT_RECALC;
841                 }
842         }
843
844         LOOP_POINTS {
845                 if(point->flag & PEP_EDIT_RECALC)
846                         if(edit->mirror_cache[p] != -1)
847                                 edit->points[edit->mirror_cache[p]].flag |= PEP_EDIT_RECALC;
848         }
849 }
850
851 /************************************************/
852 /*                      Edit Calculation                                        */
853 /************************************************/
854 /* tries to stop edited particles from going through the emitter's surface */
855 static void pe_deflect_emitter(Scene *scene, Object *ob, PTCacheEdit *edit)
856 {
857         ParticleEditSettings *pset= PE_settings(scene);
858         ParticleSystem *psys;
859         ParticleSystemModifierData *psmd;
860         POINT_P; KEY_K;
861         int index;
862         float *vec, *nor, dvec[3], dot, dist_1st=0.0f;
863         float hairimat[4][4], hairmat[4][4];
864
865         if(edit==NULL || edit->psys==NULL || (pset->flag & PE_DEFLECT_EMITTER)==0 || (edit->psys->flag & PSYS_GLOBAL_HAIR))
866                 return;
867
868         psys = edit->psys;
869         psmd = psys_get_modifier(ob,psys);
870
871         if(!psmd->dm)
872                 return;
873
874         LOOP_EDITED_POINTS {
875                 psys_mat_hair_to_object(ob, psmd->dm, psys->part->from, psys->particles + p, hairmat);
876         
877                 LOOP_KEYS {
878                         mul_m4_v3(hairmat, key->co);
879                 }
880
881                 LOOP_KEYS {
882                         if(k==0) {
883                                 dist_1st = len_v3v3((key+1)->co, key->co);
884                                 dist_1st *= 0.75f * pset->emitterdist;
885                         }
886                         else {
887                                 index= BLI_kdtree_find_nearest(edit->emitter_field,key->co,NULL,NULL);
888                                 
889                                 vec=edit->emitter_cosnos +index*6;
890                                 nor=vec+3;
891
892                                 sub_v3_v3v3(dvec, key->co, vec);
893
894                                 dot=dot_v3v3(dvec,nor);
895                                 VECCOPY(dvec,nor);
896
897                                 if(dot>0.0f) {
898                                         if(dot<dist_1st) {
899                                                 normalize_v3(dvec);
900                                                 mul_v3_fl(dvec,dist_1st-dot);
901                                                 add_v3_v3(key->co, dvec);
902                                         }
903                                 }
904                                 else {
905                                         normalize_v3(dvec);
906                                         mul_v3_fl(dvec,dist_1st-dot);
907                                         add_v3_v3(key->co, dvec);
908                                 }
909                                 if(k==1)
910                                         dist_1st*=1.3333f;
911                         }
912                 }
913                 
914                 invert_m4_m4(hairimat,hairmat);
915
916                 LOOP_KEYS {
917                         mul_m4_v3(hairimat, key->co);
918                 }
919         }
920 }
921 /* force set distances between neighbouring keys */
922 void PE_apply_lengths(Scene *scene, PTCacheEdit *edit)
923 {
924         
925         ParticleEditSettings *pset=PE_settings(scene);
926         POINT_P; KEY_K;
927         float dv1[3];
928
929         if(edit==0 || (pset->flag & PE_KEEP_LENGTHS)==0)
930                 return;
931
932         if(edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR)
933                 return;
934
935         LOOP_EDITED_POINTS {
936                 LOOP_KEYS {
937                         if(k) {
938                                 sub_v3_v3v3(dv1, key->co, (key - 1)->co);
939                                 normalize_v3(dv1);
940                                 mul_v3_fl(dv1, (key - 1)->length);
941                                 add_v3_v3v3(key->co, (key - 1)->co, dv1);
942                         }
943                 }
944         }
945 }
946 /* try to find a nice solution to keep distances between neighbouring keys */
947 static void pe_iterate_lengths(Scene *scene, PTCacheEdit *edit)
948 {
949         ParticleEditSettings *pset=PE_settings(scene);
950         POINT_P;
951         PTCacheEditKey *key;
952         int j, k;
953         float tlen;
954         float dv0[3]= {0.0f, 0.0f, 0.0f};
955         float dv1[3]= {0.0f, 0.0f, 0.0f};
956         float dv2[3]= {0.0f, 0.0f, 0.0f};
957
958         if(edit==0 || (pset->flag & PE_KEEP_LENGTHS)==0)
959                 return;
960
961         if(edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR)
962                 return;
963
964         LOOP_EDITED_POINTS {
965                 for(j=1; j<point->totkey; j++) {
966                         float mul= 1.0f / (float)point->totkey;
967
968                         if(pset->flag & PE_LOCK_FIRST) {
969                                 key= point->keys + 1;
970                                 k= 1;
971                                 dv1[0]= dv1[1]= dv1[2]= 0.0;
972                         }
973                         else {
974                                 key= point->keys;
975                                 k= 0;
976                                 dv0[0]= dv0[1]= dv0[2]= 0.0;
977                         }
978
979                         for(; k<point->totkey; k++, key++) {
980                                 if(k) {
981                                         sub_v3_v3v3(dv0, (key - 1)->co, key->co);
982                                         tlen= normalize_v3(dv0);
983                                         mul_v3_fl(dv0, (mul * (tlen - (key - 1)->length)));
984                                 }
985
986                                 if(k < point->totkey - 1) {
987                                         sub_v3_v3v3(dv2, (key + 1)->co, key->co);
988                                         tlen= normalize_v3(dv2);
989                                         mul_v3_fl(dv2, mul * (tlen - key->length));
990                                 }
991
992                                 if(k) {
993                                         add_v3_v3((key-1)->co, dv1);
994                                 }
995
996                                 VECADD(dv1,dv0,dv2);
997                         }
998                 }
999         }
1000 }
1001 /* set current distances to be kept between neighbouting keys */
1002 static void recalc_lengths(PTCacheEdit *edit)
1003 {
1004         POINT_P; KEY_K;
1005
1006         if(edit==0)
1007                 return;
1008
1009         LOOP_EDITED_POINTS {
1010                 key= point->keys;
1011                 for(k=0; k<point->totkey-1; k++, key++) {
1012                         key->length= len_v3v3(key->co, (key + 1)->co);
1013                 }
1014         }
1015 }
1016
1017 /* calculate a tree for finding nearest emitter's vertice */
1018 static void recalc_emitter_field(Object *ob, ParticleSystem *psys)
1019 {
1020         DerivedMesh *dm=psys_get_modifier(ob,psys)->dm;
1021         PTCacheEdit *edit= psys->edit;
1022         MFace *mface;
1023         MVert *mvert;
1024         float *vec, *nor;
1025         int i, totface, totvert;
1026
1027         if(!dm)
1028                 return;
1029
1030         if(edit->emitter_cosnos)
1031                 MEM_freeN(edit->emitter_cosnos);
1032
1033         BLI_kdtree_free(edit->emitter_field);
1034
1035         totface=dm->getNumFaces(dm);
1036         totvert=dm->getNumVerts(dm);
1037
1038         edit->emitter_cosnos=MEM_callocN(totface*6*sizeof(float),"emitter cosnos");
1039
1040         edit->emitter_field= BLI_kdtree_new(totface);
1041
1042         vec=edit->emitter_cosnos;
1043         nor=vec+3;
1044
1045         mvert=dm->getVertDataArray(dm,CD_MVERT);
1046         for(i=0; i<totface; i++, vec+=6, nor+=6) {
1047                 mface=dm->getFaceData(dm,i,CD_MFACE);
1048
1049                 mvert=dm->getVertData(dm,mface->v1,CD_MVERT);
1050                 VECCOPY(vec,mvert->co);
1051                 VECCOPY(nor,mvert->no);
1052
1053                 mvert=dm->getVertData(dm,mface->v2,CD_MVERT);
1054                 VECADD(vec,vec,mvert->co);
1055                 VECADD(nor,nor,mvert->no);
1056
1057                 mvert=dm->getVertData(dm,mface->v3,CD_MVERT);
1058                 VECADD(vec,vec,mvert->co);
1059                 VECADD(nor,nor,mvert->no);
1060
1061                 if(mface->v4) {
1062                         mvert=dm->getVertData(dm,mface->v4,CD_MVERT);
1063                         VECADD(vec,vec,mvert->co);
1064                         VECADD(nor,nor,mvert->no);
1065                         
1066                         mul_v3_fl(vec,0.25);
1067                 }
1068                 else
1069                         mul_v3_fl(vec,0.3333f);
1070
1071                 normalize_v3(nor);
1072
1073                 BLI_kdtree_insert(edit->emitter_field, i, vec, NULL);
1074         }
1075
1076         BLI_kdtree_balance(edit->emitter_field);
1077 }
1078
1079 static void PE_update_selection(Scene *scene, Object *ob, int useflag)
1080 {
1081         PTCacheEdit *edit= PE_get_current(scene, ob);
1082         HairKey *hkey;
1083         POINT_P; KEY_K;
1084
1085         /* flag all particles to be updated if not using flag */
1086         if(!useflag)
1087                 LOOP_POINTS
1088                         point->flag |= PEP_EDIT_RECALC;
1089
1090         /* flush edit key flag to hair key flag to preserve selection 
1091          * on save */
1092         if(edit->psys) LOOP_POINTS {
1093                 hkey = edit->psys->particles[p].hair;
1094                 LOOP_KEYS {
1095                         hkey->editflag= key->flag;
1096                         hkey++;
1097                 }
1098         }
1099
1100         psys_cache_edit_paths(scene, ob, edit, CFRA);
1101
1102
1103         /* disable update flag */
1104         LOOP_POINTS
1105                 point->flag &= ~PEP_EDIT_RECALC;
1106 }
1107
1108 static void update_world_cos(Object *ob, PTCacheEdit *edit)
1109 {
1110         ParticleSystem *psys = edit->psys;
1111         ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys);
1112         POINT_P; KEY_K;
1113         float hairmat[4][4];
1114
1115         if(psys==0 || psys->edit==0 || psmd->dm==NULL)
1116                 return;
1117
1118         LOOP_POINTS {
1119                 if(!(psys->flag & PSYS_GLOBAL_HAIR))
1120                         psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, psys->particles+p, hairmat);
1121
1122                 LOOP_KEYS {
1123                         VECCOPY(key->world_co,key->co);
1124                         if(!(psys->flag & PSYS_GLOBAL_HAIR))
1125                                 mul_m4_v3(hairmat, key->world_co);
1126                 }
1127         }
1128 }
1129 static void update_velocities(PTCacheEdit *edit)
1130 {
1131         /*TODO: get frs_sec properly */
1132         float vec1[3], vec2[3], frs_sec, dfra;
1133         POINT_P; KEY_K;
1134
1135         /* hair doesn't use velocities */
1136         if(edit->psys || !edit->points || !edit->points->keys->vel)
1137                 return;
1138
1139         frs_sec = edit->pid.flag & PTCACHE_VEL_PER_SEC ? 25.0f : 1.0f;
1140
1141         LOOP_EDITED_POINTS {
1142                 LOOP_KEYS {
1143                         if(k==0) {
1144                                 dfra = *(key+1)->time - *key->time;
1145
1146                                 if(dfra <= 0.0f)
1147                                         continue;
1148
1149                                 VECSUB(key->vel, (key+1)->co, key->co);
1150
1151                                 if(point->totkey>2) {
1152                                         VECSUB(vec1, (key+1)->co, (key+2)->co);
1153                                         project_v3_v3v3(vec2, vec1, key->vel);
1154                                         VECSUB(vec2, vec1, vec2);
1155                                         VECADDFAC(key->vel, key->vel, vec2, 0.5f);
1156                                 }
1157                         }
1158                         else if(k==point->totkey-1) {
1159                                 dfra = *key->time - *(key-1)->time;
1160
1161                                 if(dfra <= 0.0f)
1162                                         continue;
1163
1164                                 VECSUB(key->vel, key->co, (key-1)->co);
1165
1166                                 if(point->totkey>2) {
1167                                         VECSUB(vec1, (key-2)->co, (key-1)->co);
1168                                         project_v3_v3v3(vec2, vec1, key->vel);
1169                                         VECSUB(vec2, vec1, vec2);
1170                                         VECADDFAC(key->vel, key->vel, vec2, 0.5f);
1171                                 }
1172                         }
1173                         else {
1174                                 dfra = *(key+1)->time - *(key-1)->time;
1175                                 
1176                                 if(dfra <= 0.0f)
1177                                         continue;
1178
1179                                 VECSUB(key->vel, (key+1)->co, (key-1)->co);
1180                         }
1181                         mul_v3_fl(key->vel, frs_sec/dfra);
1182                 }
1183         }
1184 }
1185
1186 void PE_update_object(Scene *scene, Object *ob, int useflag)
1187 {
1188         /* use this to do partial particle updates, not usable when adding or
1189            removing, then a full redo is necessary and calling this may crash */
1190         ParticleEditSettings *pset= PE_settings(scene);
1191         PTCacheEdit *edit = PE_get_current(scene, ob);
1192         POINT_P;
1193
1194         if(!edit)
1195                 return;
1196
1197         /* flag all particles to be updated if not using flag */
1198         if(!useflag)
1199                 LOOP_POINTS {
1200                         point->flag |= PEP_EDIT_RECALC;
1201                 }
1202
1203         /* do post process on particle edit keys */
1204         pe_iterate_lengths(scene, edit);
1205         pe_deflect_emitter(scene, ob, edit);
1206         PE_apply_lengths(scene, edit);
1207         if(pe_x_mirror(ob))
1208                 PE_apply_mirror(ob,edit->psys);
1209         if(edit->psys)
1210                 update_world_cos(ob, edit);
1211         if(pset->flag & PE_AUTO_VELOCITY)
1212                 update_velocities(edit);
1213         PE_hide_keys_time(scene, edit, CFRA);
1214
1215         /* regenerate path caches */
1216         psys_cache_edit_paths(scene, ob, edit, CFRA);
1217
1218         /* disable update flag */
1219         LOOP_POINTS {
1220                 point->flag &= ~PEP_EDIT_RECALC;
1221         }
1222
1223         if(edit->psys)
1224                 edit->psys->flag &= ~PSYS_HAIR_UPDATED;
1225 }
1226
1227 /************************************************/
1228 /*                      Edit Selections                                         */
1229 /************************************************/
1230
1231 /*-----selection callbacks-----*/
1232
1233 static void select_key(PEData *data, int point_index, int key_index)
1234 {
1235         PTCacheEdit *edit = data->edit;
1236         PTCacheEditPoint *point = edit->points + point_index;
1237         PTCacheEditKey *key = point->keys + key_index;
1238
1239         if(data->select)
1240                 key->flag |= PEK_SELECT;
1241         else
1242                 key->flag &= ~PEK_SELECT;
1243
1244         point->flag |= PEP_EDIT_RECALC;
1245 }
1246
1247 static void select_keys(PEData *data, int point_index, int UNUSED(key_index))
1248 {
1249         PTCacheEdit *edit = data->edit;
1250         PTCacheEditPoint *point = edit->points + point_index;
1251         KEY_K;
1252
1253         LOOP_KEYS {
1254                 if(data->select)
1255                         key->flag |= PEK_SELECT;
1256                 else
1257                         key->flag &= ~PEK_SELECT;
1258         }
1259
1260         point->flag |= PEP_EDIT_RECALC;
1261 }
1262
1263 static void toggle_key_select(PEData *data, int point_index, int key_index)
1264 {
1265         PTCacheEdit *edit = data->edit;
1266         PTCacheEditPoint *point = edit->points + point_index;
1267         PTCacheEditKey *key = point->keys + key_index;
1268
1269         key->flag ^= PEK_SELECT;
1270         point->flag |= PEP_EDIT_RECALC;
1271 }
1272
1273 /************************ de select all operator ************************/
1274
1275 static int select_all_exec(bContext *C, wmOperator *op)
1276 {
1277         Scene *scene= CTX_data_scene(C);
1278         Object *ob= CTX_data_active_object(C);
1279         PTCacheEdit *edit= PE_get_current(scene, ob);
1280         POINT_P; KEY_K;
1281         int action = RNA_enum_get(op->ptr, "action");
1282
1283         if (action == SEL_TOGGLE) {
1284                 action = SEL_SELECT;
1285                 LOOP_VISIBLE_POINTS {
1286                         LOOP_SELECTED_KEYS {
1287                                 action = SEL_DESELECT;
1288                                 break;
1289                         }
1290
1291                         if (action == SEL_DESELECT)
1292                                 break;
1293                 }
1294         }
1295
1296         LOOP_VISIBLE_POINTS {
1297                 LOOP_VISIBLE_KEYS {
1298                         switch (action) {
1299                         case SEL_SELECT:
1300                                 if ((key->flag & PEK_SELECT) == 0) {
1301                                         key->flag |= PEK_SELECT;
1302                                         point->flag |= PEP_EDIT_RECALC;
1303                                 }
1304                                 break;
1305                         case SEL_DESELECT:
1306                                 if (key->flag & PEK_SELECT) {
1307                                         key->flag &= ~PEK_SELECT;
1308                                         point->flag |= PEP_EDIT_RECALC;
1309                                 }
1310                                 break;
1311                         case SEL_INVERT:
1312                                 if ((key->flag & PEK_SELECT) == 0) {
1313                                         key->flag |= PEK_SELECT;
1314                                         point->flag |= PEP_EDIT_RECALC;
1315                                 } else {
1316                                         key->flag &= ~PEK_SELECT;
1317                                         point->flag |= PEP_EDIT_RECALC;
1318                                 }
1319                                 break;
1320                         }
1321                 }
1322         }
1323
1324         PE_update_selection(scene, ob, 1);
1325         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1326
1327         return OPERATOR_FINISHED;
1328 }
1329
1330 void PARTICLE_OT_select_all(wmOperatorType *ot)
1331 {
1332         /* identifiers */
1333         ot->name= "Selection of all particles";
1334         ot->idname= "PARTICLE_OT_select_all";
1335         
1336         /* api callbacks */
1337         ot->exec= select_all_exec;
1338         ot->poll= PE_poll;
1339
1340         /* flags */
1341         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1342
1343         WM_operator_properties_select_all(ot);
1344 }
1345
1346 /************************ pick select operator ************************/
1347
1348 int PE_mouse_particles(bContext *C, short *mval, int extend)
1349 {
1350         PEData data;
1351         Scene *scene= CTX_data_scene(C);
1352         Object *ob= CTX_data_active_object(C);
1353         PTCacheEdit *edit= PE_get_current(scene, ob);
1354         POINT_P; KEY_K;
1355         
1356         if(!PE_start_edit(edit))
1357                 return OPERATOR_CANCELLED;
1358
1359         if(!extend) {
1360                 LOOP_VISIBLE_POINTS {
1361                         LOOP_SELECTED_KEYS {
1362                                 key->flag &= ~PEK_SELECT;
1363                                 point->flag |= PEP_EDIT_RECALC;
1364                         }
1365                 }
1366         }
1367
1368         PE_set_view3d_data(C, &data);
1369         data.mval= mval;
1370         data.rad= 75.0f;
1371
1372         for_mouse_hit_keys(&data, toggle_key_select, 1);  /* nearest only */
1373
1374         PE_update_selection(scene, ob, 1);
1375         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1376
1377         return OPERATOR_FINISHED;
1378 }
1379
1380 /************************ select first operator ************************/
1381
1382 static void select_root(PEData *data, int point_index)
1383 {
1384         if (data->edit->points[point_index].flag & PEP_HIDE)
1385                 return;
1386         
1387         data->edit->points[point_index].keys->flag |= PEK_SELECT;
1388         data->edit->points[point_index].flag |= PEP_EDIT_RECALC; /* redraw selection only */
1389 }
1390
1391 static int select_roots_exec(bContext *C, wmOperator *UNUSED(op))
1392 {
1393         PEData data;
1394
1395         PE_set_data(C, &data);
1396         foreach_point(&data, select_root);
1397
1398         PE_update_selection(data.scene, data.ob, 1);
1399         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1400
1401         return OPERATOR_FINISHED;
1402 }
1403
1404 void PARTICLE_OT_select_roots(wmOperatorType *ot)
1405 {
1406         /* identifiers */
1407         ot->name= "Select Roots";
1408         ot->idname= "PARTICLE_OT_select_roots";
1409         
1410         /* api callbacks */
1411         ot->exec= select_roots_exec;
1412         ot->poll= PE_poll;
1413
1414         /* flags */
1415         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1416 }
1417
1418 /************************ select last operator ************************/
1419
1420 static void select_tip(PEData *data, int point_index)
1421 {
1422         PTCacheEditPoint *point = data->edit->points + point_index;
1423         
1424         if (point->flag & PEP_HIDE)
1425                 return;
1426         
1427         point->keys[point->totkey - 1].flag |= PEK_SELECT;
1428         point->flag |= PEP_EDIT_RECALC; /* redraw selection only */
1429 }
1430
1431 static int select_tips_exec(bContext *C, wmOperator *UNUSED(op))
1432 {
1433         PEData data;
1434
1435         PE_set_data(C, &data);
1436         foreach_point(&data, select_tip);
1437
1438         PE_update_selection(data.scene, data.ob, 1);
1439         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1440
1441         return OPERATOR_FINISHED;
1442 }
1443
1444 void PARTICLE_OT_select_tips(wmOperatorType *ot)
1445 {
1446         /* identifiers */
1447         ot->name= "Select Tips";
1448         ot->idname= "PARTICLE_OT_select_tips";
1449         
1450         /* api callbacks */
1451         ot->exec= select_tips_exec;
1452         ot->poll= PE_poll;
1453
1454         /* flags */
1455         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1456 }
1457
1458 /************************ select linked operator ************************/
1459
1460 static int select_linked_exec(bContext *C, wmOperator *op)
1461 {
1462         PEData data;
1463         short mval[2];
1464         int location[2];
1465
1466         RNA_int_get_array(op->ptr, "location", location);
1467         mval[0]= location[0];
1468         mval[1]= location[1];
1469
1470         view3d_operator_needs_opengl(C);
1471
1472         PE_set_view3d_data(C, &data);
1473         data.mval= mval;
1474         data.rad=75.0f;
1475         data.select= !RNA_boolean_get(op->ptr, "deselect");
1476
1477         for_mouse_hit_keys(&data, select_keys, 1);  /* nearest only */
1478         PE_update_selection(data.scene, data.ob, 1);
1479         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1480
1481         return OPERATOR_FINISHED;
1482 }
1483
1484 static int select_linked_invoke(bContext *C, wmOperator *op, wmEvent *event)
1485 {
1486         ARegion *ar= CTX_wm_region(C);
1487         int location[2];
1488
1489         location[0]= event->x - ar->winrct.xmin;
1490         location[1]= event->y - ar->winrct.ymin;
1491         RNA_int_set_array(op->ptr, "location", location);
1492
1493         return select_linked_exec(C, op);
1494 }
1495
1496 void PARTICLE_OT_select_linked(wmOperatorType *ot)
1497 {
1498         /* identifiers */
1499         ot->name= "Select Linked";
1500         ot->idname= "PARTICLE_OT_select_linked";
1501         
1502         /* api callbacks */
1503         ot->exec= select_linked_exec;
1504         ot->invoke= select_linked_invoke;
1505         ot->poll= PE_poll_view3d;
1506
1507         /* flags */
1508         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1509
1510         /* properties */
1511         RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect linked keys rather than selecting them.");
1512         RNA_def_int_vector(ot->srna, "location", 2, NULL, 0, INT_MAX, "Location", "", 0, 16384);
1513 }
1514
1515 /************************ border select operator ************************/
1516
1517 int PE_border_select(bContext *C, rcti *rect, int select, int extend)
1518 {
1519         Scene *scene= CTX_data_scene(C);
1520         Object *ob= CTX_data_active_object(C);
1521         PTCacheEdit *edit= PE_get_current(scene, ob);
1522         PEData data;
1523
1524         if(!PE_start_edit(edit))
1525                 return OPERATOR_CANCELLED;
1526
1527         if (extend == 0 && select) {
1528                 POINT_P; KEY_K;
1529
1530                 LOOP_VISIBLE_POINTS {
1531                         LOOP_SELECTED_KEYS {
1532                                 key->flag &= ~PEK_SELECT;
1533                                 point->flag |= PEP_EDIT_RECALC;
1534                         }
1535                 }
1536         }
1537
1538         PE_set_view3d_data(C, &data);
1539         data.rect= rect;
1540         data.select= select;
1541
1542         for_mouse_hit_keys(&data, select_key, 0);
1543
1544         PE_update_selection(scene, ob, 1);
1545         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1546
1547         return OPERATOR_FINISHED;
1548 }
1549
1550 /************************ circle select operator ************************/
1551
1552 int PE_circle_select(bContext *C, int selecting, short *mval, float rad)
1553 {
1554         Scene *scene= CTX_data_scene(C);
1555         Object *ob= CTX_data_active_object(C);
1556         PTCacheEdit *edit= PE_get_current(scene, ob);
1557         PEData data;
1558
1559         if(!PE_start_edit(edit))
1560                 return OPERATOR_FINISHED;
1561
1562         PE_set_view3d_data(C, &data);
1563         data.mval= mval;
1564         data.rad= rad;
1565         data.select= selecting;
1566
1567         for_mouse_hit_keys(&data, select_key, 0);
1568
1569         PE_update_selection(scene, ob, 1);
1570         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1571
1572         return OPERATOR_FINISHED;
1573 }
1574
1575 /************************ lasso select operator ************************/
1576
1577 int PE_lasso_select(bContext *C, short mcords[][2], short moves, short select)
1578 {
1579         Scene *scene= CTX_data_scene(C);
1580         Object *ob= CTX_data_active_object(C);
1581         ARegion *ar= CTX_wm_region(C);
1582         ParticleEditSettings *pset= PE_settings(scene);
1583         PTCacheEdit *edit = PE_get_current(scene, ob);
1584         ParticleSystem *psys = edit->psys;
1585         ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
1586         POINT_P; KEY_K;
1587         float co[3], mat[4][4];
1588         short vertco[2];
1589
1590         if(!PE_start_edit(edit))
1591                 return OPERATOR_CANCELLED;
1592
1593         unit_m4(mat);
1594
1595         LOOP_VISIBLE_POINTS {
1596                 if(edit->psys && !(psys->flag & PSYS_GLOBAL_HAIR))
1597                         psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, psys->particles + p, mat);
1598
1599                 if(pset->selectmode==SCE_SELECT_POINT) {
1600                         LOOP_KEYS {
1601                                 VECCOPY(co, key->co);
1602                                 mul_m4_v3(mat, co);
1603                                 project_short(ar, co, vertco);
1604                                 if((vertco[0] != IS_CLIPPED) && lasso_inside(mcords,moves,vertco[0],vertco[1])) {
1605                                         if(select && !(key->flag & PEK_SELECT)) {
1606                                                 key->flag |= PEK_SELECT;
1607                                                 point->flag |= PEP_EDIT_RECALC;
1608                                         }
1609                                         else if(key->flag & PEK_SELECT) {
1610                                                 key->flag &= ~PEK_SELECT;
1611                                                 point->flag |= PEP_EDIT_RECALC;
1612                                         }
1613                                 }
1614                         }
1615                 }
1616                 else if(pset->selectmode==SCE_SELECT_END) {
1617                         key= point->keys + point->totkey - 1;
1618
1619                         VECCOPY(co, key->co);
1620                         mul_m4_v3(mat, co);
1621                         project_short(ar, co,vertco);
1622                         if((vertco[0] != IS_CLIPPED) && lasso_inside(mcords,moves,vertco[0],vertco[1])) {
1623                                 if(select && !(key->flag & PEK_SELECT)) {
1624                                         key->flag |= PEK_SELECT;
1625                                         point->flag |= PEP_EDIT_RECALC;
1626                                 }
1627                                 else if(key->flag & PEK_SELECT) {
1628                                         key->flag &= ~PEK_SELECT;
1629                                         point->flag |= PEP_EDIT_RECALC;
1630                                 }
1631                         }
1632                 }
1633         }
1634
1635         PE_update_selection(scene, ob, 1);
1636         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1637
1638         return OPERATOR_FINISHED;
1639 }
1640
1641 /*************************** hide operator **************************/
1642
1643 static int hide_exec(bContext *C, wmOperator *op)
1644 {
1645         Object *ob= CTX_data_active_object(C);
1646         Scene *scene= CTX_data_scene(C);
1647         PTCacheEdit *edit= PE_get_current(scene, ob);
1648         POINT_P; KEY_K;
1649         
1650         if(RNA_enum_get(op->ptr, "unselected")) {
1651                 LOOP_UNSELECTED_POINTS {
1652                         point->flag |= PEP_HIDE;
1653                         point->flag |= PEP_EDIT_RECALC;
1654
1655                         LOOP_KEYS
1656                                 key->flag &= ~PEK_SELECT;
1657                 }
1658         }
1659         else {
1660                 LOOP_SELECTED_POINTS {
1661                         point->flag |= PEP_HIDE;
1662                         point->flag |= PEP_EDIT_RECALC;
1663
1664                         LOOP_KEYS
1665                                 key->flag &= ~PEK_SELECT;
1666                 }
1667         }
1668
1669         PE_update_selection(scene, ob, 1);
1670         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1671
1672         return OPERATOR_FINISHED;
1673 }
1674
1675 void PARTICLE_OT_hide(wmOperatorType *ot)
1676 {
1677         /* identifiers */
1678         ot->name= "Hide Selected";
1679         ot->idname= "PARTICLE_OT_hide";
1680         
1681         /* api callbacks */
1682         ot->exec= hide_exec;
1683         ot->poll= PE_poll;
1684
1685         /* flags */
1686         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1687
1688         /* props */
1689         RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected.");
1690 }
1691
1692 /*************************** reveal operator **************************/
1693
1694 static int reveal_exec(bContext *C, wmOperator *UNUSED(op))
1695 {
1696         Object *ob= CTX_data_active_object(C);
1697         Scene *scene= CTX_data_scene(C);
1698         PTCacheEdit *edit= PE_get_current(scene, ob);
1699         POINT_P; KEY_K;
1700
1701         LOOP_POINTS {
1702                 if(point->flag & PEP_HIDE) {
1703                         point->flag &= ~PEP_HIDE;
1704                         point->flag |= PEP_EDIT_RECALC;
1705
1706                         LOOP_KEYS
1707                                 key->flag |= PEK_SELECT;
1708                 }
1709         }
1710
1711         PE_update_selection(scene, ob, 1);
1712         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, ob);
1713
1714         return OPERATOR_FINISHED;
1715 }
1716
1717 void PARTICLE_OT_reveal(wmOperatorType *ot)
1718 {
1719         /* identifiers */
1720         ot->name= "Reveal";
1721         ot->idname= "PARTICLE_OT_reveal";
1722         
1723         /* api callbacks */
1724         ot->exec= reveal_exec;
1725         ot->poll= PE_poll;
1726
1727         /* flags */
1728         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1729 }
1730
1731 /************************ select less operator ************************/
1732
1733 static void select_less_keys(PEData *data, int point_index)
1734 {
1735         PTCacheEdit *edit= data->edit;
1736         PTCacheEditPoint *point = edit->points + point_index;
1737         KEY_K;
1738
1739         LOOP_SELECTED_KEYS {
1740                 if(k==0) {
1741                         if(((key+1)->flag&PEK_SELECT)==0)
1742                                 key->flag |= PEK_TAG;
1743                 }
1744                 else if(k==point->totkey-1) {
1745                         if(((key-1)->flag&PEK_SELECT)==0)
1746                                 key->flag |= PEK_TAG;
1747                 }
1748                 else {
1749                         if((((key-1)->flag & (key+1)->flag) & PEK_SELECT)==0)
1750                                 key->flag |= PEK_TAG;
1751                 }
1752         }
1753
1754         LOOP_KEYS {
1755                 if(key->flag&PEK_TAG) {
1756                         key->flag &= ~(PEK_TAG|PEK_SELECT);
1757                         point->flag |= PEP_EDIT_RECALC; /* redraw selection only */
1758                 }
1759         }
1760 }
1761
1762 static int select_less_exec(bContext *C, wmOperator *UNUSED(op))
1763 {
1764         PEData data;
1765
1766         PE_set_data(C, &data);
1767         foreach_point(&data, select_less_keys);
1768
1769         PE_update_selection(data.scene, data.ob, 1);
1770         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1771
1772         return OPERATOR_FINISHED;
1773 }
1774
1775 void PARTICLE_OT_select_less(wmOperatorType *ot)
1776 {
1777         /* identifiers */
1778         ot->name= "Select Less";
1779         ot->idname= "PARTICLE_OT_select_less";
1780         
1781         /* api callbacks */
1782         ot->exec= select_less_exec;
1783         ot->poll= PE_poll;
1784
1785         /* flags */
1786         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1787 }
1788
1789 /************************ select more operator ************************/
1790
1791 static void select_more_keys(PEData *data, int point_index)
1792 {
1793         PTCacheEdit *edit= data->edit;
1794         PTCacheEditPoint *point = edit->points + point_index;
1795         KEY_K;
1796
1797         LOOP_KEYS {
1798                 if(key->flag & PEK_SELECT) continue;
1799
1800                 if(k==0) {
1801                         if((key+1)->flag&PEK_SELECT)
1802                                 key->flag |= PEK_TAG;
1803                 }
1804                 else if(k==point->totkey-1) {
1805                         if((key-1)->flag&PEK_SELECT)
1806                                 key->flag |= PEK_TAG;
1807                 }
1808                 else {
1809                         if(((key-1)->flag | (key+1)->flag) & PEK_SELECT)
1810                                 key->flag |= PEK_TAG;
1811                 }
1812         }
1813
1814         LOOP_KEYS {
1815                 if(key->flag&PEK_TAG) {
1816                         key->flag &= ~PEK_TAG;
1817                         key->flag |= PEK_SELECT;
1818                         point->flag |= PEP_EDIT_RECALC; /* redraw selection only */
1819                 }
1820         }
1821 }
1822
1823 static int select_more_exec(bContext *C, wmOperator *UNUSED(op))
1824 {
1825         PEData data;
1826
1827         PE_set_data(C, &data);
1828         foreach_point(&data, select_more_keys);
1829
1830         PE_update_selection(data.scene, data.ob, 1);
1831         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1832
1833         return OPERATOR_FINISHED;
1834 }
1835
1836 void PARTICLE_OT_select_more(wmOperatorType *ot)
1837 {
1838         /* identifiers */
1839         ot->name= "Select More";
1840         ot->idname= "PARTICLE_OT_select_more";
1841         
1842         /* api callbacks */
1843         ot->exec= select_more_exec;
1844         ot->poll= PE_poll;
1845
1846         /* flags */
1847         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1848 }
1849
1850 static int select_inverse_exec(bContext *C, wmOperator *UNUSED(op))
1851 {
1852         PEData data;
1853         PTCacheEdit *edit;
1854         POINT_P; KEY_K;
1855
1856         PE_set_data(C, &data);
1857
1858         edit= PE_get_current(data.scene, data.ob);
1859
1860         LOOP_VISIBLE_POINTS {
1861                 LOOP_KEYS {
1862                         key->flag ^= PEK_SELECT;
1863                         point->flag |= PEP_EDIT_RECALC; /* redraw selection only */
1864                 }
1865         }
1866
1867         PE_update_selection(data.scene, data.ob, 1);
1868         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_SELECTED, data.ob);
1869
1870         return OPERATOR_FINISHED;
1871 }
1872
1873 void PARTICLE_OT_select_inverse(wmOperatorType *ot)
1874 {
1875         /* identifiers */
1876         ot->name= "Select Inverse";
1877         ot->idname= "PARTICLE_OT_select_inverse";
1878
1879         /* api callbacks */
1880         ot->exec= select_inverse_exec;
1881         ot->poll= PE_poll;
1882
1883         /* flags */
1884         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1885 }
1886
1887 /************************ rekey operator ************************/
1888
1889 static void rekey_particle(PEData *data, int pa_index)
1890 {
1891         PTCacheEdit *edit= data->edit;
1892         ParticleSystem *psys= edit->psys;
1893         ParticleSimulationData sim= {0};
1894         ParticleData *pa= psys->particles + pa_index;
1895         PTCacheEditPoint *point = edit->points + pa_index;
1896         ParticleKey state;
1897         HairKey *key, *new_keys, *okey;
1898         PTCacheEditKey *ekey;
1899         float dval, sta, end;
1900         int k;
1901
1902         sim.scene= data->scene;
1903         sim.ob= data->ob;
1904         sim.psys= edit->psys;
1905
1906         pa->flag |= PARS_REKEY;
1907
1908         key= new_keys= MEM_callocN(data->totrekey * sizeof(HairKey),"Hair re-key keys");
1909
1910         okey = pa->hair;
1911         /* root and tip stay the same */
1912         VECCOPY(key->co, okey->co);
1913         VECCOPY((key + data->totrekey - 1)->co, (okey + pa->totkey - 1)->co);
1914
1915         sta= key->time= okey->time;
1916         end= (key + data->totrekey - 1)->time= (okey + pa->totkey - 1)->time;
1917         dval= (end - sta) / (float)(data->totrekey - 1);
1918
1919         /* interpolate new keys from old ones */
1920         for(k=1,key++; k<data->totrekey-1; k++,key++) {
1921                 state.time= (float)k / (float)(data->totrekey-1);
1922                 psys_get_particle_on_path(&sim, pa_index, &state, 0);
1923                 VECCOPY(key->co, state.co);
1924                 key->time= sta + k * dval;
1925         }
1926
1927         /* replace keys */
1928         if(pa->hair)
1929                 MEM_freeN(pa->hair);
1930         pa->hair= new_keys;
1931
1932         point->totkey=pa->totkey=data->totrekey;
1933
1934
1935         if(point->keys)
1936                 MEM_freeN(point->keys);
1937         ekey= point->keys= MEM_callocN(pa->totkey * sizeof(PTCacheEditKey),"Hair re-key edit keys");
1938                 
1939         for(k=0, key=pa->hair; k<pa->totkey; k++, key++, ekey++) {
1940                 ekey->co= key->co;
1941                 ekey->time= &key->time;
1942                 if(!(psys->flag & PSYS_GLOBAL_HAIR))
1943                         ekey->flag |= PEK_USE_WCO;
1944         }
1945
1946         pa->flag &= ~PARS_REKEY;
1947         point->flag |= PEP_EDIT_RECALC;
1948 }
1949
1950 static int rekey_exec(bContext *C, wmOperator *op)
1951 {
1952         PEData data;
1953
1954         PE_set_data(C, &data);
1955
1956         data.dval= 1.0f / (float)(data.totrekey-1);
1957         data.totrekey= RNA_int_get(op->ptr, "keys");
1958
1959         foreach_selected_point(&data, rekey_particle);
1960         
1961         recalc_lengths(data.edit);
1962         PE_update_object(data.scene, data.ob, 1);
1963         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, data.ob);
1964
1965         return OPERATOR_FINISHED;
1966 }
1967
1968 void PARTICLE_OT_rekey(wmOperatorType *ot)
1969 {
1970         /* identifiers */
1971         ot->name= "Rekey";
1972         ot->idname= "PARTICLE_OT_rekey";
1973         
1974         /* api callbacks */
1975         ot->exec= rekey_exec;
1976         ot->invoke= WM_operator_props_popup;
1977         ot->poll= PE_poll;
1978
1979         /* flags */
1980         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1981
1982         /* properties */
1983         RNA_def_int(ot->srna, "keys", 2, 2, INT_MAX, "Number of Keys", "", 2, 100);
1984 }
1985
1986 static void rekey_particle_to_time(Scene *scene, Object *ob, int pa_index, float path_time)
1987 {
1988         PTCacheEdit *edit= PE_get_current(scene, ob);
1989         ParticleSystem *psys;
1990         ParticleSimulationData sim= {0};
1991         ParticleData *pa;
1992         ParticleKey state;
1993         HairKey *new_keys, *key;
1994         PTCacheEditKey *ekey;
1995         int k;
1996
1997         if(!edit || !edit->psys) return;
1998
1999         psys = edit->psys;
2000
2001         sim.scene= scene;
2002         sim.ob= ob;
2003         sim.psys= psys;
2004
2005         pa= psys->particles + pa_index;
2006
2007         pa->flag |= PARS_REKEY;
2008
2009         key= new_keys= MEM_dupallocN(pa->hair);
2010         
2011         /* interpolate new keys from old ones (roots stay the same) */
2012         for(k=1, key++; k < pa->totkey; k++, key++) {
2013                 state.time= path_time * (float)k / (float)(pa->totkey-1);
2014                 psys_get_particle_on_path(&sim, pa_index, &state, 0);
2015                 VECCOPY(key->co, state.co);
2016         }
2017
2018         /* replace hair keys */
2019         if(pa->hair)
2020                 MEM_freeN(pa->hair);
2021         pa->hair= new_keys;
2022
2023         /* update edit pointers */
2024         for(k=0, key=pa->hair, ekey=edit->points[pa_index].keys; k<pa->totkey; k++, key++, ekey++) {
2025                 ekey->co= key->co;
2026                 ekey->time= &key->time;
2027         }
2028
2029         pa->flag &= ~PARS_REKEY;
2030 }
2031
2032 /************************* utilities **************************/
2033
2034 static int remove_tagged_particles(Object *ob, ParticleSystem *psys, int mirror)
2035 {
2036         PTCacheEdit *edit = psys->edit;
2037         ParticleData *pa, *npa=0, *new_pars=0;
2038         POINT_P;
2039         PTCacheEditPoint *npoint=0, *new_points=0;
2040         ParticleSystemModifierData *psmd;
2041         int i, totpart, new_totpart= psys->totpart, removed= 0;
2042
2043         if(mirror) {
2044                 /* mirror tags */
2045                 psmd= psys_get_modifier(ob, psys);
2046                 totpart= psys->totpart;
2047
2048                 LOOP_TAGGED_POINTS {
2049                         PE_mirror_particle(ob, psmd->dm, psys, psys->particles + p, NULL);
2050                 }
2051         }
2052
2053         LOOP_TAGGED_POINTS {
2054                 new_totpart--;
2055                 removed++;
2056         }
2057
2058         if(new_totpart != psys->totpart) {
2059                 if(new_totpart) {
2060                         npa= new_pars= MEM_callocN(new_totpart * sizeof(ParticleData), "ParticleData array");
2061                         npoint= new_points= MEM_callocN(new_totpart * sizeof(PTCacheEditPoint), "PTCacheEditKey array");
2062                 }
2063
2064                 pa= psys->particles;
2065                 point= edit->points;
2066                 for(i=0; i<psys->totpart; i++, pa++, point++) {
2067                         if(point->flag & PEP_TAG) {
2068                                 if(point->keys)
2069                                         MEM_freeN(point->keys);
2070                                 if(pa->hair)
2071                                         MEM_freeN(pa->hair);
2072                         }
2073                         else {
2074                                 memcpy(npa, pa, sizeof(ParticleData));
2075                                 memcpy(npoint, point, sizeof(PTCacheEditPoint));
2076                                 npa++;
2077                                 npoint++;
2078                         }
2079                 }
2080
2081                 if(psys->particles) MEM_freeN(psys->particles);
2082                 psys->particles= new_pars;
2083
2084                 if(edit->points) MEM_freeN(edit->points);
2085                 edit->points= new_points;
2086
2087                 if(edit->mirror_cache) {
2088                         MEM_freeN(edit->mirror_cache);
2089                         edit->mirror_cache= NULL;
2090                 }
2091
2092                 if(psys->child) {
2093                         MEM_freeN(psys->child);
2094                         psys->child= NULL;
2095                         psys->totchild=0;
2096                 }
2097
2098                 edit->totpoint= psys->totpart= new_totpart;
2099         }
2100
2101         return removed;
2102 }
2103
2104 static void remove_tagged_keys(Object *ob, ParticleSystem *psys)
2105 {
2106         PTCacheEdit *edit= psys->edit;
2107         ParticleData *pa;
2108         HairKey *hkey, *nhkey, *new_hkeys=0;
2109         POINT_P; KEY_K;
2110         PTCacheEditKey *nkey, *new_keys;
2111         ParticleSystemModifierData *psmd;
2112         short new_totkey;
2113
2114         if(pe_x_mirror(ob)) {
2115                 /* mirror key tags */
2116                 psmd= psys_get_modifier(ob, psys);
2117
2118                 LOOP_POINTS {
2119                         LOOP_TAGGED_KEYS {
2120                                 PE_mirror_particle(ob, psmd->dm, psys, psys->particles + p, NULL);
2121                                 break;
2122                         }
2123                 }
2124         }
2125
2126         LOOP_POINTS {
2127                 new_totkey= point->totkey;
2128                 LOOP_TAGGED_KEYS {
2129                         new_totkey--;
2130                 }
2131                 /* we can't have elements with less than two keys*/
2132                 if(new_totkey < 2)
2133                         point->flag |= PEP_TAG;
2134         }
2135         remove_tagged_particles(ob, psys, pe_x_mirror(ob));
2136
2137         LOOP_POINTS {
2138                 pa = psys->particles + p;
2139                 new_totkey= pa->totkey;
2140
2141                 LOOP_TAGGED_KEYS {
2142                         new_totkey--;
2143                 }
2144
2145                 if(new_totkey != pa->totkey) {
2146                         nhkey= new_hkeys= MEM_callocN(new_totkey*sizeof(HairKey), "HairKeys");
2147                         nkey= new_keys= MEM_callocN(new_totkey*sizeof(PTCacheEditKey), "particle edit keys");
2148
2149                         hkey= pa->hair;
2150                         LOOP_KEYS {
2151                                 while(key->flag & PEK_TAG && hkey < pa->hair + pa->totkey) {
2152                                         key++;
2153                                         hkey++;
2154                                 }
2155
2156                                 if(hkey < pa->hair + pa->totkey) {
2157                                         VECCOPY(nhkey->co, hkey->co);
2158                                         nhkey->editflag = hkey->editflag;
2159                                         nhkey->time= hkey->time;
2160                                         nhkey->weight= hkey->weight;
2161                                         
2162                                         nkey->co= nhkey->co;
2163                                         nkey->time= &nhkey->time;
2164                                         /* these can be copied from old edit keys */
2165                                         nkey->flag = key->flag;
2166                                         nkey->ftime = key->ftime;
2167                                         nkey->length = key->length;
2168                                         VECCOPY(nkey->world_co, key->world_co);
2169                                 }
2170                                 nkey++;
2171                                 nhkey++;
2172                                 hkey++;
2173                         }
2174
2175                         if(pa->hair)
2176                                 MEM_freeN(pa->hair);
2177
2178                         if(point->keys)
2179                                 MEM_freeN(point->keys);
2180                         
2181                         pa->hair= new_hkeys;
2182                         point->keys= new_keys;
2183
2184                         point->totkey= pa->totkey= new_totkey;
2185
2186                         /* flag for recalculating length */
2187                         point->flag |= PEP_EDIT_RECALC;
2188                 }
2189         }
2190 }
2191
2192 /************************ subdivide opertor *********************/
2193
2194 /* works like normal edit mode subdivide, inserts keys between neighbouring selected keys */
2195 static void subdivide_particle(PEData *data, int pa_index)
2196 {
2197         PTCacheEdit *edit= data->edit;
2198         ParticleSystem *psys= edit->psys;
2199         ParticleSimulationData sim= {0};
2200         ParticleData *pa= psys->particles + pa_index;
2201         PTCacheEditPoint *point = edit->points + pa_index;
2202         ParticleKey state;
2203         HairKey *key, *nkey, *new_keys;
2204         PTCacheEditKey *ekey, *nekey, *new_ekeys;
2205
2206         int k;
2207         short totnewkey=0;
2208         float endtime;
2209
2210         sim.scene= data->scene;
2211         sim.ob= data->ob;
2212         sim.psys= edit->psys;
2213
2214         for(k=0, ekey=point->keys; k<pa->totkey-1; k++,ekey++) {
2215                 if(ekey->flag&PEK_SELECT && (ekey+1)->flag&PEK_SELECT)
2216                         totnewkey++;
2217         }
2218
2219         if(totnewkey==0) return;
2220
2221         pa->flag |= PARS_REKEY;
2222
2223         nkey= new_keys= MEM_callocN((pa->totkey+totnewkey)*(sizeof(HairKey)),"Hair subdivide keys");
2224         nekey= new_ekeys= MEM_callocN((pa->totkey+totnewkey)*(sizeof(PTCacheEditKey)),"Hair subdivide edit keys");
2225         
2226         key = pa->hair;
2227         endtime= key[pa->totkey-1].time;
2228
2229         for(k=0, ekey=point->keys; k<pa->totkey-1; k++, key++, ekey++) {
2230
2231                 memcpy(nkey,key,sizeof(HairKey));
2232                 memcpy(nekey,ekey,sizeof(PTCacheEditKey));
2233
2234                 nekey->co= nkey->co;
2235                 nekey->time= &nkey->time;
2236
2237                 nkey++;
2238                 nekey++;
2239
2240                 if(ekey->flag & PEK_SELECT && (ekey+1)->flag & PEK_SELECT) {
2241                         nkey->time= (key->time + (key+1)->time)*0.5f;
2242                         state.time= (endtime != 0.0f)? nkey->time/endtime: 0.0f;
2243                         psys_get_particle_on_path(&sim, pa_index, &state, 0);
2244                         VECCOPY(nkey->co, state.co);
2245
2246                         nekey->co= nkey->co;
2247                         nekey->time= &nkey->time;
2248                         nekey->flag |= PEK_SELECT;
2249                         if(!(psys->flag & PSYS_GLOBAL_HAIR))
2250                                 nekey->flag |= PEK_USE_WCO;
2251
2252                         nekey++;
2253                         nkey++;
2254                 }
2255         }
2256         /*tip still not copied*/
2257         memcpy(nkey,key,sizeof(HairKey));
2258         memcpy(nekey,ekey,sizeof(PTCacheEditKey));
2259
2260         nekey->co= nkey->co;
2261         nekey->time= &nkey->time;
2262
2263         if(pa->hair)
2264                 MEM_freeN(pa->hair);
2265         pa->hair= new_keys;
2266
2267         if(point->keys)
2268                 MEM_freeN(point->keys);
2269         point->keys= new_ekeys;
2270
2271         point->totkey = pa->totkey = pa->totkey + totnewkey;
2272         point->flag |= PEP_EDIT_RECALC;
2273         pa->flag &= ~PARS_REKEY;
2274 }
2275
2276 static int subdivide_exec(bContext *C, wmOperator *UNUSED(op))
2277 {
2278         PEData data;
2279
2280         PE_set_data(C, &data);
2281         foreach_point(&data, subdivide_particle);
2282         
2283         recalc_lengths(data.edit);
2284         PE_update_object(data.scene, data.ob, 1);
2285         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, data.ob);
2286
2287         return OPERATOR_FINISHED;
2288 }
2289
2290 void PARTICLE_OT_subdivide(wmOperatorType *ot)
2291 {
2292         /* identifiers */
2293         ot->name= "Subdivide";
2294         ot->idname= "PARTICLE_OT_subdivide";
2295         
2296         /* api callbacks */
2297         ot->exec= subdivide_exec;
2298         ot->poll= PE_poll;
2299
2300         /* flags */
2301         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2302 }
2303
2304 /************************ remove doubles opertor *********************/
2305
2306 static int remove_doubles_exec(bContext *C, wmOperator *op)
2307 {
2308         Scene *scene= CTX_data_scene(C);
2309         Object *ob= CTX_data_active_object(C);
2310         PTCacheEdit *edit= PE_get_current(scene, ob);
2311         ParticleSystem *psys = edit->psys;
2312         ParticleSystemModifierData *psmd;
2313         KDTree *tree;
2314         KDTreeNearest nearest[10];
2315         POINT_P;
2316         float mat[4][4], co[3], threshold= RNA_float_get(op->ptr, "threshold");
2317         int n, totn, removed, totremoved;
2318
2319         if(psys->flag & PSYS_GLOBAL_HAIR)
2320                 return OPERATOR_CANCELLED;
2321
2322         edit= psys->edit;
2323         psmd= psys_get_modifier(ob, psys);
2324         totremoved= 0;
2325
2326         do {
2327                 removed= 0;
2328
2329                 tree=BLI_kdtree_new(psys->totpart);
2330                         
2331                 /* insert particles into kd tree */
2332                 LOOP_SELECTED_POINTS {
2333                         psys_mat_hair_to_object(ob, psmd->dm, psys->part->from, psys->particles+p, mat);
2334                         VECCOPY(co, point->keys->co);
2335                         mul_m4_v3(mat, co);
2336                         BLI_kdtree_insert(tree, p, co, NULL);
2337                 }
2338
2339                 BLI_kdtree_balance(tree);
2340
2341                 /* tag particles to be removed */
2342                 LOOP_SELECTED_POINTS {
2343                         psys_mat_hair_to_object(ob, psmd->dm, psys->part->from, psys->particles+p, mat);
2344                         VECCOPY(co, point->keys->co);
2345                         mul_m4_v3(mat, co);
2346
2347                         totn= BLI_kdtree_find_n_nearest(tree,10,co,NULL,nearest);
2348
2349                         for(n=0; n<totn; n++) {
2350                                 /* this needs a custom threshold still */
2351                                 if(nearest[n].index > p && nearest[n].dist < threshold) {
2352                                         if(!(point->flag & PEP_TAG)) {
2353                                                 point->flag |= PEP_TAG;
2354                                                 removed++;
2355                                         }
2356                                 }
2357                         }
2358                 }
2359
2360                 BLI_kdtree_free(tree);
2361
2362                 /* remove tagged particles - don't do mirror here! */
2363                 remove_tagged_particles(ob, psys, 0);
2364                 totremoved += removed;
2365         } while(removed);
2366
2367         if(totremoved == 0)
2368                 return OPERATOR_CANCELLED;
2369
2370         BKE_reportf(op->reports, RPT_INFO, "Remove %d double particles.", totremoved);
2371
2372         DAG_id_flush_update(&ob->id, OB_RECALC_DATA);
2373         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob);
2374
2375         return OPERATOR_FINISHED;
2376 }
2377
2378 void PARTICLE_OT_remove_doubles(wmOperatorType *ot)
2379 {
2380         /* identifiers */
2381         ot->name= "Remove Doubles";
2382         ot->idname= "PARTICLE_OT_remove_doubles";
2383         
2384         /* api callbacks */
2385         ot->exec= remove_doubles_exec;
2386         ot->poll= PE_poll;
2387
2388         /* flags */
2389         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2390
2391         /* properties */
2392         RNA_def_float(ot->srna, "threshold", 0.0002f, 0.0f, FLT_MAX, "Threshold", "Threshold distance withing which particles are removed", 0.00001f, 0.1f);
2393 }
2394
2395
2396 static int weight_set_exec(bContext *C, wmOperator *op)
2397 {
2398         Scene *scene= CTX_data_scene(C);
2399         ParticleEditSettings *pset= PE_settings(scene);
2400         Object *ob= CTX_data_active_object(C);
2401         PTCacheEdit *edit= PE_get_current(scene, ob);
2402         ParticleSystem *psys = edit->psys;
2403         POINT_P;
2404         KEY_K;
2405         HairKey *hkey;
2406         float weight;
2407         ParticleBrushData *brush= &pset->brush[pset->brushtype];
2408     float factor= RNA_float_get(op->ptr, "factor");
2409
2410         weight= brush->strength;
2411         edit= psys->edit;
2412
2413         LOOP_SELECTED_POINTS {
2414                 ParticleData *pa= psys->particles + p;
2415
2416                 LOOP_SELECTED_KEYS {
2417                         hkey= pa->hair + k;
2418                         hkey->weight= interpf(weight, hkey->weight, factor);
2419                 }
2420         }
2421
2422         DAG_id_flush_update(&ob->id, OB_RECALC_DATA);
2423         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob);
2424
2425         return OPERATOR_FINISHED;
2426 }
2427
2428 void PARTICLE_OT_weight_set(wmOperatorType *ot)
2429 {
2430         /* identifiers */
2431         ot->name= "Weight Set";
2432         ot->idname= "PARTICLE_OT_weight_set";
2433
2434         /* api callbacks */
2435         ot->exec= weight_set_exec;
2436         ot->poll= PE_poll;
2437
2438         /* flags */
2439         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2440     
2441     RNA_def_float(ot->srna, "factor", 1, 0, 1, "Factor", "", 0, 1);
2442 }
2443
2444 /************************ cursor drawing *******************************/
2445
2446 static void brush_drawcursor(bContext *C, int x, int y, void *UNUSED(customdata))
2447 {
2448         ParticleEditSettings *pset= PE_settings(CTX_data_scene(C));
2449         ParticleBrushData *brush;
2450
2451         if(pset->brushtype < 0)
2452                 return;
2453
2454         brush= &pset->brush[pset->brushtype];
2455
2456         if(brush) {
2457                 glPushMatrix();
2458
2459                 glTranslatef((float)x, (float)y, 0.0f);
2460
2461                 glColor4ub(255, 255, 255, 128);
2462                 glEnable(GL_LINE_SMOOTH );
2463                 glEnable(GL_BLEND);
2464                 glutil_draw_lined_arc(0.0, M_PI*2.0, brush->size, 40);
2465                 glDisable(GL_BLEND);
2466                 glDisable(GL_LINE_SMOOTH );
2467                 
2468                 glPopMatrix();
2469         }
2470 }
2471
2472 static void toggle_particle_cursor(bContext *C, int enable)
2473 {
2474         ParticleEditSettings *pset= PE_settings(CTX_data_scene(C));
2475
2476         if(pset->paintcursor && !enable) {
2477                 WM_paint_cursor_end(CTX_wm_manager(C), pset->paintcursor);
2478                 pset->paintcursor = NULL;
2479         }
2480         else if(enable)
2481                 pset->paintcursor= WM_paint_cursor_activate(CTX_wm_manager(C), PE_poll_view3d, brush_drawcursor, NULL);
2482 }
2483
2484 /********************* radial control operator *********************/
2485
2486 static int brush_radial_control_invoke(bContext *C, wmOperator *op, wmEvent *event)
2487 {
2488         ParticleEditSettings *pset= PE_settings(CTX_data_scene(C));
2489         ParticleBrushData *brush;
2490         int mode = RNA_enum_get(op->ptr, "mode");
2491         float original_value=1.0f;
2492
2493         if(pset->brushtype < 0)
2494                 return OPERATOR_CANCELLED;
2495
2496         brush= &pset->brush[pset->brushtype];
2497
2498         toggle_particle_cursor(C, 0);
2499
2500         if(mode == WM_RADIALCONTROL_SIZE)
2501                 original_value = brush->size;
2502         else if(mode == WM_RADIALCONTROL_STRENGTH)
2503                 original_value = brush->strength;
2504
2505         RNA_float_set(op->ptr, "initial_value", original_value);
2506
2507         return WM_radial_control_invoke(C, op, event);
2508 }
2509
2510 static int brush_radial_control_modal(bContext *C, wmOperator *op, wmEvent *event)
2511 {
2512         int ret = WM_radial_control_modal(C, op, event);
2513
2514         if(ret != OPERATOR_RUNNING_MODAL)
2515                 toggle_particle_cursor(C, 1);
2516
2517         return ret;
2518 }
2519
2520 static int brush_radial_control_exec(bContext *C, wmOperator *op)
2521 {
2522         ParticleEditSettings *pset= PE_settings(CTX_data_scene(C));
2523         ParticleBrushData *brush;
2524         int mode = RNA_enum_get(op->ptr, "mode");
2525         float new_value = RNA_float_get(op->ptr, "new_value");
2526
2527         if(pset->brushtype < 0)
2528                 return OPERATOR_CANCELLED;
2529
2530         brush= &pset->brush[pset->brushtype];
2531
2532         if(mode == WM_RADIALCONTROL_SIZE)
2533                 brush->size= new_value;
2534         else if(mode == WM_RADIALCONTROL_STRENGTH)
2535                 brush->strength= new_value;
2536
2537         WM_event_add_notifier(C, NC_WINDOW, NULL);
2538
2539         return OPERATOR_FINISHED;
2540 }
2541
2542 void PARTICLE_OT_brush_radial_control(wmOperatorType *ot)
2543 {
2544         WM_OT_radial_control_partial(ot);
2545
2546         ot->name= "Brush Radial Control";
2547         ot->idname= "PARTICLE_OT_brush_radial_control";
2548
2549         ot->invoke= brush_radial_control_invoke;
2550         ot->modal= brush_radial_control_modal;
2551         ot->exec= brush_radial_control_exec;
2552         ot->poll= PE_poll;
2553         
2554         /* flags */
2555         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2556 }
2557
2558 /*************************** delete operator **************************/
2559
2560 enum { DEL_PARTICLE, DEL_KEY };
2561
2562 static EnumPropertyItem delete_type_items[]= {
2563         {DEL_PARTICLE, "PARTICLE", 0, "Particle", ""},
2564         {DEL_KEY, "KEY", 0, "Key", ""},
2565         {0, NULL, 0, NULL, NULL}};
2566
2567 static void set_delete_particle(PEData *data, int pa_index)
2568 {
2569         PTCacheEdit *edit= data->edit;
2570
2571         edit->points[pa_index].flag |= PEP_TAG;
2572 }
2573
2574 static void set_delete_particle_key(PEData *data, int pa_index, int key_index)
2575 {
2576         PTCacheEdit *edit= data->edit;
2577
2578         edit->points[pa_index].keys[key_index].flag |= PEK_TAG;
2579 }
2580
2581 static int delete_exec(bContext *C, wmOperator *op)
2582 {
2583         PEData data;
2584         int type= RNA_enum_get(op->ptr, "type");
2585
2586         PE_set_data(C, &data);
2587
2588         if(type == DEL_KEY) {
2589                 foreach_selected_key(&data, set_delete_particle_key);
2590                 remove_tagged_keys(data.ob, data.edit->psys);
2591                 recalc_lengths(data.edit);
2592         }
2593         else if(type == DEL_PARTICLE) {
2594                 foreach_selected_point(&data, set_delete_particle);
2595                 remove_tagged_particles(data.ob, data.edit->psys, pe_x_mirror(data.ob));
2596                 recalc_lengths(data.edit);
2597         }
2598
2599         DAG_id_flush_update(&data.ob->id, OB_RECALC_DATA);
2600         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, data.ob);
2601
2602         return OPERATOR_FINISHED;
2603 }
2604
2605 void PARTICLE_OT_delete(wmOperatorType *ot)
2606 {
2607         /* identifiers */
2608         ot->name= "Delete";
2609         ot->idname= "PARTICLE_OT_delete";
2610         
2611         /* api callbacks */
2612         ot->exec= delete_exec;
2613         ot->invoke= WM_menu_invoke;
2614         ot->poll= PE_hair_poll;
2615
2616         /* flags */
2617         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2618
2619         /* properties */
2620         ot->prop= RNA_def_enum(ot->srna, "type", delete_type_items, DEL_PARTICLE, "Type", "Delete a full particle or only keys.");
2621 }
2622
2623 /*************************** mirror operator **************************/
2624
2625 static void PE_mirror_x(Scene *scene, Object *ob, int tagged)
2626 {
2627         Mesh *me= (Mesh*)(ob->data);
2628         ParticleSystemModifierData *psmd;
2629         PTCacheEdit *edit= PE_get_current(scene, ob);
2630         ParticleSystem *psys = edit->psys;
2631         ParticleData *pa, *newpa, *new_pars;
2632         PTCacheEditPoint *newpoint, *new_points;
2633         POINT_P; KEY_K;
2634         HairKey *hkey;
2635         int *mirrorfaces;
2636         int rotation, totpart, newtotpart;
2637
2638         if(psys->flag & PSYS_GLOBAL_HAIR)
2639                 return;
2640
2641         psmd= psys_get_modifier(ob, psys);
2642         if(!psmd->dm)
2643                 return;
2644
2645         mirrorfaces= mesh_get_x_mirror_faces(ob, NULL);
2646
2647         if(!edit->mirror_cache)
2648                 PE_update_mirror_cache(ob, psys);
2649
2650         totpart= psys->totpart;
2651         newtotpart= psys->totpart;
2652         LOOP_VISIBLE_POINTS {
2653                 pa = psys->particles + p;
2654                 if(!tagged) {
2655                         if(point_is_selected(point)) {
2656                                 if(edit->mirror_cache[p] != -1) {
2657                                         /* already has a mirror, don't need to duplicate */
2658                                         PE_mirror_particle(ob, psmd->dm, psys, pa, NULL);
2659                                         continue;
2660                                 }
2661                                 else
2662                                         point->flag |= PEP_TAG;
2663                         }
2664                 }
2665
2666                 if((point->flag & PEP_TAG) && mirrorfaces[pa->num*2] != -1)
2667                         newtotpart++;
2668         }
2669
2670         if(newtotpart != psys->totpart) {
2671                 /* allocate new arrays and copy existing */
2672                 new_pars= MEM_callocN(newtotpart*sizeof(ParticleData), "ParticleData new");
2673                 new_points= MEM_callocN(newtotpart*sizeof(PTCacheEditPoint), "PTCacheEditPoint new");
2674
2675                 if(psys->particles) {
2676                         memcpy(new_pars, psys->particles, totpart*sizeof(ParticleData));
2677                         MEM_freeN(psys->particles);
2678                 }
2679                 psys->particles= new_pars;
2680
2681                 if(edit->points) {
2682                         memcpy(new_points, edit->points, totpart*sizeof(PTCacheEditPoint));
2683                         MEM_freeN(edit->points);
2684                 }
2685                 edit->points= new_points;
2686
2687                 if(edit->mirror_cache) {
2688                         MEM_freeN(edit->mirror_cache);
2689                         edit->mirror_cache= NULL;
2690                 }
2691
2692                 edit->totpoint= psys->totpart= newtotpart;
2693                         
2694                 /* create new elements */
2695                 newpa= psys->particles + totpart;
2696                 newpoint= edit->points + totpart;
2697
2698                 for(p=0, point=edit->points; p<totpart; p++, point++) {
2699                         pa = psys->particles + p;
2700
2701                         if(point->flag & PEP_HIDE)
2702                                 continue;
2703                         if(!(point->flag & PEP_TAG) || mirrorfaces[pa->num*2] == -1)
2704                                 continue;
2705
2706                         /* duplicate */
2707                         *newpa= *pa;
2708                         *newpoint= *point;
2709                         if(pa->hair) newpa->hair= MEM_dupallocN(pa->hair);
2710                         if(point->keys) newpoint->keys= MEM_dupallocN(point->keys);
2711
2712                         /* rotate weights according to vertex index rotation */
2713                         rotation= mirrorfaces[pa->num*2+1];
2714                         newpa->fuv[0]= pa->fuv[2];
2715                         newpa->fuv[1]= pa->fuv[1];
2716                         newpa->fuv[2]= pa->fuv[0];
2717                         newpa->fuv[3]= pa->fuv[3];
2718                         while(rotation-- > 0)
2719                                 if(me->mface[pa->num].v4)
2720                                         SHIFT4(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2], newpa->fuv[3])
2721                                 else
2722                                         SHIFT3(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2])
2723
2724                         /* assign face inddex */
2725                         newpa->num= mirrorfaces[pa->num*2];
2726                         newpa->num_dmcache= psys_particle_dm_face_lookup(ob,psmd->dm,newpa->num,newpa->fuv, NULL);
2727
2728                         /* update edit key pointers */
2729                         key= newpoint->keys;
2730                         for(k=0, hkey=newpa->hair; k<newpa->totkey; k++, hkey++, key++) {
2731                                 key->co= hkey->co;
2732                                 key->time= &hkey->time;
2733                         }
2734
2735                         /* map key positions as mirror over x axis */
2736                         PE_mirror_particle(ob, psmd->dm, psys, pa, newpa);
2737
2738                         newpa++;
2739                         newpoint++;
2740                 }
2741         }
2742
2743         LOOP_POINTS {
2744                 point->flag &= ~PEP_TAG;
2745         }
2746
2747         MEM_freeN(mirrorfaces);
2748 }
2749
2750 static int mirror_exec(bContext *C, wmOperator *UNUSED(op))
2751 {
2752         Scene *scene= CTX_data_scene(C);
2753         Object *ob= CTX_data_active_object(C);
2754         PTCacheEdit *edit= PE_get_current(scene, ob);
2755         
2756         PE_mirror_x(scene, ob, 0);
2757
2758         update_world_cos(ob, edit);
2759         WM_event_add_notifier(C, NC_OBJECT|ND_PARTICLE|NA_EDITED, ob);
2760         DAG_id_flush_update(&ob->id, OB_RECALC_DATA);
2761
2762         return OPERATOR_FINISHED;
2763 }
2764
2765 void PARTICLE_OT_mirror(wmOperatorType *ot)
2766 {
2767         /* identifiers */
2768         ot->name= "Mirror";
2769         ot->idname= "PARTICLE_OT_mirror";
2770         
2771         /* api callbacks */
2772         ot->exec= mirror_exec;
2773         ot->poll= PE_poll;
2774
2775         /* flags */
2776         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2777 }
2778
2779 /************************* brush edit callbacks ********************/
2780
2781 static void brush_comb(PEData *data, float UNUSED(mat[][4]), float imat[][4], int point_index, int key_index, PTCacheEditKey *key)
2782 {
2783         ParticleEditSettings *pset= PE_settings(data->scene);
2784         float cvec[3], fac;
2785
2786         if(pset->flag & PE_LOCK_FIRST && key_index == 0) return;
2787
2788         fac= (float)pow((double)(1.0f - data->dist / data->rad), (double)data->combfac);
2789
2790         VECCOPY(cvec,data->dvec);
2791         mul_mat3_m4_v3(imat,cvec);
2792         mul_v3_fl(cvec, fac);
2793         VECADD(key->co, key->co, cvec);
2794
2795         (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC;
2796 }
2797
2798 static void brush_cut(PEData *data, int pa_index)
2799 {
2800         PTCacheEdit *edit = data->edit;
2801         ARegion *ar= data->vc.ar;
2802         Object *ob= data->ob;
2803         ParticleEditSettings *pset= PE_settings(data->scene);
2804         ParticleCacheKey *key= edit->pathcache[pa_index];
2805         float rad2, cut_time= 1.0;
2806         float x0, x1, v0, v1, o0, o1, xo0, xo1, d, dv;
2807         int k, cut, keys= (int)pow(2.0, (double)pset->draw_step);
2808         short vertco[2];
2809
2810         /* blunt scissors */
2811         if(BLI_frand() > data->cutfac) return;
2812
2813         /* don't cut hidden */
2814         if(edit->points[pa_index].flag & PEP_HIDE)
2815                 return;
2816
2817         rad2= data->rad * data->rad;
2818
2819         cut=0;
2820
2821         project_short_noclip(ar, key->co, vertco);
2822         x0= (float)vertco[0];
2823         x1= (float)vertco[1];
2824
2825         o0= (float)data->mval[0];
2826         o1= (float)data->mval[1];
2827         
2828         xo0= x0 - o0;
2829         xo1= x1 - o1;
2830
2831         /* check if root is inside circle */
2832         if(xo0*xo0 + xo1*xo1 < rad2 && key_test_depth(data, key->co)) {
2833                 cut_time= -1.0f;
2834                 cut= 1;
2835         }
2836         else {
2837                 /* calculate path time closest to root that was inside the circle */
2838                 for(k=1, key++; k<=keys; k++, key++) {
2839                         project_short_noclip(ar, key->co, vertco);
2840
2841                         if(key_test_depth(data, key->co) == 0) {
2842                                 x0= (float)vertco[0];
2843                                 x1= (float)vertco[1];
2844
2845                                 xo0= x0 - o0;
2846                                 xo1= x1 - o1;
2847                                 continue;
2848                         }
2849
2850                         v0= (float)vertco[0] - x0;
2851                         v1= (float)vertco[1] - x1;
2852
2853                         dv= v0*v0 + v1*v1;
2854
2855                         d= (v0*xo1 - v1*xo0);
2856                         
2857                         d= dv * rad2 - d*d;
2858
2859                         if(d > 0.0f) {
2860                                 d= sqrt(d);
2861
2862                                 cut_time= -(v0*xo0 + v1*xo1 + d);
2863
2864                                 if(cut_time > 0.0f) {
2865                                         cut_time /= dv;
2866
2867                                         if(cut_time < 1.0f) {
2868                                                 cut_time += (float)(k-1);
2869                                                 cut_time /= (float)keys;
2870                                                 cut= 1;
2871                                                 break;
2872                                         }
2873                                 }
2874                         }
2875
2876                         x0= (float)vertco[0];
2877                         x1= (float)vertco[1];
2878
2879                         xo0= x0 - o0;
2880                         xo1= x1 - o1;
2881                 }
2882         }
2883
2884         if(cut) {
2885                 if(cut_time < 0.0f) {
2886                         edit->points[pa_index].flag |= PEP_TAG;
2887                 }
2888                 else {
2889                         rekey_particle_to_time(data->scene, ob, pa_index, cut_time);
2890                         edit->points[pa_index].flag |= PEP_EDIT_RECALC;
2891                 }
2892         }
2893 }
2894
2895 static void brush_length(PEData *data, int point_index)
2896 {
2897         PTCacheEdit *edit= data->edit;
2898         PTCacheEditPoint *point = edit->points + point_index;
2899         KEY_K;
2900         float dvec[3],pvec[3] = {0.0f, 0.0f, 0.0f};
2901
2902         LOOP_KEYS {
2903                 if(k==0) {
2904                         VECCOPY(pvec,key->co);
2905                 }
2906                 else {
2907                         VECSUB(dvec,key->co,pvec);
2908                         VECCOPY(pvec,key->co);
2909                         mul_v3_fl(dvec,data->growfac);
2910                         VECADD(key->co,(key-1)->co,dvec);
2911                 }
2912         }
2913
2914         point->flag |= PEP_EDIT_RECALC;
2915 }
2916
2917 static void brush_puff(PEData *data, int point_index)
2918 {
2919         PTCacheEdit *edit = data->edit;
2920         ParticleSystem *psys = edit->psys;
2921         PTCacheEditPoint *point = edit->points + point_index;
2922         KEY_K;
2923         float mat[4][4], imat[4][4];
2924
2925         float lastco[3], rootco[3] = {0.0f, 0.0f, 0.0f}, co[3], nor[3], kco[3], dco[3], ofs[3] = {0.0f, 0.0f, 0.0f}, fac=0.0f, length=0.0f;
2926         int puff_volume = 0;
2927         int change= 0;
2928
2929         {
2930                 ParticleEditSettings *pset= PE_settings(data->scene);
2931                 ParticleBrushData *brush= &pset->brush[pset->brushtype];
2932                 puff_volume = brush->flag & PE_BRUSH_DATA_PUFF_VOLUME;
2933         }
2934
2935         if(psys && !(psys->flag & PSYS_GLOBAL_HAIR)) {
2936                 psys_mat_hair_to_global(data->ob, data->dm, psys->part->from, psys->particles + point_index, mat);
2937                 invert_m4_m4(imat,mat);
2938         }
2939         else {
2940                 unit_m4(mat);
2941                 unit_m4(imat);
2942         }
2943
2944         LOOP_KEYS {
2945                 if(k==0) {
2946                         /* find root coordinate and normal on emitter */
2947                         VECCOPY(co, key->co);
2948                         mul_m4_v3(mat, co);
2949                         mul_v3_m4v3(kco, data->ob->imat, co); /* use 'kco' as the object space version of worldspace 'co', ob->imat is set before calling */
2950
2951                         point_index= BLI_kdtree_find_nearest(edit->emitter_field, kco, NULL, NULL);
2952                         if(point_index == -1) return;
2953
2954                         VECCOPY(rootco, co);
2955                         copy_v3_v3(nor, &edit->emitter_cosnos[point_index*6+3]);
2956                         mul_mat3_m4_v3(data->ob->obmat, nor); /* normal into worldspace */
2957
2958                         normalize_v3(nor);
2959                         length= 0.0f;
2960
2961                         fac= (float)pow((double)(1.0f - data->dist / data->rad), (double)data->pufffac);
2962                         fac *= 0.025f;
2963                         if(data->invert)
2964                                 fac= -fac;
2965                 }
2966                 else {
2967                         /* compute position as if hair was standing up straight.
2968                          * */
2969                         VECCOPY(lastco, co);
2970                         VECCOPY(co, key->co);
2971                         mul_m4_v3(mat, co);
2972                         length += len_v3v3(lastco, co);
2973                         if((data->select==0 || (key->flag & PEK_SELECT)) && !(key->flag & PEK_HIDE)) {
2974                                 VECADDFAC(kco, rootco, nor, length);
2975
2976                                 /* blend between the current and straight position */
2977                                 VECSUB(dco, kco, co);
2978                                 VECADDFAC(co, co, dco, fac);
2979
2980                                 /* re-use dco to compare before and after translation and add to the offset  */
2981                                 VECCOPY(dco, key->co);
2982
2983                                 mul_v3_m4v3(key->co, imat, co);
2984
2985                                 if(puff_volume) {
2986                                         /* accumulate the total distance moved to apply to unselected
2987                                          * keys that come after */
2988                                         ofs[0] += key->co[0] - dco[0];
2989                                         ofs[1] += key->co[1] - dco[1];
2990                                         ofs[2] += key->co[2] - dco[2];
2991                                 }
2992                                 change = 1;
2993                         }
2994                         else {
2995
2996                                 if(puff_volume) {
2997 #if 0
2998                                         /* this is simple but looks bad, adds annoying kinks */
2999                                         add_v3_v3(key->co, ofs);
3000 #else
3001                                         /* translate (not rotate) the rest of the hair if its not selected  */
3002                                         if(ofs[0] || ofs[1] || ofs[2]) {
3003 #if 0                                   /* kindof works but looks worse then whats below */
3004
3005                                                 /* Move the unselected point on a vector based on the
3006                                                  * hair direction and the offset */
3007                                                 float c1[3], c2[3];
3008                                                 VECSUB(dco, lastco, co);
3009                                                 mul_mat3_m4_v3(imat, dco); /* into particle space */
3010
3011                                                 /* move the point allong a vector perpendicular to the
3012                                                  * hairs direction, reduces odd kinks, */
3013                                                 cross_v3_v3v3(c1, ofs, dco);
3014                                                 cross_v3_v3v3(c2, c1, dco);
3015                                                 normalize_v3(c2);
3016                                                 mul_v3_fl(c2, len_v3(ofs));
3017                                                 add_v3_v3(key->co, c2);
3018 #else
3019                                                 /* Move the unselected point on a vector based on the
3020                                                  * the normal of the closest geometry */
3021                                                 float oco[3], onor[3];
3022                                                 VECCOPY(oco, key->co);
3023                                                 mul_m4_v3(mat, oco);
3024                                                 mul_v3_m4v3(kco, data->ob->imat, oco); /* use 'kco' as the object space version of worldspace 'co', ob->imat is set before calling */
3025
3026                                                 point_index= BLI_kdtree_find_nearest(edit->emitter_field, kco, NULL, NULL);
3027                                                 if(point_index != -1) {
3028                                                         copy_v3_v3(onor, &edit->emitter_cosnos[point_index*6+3]);
3029                                                         mul_mat3_m4_v3(data->ob->obmat, onor); /* normal into worldspace */
3030                                                         mul_mat3_m4_v3(imat, onor); /* worldspace into particle space */
3031                                                         normalize_v3(onor);
3032
3033
3034                                                         mul_v3_fl(onor, len_v3(ofs));
3035                                                         add_v3_v3(key->co, onor);
3036                                                 }
3037 #endif
3038                                         }
3039 #endif
3040                                 }
3041                         }
3042                 }
3043         }
3044
3045         if(change)
3046                 point->flag |= PEP_EDIT_RECALC;
3047 }
3048
3049
3050 static void brush_weight(PEData *data, float UNUSED(mat[][4]), float UNUSED(imat[][4]), int point_index, int key_index, PTCacheEditKey *UNUSED(key))
3051 {
3052         /* roots have full weight allways */
3053         if(key_index) {
3054                 PTCacheEdit *edit = data->edit;
3055                 ParticleSystem *psys = edit->psys;
3056
3057                 ParticleData *pa= psys->particles + point_index;
3058                 pa->hair[key_index].weight = data->weightfac;
3059
3060                 (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC;
3061         }
3062 }
3063
3064 static void brush_smooth_get(PEData *data, float mat[][4], float UNUSED(imat[][4]), int UNUSED(point_index), int key_index, PTCacheEditKey *key)
3065 {       
3066         if(key_index) {
3067                 float dvec[3];
3068
3069                 sub_v3_v3v3(dvec,key->co,(key-1)->co);
3070                 mul_mat3_m4_v3(mat,dvec);
3071                 VECADD(data->vec,data->vec,dvec);
3072                 data->tot++;
3073         }
3074 }
3075
3076 static void brush_smooth_do(PEData *data, float UNUSED(mat[][4]), float imat[][4], int point_index, int key_index, PTCacheEditKey *key)
3077 {
3078         float vec[3], dvec[3];
3079         
3080         if(key_index) {
3081                 VECCOPY(vec,data->vec);
3082                 mul_mat3_m4_v3(imat,vec);
3083
3084                 sub_v3_v3v3(dvec,key->co,(key-1)->co);
3085
3086                 VECSUB(dvec,vec,dvec);
3087                 mul_v3_fl(dvec,data->smoothfac);
3088                 
3089                 VECADD(key->co,key->co,dvec);
3090         }
3091
3092         (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC;
3093 }
3094
3095 static int brush_add(PEData *data, short number)
3096 {
3097         Scene *scene= data->scene;
3098         Object *ob= data->ob;
3099         PTCacheEdit *edit = data->edit;
3100         ParticleSystem *psys= edit->psys;
3101         ParticleData *add_pars= MEM_callocN(number*sizeof(ParticleData),"ParticleData add");
3102         ParticleSystemModifierData *psmd= psys_get_modifier(ob,psys);
3103         ParticleSimulationData sim= {0};
3104         ParticleEditSettings *pset= PE_settings(scene);
3105         int i, k, n= 0, totpart= psys->totpart;
3106         float mco[2];
3107         short dmx= 0, dmy= 0;
3108         float co1[3], co2[3], min_d, imat[4][4];
3109         float framestep, timestep;
3110         short size= pset->brush[PE_BRUSH_ADD].size;
3111         short size2= size*size;
3112         DerivedMesh *dm=0;
3113         invert_m4_m4(imat,ob->obmat);
3114
3115         if(psys->flag & PSYS_GLOBAL_HAIR)
3116                 return 0;
3117
3118         BLI_srandom(psys->seed+data->mval[0]+data->mval[1]);
3119
3120         sim.scene= scene;
3121         sim.ob= ob;
3122         sim.psys= psys;
3123         sim.psmd= psmd;
3124
3125         timestep= psys_get_timestep(&sim);
3126
3127         /* painting onto the deformed mesh, could be an option? */
3128         if(psmd->dm->deformedOnly)
3129                 dm= psmd->dm;
3130         else
3131                 dm= mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
3132
3133         for(i=0; i<number; i++) {
3134                 if(number>1) {
3135                         dmx=dmy=size;
3136                         while(dmx*dmx+dmy*dmy>size2) {
3137                                 dmx=(short)((2.0f*BLI_frand()-1.0f)*size);
3138                                 dmy=(short)((2.0f*BLI_frand()-1.0f)*size);
3139                         }
3140                 }
3141
3142                 mco[0]= data->mval[0] + dmx;
3143                 mco[1]= data->mval[1] + dmy;
3144                 viewline(data->vc.ar, data->vc.v3d, mco, co1, co2);
3145
3146                 mul_m4_v3(imat,co1);
3147                 mul_m4_v3(imat,co2);
3148                 min_d=2.0;
3149                 
3150                 /* warning, returns the derived mesh face */
3151                 if(psys_intersect_dm(scene, ob,dm,0,co1,co2,&min_d,&add_pars[n].num,add_pars[n].fuv,0,0,0,0)) {
3152                         add_pars[n].num_dmcache= psys_particle_dm_face_lookup(ob,psmd->dm,add_pars[n].num,add_pars[n].fuv,NULL);
3153                         n++;
3154                 }
3155         }
3156         if(n) {
3157                 int newtotpart=totpart+n;
3158                 float hairmat[4][4], cur_co[3];
3159                 KDTree *tree=0;
3160                 ParticleData *pa, *new_pars= MEM_callocN(newtotpart*sizeof(ParticleData),"ParticleData new");
3161                 PTCacheEditPoint *point, *new_points= MEM_callocN(newtotpart*sizeof(PTCacheEditPoint),"PTCacheEditPoint array new");
3162                 PTCacheEditKey *key;
3163                 HairKey *hkey;
3164
3165                 /* save existing elements */
3166                 memcpy(new_pars, psys->particles, totpart * sizeof(ParticleData));
3167                 memcpy(new_points, edit->points, totpart * sizeof(PTCacheEditPoint));
3168
3169                 /* change old arrays to new ones */
3170                 if(psys->particles) MEM_freeN(psys->particles);
3171                 psys->particles= new_pars;
3172
3173                 if(edit->points) MEM_freeN(edit->points);
3174                 edit->points= new_points;
3175
3176                 if(edit->mirror_cache) {
3177                         MEM_freeN(edit->mirror_cache);
3178                         edit->mirror_cache= NULL;
3179                 }
3180
3181                 /* create tree for interpolation */
3182                 if(pset->flag & PE_INTERPOLATE_ADDED && psys->totpart) {
3183                         tree=BLI_kdtree_new(psys->totpart);
3184                         
3185                         for(i=0, pa=psys->particles; i<totpart; i++, pa++) {
3186                                 psys_particle_on_dm(psmd->dm,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,cur_co,0,0,0,0,0);
3187                                 BLI_kdtree_insert(tree, i, cur_co, NULL);
3188                         }
3189
3190                         BLI_kdtree_balance(tree);
3191                 }
3192
3193                 edit->totpoint= psys->totpart= newtotpart;
3194
3195                 /* create new elements */
3196                 pa= psys->particles + totpart;
3197                 point= edit->points + totpart;
3198
3199                 for(i=totpart; i<newtotpart; i++, pa++, point++) {
3200                         memcpy(pa, add_pars + i - totpart, sizeof(ParticleData));
3201                         pa->hair= MEM_callocN(pset->totaddkey * sizeof(HairKey), "BakeKey key add");
3202                         key= point->keys= MEM_callocN(pset->totaddkey * sizeof(PTCacheEditKey), "PTCacheEditKey add");
3203                         point->totkey= pa->totkey= pset->totaddkey;
3204
3205                         for(k=0, hkey=pa->hair; k<pa->totkey; k++, hkey++, key++) {
3206                                 key->co= hkey->co;
3207                                 key->time= &hkey->time;
3208
3209                                 if(!(psys->flag & PSYS_GLOBAL_HAIR))
3210                                         key->flag |= PEK_USE_WCO;
3211                         }
3212                         
3213                         pa->size= 1.0f;
3214                         initialize_particle(&sim, pa,i);
3215                         reset_particle(&sim, pa, 0.0, 1.0);
3216                         point->flag |= PEP_EDIT_RECALC;
3217                         if(pe_x_mirror(ob))
3218                                 point->flag |= PEP_TAG; /* signal for duplicate */
3219                         
3220                         framestep= pa->lifetime/(float)(pset->totaddkey-1);
3221
3222                         if(tree) {
3223                                 ParticleData *ppa;
3224                                 HairKey *hkey;
3225                                 ParticleKey key[3];
3226                                 KDTreeNearest ptn[3];
3227                                 int w, maxw;
3228                                 float maxd, mind, dd, totw=0.0, weight[3];
3229
3230                                 psys_particle_on_dm(psmd->dm,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co1,0,0,0,0,0);
3231                                 maxw= BLI_kdtree_find_n_nearest(tree,3,co1,NULL,ptn);
3232
3233                                 maxd= ptn[maxw-1].dist;
3234                                 mind= ptn[0].dist;
3235                                 dd= maxd - mind;
3236                                 
3237                                 for(w=0; w<maxw; w++) {
3238                                         weight[w]= (float)pow(2.0, (double)(-6.0f * ptn[w].dist / maxd));
3239                                         totw += weight[w];
3240                                 }
3241                                 for(;w<3; w++) {
3242                                         weight[w]= 0.0f;
3243                                 }
3244