svn merge -r 12856:12937 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[blender.git] / source / blender / src / editparticle.c
1 /* editparticle.c
2  *
3  *
4  * $Id: editparticle.c $
5  *
6  * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version. The Blender
12  * Foundation also sells licenses for use in proprietary software under
13  * the Blender License.  See http://www.blender.org/BL/ for information
14  * about this.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software Foundation,
23  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
24  *
25  * The Original Code is Copyright (C) 2007 by Janne Karhu.
26  * All rights reserved.
27  *
28  * The Original Code is: all of this file.
29  *
30  * Contributor(s): none yet.
31  *
32  * ***** END GPL/BL DUAL LICENSE BLOCK *****
33  */
34
35 #include <stdlib.h>
36 #include <math.h>
37 #include <string.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_scene_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_meshdata_types.h"
44 #include "DNA_modifier_types.h"
45 #include "DNA_object_force.h"
46 #include "DNA_object_types.h"
47 #include "DNA_vec_types.h"
48 #include "DNA_userdef_types.h"
49 #include "DNA_view3d_types.h"
50 #include "DNA_screen_types.h"
51 #include "DNA_space_types.h"
52
53 #include "BKE_bad_level_calls.h"
54 #include "BKE_DerivedMesh.h"
55 #include "BKE_depsgraph.h"
56
57 #include "BKE_global.h"
58 #include "BKE_object.h"
59 #include "BKE_mesh.h"
60 #include "BKE_modifier.h"
61 #include "BKE_particle.h"
62 #include "BKE_scene.h"
63 #include "BKE_utildefines.h" 
64
65 #include "BSE_edit.h"
66
67 #include "BLI_arithb.h"
68 #include "BLI_blenlib.h"
69 #include "BLI_dynstr.h"
70 #include "BLI_kdtree.h"
71 #include "BLI_rand.h"
72
73 #include "PIL_time.h"
74
75 #include "BIF_gl.h"
76 #include "BIF_glutil.h"
77 #include "BIF_graphics.h"
78 #include "BIF_editparticle.h"
79 #include "BIF_editview.h"
80 #include "BIF_interface.h"
81 #include "BIF_meshtools.h"
82 #include "BIF_mywindow.h"
83 #include "BIF_resources.h"
84 #include "BIF_screen.h"
85 #include "BIF_space.h"
86
87 #include "BSE_view.h"
88
89 #include "BDR_editobject.h" //rightmouse_transform()
90 #include "BDR_drawobject.h"
91
92 #include "blendef.h"
93 #include "mydevice.h"
94
95 static void ParticleUndo_clear(ParticleSystem *psys);
96
97 #define LOOP_PARTICLES(i,pa) for(i=0, pa=psys->particles; i<totpart; i++, pa++)
98 #define LOOP_KEYS(k,key) if(psys->edit)for(k=0, key=psys->edit->keys[i]; k<pa->totkey; k++, key++)
99
100 void PE_free_particle_edit(ParticleSystem *psys)
101 {
102         ParticleEdit *edit=psys->edit;
103         int i, totpart=psys->totpart;
104
105         if(edit==0) return;
106
107         ParticleUndo_clear(psys);
108
109         if(edit->keys){
110                 for(i=0; i<totpart; i++){
111                         if(edit->keys[i])
112                                 MEM_freeN(edit->keys[i]);
113                 }
114                 MEM_freeN(edit->keys);
115         }
116
117         if(edit->mirror_cache)
118                 MEM_freeN(edit->mirror_cache);
119
120         if(edit->emitter_cosnos){
121                 MEM_freeN(edit->emitter_cosnos);
122                 edit->emitter_cosnos=0;
123         }
124
125         if(edit->emitter_field){
126                 BLI_kdtree_free(edit->emitter_field);
127                 edit->emitter_field=0;
128         }
129
130         MEM_freeN(edit);
131
132         psys->edit=NULL;
133 }
134 /************************************************/
135 /*                      Edit Mode Helpers                                       */
136 /************************************************/
137 int PE_can_edit(ParticleSystem *psys)
138 {
139         return (psys && psys->edit && (G.f & G_PARTICLEEDIT));
140 }
141
142 ParticleEditSettings *PE_settings()
143 {
144         return &G.scene->toolsettings->particle;
145 }
146
147 void PE_change_act(void *ob_v, void *act_v)
148 {
149         Object *ob = ob_v;
150         ParticleSystem *psys;
151         short act = *((short*)act_v) - 1;
152
153         if((psys=psys_get_current(ob)))
154                 psys->flag &= ~PSYS_CURRENT;
155
156         if(act>=0){
157                 if((psys=BLI_findlink(&ob->particlesystem,act))) {
158                         psys->flag |= PSYS_CURRENT;
159
160                         if(psys_check_enabled(ob, psys)) {
161                                 if(G.f & G_PARTICLEEDIT && !psys->edit)
162                                         PE_create_particle_edit(ob, psys);
163                                 PE_recalc_world_cos(ob, psys);
164                         }
165                 }
166         }
167 }
168
169 /* always gets atleast the first particlesystem even if PSYS_CURRENT flag is not set */
170 ParticleSystem *PE_get_current(Object *ob)
171 {
172         ParticleSystem *psys;
173
174         if(ob==NULL)
175                 return NULL;
176
177         psys= ob->particlesystem.first;
178         while(psys){
179                 if(psys->flag & PSYS_CURRENT)
180                         break;
181                 psys=psys->next;
182         }
183
184         if(psys==NULL && ob->particlesystem.first){
185                 psys=ob->particlesystem.first;
186                 psys->flag |= PSYS_CURRENT;
187         }
188
189         if(psys && psys_check_enabled(ob, psys) && ob == OBACT && (G.f & G_PARTICLEEDIT))
190                 if(psys->part->type == PART_HAIR && psys->flag & PSYS_EDITED)
191                         if(psys->edit == NULL)
192                                 PE_create_particle_edit(ob, psys);
193
194         return psys;
195 }
196 /* returns -1 if no system has PSYS_CURRENT flag */
197 short PE_get_current_num(Object *ob)
198 {
199         short num=0;
200         ParticleSystem *psys = ob->particlesystem.first;
201
202         while(psys){
203                 if(psys->flag & PSYS_CURRENT)
204                         return num;
205                 num++;
206                 psys=psys->next;
207         }
208
209         return -1;
210 }
211
212 void PE_hide_keys_time(ParticleSystem *psys, float cfra)
213 {
214         ParticleData *pa;
215         ParticleEditKey *key;
216         ParticleEditSettings *pset=PE_settings();
217         int i,k,totpart=psys->totpart;
218
219         if(pset->draw_timed && G.scene->selectmode==SCE_SELECT_POINT){
220                 LOOP_PARTICLES(i,pa){
221                         LOOP_KEYS(k,key){
222                                 if(fabs(cfra-*key->time) < pset->draw_timed)
223                                         key->flag &= ~PEK_HIDE;
224                                 else{
225                                         key->flag |= PEK_HIDE;
226                                         key->flag &= ~PEK_SELECT;
227                                 }
228                         }
229                 }
230         }
231         else{
232                 LOOP_PARTICLES(i,pa){
233                         LOOP_KEYS(k,key){
234                                 key->flag &= ~PEK_HIDE;
235                         }
236                 }
237         }
238 }
239
240 static int key_inside_circle(short mco[2], float rad, float co[3], float *distance)
241 {
242         float dx,dy,dist;
243         short vertco[2];
244
245         project_short(co,vertco);
246         dx=(float)(mco[0]-vertco[0]);
247         dy=(float)(mco[1]-vertco[1]);
248         dist=(float)sqrt((double)(dx*dx + dy*dy));
249
250         if(dist<=rad){
251                 if(distance) *distance=dist;
252                 return 1;
253         }
254         else
255                 return 0;
256 }
257 static int key_inside_rect(rcti *rect, float co[3])
258 {
259         short vertco[2];
260
261         project_short(co,vertco);
262
263         if(vertco[0] > rect->xmin && vertco[0] < rect->xmax &&
264                         vertco[1] > rect->ymin && vertco[1] < rect->ymax)
265                 return 1;
266         else
267                 return 0;
268 }
269 static int test_key_depth(float *co, bglMats *mats){
270         double ux, uy, uz;
271         float depth;
272         short wco[3], x,y;
273
274         if((G.vd->flag & V3D_ZBUF_SELECT)==0) return 1;
275
276         gluProject(co[0],co[1],co[2], mats->modelview, mats->projection,
277                         (GLint *)mats->viewport, &ux, &uy, &uz );
278
279         project_short(co,wco);
280
281         x=wco[0];
282         y=wco[1];
283
284         if(G.vd->depths && x<G.vd->depths->w && y<G.vd->depths->h){
285                 if((float)uz>G.vd->depths->depths[y*G.vd->depths->w+x])
286                         return 0;
287                 else
288                         return 1;
289         }
290         else{
291                 x+= (short)curarea->winrct.xmin;
292                 y+= (short)curarea->winrct.ymin;
293
294                 glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
295
296                 if((float)uz>depth)
297                         return 0;
298                 else
299                         return 1;
300         }
301 }
302
303 static int particle_is_selected(ParticleSystem *psys, ParticleData *pa)
304 {
305         ParticleEditKey *key;
306         int sel, i, k;
307
308         if(pa->flag&PARS_HIDE) return 0;
309
310         sel=0;
311         i= pa - psys->particles;
312         LOOP_KEYS(k,key)
313                 if(key->flag&PEK_SELECT)
314                         return 1;
315         
316         return 0;
317 }
318
319 /*-----iterators over editable particles-----*/
320 static void for_mouse_hit_keys(int nearest, ParticleSystem *psys, void (*func)(ParticleSystem *psys, int pa_index, int key_index, void *userData), void *userData){
321         /* these are allways the first in this userData */
322         struct { short *mval; float rad; rcti *rect;} *data = userData;
323         ParticleData *pa;
324         ParticleEditKey *key;
325         bglMats mats;
326         int i,k, totpart, nearest_pa=-1, nearest_key=-1;
327         float dist=data->rad;
328
329         if(psys==0 || G.scene->selectmode==SCE_SELECT_PATH) return;
330
331         totpart=psys->totpart;
332
333         bgl_get_mats(&mats);
334
335         LOOP_PARTICLES(i,pa){
336                 if(pa->flag & PARS_HIDE) continue;
337
338                 if(G.scene->selectmode==SCE_SELECT_END){
339                         key=psys->edit->keys[i]+pa->totkey-1;
340
341                         if(nearest){
342                                 if(key_inside_circle(data->mval,dist,key->world_co,&dist) && test_key_depth(key->world_co,&mats)){
343                                         nearest_pa=i;
344                                         nearest_key=pa->totkey-1;
345                                 }
346                         }
347                         else if(((data->mval)?
348                                                 key_inside_circle(data->mval,data->rad,key->world_co,0):
349                                                 key_inside_rect(data->rect,key->world_co)) && test_key_depth(key->world_co,&mats))
350                                 func(psys,i,pa->totkey-1,userData);
351                 }
352                 else{
353                         key=psys->edit->keys[i];
354
355                         LOOP_KEYS(k,key){
356                                 if(key->flag&PEK_HIDE) continue;
357
358                                 if(nearest){
359                                         if(key_inside_circle(data->mval,dist,key->world_co,&dist) && test_key_depth(key->world_co,&mats)){
360                                                 nearest_pa=i;
361                                                 nearest_key=k;
362                                         }
363                                 }
364                                 else if(((data->mval)?
365                                                         key_inside_circle(data->mval,data->rad,key->world_co,0):
366                                                         key_inside_rect(data->rect,key->world_co)) && test_key_depth(key->world_co,&mats))
367                                         func(psys,i,k,userData);
368                         }
369                 }
370         }
371         if(nearest && nearest_pa>-1){
372                 func(psys,nearest_pa,nearest_key,userData);
373         }
374 }
375 static void foreach_mouse_hit_element(int selected, ParticleSystem *psys,void (*func)(ParticleSystem *psys, int index, void *userData), void *userData){
376         /* these are allways the first in this userData */
377         struct { short *mval; float rad; rcti* rect; float dist;} *data = userData;
378         ParticleData *pa;
379         ParticleEditKey *key;
380         bglMats mats;
381         int i,k, totpart;
382
383         if(psys==0) return;
384
385         totpart=psys->totpart;
386
387         bgl_get_mats(&mats);
388
389         if(G.scene->selectmode==SCE_SELECT_PATH)
390                 selected=0;
391
392         LOOP_PARTICLES(i,pa){
393                 if(pa->flag & PARS_HIDE) continue;
394
395                 if(G.scene->selectmode==SCE_SELECT_END){
396                         key=psys->edit->keys[i]+pa->totkey-1;
397                         if(key_inside_circle(data->mval,data->rad,key->world_co,&data->dist) && (selected==0 || key->flag&PEK_SELECT) && test_key_depth(key->world_co,&mats))
398                                 func(psys,i,userData);
399                 }
400                 else{
401                         LOOP_KEYS(k,key){
402                                 if(key->flag&PEK_HIDE) continue;
403
404                                 if(key_inside_circle(data->mval,data->rad,key->world_co,&data->dist) && (selected==0 || key->flag&PEK_SELECT) && test_key_depth(key->world_co,&mats)){
405                                         func(psys,i,userData);
406                                         break;
407                                 }
408                         }
409                 }
410         }
411 }
412 static void foreach_mouse_hit_key(int selected, ParticleSystem *psys,void (*func)(ParticleSystem *psys, float mat[][4], float imat[][4], int bel_index, int key_index, void *userData), void *userData){
413         /* these are allways the first in this userData */
414         struct { Object *ob; short *mval; float rad; rcti* rect; float dist;} *data = userData;
415         ParticleData *pa;
416         ParticleEditKey *key;
417         ParticleSystemModifierData *psmd=0;
418         bglMats mats;
419         int i,k, totpart;
420         float mat[4][4], imat[4][4];
421
422         if(psys==0) return;
423
424         psmd=psys_get_modifier(data->ob,psys);
425
426         totpart=psys->totpart;
427
428         bgl_get_mats(&mats);
429
430         if(G.scene->selectmode==SCE_SELECT_PATH)
431                 selected=0;
432
433         Mat4One(imat);
434         Mat4One(mat);
435
436         LOOP_PARTICLES(i,pa){
437                 if(pa->flag & PARS_HIDE) continue;
438
439                 psys_mat_hair_to_global(data->ob, psmd->dm, psys->part->from, pa, mat);
440                 //psys_geometry_mat(psmd->dm,pa,tmat);
441                 //Mat4MulMat4(mat,tmat,data->ob->obmat);
442                 Mat4Invert(imat,mat);
443
444                 if(G.scene->selectmode==SCE_SELECT_END){
445                         key=psys->edit->keys[i]+pa->totkey-1;
446                         if(key_inside_circle(data->mval,data->rad,key->world_co,&data->dist) && (selected==0 || key->flag&PEK_SELECT) && test_key_depth(key->world_co,&mats))
447                                 func(psys,mat,imat,i,pa->totkey-1,userData);
448                 }
449                 else{
450                         LOOP_KEYS(k,key){
451                                 if(key->flag&PEK_HIDE) continue;
452
453                                 if(key_inside_circle(data->mval,data->rad,key->world_co,&data->dist) && (selected==0 || key->flag&PEK_SELECT) && test_key_depth(key->world_co,&mats)){
454                                         func(psys,mat,imat,i,k,userData);
455                                 }
456                         }
457                 }
458         }
459 }
460 static void foreach_selected_element(ParticleSystem *psys, void (*func)(ParticleSystem *psys, int index, void *userData), void *userData){
461         ParticleData *pa;
462         int i,totpart;
463
464         if(psys==0) return;
465
466         totpart=psys->totpart;
467
468         LOOP_PARTICLES(i,pa)
469                 if(particle_is_selected(psys, pa))
470                         func(psys,i,userData);
471 }
472 static void foreach_selected_key(ParticleSystem *psys, void (*func)(ParticleSystem *psys, int pa_index, int key_index, void *userData), void *userData){
473         ParticleData *pa;
474         ParticleEditKey *key;
475         int i,k,totpart;
476
477         if(psys==0) return;
478
479         totpart=psys->totpart;
480
481         LOOP_PARTICLES(i,pa){
482                 if(pa->flag&PARS_HIDE) continue;
483
484                 key=psys->edit->keys[i];
485                 LOOP_KEYS(k,key){
486                         if(key->flag&PEK_SELECT)
487                                 func(psys,i,k,userData);
488                 }
489         }
490 }
491 void PE_foreach_element(ParticleSystem *psys, void (*func)(ParticleSystem *psys, int index, void *userData), void *userData)
492 {
493         int i,totpart;
494
495         if(psys==0) return;
496
497         totpart=psys->totpart;
498
499         for(i=0; i<totpart; i++)
500                 func(psys,i,userData);
501 }
502 static int count_selected_keys(ParticleSystem *psys)
503 {
504         ParticleData *pa;
505         ParticleEditKey *key;
506         int i,k,totpart,sel=0;
507
508         if(psys==0) return 0;
509
510         totpart=psys->totpart;
511
512         LOOP_PARTICLES(i,pa){
513                 if(pa->flag&PARS_HIDE) continue;
514
515                 key=psys->edit->keys[i];
516                 if(G.scene->selectmode==SCE_SELECT_POINT){
517                         for(k=0; k<pa->totkey; k++,key++){
518                                 if(key->flag&PEK_SELECT)
519                                         sel++;
520                         }
521                 }
522                 else if(G.scene->selectmode==SCE_SELECT_END){
523                         key+=pa->totkey-1;
524                         if(key->flag&PEK_SELECT)
525                                 sel++;
526                 }
527         }
528         return sel;
529 }
530
531 /************************************************/
532 /*                      Particle Edit Mirroring                         */
533 /************************************************/
534
535 static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys)
536 {
537         ParticleEdit *edit;
538         ParticleData *pa;
539         ParticleSystemModifierData *psmd;
540         KDTree *tree;
541         KDTreeNearest nearest;
542         float mat[4][4], co[3];
543         int i, index, totpart;
544
545         edit= psys->edit;
546         psmd= psys_get_modifier(ob, psys);
547         totpart= psys->totpart;
548
549         tree= BLI_kdtree_new(totpart);
550
551         /* insert particles into kd tree */
552         LOOP_PARTICLES(i,pa) {
553                 psys_mat_hair_to_orco(ob, psmd->dm, psys->part->from, pa, mat);
554                 VECCOPY(co, pa->hair[0].co);
555                 Mat4MulVecfl(mat, co);
556                 BLI_kdtree_insert(tree, i, co, NULL);
557         }
558
559         BLI_kdtree_balance(tree);
560
561         /* lookup particles and set in mirror cache */
562         if(!edit->mirror_cache)
563                 edit->mirror_cache= MEM_callocN(sizeof(int)*totpart, "PE mirror cache");
564         
565         LOOP_PARTICLES(i,pa) {
566                 psys_mat_hair_to_orco(ob, psmd->dm, psys->part->from, pa, mat);
567                 VECCOPY(co, pa->hair[0].co);
568                 Mat4MulVecfl(mat, co);
569                 co[0]= -co[0];
570
571                 index= BLI_kdtree_find_nearest(tree, co, NULL, &nearest);
572
573                 /* this needs a custom threshold still, duplicated for editmode mirror */
574                 if(index != -1 && index != i && (nearest.dist <= 0.0002f))
575                         edit->mirror_cache[i]= index;
576                 else
577                         edit->mirror_cache[i]= -1;
578         }
579
580         /* make sure mirrors are in two directions */
581         LOOP_PARTICLES(i,pa) {
582                 if(edit->mirror_cache[i]) {
583                         index= edit->mirror_cache[i];
584                         if(edit->mirror_cache[index] != i)
585                                 edit->mirror_cache[i]= -1;
586                 }
587         }
588
589         BLI_kdtree_free(tree);
590 }
591
592 static void PE_mirror_particle(Object *ob, DerivedMesh *dm, ParticleSystem *psys, ParticleData *pa, ParticleData *mpa)
593 {
594         HairKey *hkey, *mhkey;
595         ParticleEditKey *key, *mkey;
596         ParticleEdit *edit;
597         float mat[4][4], mmat[4][4], immat[4][4];
598         int i, mi, k;
599
600         edit= psys->edit;
601         i= pa - psys->particles;
602
603         if(!edit->mirror_cache)
604                 PE_update_mirror_cache(ob, psys);
605
606         /* find mirrored particle if needed */
607         if(!mpa) {
608                 mi= edit->mirror_cache[i];
609                 if(mi == -1)
610                         return;
611                 mpa= psys->particles + mi;
612         }
613         else
614                 mi= mpa - psys->particles;
615
616         /* make sure they have the same amount of keys */
617         if(pa->totkey != mpa->totkey) {
618                 if(mpa->hair) MEM_freeN(mpa->hair);
619                 if(edit->keys[mi]) MEM_freeN(edit->keys[mi]);
620
621                 mpa->hair= MEM_dupallocN(pa->hair);
622                 edit->keys[mi]= MEM_dupallocN(edit->keys[i]);
623                 mpa->totkey= pa->totkey;
624
625                 mhkey= mpa->hair;
626                 mkey= edit->keys[mi];
627                 for(k=0; k<mpa->totkey; k++, mkey++, mhkey++) {
628                         mkey->co= mhkey->co;
629                         mkey->time= &mhkey->time;
630                         mkey->flag &= PEK_SELECT;
631                 }
632         }
633
634         /* mirror positions and tags */
635         psys_mat_hair_to_orco(ob, dm, psys->part->from, pa, mat);
636         psys_mat_hair_to_orco(ob, dm, psys->part->from, mpa, mmat);
637         Mat4Invert(immat, mmat);
638
639         hkey=pa->hair;
640         mhkey=mpa->hair;
641         key= edit->keys[i];
642         mkey= edit->keys[mi];
643         for(k=0; k<pa->totkey; k++, hkey++, mhkey++, key++, mkey++) {
644                 VECCOPY(mhkey->co, hkey->co);
645                 Mat4MulVecfl(mat, mhkey->co);
646                 mhkey->co[0]= -mhkey->co[0];
647                 Mat4MulVecfl(immat, mhkey->co);
648
649                 if(key->flag & PEK_TAG)
650                         mkey->flag |= PEK_TAG;
651         }
652
653         if(pa->flag & PARS_TAG)
654                 mpa->flag |= PARS_TAG;
655         if(pa->flag & PARS_EDIT_RECALC)
656                 mpa->flag |= PARS_EDIT_RECALC;
657 }
658
659 static void PE_apply_mirror(Object *ob, ParticleSystem *psys)
660 {
661         ParticleEdit *edit;
662         ParticleData *pa;
663         ParticleSystemModifierData *psmd;
664         int i, totpart;
665
666         edit= psys->edit;
667         psmd= psys_get_modifier(ob, psys);
668         totpart= psys->totpart;
669
670         /* we delay settings the PARS_EDIT_RECALC for mirrored particles
671          * to avoid doing mirror twice */
672         LOOP_PARTICLES(i,pa) {
673                 if(pa->flag & PARS_EDIT_RECALC) {
674                         PE_mirror_particle(ob, psmd->dm, psys, pa, NULL);
675
676                         if(edit->mirror_cache[i] != -1)
677                                 psys->particles[edit->mirror_cache[i]].flag &= ~PARS_EDIT_RECALC;
678                 }
679         }
680
681         LOOP_PARTICLES(i,pa)
682                 if(pa->flag & PARS_EDIT_RECALC)
683                         if(edit->mirror_cache[i] != -1)
684                                 psys->particles[edit->mirror_cache[i]].flag |= PARS_EDIT_RECALC;
685
686         edit->totkeys= psys_count_keys(psys);
687 }
688
689 /************************************************/
690 /*                      Edit Calculation                                        */
691 /************************************************/
692 /* tries to stop edited particles from going through the emitter's surface */
693 static void PE_deflect_emitter(Object *ob, ParticleSystem *psys)
694 {
695         ParticleEdit *edit;
696         ParticleData *pa;
697         ParticleEditKey *key;
698         ParticleEditSettings *pset = PE_settings();
699         ParticleSystemModifierData *psmd = psys_get_modifier(ob,psys);
700         int i,k,totpart,index;
701         float *vec, *nor, dvec[3], dot, dist_1st;
702         float hairimat[4][4], hairmat[4][4];
703
704         if(psys==0)
705                 return;
706
707         if((pset->flag & PE_DEFLECT_EMITTER)==0)
708                 return;
709
710         edit=psys->edit;
711         totpart=psys->totpart;
712
713         LOOP_PARTICLES(i,pa){
714                 if(!(pa->flag & PARS_EDIT_RECALC))
715                         continue;
716                 
717                 psys_mat_hair_to_object(ob, psmd->dm, psys->part->from, pa, hairmat);
718                 
719                 LOOP_KEYS(k,key){
720                         Mat4MulVecfl(hairmat, key->co);
721                 }
722         //}
723
724         //LOOP_PARTICLES(i,pa){
725                 key=psys->edit->keys[i]+1;
726
727                 dist_1st=VecLenf((key-1)->co,key->co);
728                 dist_1st*=0.75f*pset->emitterdist;
729
730                 for(k=1; k<pa->totkey; k++, key++){
731                         index= BLI_kdtree_find_nearest(edit->emitter_field,key->co,NULL,NULL);
732                         
733                         vec=edit->emitter_cosnos +index*6;
734                         nor=vec+3;
735
736                         VecSubf(dvec, key->co, vec);
737
738                         dot=Inpf(dvec,nor);
739                         VECCOPY(dvec,nor);
740
741                         if(dot>0.0f){
742                                 if(dot<dist_1st){
743                                         Normalize(dvec);
744                                         VecMulf(dvec,dist_1st-dot);
745                                         VecAddf(key->co,key->co,dvec);
746                                 }
747                         }
748                         else{
749                                 Normalize(dvec);
750                                 VecMulf(dvec,dist_1st-dot);
751                                 VecAddf(key->co,key->co,dvec);
752                         }
753                         if(k==1)
754                                 dist_1st*=1.3333f;
755                 }
756         //}
757
758         //LOOP_PARTICLES(i,pa){
759                 
760                 Mat4Invert(hairimat,hairmat);
761
762                 LOOP_KEYS(k,key){
763                         Mat4MulVecfl(hairimat, key->co);
764                 }
765         }
766 }
767 /* force set distances between neighbouring keys */
768 void PE_apply_lengths(ParticleSystem *psys)
769 {
770         ParticleEdit *edit;
771         ParticleData *pa;
772         ParticleEditKey *key;
773         ParticleEditSettings *pset=PE_settings();
774         int i,k,totpart;
775         float dv1[3];
776
777         if(psys==0)
778                 return;
779
780         if((pset->flag & PE_KEEP_LENGTHS)==0)
781                 return;
782
783         edit=psys->edit;
784         totpart=psys->totpart;
785
786         LOOP_PARTICLES(i,pa){
787                 if(!(pa->flag & PARS_EDIT_RECALC))
788                         continue;
789                 
790                 for(k=1, key=edit->keys[i] + 1; k<pa->totkey; k++, key++){
791                         VecSubf(dv1, key->co, (key - 1)->co);
792                         Normalize(dv1);
793                         VecMulf(dv1, (key - 1)->length);
794                         VecAddf(key->co, (key - 1)->co, dv1);
795                 }
796         }
797 }
798 /* try to find a nice solution to keep distances between neighbouring keys */
799 static void PE_iterate_lengths(ParticleSystem *psys)
800 {
801         ParticleEdit *edit;
802         ParticleData *pa;
803         ParticleEditKey *key;
804         ParticleEditSettings *pset=PE_settings();
805         int i, j, k,totpart;
806         float tlen;
807         float dv0[3] = {0.0f, 0.0f, 0.0f};
808         float dv1[3] = {0.0f, 0.0f, 0.0f};
809         float dv2[3] = {0.0f, 0.0f, 0.0f};
810
811         if(psys==0)
812                 return;
813
814         if((pset->flag & PE_KEEP_LENGTHS)==0)
815                 return;
816
817         edit=psys->edit;
818         totpart=psys->totpart;
819
820         LOOP_PARTICLES(i,pa){
821                 if(!(pa->flag & PARS_EDIT_RECALC))
822                         continue;
823
824                 for(j=1; j<pa->totkey; j++){
825                         float mul = 1.0f / (float)pa->totkey;
826
827                         if(pset->flag & PE_LOCK_FIRST){
828                                 key = edit->keys[i] + 1;
829                                 k = 1;
830                                 dv1[0] = dv1[1] = dv1[2] = 0.0;
831                         }
832                         else{
833                                 key = edit->keys[i];
834                                 k = 0;
835                                 dv0[0] = dv0[1] = dv0[2] = 0.0;
836                         }
837
838                         for(; k<pa->totkey; k++, key++){
839                                 if(k){
840                                         VecSubf(dv0, (key - 1)->co, key->co);
841                                         tlen = Normalize(dv0);
842                                         VecMulf(dv0, (mul * (tlen - (key - 1)->length)));
843                                 }
844
845                                 if(k < pa->totkey - 1){
846                                         VecSubf(dv2, (key + 1)->co, key->co);
847                                         tlen = Normalize(dv2);
848                                         VecMulf(dv2, mul * (tlen - key->length));
849                                 }
850
851                                 if(k){
852                                         VecAddf((key-1)->co,(key-1)->co,dv1);
853                                 }
854
855                                 VECADD(dv1,dv0,dv2);
856                         }
857                 }
858         }
859 }
860 /* set current distances to be kept between neighbouting keys */
861 static void recalc_lengths(ParticleSystem *psys)
862 {
863         ParticleData *pa;
864         ParticleEditKey *key;
865         int i, k, totpart;
866
867         if(psys==0)
868                 return;
869
870         totpart = psys->totpart;
871
872         LOOP_PARTICLES(i,pa){
873                 key = psys->edit->keys[i];
874                 for(k=0; k<pa->totkey-1; k++, key++){
875                         key->length = VecLenf(key->co, (key + 1)->co);
876                 }
877         }
878 }
879 /* calculate and store key locations in world coordinates */
880 void PE_recalc_world_cos(Object *ob, ParticleSystem *psys)
881 {
882         ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
883         ParticleData *pa;
884         ParticleEditKey *key;
885         int i, k, totpart;
886         float hairmat[4][4];
887
888         if(psys==0)
889                 return;
890
891         totpart = psys->totpart;
892
893         LOOP_PARTICLES(i,pa){
894                 psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, pa, hairmat);
895
896                 LOOP_KEYS(k,key){
897                         VECCOPY(key->world_co,key->co);
898                         Mat4MulVecfl(hairmat, key->world_co);
899                 }
900         }
901 }
902 /* calculate a tree for finding nearest emitter's vertice */
903 static void recalc_emitter_field(Object *ob, ParticleSystem *psys)
904 {
905         DerivedMesh *dm=psys_get_modifier(ob,psys)->dm;
906         ParticleEdit *edit = psys->edit;
907         MFace *mface;
908         MVert *mvert;
909         float *vec, *nor;
910         int i, totface, totvert;
911
912         if(edit->emitter_cosnos)
913                 MEM_freeN(edit->emitter_cosnos);
914
915         BLI_kdtree_free(edit->emitter_field);
916
917         totface=dm->getNumFaces(dm);
918         totvert=dm->getNumVerts(dm);
919
920         edit->emitter_cosnos=MEM_callocN(totface*6*sizeof(float),"emitter cosnos");
921
922         edit->emitter_field= BLI_kdtree_new(totface);
923
924         vec=edit->emitter_cosnos;
925         nor=vec+3;
926
927         mvert=dm->getVertDataArray(dm,CD_MVERT);
928         for(i=0; i<totface; i++, vec+=6, nor+=6){
929                 mface=dm->getFaceData(dm,i,CD_MFACE);
930
931                 mvert=dm->getVertData(dm,mface->v1,CD_MVERT);
932                 VECCOPY(vec,mvert->co);
933                 VECCOPY(nor,mvert->no);
934
935                 mvert=dm->getVertData(dm,mface->v2,CD_MVERT);
936                 VECADD(vec,vec,mvert->co);
937                 VECADD(nor,nor,mvert->no);
938
939                 mvert=dm->getVertData(dm,mface->v3,CD_MVERT);
940                 VECADD(vec,vec,mvert->co);
941                 VECADD(nor,nor,mvert->no);
942
943                 if (mface->v4){
944                         mvert=dm->getVertData(dm,mface->v4,CD_MVERT);
945                         VECADD(vec,vec,mvert->co);
946                         VECADD(nor,nor,mvert->no);
947                         
948                         VecMulf(vec,0.25);
949                 }
950                 else
951                         VecMulf(vec,0.3333f);
952
953                 Normalize(nor);
954
955                 BLI_kdtree_insert(edit->emitter_field, i, vec, NULL);
956         }
957
958         BLI_kdtree_balance(edit->emitter_field);
959 }
960
961 void PE_update_selection(Object *ob, int useflag)
962 {
963         ParticleSystem *psys= PE_get_current(ob);
964         ParticleEdit *edit= psys->edit;
965         ParticleEditSettings *pset= PE_settings();
966         ParticleSettings *part= psys->part;
967         ParticleData *pa;
968         HairKey *hkey;
969         ParticleEditKey *key;
970         float cfra= CFRA;
971         int i, k, totpart;
972
973         totpart= psys->totpart;
974
975         /* flag all particles to be updated if not using flag */
976         if(!useflag)
977                 LOOP_PARTICLES(i,pa)
978                         pa->flag |= PARS_EDIT_RECALC;
979
980         /* flush edit key flag to hair key flag to preserve selection 
981          * on save */
982         LOOP_PARTICLES(i,pa) {
983                 key = edit->keys[i];
984
985                 for(k=0, hkey=pa->hair; k<pa->totkey; k++, hkey++, key++)
986                         hkey->editflag= key->flag;
987         }
988
989         psys_cache_paths(ob, psys, CFRA, 1);
990
991         if(part->childtype && (pset->flag & PE_SHOW_CHILD))
992                 psys_cache_child_paths(ob, psys, cfra, 1);
993
994         /* disable update flag */
995         LOOP_PARTICLES(i,pa)
996                 pa->flag &= ~PARS_EDIT_RECALC;
997 }
998
999 void PE_update_object(Object *ob, int useflag)
1000 {
1001         ParticleSystem *psys= PE_get_current(ob);
1002         ParticleEditSettings *pset= PE_settings();
1003         ParticleSettings *part= psys->part;
1004         ParticleData *pa;
1005         float cfra= CFRA;
1006         int i, totpart= psys->totpart;
1007
1008         /* flag all particles to be updated if not using flag */
1009         if(!useflag)
1010                 LOOP_PARTICLES(i,pa)
1011                         pa->flag |= PARS_EDIT_RECALC;
1012
1013         /* do post process on particle edit keys */
1014         PE_iterate_lengths(psys);
1015         PE_deflect_emitter(ob,psys);
1016         PE_apply_lengths(psys);
1017         if(pset->flag & PE_X_MIRROR)
1018                 PE_apply_mirror(ob,psys);
1019         PE_recalc_world_cos(ob,psys);
1020         PE_hide_keys_time(psys,cfra);
1021
1022         /* regenerate path caches */
1023         psys_cache_paths(ob, psys, cfra, 1);
1024
1025         if(part->childtype && (pset->flag & PE_SHOW_CHILD))
1026                 psys_cache_child_paths(ob, psys, cfra, 1);
1027
1028         /* disable update flag */
1029         LOOP_PARTICLES(i,pa)
1030                 pa->flag &= ~PARS_EDIT_RECALC;
1031 }
1032
1033 /* initialize needed data for bake edit */
1034 void PE_create_particle_edit(Object *ob, ParticleSystem *psys)
1035 {
1036         ParticleEdit *edit=psys->edit;
1037         ParticleData *pa;
1038         ParticleEditKey *key;
1039         HairKey *hkey;
1040         int i,k, totpart=psys->totpart, alloc=1;
1041
1042         if((psys->flag & PSYS_EDITED)==0)
1043                 return;
1044
1045         if(edit){
1046                 int newtotkeys = psys_count_keys(psys);
1047                 if(newtotkeys == edit->totkeys)
1048                         alloc=0;
1049         }
1050
1051         if(alloc){
1052                 if(edit){
1053                         error("ParticleEdit exists allready! Poke jahka!");
1054                         PE_free_particle_edit(psys);
1055                 }
1056
1057                 edit=psys->edit=MEM_callocN(sizeof(ParticleEdit), "PE_create_particle_edit");
1058
1059                 edit->keys=MEM_callocN(totpart*sizeof(ParticleEditKey*),"ParticleEditKey array");
1060
1061                 LOOP_PARTICLES(i,pa){
1062                         key = edit->keys[i] = MEM_callocN(pa->totkey*sizeof(ParticleEditKey),"ParticleEditKeys");
1063                         for(k=0, hkey=pa->hair; k<pa->totkey; k++, hkey++, key++){
1064                                 key->co = hkey->co;
1065                                 key->time = &hkey->time;
1066                                 key->flag= hkey->editflag;
1067                         }
1068                 }
1069
1070                 edit->totkeys = psys_count_keys(psys);
1071         }
1072
1073         recalc_lengths(psys);
1074         recalc_emitter_field(ob, psys);
1075         PE_recalc_world_cos(ob, psys);
1076
1077         if(alloc) {
1078                 ParticleUndo_clear(psys);
1079                 PE_undo_push("Original");
1080         }
1081 }
1082
1083 /* toggle particle mode on & off */
1084 void PE_set_particle_edit(void)
1085 {
1086         Object *ob= OBACT;
1087         ParticleSystem *psys = PE_get_current(ob);
1088
1089         scrarea_queue_headredraw(curarea);
1090         
1091         //if(!ob || ob->id.lib) return; /* is the id.lib test needed? -jahka*/
1092         if(ob==0 || psys==0) return;
1093         
1094         if(psys==0){
1095                 if(ob->particlesystem.first){
1096                         psys=ob->particlesystem.first;
1097                         psys->flag |= PSYS_CURRENT;
1098                 }
1099                 else
1100                         return;
1101         }
1102
1103         if((G.f & G_PARTICLEEDIT)==0){
1104                 if(psys && psys->part->type == PART_HAIR && psys->flag & PSYS_EDITED) {
1105                         if(psys_check_enabled(ob, psys)) {
1106                                 if(psys->edit==0)
1107                                         PE_create_particle_edit(ob, psys);
1108                                 PE_recalc_world_cos(ob, psys);
1109                         }
1110                 }
1111
1112                 G.f |= G_PARTICLEEDIT;
1113         }
1114         else{
1115                 G.f &= ~G_PARTICLEEDIT;
1116
1117                 if(psys->soft)
1118                         psys->softflag |= OB_SB_REDO;
1119         }
1120
1121         DAG_object_flush_update(G.scene, OBACT, OB_RECALC_DATA);
1122
1123         allqueue(REDRAWVIEW3D, 1);      /* including header */
1124         allqueue(REDRAWBUTSOBJECT, 0);
1125 }
1126 /************************************************/
1127 /*                      Edit Selections                                         */
1128 /************************************************/
1129 /*-----selection callbacks-----*/
1130 static void select_key(ParticleSystem *psys, int pa_index, int key_index, void *userData)
1131 {
1132         struct { short *mval; float rad; rcti* rect; int select; } *data = userData;
1133         ParticleData *pa = psys->particles + pa_index;
1134         ParticleEditKey *key = psys->edit->keys[pa_index] + key_index;
1135
1136         if(data->select)
1137                 key->flag|=PEK_SELECT;
1138         else
1139                 key->flag&=~PEK_SELECT;
1140
1141         pa->flag |= PARS_EDIT_RECALC;
1142 }
1143 static void select_keys(ParticleSystem *psys, int pa_index, int key_index, void *userData)
1144 {
1145         struct { short *mval; float rad; rcti* rect; int select; } *data = userData;
1146         ParticleData *pa = psys->particles + pa_index;
1147         ParticleEditKey *key = psys->edit->keys[pa_index];
1148         int k;
1149
1150         for(k=0; k<pa->totkey; k++,key++){
1151                 if(data->select)
1152                         key->flag|=PEK_SELECT;
1153                 else
1154                         key->flag&=~PEK_SELECT;
1155         }
1156
1157         pa->flag |= PARS_EDIT_RECALC;
1158 }
1159 static void toggle_key_select(ParticleSystem *psys, int pa_index, int key_index, void *userData)
1160 {
1161         ParticleData *pa = psys->particles + pa_index;
1162
1163         if(psys->edit->keys[pa_index][key_index].flag&PEK_SELECT)
1164                 psys->edit->keys[pa_index][key_index].flag&=~PEK_SELECT;
1165         else
1166                 psys->edit->keys[pa_index][key_index].flag|=PEK_SELECT;
1167         
1168         pa->flag |= PARS_EDIT_RECALC;
1169 }
1170 static void select_root(ParticleSystem *psys, int index, void *userData)
1171 {
1172         psys->edit->keys[index]->flag |= PEK_SELECT;
1173 }
1174
1175 static void select_tip(ParticleSystem *psys, int index, void *userData)
1176 {
1177         ParticleData *pa = psys->particles + index;
1178         ParticleEditKey *key = psys->edit->keys[index] + pa->totkey-1;
1179
1180         key->flag |= PEK_SELECT;
1181 }
1182 static void select_more_keys(ParticleSystem *psys, int index, void *userData)
1183 {
1184         ParticleEdit *edit = psys->edit;
1185         ParticleData *pa = psys->particles+index;
1186         ParticleEditKey *key;
1187         int k;
1188
1189         for(k=0,key=edit->keys[index]; k<pa->totkey; k++,key++){
1190                 if(key->flag&PEK_SELECT) continue;
1191
1192                 if(k==0){
1193                         if((key+1)->flag&PEK_SELECT)
1194                                 key->flag |= PEK_TO_SELECT;
1195                 }
1196                 else if(k==pa->totkey-1){
1197                         if((key-1)->flag&PEK_SELECT)
1198                                 key->flag |= PEK_TO_SELECT;
1199                 }
1200                 else{
1201                         if(((key-1)->flag | (key+1)->flag) & PEK_SELECT)
1202                                 key->flag |= PEK_TO_SELECT;
1203                 }
1204         }
1205
1206         for(k=0,key=edit->keys[index]; k<pa->totkey; k++,key++){
1207                 if(key->flag&PEK_TO_SELECT){
1208                         key->flag &= ~PEK_TO_SELECT;
1209                         key->flag |= PEK_SELECT;
1210                 }
1211         }
1212 }
1213
1214 static void select_less_keys(ParticleSystem *psys, int index, void *userData)
1215 {
1216         ParticleEdit *edit = psys->edit;
1217         ParticleData *pa = psys->particles+index;
1218         ParticleEditKey *key;
1219         int k;
1220
1221         for(k=0,key=edit->keys[index]; k<pa->totkey; k++,key++){
1222                 if((key->flag&PEK_SELECT)==0) continue;
1223
1224                 if(k==0){
1225                         if(((key+1)->flag&PEK_SELECT)==0)
1226                                 key->flag |= PEK_TO_SELECT;
1227                 }
1228                 else if(k==pa->totkey-1){
1229                         if(((key-1)->flag&PEK_SELECT)==0)
1230                                 key->flag |= PEK_TO_SELECT;
1231                 }
1232                 else{
1233                         if((((key-1)->flag & (key+1)->flag) & PEK_SELECT)==0)
1234                                 key->flag |= PEK_TO_SELECT;
1235                 }
1236         }
1237
1238         for(k=0,key=edit->keys[index]; k<pa->totkey; k++,key++){
1239                 if(key->flag&PEK_TO_SELECT)
1240                         key->flag &= ~(PEK_TO_SELECT|PEK_SELECT);
1241         }
1242 }
1243
1244 /*-----using above callbacks-----*/
1245 void PE_deselectall(void)
1246 {
1247         Object *ob = OBACT;
1248         ParticleSystem *psys = PE_get_current(ob);
1249         ParticleEdit *edit = 0;
1250         ParticleData *pa;
1251         ParticleEditKey *key;
1252         int i,k,totpart, sel = 0;
1253                 
1254         if(!PE_can_edit(psys)) return;
1255         
1256         edit = psys->edit;
1257
1258         totpart = psys->totpart;
1259         
1260         LOOP_PARTICLES(i,pa){
1261                 if(pa->flag & PARS_HIDE) continue;
1262                 LOOP_KEYS(k,key){
1263                         if(key->flag&PEK_SELECT){
1264                                 sel = 1;
1265                                 key->flag &= ~PEK_SELECT;
1266                                 pa->flag |= PARS_EDIT_RECALC;
1267                         }
1268                 }
1269         }
1270
1271         if(sel==0){
1272                 LOOP_PARTICLES(i,pa){
1273                         if(pa->flag & PARS_HIDE) continue;
1274                         LOOP_KEYS(k,key){
1275                                 if(!(key->flag & PEK_SELECT)) {
1276                                         key->flag |= PEK_SELECT;
1277                                         pa->flag |= PARS_EDIT_RECALC;
1278                                 }
1279                         }
1280                 }
1281         }
1282
1283         PE_update_selection(ob, 1);
1284
1285         BIF_undo_push("(De)select all keys");
1286         allqueue(REDRAWVIEW3D, 1);
1287 }
1288 void PE_mouse_particles(void)
1289 {
1290         struct { short *mval; float rad; rcti* rect; int select; } data;
1291         Object *ob = OBACT;
1292         ParticleSystem *psys = PE_get_current(ob);
1293         ParticleEdit *edit = 0;
1294         ParticleData *pa;
1295         ParticleEditKey *key;
1296         short mval[2];
1297         int i,k,totpart;
1298
1299         if(!PE_can_edit(psys)) return;
1300
1301         edit = psys->edit;
1302
1303         totpart = psys->totpart;
1304
1305         bglFlush();
1306         glReadBuffer(GL_BACK);
1307         glDrawBuffer(GL_BACK);
1308         persp(PERSP_VIEW);
1309
1310         if(G.qual != LR_SHIFTKEY)
1311                 LOOP_PARTICLES(i,pa){
1312                         if(pa->flag & PARS_HIDE) continue;
1313                         LOOP_KEYS(k,key){
1314                                 if(key->flag & PEK_SELECT) {
1315                                         key->flag &= ~PEK_SELECT;
1316                                         pa->flag |= PARS_EDIT_RECALC;
1317                                 }
1318                         }
1319                 }
1320
1321         getmouseco_areawin(mval);
1322
1323         data.mval=mval;
1324         data.rad=75.0f;
1325         data.rect=0;
1326         data.select=0;
1327
1328         for_mouse_hit_keys(1,psys,toggle_key_select,&data);
1329
1330         PE_update_selection(ob, 1);
1331
1332         rightmouse_transform();
1333
1334         allqueue(REDRAWVIEW3D, 1);
1335 }
1336 void PE_select_root()
1337 {
1338         Object *ob=OBACT;
1339         ParticleSystem *psys = PE_get_current(ob);
1340
1341         if(!PE_can_edit(psys)) return;
1342
1343         PE_foreach_element(psys,select_root,NULL);
1344         BIF_undo_push("Select first");
1345 }
1346 void PE_select_tip()
1347 {
1348         Object *ob=OBACT;
1349         ParticleSystem *psys = PE_get_current(ob);
1350
1351         if(!PE_can_edit(psys)) return;
1352
1353         PE_foreach_element(psys,select_tip,NULL);
1354         BIF_undo_push("Select last");
1355 }
1356 void PE_select_linked(void)
1357 {
1358         struct { short *mval; float rad; rcti* rect; int select; } data;
1359         Object *ob = OBACT;
1360         ParticleSystem *psys = PE_get_current(ob);
1361         short mval[2];
1362
1363         if(!PE_can_edit(psys)) return;
1364
1365         getmouseco_areawin(mval);
1366
1367         data.mval=mval;
1368         data.rad=75.0f;
1369         data.rect=0;
1370         data.select=(G.qual != LR_SHIFTKEY);
1371
1372         for_mouse_hit_keys(1,psys,select_keys,&data);
1373
1374         PE_update_selection(ob, 1);
1375
1376         BIF_undo_push("Select linked keys");
1377
1378         allqueue(REDRAWVIEW3D, 1);
1379         return;
1380 }
1381 void PE_borderselect(void)
1382 {
1383         struct { short *mval; float rad; rcti* rect; int select; } data;
1384         Object *ob = OBACT;
1385         ParticleSystem *psys = PE_get_current(ob);
1386         rcti rect;
1387         int val;
1388
1389         if(!PE_can_edit(psys)) return;
1390
1391         setlinestyle(2);
1392         val= get_border(&rect, 3);
1393         setlinestyle(0);
1394         
1395         if(val==0) return;
1396
1397         data.mval=0;
1398         data.rect=&rect;
1399         data.select=(val==LEFTMOUSE);
1400
1401         for_mouse_hit_keys(0,psys,select_key,&data);
1402
1403         PE_update_selection(ob, 1);
1404
1405         BIF_undo_push("Select keys");
1406
1407         allqueue(REDRAWVIEW3D, 1);
1408         return;
1409 }
1410 void PE_selectionCB(short selecting, Object *editobj, short *mval, float rad)
1411 {
1412         struct { short *mval; float rad; rcti* rect; int select; } data;
1413         ParticleSystem *psys = PE_get_current(OBACT);
1414
1415         if(!PE_can_edit(psys)) return;
1416
1417         data.mval=mval;
1418         data.rad=rad;
1419         data.rect=0;
1420         data.select=(selecting==LEFTMOUSE);
1421
1422         for_mouse_hit_keys(0,psys,select_key,&data);
1423
1424         draw_sel_circle(0, 0, 0, 0, 0); /* signal */
1425         force_draw(0);
1426 }
1427 void PE_do_lasso_select(short mcords[][2], short moves, short select)
1428 {
1429         Object *ob = OBACT;
1430         ParticleSystem *psys = PE_get_current(ob);
1431         ParticleSystemModifierData *psmd;
1432         ParticleEdit *edit;
1433         ParticleData *pa;
1434         ParticleEditKey *key;
1435         float co[3], mat[4][4];
1436         short vertco[2];
1437         int i, k, totpart;
1438
1439         if(!PE_can_edit(psys)) return;
1440
1441         psmd= psys_get_modifier(ob, psys);
1442         edit=psys->edit;
1443         totpart=psys->totpart;
1444
1445         LOOP_PARTICLES(i,pa){
1446                 if(pa->flag & PARS_HIDE) continue;
1447
1448                 psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, pa, mat);
1449
1450                 if(G.scene->selectmode==SCE_SELECT_POINT){
1451                         LOOP_KEYS(k,key){
1452                                 VECCOPY(co, key->co);
1453                                 Mat4MulVecfl(mat, co);
1454                                 project_short(co,vertco);
1455                                 if(lasso_inside(mcords,moves,vertco[0],vertco[1])){
1456                                         if(select && !(key->flag & PEK_SELECT)) {
1457                                                 key->flag|=PEK_SELECT;
1458                                                 pa->flag |= PARS_EDIT_RECALC;
1459                                         }
1460                                         else if(key->flag & PEK_SELECT) {
1461                                                 key->flag&=~PEK_SELECT;
1462                                                 pa->flag |= PARS_EDIT_RECALC;
1463                                         }
1464                                 }
1465                         }
1466                 }
1467                 else if(G.scene->selectmode==SCE_SELECT_END){
1468                         key = edit->keys[i] + pa->totkey - 1;
1469
1470                         VECCOPY(co, key->co);
1471                         Mat4MulVecfl(mat, co);
1472                         project_short(co,vertco);
1473                         if(lasso_inside(mcords,moves,vertco[0],vertco[1])){
1474                                 if(select && !(key->flag & PEK_SELECT)) {
1475                                         key->flag|=PEK_SELECT;
1476                                         pa->flag |= PARS_EDIT_RECALC;
1477                                 }
1478                                 else if(key->flag & PEK_SELECT) {
1479                                         key->flag&=~PEK_SELECT;
1480                                         pa->flag |= PARS_EDIT_RECALC;
1481                                 }
1482                         }
1483                 }
1484         }
1485
1486         PE_update_selection(ob, 1);
1487
1488         BIF_undo_push("Lasso select particles");
1489
1490         allqueue(REDRAWVIEW3D, 1);
1491 }
1492 void PE_hide(int mode)
1493 {
1494         ParticleSystem *psys = PE_get_current(OBACT);
1495         ParticleEdit *edit;
1496         ParticleData *pa;
1497         int i,totpart;
1498
1499         if(!PE_can_edit(psys)) return;
1500
1501         edit = psys->edit;
1502         totpart = psys->totpart;
1503         
1504         if(mode == 0){ /* reveal all particles */
1505                 LOOP_PARTICLES(i,pa){
1506                         pa->flag &= ~PARS_HIDE;
1507                 }
1508         }
1509         else if(mode == 1){ /* hide unselected particles */
1510                 LOOP_PARTICLES(i,pa)
1511                         if(particle_is_selected(psys, pa))
1512                                 pa->flag |= PARS_HIDE;
1513         }
1514         else{ /* hide selected particles */
1515                 LOOP_PARTICLES(i,pa)
1516                         if(particle_is_selected(psys, pa))
1517                                 pa->flag |= PARS_HIDE;
1518         }
1519
1520         BIF_undo_push("(Un)hide elements");
1521         
1522         allqueue(REDRAWVIEW3D, 1);
1523 }
1524 void PE_select_less(void)
1525 {
1526         ParticleSystem *psys = PE_get_current(OBACT);
1527
1528         if(!PE_can_edit(psys)) return;
1529
1530         PE_foreach_element(psys,select_less_keys,NULL);
1531         
1532         BIF_undo_push("Select less");
1533         allqueue(REDRAWVIEW3D, 1);
1534 }
1535 void PE_select_more(void)
1536 {
1537         ParticleSystem *psys = PE_get_current(OBACT);
1538
1539         if(!PE_can_edit(psys)) return;
1540
1541         PE_foreach_element(psys,select_more_keys,NULL);
1542         
1543         BIF_undo_push("Select more");
1544         allqueue(REDRAWVIEW3D, 1);
1545 }
1546 /************************************************/
1547 /*                      Edit Rekey                                                      */
1548 /************************************************/
1549 static void rekey_element(ParticleSystem *psys, int index, void *userData)
1550 {
1551         struct { Object *ob; float dval; } *data = userData;
1552         ParticleData *pa = psys->particles + index;
1553         ParticleEdit *edit = psys->edit;
1554         ParticleEditSettings *pset = PE_settings();
1555         ParticleKey state;
1556         HairKey *key, *new_keys;
1557         ParticleEditKey *ekey;
1558         float dval, sta, end;
1559         int k;
1560
1561         pa->flag |= PARS_REKEY;
1562
1563         key = new_keys = MEM_callocN(pset->totrekey * sizeof(HairKey),"Hair re-key keys");
1564
1565         /* root and tip stay the same */
1566         VECCOPY(key->co, pa->hair->co);
1567         VECCOPY((key + pset->totrekey - 1)->co, (pa->hair + pa->totkey - 1)->co);
1568
1569         sta = key->time = pa->hair->time;
1570         end = (key + pset->totrekey - 1)->time = (pa->hair + pa->totkey - 1)->time;
1571         dval = (end - sta) / (float)(pset->totrekey - 1);
1572
1573         /* interpolate new keys from old ones */
1574         for(k=1,key++; k<pset->totrekey-1; k++,key++) {
1575                 state.time = (float)k / (float)(pset->totrekey-1);
1576                 psys_get_particle_on_path(data->ob, psys, index, &state, 0);
1577                 VECCOPY(key->co, state.co);
1578                 key->time = sta + k * dval;
1579         }
1580
1581         /* replace keys */
1582         if(pa->hair)
1583                 MEM_freeN(pa->hair);
1584         pa->hair = new_keys;
1585
1586         pa->totkey=pset->totrekey;
1587
1588         if(edit->keys[index])
1589                 MEM_freeN(edit->keys[index]);
1590         ekey = edit->keys[index] = MEM_callocN(pa->totkey * sizeof(ParticleEditKey),"Hair re-key edit keys");
1591                 
1592         for(k=0, key=pa->hair; k<pa->totkey; k++, key++, ekey++) {
1593                 ekey->co = key->co;
1594                 ekey->time = &key->time;
1595         }
1596
1597         pa->flag &= ~PARS_REKEY;
1598         pa->flag |= PARS_EDIT_RECALC;
1599 }
1600 void PE_rekey(void)
1601 {
1602         Object *ob=OBACT;
1603         ParticleSystem *psys = PE_get_current(ob);
1604         ParticleEditSettings *pset = PE_settings();
1605         struct { Object *ob; float dval; } data;
1606
1607         if(!PE_can_edit(psys)) return;
1608
1609         data.ob = ob;
1610         data.dval = 1.0f / (float)(pset->totrekey-1);
1611
1612         foreach_selected_element(psys,rekey_element,&data);
1613         
1614         psys->edit->totkeys = psys_count_keys(psys);
1615
1616         recalc_lengths(psys);
1617         
1618         PE_update_object(ob, 1);
1619
1620         BIF_undo_push("Re-key particles");
1621 }
1622 static void rekey_element_to_time(int index, float path_time)
1623 {
1624         Object *ob = OBACT;
1625         ParticleSystem *psys = PE_get_current(ob);
1626         ParticleEdit *edit=0;
1627         ParticleData *pa;
1628         ParticleKey state;
1629         HairKey *new_keys, *key;
1630         ParticleEditKey *ekey;
1631         int k;
1632
1633         if(psys==0) return;
1634
1635         edit = psys->edit;
1636
1637         pa = psys->particles + index;
1638
1639         pa->flag |= PARS_REKEY;
1640
1641         key = new_keys = MEM_dupallocN(pa->hair);
1642         
1643         /* interpolate new keys from old ones (roots stay the same) */
1644         for(k=1, key++; k < pa->totkey; k++, key++) {
1645                 state.time = path_time * (float)k / (float)(pa->totkey-1);
1646                 psys_get_particle_on_path(ob, psys, index, &state, 0);
1647                 VECCOPY(key->co, state.co);
1648         }
1649
1650         /* replace hair keys */
1651         if(pa->hair)
1652                 MEM_freeN(pa->hair);
1653         pa->hair = new_keys;
1654
1655         /* update edit pointers */
1656         for(k=0, key=pa->hair, ekey=edit->keys[index]; k<pa->totkey; k++, key++, ekey++) {
1657                 ekey->co = key->co;
1658                 ekey->time = &key->time;
1659         }
1660
1661         pa->flag &= ~PARS_REKEY;
1662 }
1663 static int remove_tagged_elements(Object *ob, ParticleSystem *psys)
1664 {
1665         ParticleEdit *edit = psys->edit;
1666         ParticleEditSettings *pset = PE_settings();
1667         ParticleData *pa, *npa=0, *new_pars=0;
1668         ParticleEditKey **key, **nkey=0, **new_keys=0;
1669         ParticleSystemModifierData *psmd;
1670         int i, totpart, new_totpart = psys->totpart, removed = 0;
1671
1672         if(pset->flag & PE_X_MIRROR) {
1673                 /* mirror tags */
1674                 psmd = psys_get_modifier(ob, psys);
1675                 totpart = psys->totpart;
1676
1677                 LOOP_PARTICLES(i,pa)
1678                         if(pa->flag & PARS_TAG)
1679                                 PE_mirror_particle(ob, psmd->dm, psys, pa, NULL);
1680         }
1681
1682         for(i=0, pa=psys->particles; i<psys->totpart; i++, pa++) {
1683                 if(pa->flag & PARS_TAG) {
1684                         new_totpart--;
1685                         removed++;
1686                 }
1687         }
1688
1689         if(new_totpart != psys->totpart) {
1690                 if(new_totpart) {
1691                         npa = new_pars = MEM_callocN(new_totpart * sizeof(ParticleData), "ParticleData array");
1692                         nkey = new_keys = MEM_callocN(new_totpart * sizeof(ParticleEditKey *), "ParticleEditKey array");
1693                 }
1694
1695                 pa = psys->particles;
1696                 key = edit->keys;
1697                 for(i=0; i<psys->totpart; i++, pa++, key++) {
1698                         if(pa->flag & PARS_TAG) {
1699                                 if(*key)
1700                                         MEM_freeN(*key);
1701                                 if(pa->hair)
1702                                         MEM_freeN(pa->hair);
1703                         }
1704                         else {
1705                                 memcpy(npa, pa, sizeof(ParticleData));
1706                                 memcpy(nkey, key, sizeof(ParticleEditKey*));
1707                                 npa++;
1708                                 nkey++;
1709                         }
1710                 }
1711
1712                 if(psys->particles) MEM_freeN(psys->particles);
1713                 psys->particles = new_pars;
1714
1715                 if(edit->keys) MEM_freeN(edit->keys);
1716                 edit->keys = new_keys;
1717
1718                 if(edit->mirror_cache) {
1719                         MEM_freeN(edit->mirror_cache);
1720                         edit->mirror_cache = NULL;
1721                 }
1722
1723                 psys->totpart = new_totpart;
1724
1725                 edit->totkeys = psys_count_keys(psys);
1726         }
1727
1728         return removed;
1729 }
1730 static void remove_tagged_keys(Object *ob, ParticleSystem *psys)
1731 {
1732         ParticleEdit *edit = psys->edit;
1733         ParticleEditSettings *pset = PE_settings();
1734         ParticleData *pa;
1735         HairKey *key, *nkey, *new_keys=0;
1736         ParticleEditKey *ekey;
1737         ParticleSystemModifierData *psmd;
1738         int i, k, totpart = psys->totpart;
1739         short new_totkey;
1740
1741         if(pset->flag & PE_X_MIRROR) {
1742                 /* mirror key tags */
1743                 psmd = psys_get_modifier(ob, psys);
1744
1745                 LOOP_PARTICLES(i,pa) {
1746                         LOOP_KEYS(k,ekey) {
1747                                 if(ekey->flag & PEK_TAG) {
1748                                         PE_mirror_particle(ob, psmd->dm, psys, pa, NULL);
1749                                         break;
1750                                 }
1751                         }
1752                 }
1753         }
1754
1755         LOOP_PARTICLES(i,pa) {
1756                 new_totkey = pa->totkey;
1757                 LOOP_KEYS(k,ekey) {
1758                         if(ekey->flag & PEK_TAG)
1759                                 new_totkey--;
1760                 }
1761                 /* we can't have elements with less than two keys*/
1762                 if(new_totkey < 2)
1763                         pa->flag |= PARS_TAG;
1764         }
1765         remove_tagged_elements(ob, psys);
1766
1767         totpart = psys->totpart;
1768
1769         LOOP_PARTICLES(i,pa) {
1770                 new_totkey = pa->totkey;
1771                 LOOP_KEYS(k,ekey) {
1772                         if(ekey->flag & PEK_TAG)
1773                                 new_totkey--;
1774                 }
1775                 if(new_totkey != pa->totkey) {
1776                         key = pa->hair;
1777                         nkey = new_keys = MEM_callocN(new_totkey*sizeof(HairKey), "HairKeys");
1778
1779                         for(k=0, ekey=edit->keys[i]; k<new_totkey; k++, key++, nkey++, ekey++) {
1780                                 while(ekey->flag & PEK_TAG && key < pa->hair + pa->totkey) {
1781                                         key++;
1782                                         ekey++;
1783                                 }
1784
1785                                 if(key < pa->hair + pa->totkey) {
1786                                         VECCOPY(nkey->co, key->co);
1787                                         nkey->time = key->time;
1788                                         nkey->weight = key->weight;
1789                                 }
1790                         }
1791                         if(pa->hair)
1792                                 MEM_freeN(pa->hair);
1793                         
1794                         pa->hair = new_keys;
1795
1796                         pa->totkey=new_totkey;
1797
1798                         if(edit->keys[i])
1799                                 MEM_freeN(edit->keys[i]);
1800                         ekey = edit->keys[i] = MEM_callocN(new_totkey*sizeof(ParticleEditKey), "particle edit keys");
1801
1802                         for(k=0, key=pa->hair; k<pa->totkey; k++, key++, ekey++) {
1803                                 ekey->co = key->co;
1804                                 ekey->time = &key->time;
1805                         }
1806                 }
1807         }
1808
1809         edit->totkeys = psys_count_keys(psys);
1810 }
1811 /* works like normal edit mode subdivide, inserts keys between neighbouring selected keys */
1812 static void subdivide_element(ParticleSystem *psys, int index, void *userData)
1813 {
1814         struct { Object *ob; } *data = userData;
1815         ParticleEdit *edit = psys->edit;
1816         ParticleData *pa = psys->particles + index;
1817         
1818         ParticleKey state;
1819         HairKey *key, *nkey, *new_keys;
1820         ParticleEditKey *ekey, *nekey, *new_ekeys;
1821
1822         int k;
1823         short totnewkey=0;
1824         float endtime;
1825
1826         for(k=0, ekey=edit->keys[index]; k<pa->totkey-1; k++,ekey++){
1827                 if(ekey->flag&PEK_SELECT && (ekey+1)->flag&PEK_SELECT)
1828                         totnewkey++;
1829         }
1830
1831         if(totnewkey==0) return;
1832
1833         pa->flag |= PARS_REKEY;
1834
1835         nkey = new_keys = MEM_callocN((pa->totkey+totnewkey)*(sizeof(HairKey)),"Hair subdivide keys");
1836         nekey = new_ekeys = MEM_callocN((pa->totkey+totnewkey)*(sizeof(ParticleEditKey)),"Hair subdivide edit keys");
1837         endtime = pa->hair[pa->totkey-1].time;
1838
1839         for(k=0, key=pa->hair, ekey=edit->keys[index]; k<pa->totkey-1; k++, key++, ekey++){
1840
1841                 memcpy(nkey,key,sizeof(HairKey));
1842                 memcpy(nekey,ekey,sizeof(ParticleEditKey));
1843
1844                 nekey->co = nkey->co;
1845                 nekey->time = &nkey->time;
1846
1847                 nkey++;
1848                 nekey++;
1849
1850                 if(ekey->flag & PEK_SELECT && (ekey+1)->flag & PEK_SELECT){
1851                         nkey->time= (key->time + (key+1)->time)*0.5f;
1852                         state.time = (endtime != 0.0f)? nkey->time/endtime: 0.0f;
1853                         psys_get_particle_on_path(data->ob, psys, index, &state, 0);
1854                         VECCOPY(nkey->co, state.co);
1855
1856                         nekey->co= nkey->co;
1857                         nekey->time= &nkey->time;
1858                         nekey->flag |= PEK_SELECT;
1859
1860                         nekey++;
1861                         nkey++;
1862                 }
1863         }
1864         /*tip still not copied*/
1865         memcpy(nkey,key,sizeof(HairKey));
1866         memcpy(nekey,ekey,sizeof(ParticleEditKey));
1867
1868         nekey->co = nkey->co;
1869         nekey->time = &nkey->time;
1870
1871         if(pa->hair)
1872                 MEM_freeN(pa->hair);
1873         pa->hair = new_keys;
1874
1875         if(edit->keys[index])
1876                 MEM_freeN(edit->keys[index]);
1877
1878         edit->keys[index] = new_ekeys;
1879
1880         pa->totkey += totnewkey;
1881         pa->flag |= PARS_EDIT_RECALC;
1882         pa->flag &= ~PARS_REKEY;
1883 }
1884 void PE_subdivide(void)
1885 {
1886         Object *ob = OBACT;
1887         ParticleSystem *psys = PE_get_current(ob);
1888         struct { Object *ob; } data;
1889
1890         if(!PE_can_edit(psys)) return;
1891
1892         data.ob= ob;
1893         PE_foreach_element(psys,subdivide_element,&data);
1894         
1895         psys->edit->totkeys = psys_count_keys(psys);
1896         
1897         recalc_lengths(psys);
1898         PE_recalc_world_cos(ob, psys);
1899
1900         PE_update_object(ob, 1);
1901         
1902         BIF_undo_push("Subdivide hair(s)");
1903 }
1904 /************************************************/
1905 /*                      Edit Brushes                                            */
1906 /************************************************/
1907 static void brush_comb(ParticleSystem *psys, float mat[][4], float imat[][4], int pa_index, int key_index, void *userData)
1908 {
1909         struct {Object *ob; short *mval; float rad; rcti* rect; float dist; float *dvec; float combfac;} *data = userData;
1910         ParticleData *pa= &psys->particles[pa_index];
1911         ParticleEditSettings *pset= PE_settings();
1912         HairKey *key = pa->hair + key_index;
1913         float cvec[3], fac;
1914
1915         if(pset->flag & PE_LOCK_FIRST && key_index == 0) return;
1916
1917         fac = (float)pow((double)(1.0f - data->dist / data->rad), (double)data->combfac);
1918
1919         VECCOPY(cvec,data->dvec);
1920         Mat4Mul3Vecfl(imat,cvec);
1921         VecMulf(cvec, fac);
1922         VECADD(key->co, key->co, cvec);
1923
1924         pa->flag |= PARS_EDIT_RECALC;
1925 }
1926 static void brush_cut(ParticleSystem *psys, int index, void *userData)
1927 {
1928         struct { short *mval; float rad; rcti* rect; int selected; float cutfac;} *data = userData;
1929         ParticleData *pa= &psys->particles[index];
1930         ParticleCacheKey *key = psys->pathcache[index];
1931         float rad2, cut_time = 1.0;
1932         float x0, x1, v0, v1, o0, o1, xo0, xo1, d, dv;
1933         int k, cut, keys = (int)pow(2.0, (double)psys->part->draw_step);
1934         short vertco[2];
1935
1936         /* blunt scissors */
1937         if(BLI_frand() > data->cutfac) return;
1938
1939         rad2 = data->rad * data->rad;
1940
1941         cut=0;
1942
1943         project_short(key->co, vertco);
1944         x0 = (float)vertco[0];
1945         x1 = (float)vertco[1];
1946
1947         o0 = (float)data->mval[0];
1948         o1 = (float)data->mval[1];
1949         
1950         xo0 = x0 - o0;
1951         xo1 = x1 - o1;
1952
1953         /* check if root is inside circle */
1954         if(xo0*xo0 + xo1*xo1 < rad2) {
1955                 cut_time = -1.0f;
1956                 cut = 1;
1957         }
1958         else {
1959                 /* calculate path time closest to root that was inside the circle */
1960                 for(k=1, key++; k<=keys; k++, key++){
1961                         project_short(key->co, vertco);
1962
1963                         v0 = (float)vertco[0] - x0;
1964                         v1 = (float)vertco[1] - x1;
1965
1966                         dv = v0*v0 + v1*v1;
1967
1968                         d = (v0*xo1 - v1*xo0);
1969                         
1970                         d = dv * rad2 - d*d;
1971
1972                         if(d > 0.0f) {
1973                                 d = sqrt(d);
1974
1975                                 cut_time = -(v0*xo0 + v1*xo1 + d);
1976
1977                                 if(cut_time > 0.0f) {
1978                                         cut_time /= dv;
1979
1980                                         if(cut_time < 1.0f) {
1981                                                 cut_time += (float)(k-1);
1982                                                 cut_time /= (float)keys;
1983                                                 cut = 1;
1984                                                 break;
1985                                         }
1986                                 }
1987                         }
1988
1989                         x0 = (float)vertco[0];
1990                         x1 = (float)vertco[1];
1991
1992                         xo0 = x0 - o0;
1993                         xo1 = x1 - o1;
1994                 }
1995         }
1996
1997         if(cut) {
1998                 if(cut_time < 0.0f) {
1999                         pa->flag |= PARS_TAG;
2000                 }
2001                 else {
2002                         rekey_element_to_time(index, cut_time);
2003                         pa->flag |= PARS_EDIT_RECALC;
2004                 }
2005         }
2006 }
2007 static void brush_length(ParticleSystem *psys, int index, void *userData)
2008 {
2009         struct { short *mval; float rad; rcti* rect; float dist; float growfac; } *data = userData;
2010         ParticleData *pa = &psys->particles[index];
2011         HairKey *key;
2012         float dvec[3],pvec[3];
2013         int k;
2014
2015         key = pa->hair;
2016         VECCOPY(pvec,key->co);
2017
2018         for(k=1, key++; k<pa->totkey; k++,key++){
2019                 VECSUB(dvec,key->co,pvec);
2020                 VECCOPY(pvec,key->co);
2021                 VecMulf(dvec,data->growfac);
2022                 VECADD(key->co,(key-1)->co,dvec);
2023         }
2024
2025         pa->flag |= PARS_EDIT_RECALC;
2026 }
2027 static void brush_puff(ParticleSystem *psys, int index, void *userData)
2028 {
2029         struct { short *mval; float rad; rcti* rect; float dist;
2030                 Object *ob; DerivedMesh *dm; float pufffac; int invert; } *data = userData;
2031         ParticleData *pa = &psys->particles[index];
2032         ParticleEdit *edit = psys->edit;
2033         HairKey *key;
2034         float mat[4][4], imat[4][4];
2035         float lastco[3], rootco[3], co[3], nor[3], kco[3], dco[3], fac, length;
2036         int k;
2037
2038         psys_mat_hair_to_global(data->ob, data->dm, psys->part->from, pa, mat);
2039         Mat4Invert(imat,mat);
2040
2041         /* find root coordinate and normal on emitter */
2042         key = pa->hair;
2043         VECCOPY(co, key->co);
2044         Mat4MulVecfl(mat, co);
2045
2046         index= BLI_kdtree_find_nearest(edit->emitter_field, co, NULL, NULL);
2047         if(index == -1) return;
2048
2049         VECCOPY(rootco, co);
2050         VecCopyf(nor, &psys->edit->emitter_cosnos[index*6+3]);
2051         Normalize(nor);
2052         length= 0.0f;
2053
2054         fac= (float)pow((double)(1.0f - data->dist / data->rad), (double)data->pufffac);
2055         fac *= 0.025f;
2056         if(data->invert)
2057                 fac= -fac;
2058
2059         for(k=1, key++; k<pa->totkey; k++, key++){
2060                 /* compute position as if hair was standing up straight */
2061                 VECCOPY(lastco, co);
2062                 VECCOPY(co, key->co);
2063                 Mat4MulVecfl(mat, co);
2064                 length += VecLenf(lastco, co);
2065
2066                 VECADDFAC(kco, rootco, nor, length);
2067
2068                 /* blend between the current and straight position */
2069                 VECSUB(dco, kco, co);
2070                 VECADDFAC(co, co, dco, fac);
2071
2072                 VECCOPY(key->co, co);
2073                 Mat4MulVecfl(imat, key->co);
2074         }
2075
2076         pa->flag |= PARS_EDIT_RECALC;
2077 }
2078 static void brush_smooth_get(ParticleSystem *psys, float mat[][4], float imat[][4], int pa_index, int key_index, void *userData)
2079 {
2080         struct { Object *ob; short *mval; float rad; rcti* rect; float dist; float vec[3]; int tot; float smoothfac;} *data = userData;
2081         ParticleData *pa= &psys->particles[pa_index];
2082         HairKey *key = pa->hair + key_index;
2083         
2084         if(key_index){
2085                 float dvec[3];
2086
2087                 VecSubf(dvec,key->co,(key-1)->co);
2088                 Mat4Mul3Vecfl(mat,dvec);
2089                 VECADD(data->vec,data->vec,dvec);
2090                 data->tot++;
2091         }
2092 }
2093 static void brush_smooth_do(ParticleSystem *psys, float mat[][4], float imat[][4], int pa_index, int key_index, void *userData)
2094 {
2095         struct { Object *ob; short *mval; float rad; rcti* rect; float dist; float vec[3]; int tot; float smoothfac;} *data = userData;
2096         ParticleData *pa= &psys->particles[pa_index];
2097         HairKey *key = pa->hair + key_index;
2098         float vec[3], dvec[3];
2099         
2100         if(key_index){
2101                 VECCOPY(vec,data->vec);
2102                 Mat4Mul3Vecfl(imat,vec);
2103
2104                 VecSubf(dvec,key->co,(key-1)->co);
2105
2106                 VECSUB(dvec,vec,dvec);
2107                 VecMulf(dvec,data->smoothfac);
2108                 
2109                 VECADD(key->co,key->co,dvec);
2110         }
2111
2112         pa->flag |= PARS_EDIT_RECALC;
2113 }
2114 #define EXPERIMENTAL_DEFORM_ONLY_PAINTING 1
2115 static void brush_add(Object *ob, ParticleSystem *psys, short *mval, short number)
2116 {
2117         ParticleData *add_pars = MEM_callocN(number*sizeof(ParticleData),"ParticleData add");
2118         ParticleSystemModifierData *psmd = psys_get_modifier(ob,psys);
2119         ParticleEditSettings *pset= PE_settings();
2120         ParticleEdit *edit = psys->edit;
2121         int i, k, n = 0, totpart = psys->totpart;
2122         short dmx = 0, dmy = 0;
2123         short mx = mval[0] - curarea->winx / 2, my = mval[1] - curarea->winy / 2;
2124         float co1[3], co2[3], vec[4], min_d, imat[4][4];
2125         float framestep, timestep = psys_get_timestep(psys->part);
2126         short size = pset->brush[PE_BRUSH_ADD].size;
2127         short size2 = size*size;
2128 #if EXPERIMENTAL_DEFORM_ONLY_PAINTING
2129         DerivedMesh *dm=0;
2130 #endif
2131         Mat4Invert(imat,ob->obmat);
2132
2133         BLI_srandom(psys->seed+mval[0]+mval[1]);
2134         
2135         /* painting onto the deformed mesh, could be an option? */
2136 #if EXPERIMENTAL_DEFORM_ONLY_PAINTING
2137         if (psmd->dm->deformedOnly)
2138                 dm = psmd->dm;
2139         else
2140                 dm = mesh_get_derived_deform(ob, CD_MASK_BAREMESH);
2141 #endif
2142         for(i=0; i<number; i++){
2143                 if(number>1){
2144                         dmx=dmy=size;
2145                         while(dmx*dmx+dmy*dmy>size2){
2146                                 dmx=(short)((2.0f*BLI_frand()-1.0f)*size);
2147                                 dmy=(short)((2.0f*BLI_frand()-1.0f)*size);
2148                         }
2149                 }
2150
2151                 /* create intersection coordinates in view Z direction at mouse coordinates */
2152                 /* Thanks to who ever wrote the "Mouse Location 3D Space" tutorial in "Blender 3D: Blending Into Python/Cookbook". */
2153                 if(G.vd->persp){
2154                         vec[0]= (2.0f*(mx+dmx)/curarea->winx);
2155                         vec[1]= (2.0f*(my+dmy)/curarea->winy);
2156                         vec[2]= -1.0f;
2157                         vec[3]= 1.0f;
2158
2159                         Mat4MulVec4fl(G.vd->persinv, vec);
2160                         VecMulf(vec, 1.0f/vec[3]);
2161
2162                         VECCOPY(co1, G.vd->viewinv[3]);
2163                         VECSUB(vec, vec, co1);
2164                         Normalize(vec);
2165
2166                         VECADDFAC(co1, G.vd->viewinv[3], vec, G.vd->near);
2167                         VECADDFAC(co2, G.vd->viewinv[3], vec, G.vd->far);
2168                 }
2169                 else {
2170                         vec[0] = 2.0f*(mx+dmx)/curarea->winx;
2171                         vec[1] = 2.0f*(my+dmy)/curarea->winy;
2172                         vec[2] = 0.0f;
2173                         vec[3] = 1.0f;
2174
2175                         Mat4MulVec4fl(G.vd->persinv,vec);
2176
2177                         VECADDFAC(co1,vec,G.vd->viewinv[2],1000.0f);
2178                         VECADDFAC(co2,vec,G.vd->viewinv[2],-1000.0f);
2179                 }
2180
2181                 Mat4MulVecfl(imat,co1);
2182                 Mat4MulVecfl(imat,co2);
2183                 min_d=2.0;
2184                 
2185                 /* warning, returns the derived mesh face */
2186 #if EXPERIMENTAL_DEFORM_ONLY_PAINTING
2187                 if(psys_intersect_dm(ob,dm,0,co1,co2,&min_d,&add_pars[n].num,add_pars[n].fuv,0,0,0,0)) {
2188                         add_pars[n].num_dmcache= psys_particle_dm_face_lookup(ob,psmd->dm,add_pars[n].num,add_pars[n].fuv,NULL);
2189                         n++;
2190                 }
2191 #else
2192 #if 0
2193                 if (psmd->dm->deformedOnly) {
2194                         if(psys_intersect_dm(ob,psmd->dm,0,co1,co2,&min_d,&add_pars[n].num,add_pars[n].fuv,0,0,0,0)){
2195                                 n++;
2196                         }
2197                 } else {
2198                         /* we need to test against the cage mesh, because 1) its faster and 2) then we can avoid converting the fuv back which is not simple */
2199                         if(psys_intersect_dm(ob,psmd->dm,0,co1,co2,&min_d,&add_pars[n].num,add_pars[n].fuv,0,0,0,0)){
2200                                 MFace *mface;
2201                                 float fuv_mod[3] = {0.0, 0.0, 0.0};
2202                                 OrigSpaceFace *osface;
2203                                 
2204                                 mface= psmd->dm->getFaceData(psmd->dm,add_pars[n].num,CD_MFACE);
2205                                 osface= psmd->dm->getFaceData(psmd->dm, add_pars[n].num, CD_ORIGSPACE);
2206                                 
2207                                 add_pars[n].fuv[2]=0.0;
2208                                 
2209                                 /* use the original index for num and the derived index for num_dmcache */
2210                                 add_pars[n].num_dmcache = add_pars[n].num;
2211                                 add_pars[n].num = *(int *)psmd->dm->getFaceData(psmd->dm, add_pars[n].num, CD_ORIGINDEX);
2212                                 
2213                                 /* This is totally unaceptable code (fakeing mesh dara) but changing the target function isnt really nice either, do this temporarily */
2214                                 if (1) { /* Evilness*/
2215                                         MFace mface_fake;
2216                                         MVert mvert_fake[4];
2217                                         //int test1,test2;
2218                                         //test1 = add_pars[n].num_dmcache;
2219                                         //test2 = add_pars[n].num;
2220                                         
2221                                         mvert_fake[0].co[2] = mvert_fake[1].co[2] = mvert_fake[2].co[2] = mvert_fake[3].co[2] = 0.0;
2222                                         
2223                                         mface_fake.v1 = 0;
2224                                         mface_fake.v2 = 1;
2225                                         mface_fake.v3 = 2;
2226                                         
2227                                         if (mface->v4) {
2228                                                 mface_fake.v4 = 3;
2229                                         } else {
2230                                                 mface_fake.v4 = 0;
2231                                         }
2232                                         
2233                                         Vec2Copyf(mvert_fake[0].co, osface->uv[0]);
2234                                         Vec2Copyf(mvert_fake[1].co, osface->uv[1]);
2235                                         Vec2Copyf(mvert_fake[2].co, osface->uv[2]);
2236                                         Vec2Copyf(mvert_fake[3].co, osface->uv[3]);
2237                                         //printf("before %f %f %i %i\n", add_pars[n].fuv[0], add_pars[n].fuv[1], test1, test2);
2238                                         psys_interpolate_face(&mvert_fake, &mface_fake, NULL, &add_pars[n].fuv, &fuv_mod, NULL, NULL, NULL);
2239                                         
2240                                         /* Apply as the UV */
2241                                         Vec2Copyf(add_pars[n].fuv, fuv_mod);
2242                                         //printf("after %f %f\n", add_pars[n].fuv[0], add_pars[n].fuv[1]);
2243                                 }
2244                                 /* Make a fake face, for calculating the derived face's fuv on the original face */
2245                                 //PointInFace2DUV(mface->v4, osface->uv[0], osface->uv[1], osface->uv[2], osface->uv[3], add_pars[n].fuv, fuv_mod);
2246                                 //Vec2Copyf(add_pars[n].fuv, fuv_mod);
2247                                 
2248                                 n++;
2249                         }
2250                 }
2251 #endif
2252 #endif
2253         }
2254         if(n){
2255                 int newtotpart=totpart+n;
2256                 float hairmat[4][4], cur_co[3];
2257                 KDTree *tree=0;
2258                 ParticleData *pa, *new_pars = MEM_callocN(newtotpart*sizeof(ParticleData),"ParticleData new");
2259                 ParticleEditKey *ekey, **key, **new_keys = MEM_callocN(newtotpart*sizeof(ParticleEditKey *),"ParticleEditKey array new");
2260                 HairKey *hkey;
2261
2262                 /* save existing elements */
2263                 memcpy(new_pars, psys->particles, totpart * sizeof(ParticleData));
2264                 memcpy(new_keys, edit->keys, totpart * sizeof(ParticleEditKey*));
2265
2266                 /* change old arrays to new ones */
2267                 if(psys->particles) MEM_freeN(psys->particles);
2268                 psys->particles = new_pars;
2269
2270                 if(edit->keys) MEM_freeN(edit->keys);
2271                 edit->keys = new_keys;
2272
2273                 if(edit->mirror_cache) {
2274                         MEM_freeN(edit->mirror_cache);
2275                         edit->mirror_cache = NULL;
2276                 }
2277
2278                 /* create tree for interpolation */
2279                 if(pset->flag & PE_INTERPOLATE_ADDED && psys->totpart){
2280                         tree=BLI_kdtree_new(psys->totpart);
2281                         
2282                         for(i=0, pa=psys->particles; i<totpart; i++, pa++) {
2283                                 psys_particle_on_dm(ob,psmd->dm,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,cur_co,0,0,0,0,0);
2284                                 BLI_kdtree_insert(tree, i, cur_co, NULL);
2285                         }
2286
2287                         BLI_kdtree_balance(tree);
2288                 }
2289
2290                 psys->totpart = newtotpart;
2291
2292                 /* create new elements */
2293                 pa = psys->particles + totpart;
2294                 key = edit->keys + totpart;
2295
2296                 for(i=totpart; i<newtotpart; i++, pa++, key++){
2297                         memcpy(pa, add_pars + i - totpart, sizeof(ParticleData));
2298                         pa->hair = MEM_callocN(pset->totaddkey * sizeof(HairKey), "BakeKey key add");
2299                         ekey = *key = MEM_callocN(pset->totaddkey * sizeof(ParticleEditKey), "ParticleEditKey add");
2300                         pa->totkey = pset->totaddkey;
2301
2302                         for(k=0, hkey=pa->hair; k<pa->totkey; k++, hkey++, ekey++) {
2303                                 ekey->co = hkey->co;
2304                                 ekey->time = &hkey->time;
2305                         }
2306                         
2307                         initialize_particle(pa,i,ob,psys,psmd);
2308                         reset_particle(pa,psys,psmd,ob,0.0,1.0,0,0,0);
2309                         pa->flag |= PARS_EDIT_RECALC;
2310                         if(pset->flag & PE_X_MIRROR)
2311                                 pa->flag |= PARS_TAG; /* signal for duplicate */
2312                         
2313                         framestep = pa->lifetime/(float)(pset->totaddkey-1);
2314
2315                         if(tree){
2316                                 HairKey *hkey;
2317                                 ParticleKey key[3];
2318                                 KDTreeNearest ptn[3];
2319                                 int w, maxw;
2320                                 float maxd, mind, dd, totw=0.0, weight[3];
2321
2322                                 psys_particle_on_dm(ob,psmd->dm,psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co1,0,0,0,0,0);
2323                                 maxw = BLI_kdtree_find_n_nearest(tree,3,co1,NULL,ptn);
2324
2325                                 maxd = ptn[maxw-1].dist;
2326                                 mind = ptn[0].dist;
2327                                 dd = maxd - mind;
2328                                 
2329                                 for(w=0; w<maxw; w++){
2330                                         weight[w] = (float)pow(2.0, (double)(-6.0f * ptn[w].dist / maxd));
2331                                         totw += weight[w];
2332                                 }
2333                                 for(;w<3; w++){
2334                                         weight[w] = 0.0f;
2335                                 }
2336
2337                                 for(w=0; w<maxw; w++)
2338                                         weight[w] /= totw;
2339
2340                                 for(k=0; k<pset->totaddkey; k++) {
2341                                         hkey = pa->hair + k;
2342                                         hkey->time = pa->time + k * framestep;
2343
2344                                         key[0].time = hkey->time/ 100.0f;
2345                                         psys_get_particle_on_path(ob, psys, ptn[0].index, key, 0);
2346                                         VecMulf(key[0].co, weight[0]);
2347                                         
2348                                         if(maxw>1) {
2349                                                 key[1].time = key[0].time;
2350                                                 psys_get_particle_on_path(ob, psys, ptn[1].index, key + 1, 0);
2351                                                 VecMulf(key[1].co, weight[1]);
2352                                                 VECADD(key[0].co, key[0].co, key[1].co);
2353
2354                                                 if(maxw>2) {                                            
2355                                                         key[2].time = key[0].time;
2356                                                         psys_get_particle_on_path(ob, psys, ptn[2].index, key + 2, 0);
2357                                                         VecMulf(key[2].co, weight[2]);
2358                                                         VECADD(key[0].co, key[0].co, key[2].co);
2359                                                 }
2360                                         }
2361
2362                                         if(k==0)
2363                                                 VECSUB(co1, pa->state.co, key[0].co);
2364
2365                                         VECADD(pa->hair[k].co, key[0].co, co1);
2366
2367                                         pa->hair[k].time = key[0].time;
2368                                 }
2369                         }
2370                         else{
2371                                 for(k=0, hkey=pa->hair; k<pset->totaddkey; k++, hkey++) {
2372                                         VECADDFAC(hkey->co, pa->state.co, pa->state.vel, k * framestep * timestep);
2373                                         pa->hair[k].time += k * framestep;
2374                                 }
2375                         }
2376                         for(k=0, hkey=pa->hair; k<pset->totaddkey; k++, hkey++) {
2377                                 psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, pa, hairmat);
2378                                 Mat4Invert(imat,hairmat);
2379                                 Mat4MulVecfl(imat, hkey->co);
2380                         }
2381                 }
2382                 edit->totkeys = psys_count_keys(psys);
2383
2384                 if(tree)
2385                         BLI_kdtree_free(tree);
2386         }
2387         if(add_pars)
2388                 MEM_freeN(add_pars);
2389         
2390 /* painting onto the deformed mesh, could be an option? */
2391 #if EXPERIMENTAL_DEFORM_ONLY_PAINTING
2392         if (!psmd->dm->deformedOnly)
2393                 dm->release(dm);
2394 #endif
2395 }
2396 static void brush_weight(ParticleSystem *psys, float mat[][4], float imat[][4], int pa_index, int key_index, void *userData)
2397 {
2398         struct { Object *ob; short *mval; float rad; rcti* rect; float dist; float weightfac;} *data = userData;
2399         ParticleData *pa;
2400
2401         /* roots have full weight allways */
2402         if(key_index) {
2403                 pa= &psys->particles[pa_index];
2404                 pa->hair[key_index].weight = data->weightfac;
2405                 pa->flag |= PARS_EDIT_RECALC;
2406         }
2407 }
2408
2409 /* returns 0 if no brush was used */
2410 int PE_brush_particles(void)
2411 {
2412         Object *ob = OBACT;
2413         ParticleSystem *psys = PE_get_current(ob);
2414         ParticleEdit *edit;
2415         ParticleEditSettings *pset = PE_settings();
2416         ParticleSystemModifierData *psmd;
2417         ParticleBrushData *brush;
2418         float vec1[3], vec2[3];
2419         short mval[2], mvalo[2], firsttime = 1, dx, dy;
2420         int selected = 0, flip, removed = 0;
2421
2422         if(!PE_can_edit(psys)) return 0;
2423
2424         edit = psys->edit;
2425         psmd= psys_get_modifier(ob, psys);
2426
2427         flip= (get_qual() == LR_SHIFTKEY);
2428
2429         if(pset->brushtype<0) return 0;
2430         brush= &pset->brush[pset->brushtype];
2431
2432         initgrabz(ob->obmat[3][0], ob->obmat[3][1], ob->obmat[3][2]);
2433
2434         getmouseco_areawin(mvalo);
2435
2436         mval[0] = mvalo[0]; mval[1] = mvalo[1];
2437
2438         while(get_mbut() & L_MOUSE){
2439                 bglFlush();
2440                 glReadBuffer(GL_BACK);
2441                 glDrawBuffer(GL_BACK);
2442                 persp(PERSP_VIEW);
2443
2444                 dx=mval[0]-mvalo[0];
2445                 dy=mval[1]-mvalo[1];
2446                 if(((pset->brushtype == PE_BRUSH_ADD) ?
2447                         (sqrt(dx * dx + dy * dy) > pset->brush[PE_BRUSH_ADD].step) : (dx != 0 || dy != 0))
2448                         || firsttime){
2449                         firsttime = 0;
2450
2451                         selected = (short)count_selected_keys(psys);
2452
2453                         switch(pset->brushtype){
2454                                 case PE_BRUSH_COMB:
2455                                 {
2456                                         struct { Object *ob; short *mval; float rad; rcti* rect; float dist; float *dvec; float combfac;} data;
2457
2458                                         data.ob = ob;
2459                                         data.mval = mval;
2460                                         data.rad = (float)brush->size;
2461
2462                                         data.combfac = (float)(brush->strength - 50) / 50.0f;
2463                                         if(data.combfac < 0.0f)
2464                                                 data.combfac = 1.0f - 9.0f * data.combfac;
2465                                         else
2466                                                 data.combfac = 1.0f - data.combfac;
2467
2468                                         Mat4Invert(ob->imat, ob->obmat);
2469
2470                                         window_to_3d(vec1, mvalo[0], mvalo[1]);
2471                                         window_to_3d(vec2, mval[0], mval[1]);
2472                                         VECSUB(vec1, vec2, vec1);
2473                                         data.dvec = vec1;
2474
2475                                         foreach_mouse_hit_key(selected, psys,brush_comb, &data);
2476                                         break;
2477                                 }
2478                                 case PE_BRUSH_CUT:
2479                                 {
2480                                         struct { short *mval; float rad; rcti* rect; int selected; float cutfac;} data;
2481
2482                                         data.mval = mval;
2483                                         data.rad = (float)brush->size;
2484
2485                                         data.selected = selected;
2486
2487                                         data.cutfac = (float)(brush->strength / 100.0f);
2488
2489                                         if(selected)
2490                                                 foreach_selected_element(psys, brush_cut, &data);
2491                                         else
2492                                                 PE_foreach_element(psys, brush_cut, &data);
2493
2494                                         removed= remove_tagged_elements(ob, psys);
2495                                         if(pset->flag & PE_KEEP_LENGTHS)
2496                                                 recalc_lengths(psys);
2497                                         break;
2498                                 }
2499                                 case PE_BRUSH_LENGTH:
2500                                 {
2501                                         struct { short *mval; float rad; rcti* rect; float dist; float growfac; } data;
2502                                         
2503                                         data.mval = mval;
2504                                         
2505                                         data.rad = (float)brush->size;
2506                                         data.growfac = (float)brush->strength / 5000.0f;
2507
2508                                         if(brush->invert ^ flip)
2509                                                 data.growfac = 1.0f - data.growfac;
2510                                         else
2511                                                 data.growfac = 1.0f + data.growfac;
2512
2513                                         foreach_mouse_hit_element(selected, psys, brush_length, &data);
2514
2515                                         if(pset->flag & PE_KEEP_LENGTHS)
2516                                                 recalc_lengths(psys);
2517                                         break;
2518                                 }
2519                                 case PE_BRUSH_PUFF:
2520                                 {
2521                                         struct { short *mval; float rad; rcti* rect; float dist;
2522                                                 Object *ob; DerivedMesh *dm; float pufffac; int invert; } data;
2523
2524                                         data.ob = ob;
2525                                         data.dm = psmd->dm;
2526                                         data.mval = mval;
2527                                         data.rad = (float)brush->size;
2528
2529                                         data.pufffac = (float)(brush->strength - 50) / 50.0f;
2530                                         if(data.pufffac < 0.0f)
2531                                                 data.pufffac = 1.0f - 9.0f * data.pufffac;
2532                                         else
2533                                                 data.pufffac = 1.0f - data.pufffac;
2534
2535                                         data.invert= (brush->invert ^ flip);
2536                                         Mat4Invert(ob->imat, ob->obmat);
2537
2538                                         foreach_mouse_hit_element(selected, psys, brush_puff, &data);
2539                                         break;
2540                                 }
2541                                 case PE_BRUSH_ADD:
2542                                         if(psys->part->from==PART_FROM_FACE){
2543                                                 brush_add(ob, psys, mval, brush->strength);
2544                                                 if(pset->flag & PE_KEEP_LENGTHS)
2545                                                         recalc_lengths(psys);
2546                                         }
2547                                         break;
2548                                 case PE_BRUSH_WEIGHT:
2549                                 {
2550                                         struct { Object *ob; short *mval; float rad; rcti* rect; float dist; float weightfac;} data;
2551
2552                                         data.ob = ob;
2553                                         data.mval = mval;
2554                                         data.rad = (float)brush->size;
2555
2556                                         data.weightfac = (float)(brush->strength / 100.0f);
2557
2558                                         foreach_mouse_hit_key(selected, psys, brush_weight, &data);
2559                                         break;
2560                                 }
2561                                 case PE_BRUSH_SMOOTH:
2562                                 {
2563                                         struct { Object *ob; short *mval; float rad; rcti* rect; float dist; float vec[3]; int tot; float smoothfac;} data;
2564
2565                                         data.ob = ob;
2566                                         data.mval = mval;
2567                                         data.rad = (float)brush->size;
2568
2569                                         data.vec[0] = data.vec[1] = data.vec[2] = 0.0f;
2570                                         data.tot = 0;
2571
2572                                         data.smoothfac = (float)(brush->strength / 100.0f);
2573
2574                                         Mat4Invert(ob->imat, ob->obmat);
2575
2576                                         foreach_mouse_hit_key(selected, psys, brush_smooth_get, &data);
2577
2578                                         if(data.tot){
2579                                                 VecMulf(data.vec, 1.0f / (float)data.tot);
2580                                                 foreach_mouse_hit_key(selected, psys, brush_smooth_do, &data);
2581                                         }
2582
2583                                         break;
2584                                 }
2585                         }
2586                         if((pset->flag & PE_KEEP_LENGTHS)==0)
2587                                 recalc_lengths(psys);
2588
2589                         if(pset->brushtype == PE_BRUSH_ADD || removed) {
2590                                 if(pset->brushtype == PE_BRUSH_ADD && (pset->flag & PE_X_MIRROR))
2591                                         PE_mirror_x(1);
2592                                 PE_recalc_world_cos(ob,psys);
2593                                 psys_free_path_cache(psys);
2594                                 DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
2595                         }
2596                         else
2597                                 PE_update_object(ob, 1);
2598                         
2599                         mvalo[0] = mval[0];
2600                         mvalo[1] = mval[1];
2601                 }
2602
2603                 force_draw(0);
2604
2605                 PIL_sleep_ms(10);
2606                 
2607                 getmouseco_areawin(mval);
2608         }
2609         allqueue(REDRAWVIEW3D, 1);
2610
2611         BIF_undo_push("Brush edit particles");
2612
2613         return 1;
2614 }
2615 static void set_delete_particle(ParticleSystem *psys, int index, void *userData)
2616 {
2617         psys->particles[index].flag |= PARS_TAG;
2618 }
2619 static void set_delete_particle_key(ParticleSystem *psys, int pa_index, int key_index, void *userData)
2620 {
2621         psys->edit->keys[pa_index][key_index].flag |= PEK_TAG;
2622 }
2623 void PE_delete_particle(void)
2624 {
2625         Object *ob=OBACT;
2626         ParticleSystem *psys = PE_get_current(ob);
2627         short event=0;
2628
2629         if(!PE_can_edit(psys)) return;
2630
2631         event= pupmenu("Erase %t|Particle%x2|Key%x1");
2632
2633         if(event<1) return;
2634
2635         if(event==1){
2636                 foreach_selected_key(psys, set_delete_particle_key, 0);
2637                 remove_tagged_keys(ob, psys);
2638                 recalc_lengths(psys);
2639         }
2640         else if(event==2){
2641                 foreach_selected_element(psys, set_delete_particle, 0);
2642                 remove_tagged_elements(ob, psys);
2643                 recalc_lengths(psys);
2644         }
2645
2646         DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
2647         allqueue(REDRAWVIEW3D, 1);
2648         BIF_undo_push("Delete particles/keys");
2649 }
2650
2651 void PE_mirror_x(int tagged)
2652 {
2653         Object *ob=OBACT;
2654         Mesh *me= (Mesh*)(ob->data);
2655         ParticleSystemModifierData *psmd;
2656         ParticleSystem *psys = PE_get_current(ob);
2657         ParticleEdit *edit;
2658         ParticleData *pa, *newpa, *new_pars;
2659         ParticleEditKey *ekey, **newkey, **key, **new_keys;
2660         HairKey *hkey;
2661         int *mirrorfaces;
2662         int i, k, rotation, totpart, newtotpart;
2663
2664         if(!PE_can_edit(psys)) return;
2665
2666         edit= psys->edit;
2667         psmd= psys_get_modifier(ob, psys);
2668
2669         mirrorfaces= mesh_get_x_mirror_faces(ob);
2670
2671         if(!edit->mirror_cache)
2672                 PE_update_mirror_cache(ob, psys);
2673
2674         totpart= psys->totpart;
2675         newtotpart= psys->totpart;
2676         LOOP_PARTICLES(i,pa) {
2677                 if(pa->flag&PARS_HIDE) continue;
2678
2679                 if(!tagged) {
2680                         if(particle_is_selected(psys, pa)) {
2681                                 if(edit->mirror_cache[i] != -1) {
2682                                         /* already has a mirror, don't need to duplicate */
2683                                         PE_mirror_particle(ob, psmd->dm, psys, pa, NULL);
2684                                         continue;
2685                                 }
2686                                 else
2687                                         pa->flag |= PARS_TAG;
2688                         }
2689                 }
2690
2691                 if((pa->flag & PARS_TAG) && mirrorfaces[pa->num*2] != -1)
2692                         newtotpart++;
2693         }
2694
2695         if(newtotpart != psys->totpart) {
2696                 /* allocate new arrays and copy existing */
2697                 new_pars= MEM_callocN(newtotpart*sizeof(ParticleData), "ParticleData new");
2698                 new_keys= MEM_callocN(newtotpart*sizeof(ParticleEditKey*), "ParticleEditKey new");
2699
2700                 memcpy(new_pars, psys->particles, totpart*sizeof(ParticleData));
2701                 memcpy(new_keys, edit->keys, totpart*sizeof(ParticleEditKey*));
2702
2703                 if(psys->particles) MEM_freeN(psys->particles);
2704                 psys->particles= new_pars;
2705
2706                 if(edit->keys) MEM_freeN(edit->keys);
2707                 edit->keys= new_keys;
2708
2709                 if(edit->mirror_cache) {
2710                         MEM_freeN(edit->mirror_cache);
2711                         edit->mirror_cache= NULL;
2712                 }
2713
2714                 psys->totpart= newtotpart;
2715                         
2716                 /* create new elements */
2717                 pa= psys->particles;
2718                 newpa= psys->particles + totpart;
2719                 key= edit->keys;
2720                 newkey= edit->keys + totpart;
2721
2722                 for(i=0; i<totpart; i++, pa++, key++) {
2723                         if(pa->flag&PARS_HIDE) continue;
2724
2725                         if(!(pa->flag & PARS_TAG) || mirrorfaces[pa->num*2] == -1)
2726                                 continue;
2727
2728                         /* duplicate */
2729                         *newpa= *pa;
2730                         if(pa->hair) newpa->hair= MEM_dupallocN(pa->hair);
2731                         if(pa->keys) newpa->keys= MEM_dupallocN(pa->keys);
2732                         if(*key) *newkey= MEM_dupallocN(*key);
2733
2734                         /* rotate weights according to vertex index rotation */
2735                         rotation= mirrorfaces[pa->num*2+1];
2736                         newpa->fuv[0]= pa->fuv[2];
2737                         newpa->fuv[1]= pa->fuv[1];
2738                         newpa->fuv[2]= pa->fuv[0];
2739                         newpa->fuv[3]= pa->fuv[3];
2740                         while(rotation-- > 0)
2741                                 if(me->mface[pa->num].v4)
2742                                         SHIFT4(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2], newpa->fuv[3])
2743                                 else
2744                                         SHIFT3(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2])
2745
2746                         /* assign face inddex */
2747                         newpa->num= mirrorfaces[pa->num*2];
2748                         newpa->num_dmcache= psys_particle_dm_face_lookup(ob,psmd->dm,newpa->num,newpa->fuv, NULL);
2749
2750                         /* update edit key pointers */
2751                         ekey= *newkey;
2752                         for(k=0, hkey=newpa->hair; k<newpa->totkey; k++, hkey++, ekey++) {
2753                                 ekey->co= hkey->co;
2754                                 ekey->time= &hkey->time;
2755                         }
2756
2757                         /* map key positions as mirror over x axis */
2758                         PE_mirror_particle(ob, psmd->dm, psys, pa, newpa);
2759
2760                         newpa++;
2761                         newkey++;
2762                 }
2763
2764                 edit->totkeys = psys_count_keys(psys);
2765         }
2766
2767         for(pa=psys->particles, i=0; i<psys->totpart; i++, pa++)
2768                 pa->flag &= ~PARS_TAG;
2769
2770         MEM_freeN(mirrorfaces);
2771
2772         if(!tagged) {
2773                 PE_recalc_world_cos(ob,psys);
2774                 DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
2775                 allqueue(REDRAWVIEW3D, 1);
2776                 BIF_undo_push("Mirror particles");
2777         }
2778 }
2779
2780 void PE_selectbrush_menu(void)
2781 {
2782         ParticleEditSettings *pset= PE_settings();
2783         int val;
2784         
2785         pupmenu_set_active(pset->brushtype);
2786         
2787         val= pupmenu("Select Brush%t|None %x0|Comb %x1|Smooth %x7|Weight %x6|Add %x5|Length %x3|Puff %x4|Cut %x2");
2788
2789         if(val>=0) {
2790                 pset->brushtype= val-1;
2791                 allqueue(REDRAWVIEW3D, 1);
2792         }
2793 }
2794
2795 /************************************************/
2796 /*                      Particle Edit Undo                                      */
2797 /************************************************/
2798 static void free_ParticleUndo(ParticleUndo *undo)
2799 {
2800         ParticleData *pa;
2801         int i;
2802
2803         for(i=0, pa=undo->particles; i<undo->totpart; i++, pa++) {
2804                 if(pa->hair)
2805                         MEM_freeN(pa->hair);
2806                 if(undo->keys[i])
2807                         MEM_freeN(undo->keys[i]);
2808         }
2809         if(undo->keys)
2810                 MEM_freeN(undo->keys);
2811
2812         if(undo->particles)
2813                 MEM_freeN(undo->particles);
2814
2815         //if(undo->emitter_cosnos)
2816         //      MEM_freeN(undo->emitter_cosnos);
2817 }
2818 static void make_ParticleUndo(ParticleSystem *psys, ParticleUndo *undo)
2819 {
2820         ParticleData *pa,*upa;
2821         int i;
2822
2823         undo->totpart = psys->totpart;
2824         undo->totkeys = psys->edit->totkeys;
2825
2826         upa = undo->particles = MEM_dupallocN(psys->particles);
2827         undo->keys = MEM_dupallocN(psys->edit->keys);
2828         
2829         for(i=0, pa=psys->particles; i<undo->totpart; i++, pa++, upa++) {
2830                 upa->hair = MEM_dupallocN(pa->hair);
2831                 undo->keys[i] = MEM_dupallocN(psys->edit->keys[i]);
2832                 /* no need to update edit key->co & key->time pointers here */
2833         }
2834 }
2835 static void get_ParticleUndo(ParticleSystem *psys, ParticleUndo *undo)
2836 {
2837         ParticleData *pa, *upa;
2838         ParticleEditKey *key;
2839         HairKey *hkey;
2840         int i, k, totpart = psys->totpart;
2841
2842         LOOP_PARTICLES(i,pa) {
2843                 if(pa->hair)
2844                         MEM_freeN(pa->hair);
2845
2846                 if(psys->edit->keys[i])
2847                         MEM_freeN(psys->edit->keys[i]);
2848         }
2849         if(psys->particles)
2850                 MEM_freeN(psys->particles);
2851         if(psys->edit->keys)
2852                 MEM_freeN(psys->edit->keys);
2853         if(psys->edit->mirror_cache) {
2854                 MEM_freeN(psys->edit->mirror_cache);
2855                 psys->edit->mirror_cache= NULL;
2856         }
2857
2858         pa = psys->particles = MEM_dupallocN(undo->particles);
2859         psys->edit->keys = MEM_dupallocN(undo->keys);
2860
2861         for(i=0,upa=undo->particles; i<undo->totpart; i++, upa++, pa++){
2862                 hkey = pa->hair = MEM_dupallocN(upa->hair);
2863                 key = psys->edit->keys[i] = MEM_dupallocN(undo->keys[i]);
2864                 for(k=0; k<pa->totkey; k++, hkey++, key++) {
2865                         key->co = hkey->co;
2866                         key->time = &hkey->time;
2867                 }
2868         }
2869
2870         psys->totpart = undo->totpart;
2871         psys->edit->totkeys = undo->totkeys;
2872 }
2873 void PE_undo_push(char *str)
2874 {
2875         ParticleSystem *psys = PE_get_current(OBACT);
2876         ParticleEdit *edit = 0;
2877         ParticleUndo *undo;
2878         int nr;
2879
2880         if(!PE_can_edit(psys)) return;
2881         edit = psys->edit;
2882
2883         /* remove all undos after (also when curundo==NULL) */
2884         while(edit->undo.last != edit->curundo) {
2885                 undo= edit->undo.last;
2886                 BLI_remlink(&edit->undo, undo);
2887                 free_ParticleUndo(undo);
2888                 MEM_freeN(undo);
2889         }
2890
2891         /* make new */
2892         edit->curundo= undo= MEM_callocN(sizeof(ParticleUndo), "particle undo file");
2893         strncpy(undo->name, str, 64-1);
2894         BLI_addtail(&edit->undo, undo);
2895         
2896         /* and limit amount to the maximum */
2897         nr= 0;
2898         undo= edit->undo.last;
2899         while(undo) {
2900                 nr++;
2901                 if(nr==U.undosteps) break;
2902                 undo= undo->prev;
2903         }
2904         if(undo) {
2905                 while(edit->undo.first!=undo) {
2906                         ParticleUndo *first= edit->undo.first;
2907                         BLI_remlink(&edit->undo, first);
2908                         free_ParticleUndo(first);
2909                         MEM_freeN(first);
2910                 }
2911         }
2912
2913         /* copy  */
2914         make_ParticleUndo(psys,edit->curundo);
2915 }
2916 void PE_undo_step(int step)
2917 {       
2918         ParticleSystem *psys = PE_get_current(OBACT);
2919         ParticleEdit *edit = 0;
2920
2921         if(!PE_can_edit(psys)) return;
2922         edit=psys->edit;
2923
2924         if(step==0) {
2925                 get_ParticleUndo(psys,edit->curundo);
2926         }
2927         else if(step==1) {
2928                 
2929                 if(edit->curundo==NULL || edit->curundo->prev==NULL) error("No more steps to undo");
2930                 else {
2931                         if(G.f & G_DEBUG) printf("undo %s\n", edit->curundo->name);
2932                         edit->curundo= edit->curundo->prev;
2933                         get_ParticleUndo(psys, edit->curundo);
2934                 }
2935         }
2936         else {
2937                 /* curundo has to remain current situation! */
2938                 
2939                 if(edit->curundo==NULL || edit->curundo->next==NULL) error("No more steps to redo");
2940                 else {
2941                         get_ParticleUndo(psys, edit->curundo->next);
2942                         edit->curundo= edit->curundo->next;
2943                         if(G.f & G_DEBUG) printf("redo %s\n", edit->curundo->name);
2944                 }
2945         }
2946
2947         DAG_object_flush_update(G.scene, OBACT, OB_RECALC_DATA);
2948         allqueue(REDRAWVIEW3D, 1);
2949         allqueue(REDRAWBUTSEDIT, 0);
2950         allqueue(REDRAWIMAGE, 0);
2951 }
2952 static void ParticleUndo_number(ParticleEdit *edit, int nr)
2953 {
2954         ParticleUndo *undo;
2955         int a=1;
2956         
2957         for(undo= edit->undo.first; undo; undo= undo->next, a++) {
2958                 if(a==nr) break;
2959         }
2960         edit->curundo= undo;
2961         PE_undo_step(0);
2962 }
2963 static void ParticleUndo_clear(ParticleSystem *psys)
2964 {
2965         ParticleUndo *undo;
2966         ParticleEdit *edit;
2967
2968         if(psys==0) return;
2969
2970         edit = psys->edit;
2971
2972         if(edit==0) return;
2973         
2974         undo= edit->undo.first;
2975         while(undo) {
2976                 free_ParticleUndo(undo);
2977                 undo= undo->next;
2978         }
2979         BLI_freelistN(&edit->undo);
2980         edit->curundo= NULL;
2981 }
2982 void PE_undo(void)
2983 {
2984         PE_undo_step(1);
2985 }
2986 void PE_redo(void)
2987 {
2988         PE_undo_step(-1);
2989 }
2990 void PE_undo_menu(void)
2991 {
2992         ParticleSystem *psys = PE_get_current(OBACT);
2993         ParticleEdit *edit = 0;
2994         ParticleUndo *undo;
2995         DynStr *ds;
2996         short event;
2997         char *menu;
2998
2999         if(!PE_can_edit(psys)) return;
3000         edit = psys->edit;
3001         
3002         ds= BLI_dynstr_new();
3003
3004         BLI_dynstr_append(ds, "Particlemode Undo History %t");
3005         
3006         for(undo= edit->undo.first; undo; undo= undo->next) {
3007                 BLI_dynstr_append(ds, "|");
3008                 BLI_dynstr_append(ds, undo->name);
3009         }
3010         
3011         menu= BLI_dynstr_get_cstring(ds);
3012         BLI_dynstr_free(ds);
3013         
3014         event= pupmenu_col(menu, 20);
3015         MEM_freeN(menu);
3016         
3017         if(event>0) ParticleUndo_number(edit,event);
3018 }
3019
3020 void PE_get_colors(char sel[4], char nosel[4])
3021 {
3022         BIF_GetThemeColor3ubv(TH_EDGE_SELECT, sel);
3023         BIF_GetThemeColor3ubv(TH_WIRE, nosel);
3024 }
3025
3026 int PE_minmax(float *min, float *max)
3027 {
3028         Object *ob = OBACT;
3029         ParticleSystem *psys = PE_get_current(ob);
3030         ParticleSystemModifierData *psmd;
3031         ParticleData *pa;
3032         ParticleEditKey *key;
3033         float co[3], mat[4][4];
3034         int i, k, totpart, ok = 0;
3035
3036         if(!PE_can_edit(psys)) return ok;
3037         
3038         psmd= psys_get_modifier(ob, psys);
3039         totpart= psys->totpart;
3040
3041         LOOP_PARTICLES(i,pa){
3042                 if(pa->flag&PARS_HIDE) continue;
3043
3044                 psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, pa, mat);
3045
3046                 LOOP_KEYS(k,key){
3047                         if(key->flag&PEK_SELECT) {
3048                                 VECCOPY(co, key->co);
3049                                 Mat4MulVecfl(mat, co);
3050                                 DO_MINMAX(co, min, max);                
3051                                 ok= 1;
3052                         }
3053                 }
3054         }
3055
3056         if(!ok) {
3057                 minmax_object(ob, min, max);
3058                 ok= 1;
3059         }
3060   
3061         return ok;
3062 }
3063