merge from trunk at r31523
[blender.git] / source / blender / blenkernel / intern / boids.c
1 /* boids.c
2  *
3  *
4  * $Id$
5  *
6  * ***** BEGIN GPL 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.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  *
22  * The Original Code is Copyright (C) 2009 by Janne Karhu.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include <string.h>
33 #include <math.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_object_force.h"
38 #include "DNA_scene_types.h"
39
40 #include "BLI_rand.h"
41 #include "BLI_math.h"
42 #include "BLI_blenlib.h"
43 #include "BLI_kdtree.h"
44 #include "BKE_collision.h"
45 #include "BKE_effect.h"
46 #include "BKE_boids.h"
47 #include "BKE_particle.h"
48 #include "BKE_utildefines.h"
49 #include "BKE_modifier.h"
50
51 #include "RNA_enum_types.h"
52
53 typedef struct BoidValues {
54         float max_speed, max_acc;
55         float max_ave, min_speed;
56         float personal_space, jump_speed;
57 } BoidValues;
58
59 static int apply_boid_rule(BoidBrainData *bbd, BoidRule *rule, BoidValues *val, ParticleData *pa, float fuzziness);
60
61 static int rule_none(BoidRule *rule, BoidBrainData *data, BoidValues *val, ParticleData *pa)
62 {
63         return 0;
64 }
65
66 static int rule_goal_avoid(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
67 {
68         BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid*) rule;
69         BoidSettings *boids = bbd->part->boids;
70         BoidParticle *bpa = pa->boid;
71         EffectedPoint epoint;
72         ListBase *effectors = bbd->sim->psys->effectors;
73         EffectorCache *cur, *eff = NULL;
74         EffectorCache temp_eff;
75         EffectorData efd, cur_efd;
76         float mul = (rule->type == eBoidRuleType_Avoid ? 1.0 : -1.0);
77         float priority = 0.0f, len = 0.0f;
78         int ret = 0;
79
80         pd_point_from_particle(bbd->sim, pa, &pa->state, &epoint);
81
82         /* first find out goal/predator with highest priority */
83         if(effectors) for(cur = effectors->first; cur; cur=cur->next) {
84                 Object *eob = cur->ob;
85                 PartDeflect *pd = cur->pd;
86
87                 if(gabr->ob && (rule->type != eBoidRuleType_Goal || gabr->ob != bpa->ground)) {
88                         if(gabr->ob == eob) {
89                                 /* TODO: effectors with multiple points */
90                                 if(get_effector_data(cur, &efd, &epoint, 0)) {
91                                         if(cur->pd && cur->pd->forcefield == PFIELD_BOID)
92                                                 priority = mul * pd->f_strength * effector_falloff(cur, &efd, &epoint, bbd->part->effector_weights);
93                                         else
94                                                 priority = 1.0;
95
96                                         eff = cur;
97                                 }
98                                 break;
99                         }
100                 }
101                 else if(rule->type == eBoidRuleType_Goal && eob == bpa->ground)
102                         ; /* skip current object */
103                 else if(pd->forcefield == PFIELD_BOID && mul * pd->f_strength > 0.0f && get_effector_data(cur, &cur_efd, &epoint, 0)) {
104                         float temp = mul * pd->f_strength * effector_falloff(cur, &cur_efd, &epoint, bbd->part->effector_weights);
105
106                         if(temp == 0.0f)
107                                 ; /* do nothing */
108                         else if(temp > priority) {
109                                 priority = temp;
110                                 eff = cur;
111                                 efd = cur_efd;
112                                 len = efd.distance;
113                         }
114                         /* choose closest object with same priority */
115                         else if(temp == priority && efd.distance < len) {
116                                 eff = cur;
117                                 efd = cur_efd;
118                                 len = efd.distance;
119                         }
120                 }
121         }
122
123         /* if the object doesn't have effector data we have to fake it */
124         if(eff == NULL && gabr->ob) {
125                 memset(&temp_eff, 0, sizeof(EffectorCache));
126                 temp_eff.ob = gabr->ob;
127                 temp_eff.scene = bbd->sim->scene;
128                 eff = &temp_eff;
129                 get_effector_data(eff, &efd, &epoint, 0);
130                 priority = 1.0f;
131         }
132
133         /* then use that effector */
134         if(priority > (rule->type==eBoidRuleType_Avoid ? gabr->fear_factor : 0.0f)) { /* with avoid, factor is "fear factor" */
135                 Object *eob = eff->ob;
136                 PartDeflect *pd = eff->pd;
137                 float surface = (pd && pd->shape == PFIELD_SHAPE_SURFACE) ? 1.0f : 0.0f;
138
139                 if(gabr->options & BRULE_GOAL_AVOID_PREDICT) {
140                         /* estimate future location of target */
141                         get_effector_data(eff, &efd, &epoint, 1);
142
143                         mul_v3_fl(efd.vel, efd.distance / (val->max_speed * bbd->timestep));
144                         add_v3_v3(efd.loc, efd.vel);
145                         sub_v3_v3v3(efd.vec_to_point, pa->prev_state.co, efd.loc);
146                         efd.distance = len_v3(efd.vec_to_point);
147                 }
148
149                 if(rule->type == eBoidRuleType_Goal && boids->options & BOID_ALLOW_CLIMB && surface!=0.0f) {
150                         if(!bbd->goal_ob || bbd->goal_priority < priority) {
151                                 bbd->goal_ob = eob;
152                                 VECCOPY(bbd->goal_co, efd.loc);
153                                 VECCOPY(bbd->goal_nor, efd.nor);
154                         }
155                 }
156                 else if(rule->type == eBoidRuleType_Avoid && bpa->data.mode == eBoidMode_Climbing &&
157                         priority > 2.0f * gabr->fear_factor) {
158                         /* detach from surface and try to fly away from danger */
159                         negate_v3_v3(efd.vec_to_point, bpa->gravity);
160                 }
161
162                 VECCOPY(bbd->wanted_co, efd.vec_to_point);
163                 mul_v3_fl(bbd->wanted_co, mul);
164
165                 bbd->wanted_speed = val->max_speed * priority;
166
167                 /* with goals factor is approach velocity factor */
168                 if(rule->type == eBoidRuleType_Goal && boids->landing_smoothness > 0.0f) {
169                         float len2 = 2.0f*len_v3(pa->prev_state.vel);
170
171                         surface *= pa->size * boids->height;
172
173                         if(len2 > 0.0f && efd.distance - surface < len2) {
174                                 len2 = (efd.distance - surface)/len2;
175                                 bbd->wanted_speed *= pow(len2, boids->landing_smoothness);
176                         }
177                 }
178
179                 ret = 1;
180         }
181
182         return ret;
183 }
184
185 static int rule_avoid_collision(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
186 {
187         BoidRuleAvoidCollision *acbr = (BoidRuleAvoidCollision*) rule;
188         KDTreeNearest *ptn = NULL;
189         ParticleTarget *pt;
190         BoidParticle *bpa = pa->boid;
191         ColliderCache *coll;
192         float vec[3] = {0.0f, 0.0f, 0.0f}, loc[3] = {0.0f, 0.0f, 0.0f};
193         float co1[3], vel1[3], co2[3], vel2[3];
194         float  len, t, inp, t_min = 2.0f;
195         int n, neighbors = 0, nearest = 0;
196         int ret = 0;
197
198         //check deflector objects first
199         if(acbr->options & BRULE_ACOLL_WITH_DEFLECTORS && bbd->sim->colliders) {
200                 ParticleCollision col;
201                 BVHTreeRayHit hit;
202                 float radius = val->personal_space * pa->size, ray_dir[3];
203
204                 VECCOPY(col.co1, pa->prev_state.co);
205                 add_v3_v3v3(col.co2, pa->prev_state.co, pa->prev_state.vel);
206                 sub_v3_v3v3(ray_dir, col.co2, col.co1);
207                 mul_v3_fl(ray_dir, acbr->look_ahead);
208                 col.t = 0.0f;
209                 hit.index = -1;
210                 hit.dist = col.ray_len = len_v3(ray_dir);
211
212                 /* find out closest deflector object */
213                 for(coll = bbd->sim->colliders->first; coll; coll=coll->next) {
214                         /* don't check with current ground object */
215                         if(coll->ob == bpa->ground)
216                                 continue;
217
218                         col.ob = coll->ob;
219                         col.md = coll->collmd;
220
221                         if(col.md && col.md->bvhtree)
222                                 BLI_bvhtree_ray_cast(col.md->bvhtree, col.co1, ray_dir, radius, &hit, particle_intersect_face, &col);
223                 }
224                 /* then avoid that object */
225                 if(hit.index>=0) {
226                         t = hit.dist/col.ray_len;
227
228                         /* avoid head-on collision */
229                         if(dot_v3v3(col.nor, pa->prev_state.ave) < -0.99) {
230                                 /* don't know why, but uneven range [0.0,1.0] */
231                                 /* works much better than even [-1.0,1.0] */
232                                 bbd->wanted_co[0] = BLI_frand();
233                                 bbd->wanted_co[1] = BLI_frand();
234                                 bbd->wanted_co[2] = BLI_frand();
235                         }
236                         else {
237                                 VECCOPY(bbd->wanted_co, col.nor);
238                         }
239
240                         mul_v3_fl(bbd->wanted_co, (1.0f - t) * val->personal_space * pa->size);
241
242                         bbd->wanted_speed = sqrt(t) * len_v3(pa->prev_state.vel);
243
244                         return 1;
245                 }
246         }
247
248         //check boids in own system
249         if(acbr->options & BRULE_ACOLL_WITH_BOIDS)
250         {
251                 neighbors = BLI_kdtree_range_search(bbd->sim->psys->tree, acbr->look_ahead * len_v3(pa->prev_state.vel), pa->prev_state.co, pa->prev_state.ave, &ptn);
252                 if(neighbors > 1) for(n=1; n<neighbors; n++) {
253                         VECCOPY(co1, pa->prev_state.co);
254                         VECCOPY(vel1, pa->prev_state.vel);
255                         VECCOPY(co2, (bbd->sim->psys->particles + ptn[n].index)->prev_state.co);
256                         VECCOPY(vel2, (bbd->sim->psys->particles + ptn[n].index)->prev_state.vel);
257
258                         sub_v3_v3v3(loc, co1, co2);
259
260                         sub_v3_v3v3(vec, vel1, vel2);
261                         
262                         inp = dot_v3v3(vec,vec);
263
264                         /* velocities not parallel */
265                         if(inp != 0.0f) {
266                                 t = -dot_v3v3(loc, vec)/inp;
267                                 /* cpa is not too far in the future so investigate further */
268                                 if(t > 0.0f && t < t_min) {
269                                         VECADDFAC(co1, co1, vel1, t);
270                                         VECADDFAC(co2, co2, vel2, t);
271                                         
272                                         sub_v3_v3v3(vec, co2, co1);
273
274                                         len = normalize_v3(vec);
275
276                                         /* distance of cpa is close enough */
277                                         if(len < 2.0f * val->personal_space * pa->size) {
278                                                 t_min = t;
279
280                                                 mul_v3_fl(vec, len_v3(vel1));
281                                                 mul_v3_fl(vec, (2.0f - t)/2.0f);
282                                                 sub_v3_v3v3(bbd->wanted_co, vel1, vec);
283                                                 bbd->wanted_speed = len_v3(bbd->wanted_co);
284                                                 ret = 1;
285                                         }
286                                 }
287                         }
288                 }
289         }
290         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
291
292         /* check boids in other systems */
293         for(pt=bbd->sim->psys->targets.first; pt; pt=pt->next) {
294                 ParticleSystem *epsys = psys_get_target_system(bbd->sim->ob, pt);
295
296                 if(epsys) {
297                         neighbors = BLI_kdtree_range_search(epsys->tree, acbr->look_ahead * len_v3(pa->prev_state.vel), pa->prev_state.co, pa->prev_state.ave, &ptn);
298                         if(neighbors > 0) for(n=0; n<neighbors; n++) {
299                                 VECCOPY(co1, pa->prev_state.co);
300                                 VECCOPY(vel1, pa->prev_state.vel);
301                                 VECCOPY(co2, (epsys->particles + ptn[n].index)->prev_state.co);
302                                 VECCOPY(vel2, (epsys->particles + ptn[n].index)->prev_state.vel);
303
304                                 sub_v3_v3v3(loc, co1, co2);
305
306                                 sub_v3_v3v3(vec, vel1, vel2);
307                                 
308                                 inp = dot_v3v3(vec,vec);
309
310                                 /* velocities not parallel */
311                                 if(inp != 0.0f) {
312                                         t = -dot_v3v3(loc, vec)/inp;
313                                         /* cpa is not too far in the future so investigate further */
314                                         if(t > 0.0f && t < t_min) {
315                                                 VECADDFAC(co1, co1, vel1, t);
316                                                 VECADDFAC(co2, co2, vel2, t);
317                                                 
318                                                 sub_v3_v3v3(vec, co2, co1);
319
320                                                 len = normalize_v3(vec);
321
322                                                 /* distance of cpa is close enough */
323                                                 if(len < 2.0f * val->personal_space * pa->size) {
324                                                         t_min = t;
325
326                                                         mul_v3_fl(vec, len_v3(vel1));
327                                                         mul_v3_fl(vec, (2.0f - t)/2.0f);
328                                                         sub_v3_v3v3(bbd->wanted_co, vel1, vec);
329                                                         bbd->wanted_speed = len_v3(bbd->wanted_co);
330                                                         ret = 1;
331                                                 }
332                                         }
333                                 }
334                         }
335
336                         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
337                 }
338         }
339
340
341         if(ptn && nearest==0)
342                 MEM_freeN(ptn);
343
344         return ret;
345 }
346 static int rule_separate(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
347 {
348         KDTreeNearest *ptn = NULL;
349         ParticleTarget *pt;
350         float len = 2.0f * val->personal_space * pa->size + 1.0f;
351         float vec[3] = {0.0f, 0.0f, 0.0f};
352         int neighbors = BLI_kdtree_range_search(bbd->sim->psys->tree, 2.0f * val->personal_space * pa->size, pa->prev_state.co, NULL, &ptn);
353         int ret = 0;
354
355         if(neighbors > 1 && ptn[1].dist!=0.0f) {
356                 sub_v3_v3v3(vec, pa->prev_state.co, bbd->sim->psys->particles[ptn[1].index].state.co);
357                 mul_v3_fl(vec, (2.0f * val->personal_space * pa->size - ptn[1].dist) / ptn[1].dist);
358                 add_v3_v3(bbd->wanted_co, vec);
359                 bbd->wanted_speed = val->max_speed;
360                 len = ptn[1].dist;
361                 ret = 1;
362         }
363         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
364
365         /* check other boid systems */
366         for(pt=bbd->sim->psys->targets.first; pt; pt=pt->next) {
367                 ParticleSystem *epsys = psys_get_target_system(bbd->sim->ob, pt);
368
369                 if(epsys) {
370                         neighbors = BLI_kdtree_range_search(epsys->tree, 2.0f * val->personal_space * pa->size, pa->prev_state.co, NULL, &ptn);
371                         
372                         if(neighbors > 0 && ptn[0].dist < len) {
373                                 sub_v3_v3v3(vec, pa->prev_state.co, ptn[0].co);
374                                 mul_v3_fl(vec, (2.0f * val->personal_space * pa->size - ptn[0].dist) / ptn[1].dist);
375                                 add_v3_v3(bbd->wanted_co, vec);
376                                 bbd->wanted_speed = val->max_speed;
377                                 len = ptn[0].dist;
378                                 ret = 1;
379                         }
380
381                         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
382                 }
383         }
384         return ret;
385 }
386 static int rule_flock(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
387 {
388         KDTreeNearest ptn[11];
389         float vec[3] = {0.0f, 0.0f, 0.0f}, loc[3] = {0.0f, 0.0f, 0.0f};
390         int neighbors = BLI_kdtree_find_n_nearest(bbd->sim->psys->tree, 11, pa->state.co, pa->prev_state.ave, ptn);
391         int n;
392         int ret = 0;
393
394         if(neighbors > 1) {
395                 for(n=1; n<neighbors; n++) {
396                         add_v3_v3(loc, bbd->sim->psys->particles[ptn[n].index].prev_state.co);
397                         add_v3_v3(vec, bbd->sim->psys->particles[ptn[n].index].prev_state.vel);
398                 }
399
400                 mul_v3_fl(loc, 1.0f/((float)neighbors - 1.0f));
401                 mul_v3_fl(vec, 1.0f/((float)neighbors - 1.0f));
402
403                 sub_v3_v3(loc, pa->prev_state.co);
404                 sub_v3_v3(vec, pa->prev_state.vel);
405
406                 add_v3_v3(bbd->wanted_co, vec);
407                 add_v3_v3(bbd->wanted_co, loc);
408                 bbd->wanted_speed = len_v3(bbd->wanted_co);
409
410                 ret = 1;
411         }
412         return ret;
413 }
414 static int rule_follow_leader(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
415 {
416         BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader*) rule;
417         float vec[3] = {0.0f, 0.0f, 0.0f}, loc[3] = {0.0f, 0.0f, 0.0f};
418         float mul, len;
419         int n = (flbr->queue_size <= 1) ? bbd->sim->psys->totpart : flbr->queue_size;
420         int i, ret = 0, p = pa - bbd->sim->psys->particles;
421
422         if(flbr->ob) {
423                 float vec2[3], t;
424
425                 /* first check we're not blocking the leader*/
426                 sub_v3_v3v3(vec, flbr->loc, flbr->oloc);
427                 mul_v3_fl(vec, 1.0f/bbd->timestep);
428
429                 sub_v3_v3v3(loc, pa->prev_state.co, flbr->oloc);
430
431                 mul = dot_v3v3(vec, vec);
432
433                 /* leader is not moving */
434                 if(mul < 0.01) {
435                         len = len_v3(loc);
436                         /* too close to leader */
437                         if(len < 2.0f * val->personal_space * pa->size) {
438                                 VECCOPY(bbd->wanted_co, loc);
439                                 bbd->wanted_speed = val->max_speed;
440                                 return 1;
441                         }
442                 }
443                 else {
444                         t = dot_v3v3(loc, vec)/mul;
445
446                         /* possible blocking of leader in near future */
447                         if(t > 0.0f && t < 3.0f) {
448                                 VECCOPY(vec2, vec);
449                                 mul_v3_fl(vec2, t);
450
451                                 sub_v3_v3v3(vec2, loc, vec2);
452
453                                 len = len_v3(vec2);
454
455                                 if(len < 2.0f * val->personal_space * pa->size) {
456                                         VECCOPY(bbd->wanted_co, vec2);
457                                         bbd->wanted_speed = val->max_speed * (3.0f - t)/3.0f;
458                                         return 1;
459                                 }
460                         }
461                 }
462
463                 /* not blocking so try to follow leader */
464                 if(p && flbr->options & BRULE_LEADER_IN_LINE) {
465                         VECCOPY(vec, bbd->sim->psys->particles[p-1].prev_state.vel);
466                         VECCOPY(loc, bbd->sim->psys->particles[p-1].prev_state.co);
467                 }
468                 else {
469                         VECCOPY(loc, flbr->oloc);
470                         sub_v3_v3v3(vec, flbr->loc, flbr->oloc);
471                         mul_v3_fl(vec, 1.0/bbd->timestep);
472                 }
473                 
474                 /* fac is seconds behind leader */
475                 VECADDFAC(loc, loc, vec, -flbr->distance);
476
477                 sub_v3_v3v3(bbd->wanted_co, loc, pa->prev_state.co);
478                 bbd->wanted_speed = len_v3(bbd->wanted_co);
479                         
480                 ret = 1;
481         }
482         else if(p % n) {
483                 float vec2[3], t, t_min = 3.0f;
484
485                 /* first check we're not blocking any leaders */
486                 for(i = 0; i< bbd->sim->psys->totpart; i+=n){
487                         VECCOPY(vec, bbd->sim->psys->particles[i].prev_state.vel);
488
489                         sub_v3_v3v3(loc, pa->prev_state.co, bbd->sim->psys->particles[i].prev_state.co);
490
491                         mul = dot_v3v3(vec, vec);
492
493                         /* leader is not moving */
494                         if(mul < 0.01) {
495                                 len = len_v3(loc);
496                                 /* too close to leader */
497                                 if(len < 2.0f * val->personal_space * pa->size) {
498                                         VECCOPY(bbd->wanted_co, loc);
499                                         bbd->wanted_speed = val->max_speed;
500                                         return 1;
501                                 }
502                         }
503                         else {
504                                 t = dot_v3v3(loc, vec)/mul;
505
506                                 /* possible blocking of leader in near future */
507                                 if(t > 0.0f && t < t_min) {
508                                         VECCOPY(vec2, vec);
509                                         mul_v3_fl(vec2, t);
510
511                                         sub_v3_v3v3(vec2, loc, vec2);
512
513                                         len = len_v3(vec2);
514
515                                         if(len < 2.0f * val->personal_space * pa->size) {
516                                                 t_min = t;
517                                                 VECCOPY(bbd->wanted_co, loc);
518                                                 bbd->wanted_speed = val->max_speed * (3.0f - t)/3.0f;
519                                                 ret = 1;
520                                         }
521                                 }
522                         }
523                 }
524
525                 if(ret) return 1;
526
527                 /* not blocking so try to follow leader */
528                 if(flbr->options & BRULE_LEADER_IN_LINE) {
529                         VECCOPY(vec, bbd->sim->psys->particles[p-1].prev_state.vel);
530                         VECCOPY(loc, bbd->sim->psys->particles[p-1].prev_state.co);
531                 }
532                 else {
533                         VECCOPY(vec, bbd->sim->psys->particles[p - p%n].prev_state.vel);
534                         VECCOPY(loc, bbd->sim->psys->particles[p - p%n].prev_state.co);
535                 }
536                 
537                 /* fac is seconds behind leader */
538                 VECADDFAC(loc, loc, vec, -flbr->distance);
539
540                 sub_v3_v3v3(bbd->wanted_co, loc, pa->prev_state.co);
541                 bbd->wanted_speed = len_v3(bbd->wanted_co);
542                 
543                 ret = 1;
544         }
545
546         return ret;
547 }
548 static int rule_average_speed(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
549 {
550         BoidParticle *bpa = pa->boid;
551         BoidRuleAverageSpeed *asbr = (BoidRuleAverageSpeed*)rule;
552         float vec[3] = {0.0f, 0.0f, 0.0f};
553
554         if(asbr->wander > 0.0f) {
555                 /* abuse pa->r_ave for wandering */
556                 bpa->wander[0] += asbr->wander * (-1.0f + 2.0f * BLI_frand());
557                 bpa->wander[1] += asbr->wander * (-1.0f + 2.0f * BLI_frand());
558                 bpa->wander[2] += asbr->wander * (-1.0f + 2.0f * BLI_frand());
559
560                 normalize_v3(bpa->wander);
561
562                 VECCOPY(vec, bpa->wander);
563
564                 mul_qt_v3(pa->prev_state.rot, vec);
565
566                 VECCOPY(bbd->wanted_co, pa->prev_state.ave);
567
568                 mul_v3_fl(bbd->wanted_co, 1.1f);
569
570                 add_v3_v3(bbd->wanted_co, vec);
571
572                 /* leveling */
573                 if(asbr->level > 0.0f && psys_uses_gravity(bbd->sim)) {
574                         project_v3_v3v3(vec, bbd->wanted_co, bbd->sim->scene->physics_settings.gravity);
575                         mul_v3_fl(vec, asbr->level);
576                         sub_v3_v3(bbd->wanted_co, vec);
577                 }
578         }
579         else {
580                 VECCOPY(bbd->wanted_co, pa->prev_state.ave);
581
582                 /* may happen at birth */
583                 if(dot_v2v2(bbd->wanted_co,bbd->wanted_co)==0.0f) {
584                         bbd->wanted_co[0] = 2.0f*(0.5f - BLI_frand());
585                         bbd->wanted_co[1] = 2.0f*(0.5f - BLI_frand());
586                         bbd->wanted_co[2] = 2.0f*(0.5f - BLI_frand());
587                 }
588                 
589                 /* leveling */
590                 if(asbr->level > 0.0f && psys_uses_gravity(bbd->sim)) {
591                         project_v3_v3v3(vec, bbd->wanted_co, bbd->sim->scene->physics_settings.gravity);
592                         mul_v3_fl(vec, asbr->level);
593                         sub_v3_v3(bbd->wanted_co, vec);
594                 }
595
596         }
597         bbd->wanted_speed = asbr->speed * val->max_speed;
598         
599         return 1;
600 }
601 static int rule_fight(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
602 {
603         BoidRuleFight *fbr = (BoidRuleFight*)rule;
604         KDTreeNearest *ptn = NULL;
605         ParticleTarget *pt;
606         ParticleData *epars;
607         ParticleData *enemy_pa = NULL;
608         BoidParticle *bpa;
609         /* friends & enemies */
610         float closest_enemy[3] = {0.0f,0.0f,0.0f};
611         float closest_dist = fbr->distance + 1.0f;
612         float f_strength = 0.0f, e_strength = 0.0f;
613         float health = 0.0f;
614         int n, ret = 0;
615
616         /* calculate own group strength */
617         int neighbors = BLI_kdtree_range_search(bbd->sim->psys->tree, fbr->distance, pa->prev_state.co, NULL, &ptn);
618         for(n=0; n<neighbors; n++) {
619                 bpa = bbd->sim->psys->particles[ptn[n].index].boid;
620                 health += bpa->data.health;
621         }
622
623         f_strength += bbd->part->boids->strength * health;
624
625         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
626
627         /* add other friendlies and calculate enemy strength and find closest enemy */
628         for(pt=bbd->sim->psys->targets.first; pt; pt=pt->next) {
629                 ParticleSystem *epsys = psys_get_target_system(bbd->sim->ob, pt);
630                 if(epsys) {
631                         epars = epsys->particles;
632
633                         neighbors = BLI_kdtree_range_search(epsys->tree, fbr->distance, pa->prev_state.co, NULL, &ptn);
634                         
635                         health = 0.0f;
636
637                         for(n=0; n<neighbors; n++) {
638                                 bpa = epars[ptn[n].index].boid;
639                                 health += bpa->data.health;
640
641                                 if(n==0 && pt->mode==PTARGET_MODE_ENEMY && ptn[n].dist < closest_dist) {
642                                         VECCOPY(closest_enemy, ptn[n].co);
643                                         closest_dist = ptn[n].dist;
644                                         enemy_pa = epars + ptn[n].index;
645                                 }
646                         }
647                         if(pt->mode==PTARGET_MODE_ENEMY)
648                                 e_strength += epsys->part->boids->strength * health;
649                         else if(pt->mode==PTARGET_MODE_FRIEND)
650                                 f_strength += epsys->part->boids->strength * health;
651
652                         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
653                 }
654         }
655         /* decide action if enemy presence found */
656         if(e_strength > 0.0f) {
657                 sub_v3_v3v3(bbd->wanted_co, closest_enemy, pa->prev_state.co);
658
659                 /* attack if in range */
660                 if(closest_dist <= bbd->part->boids->range + pa->size + enemy_pa->size) {
661                         float damage = BLI_frand();
662                         float enemy_dir[3];
663
664                         normalize_v3_v3(enemy_dir, bbd->wanted_co);
665
666                         /* fight mode */
667                         bbd->wanted_speed = 0.0f;
668
669                         /* must face enemy to fight */
670                         if(dot_v3v3(pa->prev_state.ave, enemy_dir)>0.5f) {
671                                 bpa = enemy_pa->boid;
672                                 bpa->data.health -= bbd->part->boids->strength * bbd->timestep * ((1.0f-bbd->part->boids->accuracy)*damage + bbd->part->boids->accuracy);
673                         }
674                 }
675                 else {
676                         /* approach mode */
677                         bbd->wanted_speed = val->max_speed;
678                 }
679
680                 /* check if boid doesn't want to fight */
681                 bpa = pa->boid;
682                 if(bpa->data.health/bbd->part->boids->health * bbd->part->boids->aggression < e_strength / f_strength) {
683                         /* decide to flee */
684                         if(closest_dist < fbr->flee_distance * fbr->distance) {
685                                 negate_v3(bbd->wanted_co);
686                                 bbd->wanted_speed = val->max_speed;
687                         }
688                         else { /* wait for better odds */
689                                 bbd->wanted_speed = 0.0f;
690                         }
691                 }
692
693                 ret = 1;
694         }
695
696         return ret;
697 }
698
699 typedef int (*boid_rule_cb)(BoidRule *rule, BoidBrainData *data, BoidValues *val, ParticleData *pa);
700
701 static boid_rule_cb boid_rules[] = {
702         rule_none,
703         rule_goal_avoid,
704         rule_goal_avoid,
705         rule_avoid_collision,
706         rule_separate,
707         rule_flock,
708         rule_follow_leader,
709         rule_average_speed,
710         rule_fight,
711         //rule_help,
712         //rule_protect,
713         //rule_hide,
714         //rule_follow_path,
715         //rule_follow_wall
716 };
717
718 static void set_boid_values(BoidValues *val, BoidSettings *boids, ParticleData *pa)
719 {
720         BoidParticle *bpa = pa->boid;
721
722         if(ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing)) {
723                 val->max_speed = boids->land_max_speed * bpa->data.health/boids->health;
724                 val->max_acc = boids->land_max_acc * val->max_speed;
725                 val->max_ave = boids->land_max_ave * M_PI * bpa->data.health/boids->health;
726                 val->min_speed = 0.0f; /* no minimum speed on land */
727                 val->personal_space = boids->land_personal_space;
728                 val->jump_speed = boids->land_jump_speed * bpa->data.health/boids->health;
729         }
730         else {
731                 val->max_speed = boids->air_max_speed * bpa->data.health/boids->health;
732                 val->max_acc = boids->air_max_acc * val->max_speed;
733                 val->max_ave = boids->air_max_ave * M_PI * bpa->data.health/boids->health;
734                 val->min_speed = boids->air_min_speed * boids->air_max_speed;
735                 val->personal_space = boids->air_personal_space;
736                 val->jump_speed = 0.0f; /* no jumping in air */
737         }
738 }
739 static Object *boid_find_ground(BoidBrainData *bbd, ParticleData *pa, float *ground_co, float *ground_nor)
740 {
741         BoidParticle *bpa = pa->boid;
742
743         if(bpa->data.mode == eBoidMode_Climbing) {
744                 SurfaceModifierData *surmd = NULL;
745                 float x[3], v[3];
746                 
747                 surmd = (SurfaceModifierData *)modifiers_findByType ( bpa->ground, eModifierType_Surface );
748
749                 /* take surface velocity into account */
750                 closest_point_on_surface(surmd, pa->state.co, x, NULL, v);
751                 add_v3_v3(x, v);
752
753                 /* get actual position on surface */
754                 closest_point_on_surface(surmd, x, ground_co, ground_nor, NULL);
755
756                 return bpa->ground;
757         }
758         else {
759                 float zvec[3] = {0.0f, 0.0f, 2000.0f};
760                 ParticleCollision col;
761                 ColliderCache *coll;
762                 BVHTreeRayHit hit;
763                 float radius = 0.0f, t, ray_dir[3];
764
765                 if(!bbd->sim->colliders)
766                         return NULL;
767
768                 copy_v3_v3(col.co1, pa->state.co);
769                 copy_v3_v3(col.co2, pa->state.co);
770                 add_v3_v3(col.co1, zvec);
771                 sub_v3_v3(col.co2, zvec);
772                 sub_v3_v3v3(ray_dir, col.co2, col.co1);
773                 col.t = 0.0f;
774                 hit.index = -1;
775                 hit.dist = col.ray_len = len_v3(ray_dir);
776
777                 /* find out upmost deflector object */
778                 for(coll = bbd->sim->colliders->first; coll; coll = coll->next){
779                         col.ob = coll->ob;
780                         col.md = coll->collmd;
781
782                         if(col.md && col.md->bvhtree)
783                                 BLI_bvhtree_ray_cast(col.md->bvhtree, col.co1, ray_dir, radius, &hit, particle_intersect_face, &col);
784                 }
785                 /* then use that object */
786                 if(hit.index>=0) {
787                         t = hit.dist/col.ray_len;
788                         interp_v3_v3v3(ground_co, col.co1, col.co2, t);
789                         normalize_v3_v3(ground_nor, col.nor);
790                         return col.hit_ob;
791                 }
792                 else {
793                         /* default to z=0 */
794                         VECCOPY(ground_co, pa->state.co);
795                         ground_co[2] = 0;
796                         ground_nor[0] = ground_nor[1] = 0.0f;
797                         ground_nor[2] = 1.0f;
798                         return NULL;
799                 }
800         }
801 }
802 static int boid_rule_applies(ParticleData *pa, BoidSettings *boids, BoidRule *rule)
803 {
804         BoidParticle *bpa = pa->boid;
805
806         if(rule==NULL)
807                 return 0;
808         
809         if(ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing) && rule->flag & BOIDRULE_ON_LAND)
810                 return 1;
811         
812         if(bpa->data.mode==eBoidMode_InAir && rule->flag & BOIDRULE_IN_AIR)
813                 return 1;
814
815         return 0;
816 }
817 void boids_precalc_rules(ParticleSettings *part, float cfra)
818 {
819         BoidState *state = part->boids->states.first;
820         BoidRule *rule;
821         for(; state; state=state->next) {
822                 for(rule = state->rules.first; rule; rule=rule->next) {
823                         if(rule->type==eBoidRuleType_FollowLeader) {
824                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader*) rule;
825
826                                 if(flbr->ob && flbr->cfra != cfra) {
827                                         /* save object locations for velocity calculations */
828                                         VECCOPY(flbr->oloc, flbr->loc);
829                                         VECCOPY(flbr->loc, flbr->ob->obmat[3]);
830                                         flbr->cfra = cfra;
831                                 }
832                         }
833                 }
834         }
835 }
836 static void boid_climb(BoidSettings *boids, ParticleData *pa, float *surface_co, float *surface_nor)
837 {
838         BoidParticle *bpa = pa->boid;
839         float nor[3], vel[3];
840         VECCOPY(nor, surface_nor);
841
842         /* gather apparent gravity */
843         VECADDFAC(bpa->gravity, bpa->gravity, surface_nor, -1.0);
844         normalize_v3(bpa->gravity);
845
846         /* raise boid it's size from surface */
847         mul_v3_fl(nor, pa->size * boids->height);
848         add_v3_v3v3(pa->state.co, surface_co, nor);
849
850         /* remove normal component from velocity */
851         project_v3_v3v3(vel, pa->state.vel, surface_nor);
852         sub_v3_v3v3(pa->state.vel, pa->state.vel, vel);
853 }
854 static float boid_goal_signed_dist(float *boid_co, float *goal_co, float *goal_nor)
855 {
856         float vec[3];
857
858         sub_v3_v3v3(vec, boid_co, goal_co);
859
860         return dot_v3v3(vec, goal_nor);
861 }
862 /* wanted_co is relative to boid location */
863 static int apply_boid_rule(BoidBrainData *bbd, BoidRule *rule, BoidValues *val, ParticleData *pa, float fuzziness)
864 {
865         if(rule==NULL)
866                 return 0;
867
868         if(boid_rule_applies(pa, bbd->part->boids, rule)==0)
869                 return 0;
870
871         if(boid_rules[rule->type](rule, bbd, val, pa)==0)
872                 return 0;
873
874         if(fuzziness < 0.0f || compare_len_v3v3(bbd->wanted_co, pa->prev_state.vel, fuzziness * len_v3(pa->prev_state.vel))==0)
875                 return 1;
876         else
877                 return 0;
878 }
879 static BoidState *get_boid_state(BoidSettings *boids, ParticleData *pa) {
880         BoidState *state = boids->states.first;
881         BoidParticle *bpa = pa->boid;
882
883         for(; state; state=state->next) {
884                 if(state->id==bpa->data.state_id)
885                         return state;
886         }
887
888         /* for some reason particle isn't at a valid state */
889         state = boids->states.first;
890         if(state)
891                 bpa->data.state_id = state->id;
892
893         return state;
894 }
895 //static int boid_condition_is_true(BoidCondition *cond) {
896 //      /* TODO */
897 //      return 0;
898 //}
899
900 /* determines the velocity the boid wants to have */
901 void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa)
902 {
903         BoidRule *rule;
904         BoidSettings *boids = bbd->part->boids;
905         BoidValues val;
906         BoidState *state = get_boid_state(boids, pa);
907         BoidParticle *bpa = pa->boid;
908         int rand;
909         //BoidCondition *cond;
910
911         if(bpa->data.health <= 0.0f) {
912                 pa->alive = PARS_DYING;
913                 pa->dietime = bbd->cfra;
914                 return;
915         }
916
917         //planned for near future
918         //cond = state->conditions.first;
919         //for(; cond; cond=cond->next) {
920         //      if(boid_condition_is_true(cond)) {
921         //              pa->boid->state_id = cond->state_id;
922         //              state = get_boid_state(boids, pa);
923         //              break; /* only first true condition is used */
924         //      }
925         //}
926
927         bbd->wanted_co[0]=bbd->wanted_co[1]=bbd->wanted_co[2]=bbd->wanted_speed=0.0f;
928
929         /* create random seed for every particle & frame */
930         BLI_srandom(bbd->sim->psys->seed + p);
931         rand = BLI_rand();
932         BLI_srandom((int)bbd->cfra + rand);
933
934         set_boid_values(&val, bbd->part->boids, pa);
935
936         /* go through rules */
937         switch(state->ruleset_type) {
938                 case eBoidRulesetType_Fuzzy:
939                 {
940                         for(rule = state->rules.first; rule; rule = rule->next) {
941                                 if(apply_boid_rule(bbd, rule, &val, pa, state->rule_fuzziness))
942                                         break; /* only first nonzero rule that comes through fuzzy rule is applied */
943                         }
944                         break;
945                 }
946                 case eBoidRulesetType_Random:
947                 {
948                         /* use random rule for each particle (allways same for same particle though) */
949                         rule = BLI_findlink(&state->rules, rand % BLI_countlist(&state->rules));
950
951                         apply_boid_rule(bbd, rule, &val, pa, -1.0);
952                 }
953                 case eBoidRulesetType_Average:
954                 {
955                         float wanted_co[3] = {0.0f, 0.0f, 0.0f}, wanted_speed = 0.0f;
956                         int n = 0;
957                         for(rule = state->rules.first; rule; rule=rule->next) {
958                                 if(apply_boid_rule(bbd, rule, &val, pa, -1.0f)) {
959                                         add_v3_v3(wanted_co, bbd->wanted_co);
960                                         wanted_speed += bbd->wanted_speed;
961                                         n++;
962                                         bbd->wanted_co[0]=bbd->wanted_co[1]=bbd->wanted_co[2]=bbd->wanted_speed=0.0f;
963                                 }
964                         }
965
966                         if(n > 1) {
967                                 mul_v3_fl(wanted_co, 1.0f/(float)n);
968                                 wanted_speed /= (float)n;
969                         }
970
971                         VECCOPY(bbd->wanted_co, wanted_co);
972                         bbd->wanted_speed = wanted_speed;
973                         break;
974                 }
975
976         }
977
978         /* decide on jumping & liftoff */
979         if(bpa->data.mode == eBoidMode_OnLand) {
980                 /* fuzziness makes boids capable of misjudgement */
981                 float mul = 1.0 + state->rule_fuzziness;
982                 
983                 if(boids->options & BOID_ALLOW_FLIGHT && bbd->wanted_co[2] > 0.0f) {
984                         float cvel[3], dir[3];
985
986                         VECCOPY(dir, pa->prev_state.ave);
987                         normalize_v2(dir);
988
989                         VECCOPY(cvel, bbd->wanted_co);
990                         normalize_v2(cvel);
991
992                         if(dot_v2v2(cvel, dir) > 0.95 / mul)
993                                 bpa->data.mode = eBoidMode_Liftoff;
994                 }
995                 else if(val.jump_speed > 0.0f) {
996                         float jump_v[3];
997                         int jump = 0;
998
999                         /* jump to get to a location */
1000                         if(bbd->wanted_co[2] > 0.0f) {
1001                                 float cvel[3], dir[3];
1002                                 float z_v, ground_v, cur_v;
1003                                 float len;
1004
1005                                 VECCOPY(dir, pa->prev_state.ave);
1006                                 normalize_v2(dir);
1007
1008                                 VECCOPY(cvel, bbd->wanted_co);
1009                                 normalize_v2(cvel);
1010
1011                                 len = len_v2(pa->prev_state.vel);
1012
1013                                 /* first of all, are we going in a suitable direction? */
1014                                 /* or at a suitably slow speed */
1015                                 if(dot_v2v2(cvel, dir) > 0.95f / mul || len <= state->rule_fuzziness) {
1016                                         /* try to reach goal at highest point of the parabolic path */
1017                                         cur_v = len_v2(pa->prev_state.vel);
1018                                         z_v = sasqrt(-2.0f * bbd->sim->scene->physics_settings.gravity[2] * bbd->wanted_co[2]);
1019                                         ground_v = len_v2(bbd->wanted_co)*sasqrt(-0.5f * bbd->sim->scene->physics_settings.gravity[2] / bbd->wanted_co[2]);
1020
1021                                         len = sasqrt((ground_v-cur_v)*(ground_v-cur_v) + z_v*z_v);
1022
1023                                         if(len < val.jump_speed * mul || bbd->part->boids->options & BOID_ALLOW_FLIGHT) {
1024                                                 jump = 1;
1025
1026                                                 len = MIN2(len, val.jump_speed);
1027
1028                                                 VECCOPY(jump_v, dir);
1029                                                 jump_v[2] = z_v;
1030                                                 mul_v3_fl(jump_v, ground_v);
1031
1032                                                 normalize_v3(jump_v);
1033                                                 mul_v3_fl(jump_v, len);
1034                                                 add_v2_v2v2(jump_v, jump_v, pa->prev_state.vel);
1035                                         }
1036                                 }
1037                         }
1038
1039                         /* jump to go faster */
1040                         if(jump == 0 && val.jump_speed > val.max_speed && bbd->wanted_speed > val.max_speed) {
1041                                 
1042                         }
1043
1044                         if(jump) {
1045                                 VECCOPY(pa->prev_state.vel, jump_v);
1046                                 bpa->data.mode = eBoidMode_Falling;
1047                         }
1048                 }
1049         }
1050 }
1051 /* tries to realize the wanted velocity taking all constraints into account */
1052 void boid_body(BoidBrainData *bbd, ParticleData *pa)
1053 {
1054         BoidSettings *boids = bbd->part->boids;
1055         BoidParticle *bpa = pa->boid;
1056         BoidValues val;
1057         EffectedPoint epoint;
1058         float acc[3] = {0.0f, 0.0f, 0.0f}, tan_acc[3], nor_acc[3];
1059         float dvec[3], bvec[3];
1060         float new_dir[3], new_speed;
1061         float old_dir[3], old_speed;
1062         float wanted_dir[3];
1063         float q[4], mat[3][3]; /* rotation */
1064         float ground_co[3] = {0.0f, 0.0f, 0.0f}, ground_nor[3] = {0.0f, 0.0f, 1.0f};
1065         float force[3] = {0.0f, 0.0f, 0.0f};
1066         float pa_mass=bbd->part->mass, dtime=bbd->dfra*bbd->timestep;
1067
1068         set_boid_values(&val, boids, pa);
1069
1070         /* make sure there's something in new velocity, location & rotation */
1071         copy_particle_key(&pa->state,&pa->prev_state,0);
1072
1073         if(bbd->part->flag & PART_SIZEMASS)
1074                 pa_mass*=pa->size;
1075
1076         /* if boids can't fly they fall to the ground */
1077         if((boids->options & BOID_ALLOW_FLIGHT)==0 && ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing)==0 && psys_uses_gravity(bbd->sim))
1078                 bpa->data.mode = eBoidMode_Falling;
1079
1080         if(bpa->data.mode == eBoidMode_Falling) {
1081                 /* Falling boids are only effected by gravity. */
1082                 acc[2] = bbd->sim->scene->physics_settings.gravity[2];
1083         }
1084         else {
1085                 /* figure out acceleration */
1086                 float landing_level = 2.0f;
1087                 float level = landing_level + 1.0f;
1088                 float new_vel[3];
1089
1090                 if(bpa->data.mode == eBoidMode_Liftoff) {
1091                         bpa->data.mode = eBoidMode_InAir;
1092                         bpa->ground = boid_find_ground(bbd, pa, ground_co, ground_nor);
1093                 }
1094                 else if(bpa->data.mode == eBoidMode_InAir && boids->options & BOID_ALLOW_LAND) {
1095                         /* auto-leveling & landing if close to ground */
1096
1097                         bpa->ground = boid_find_ground(bbd, pa, ground_co, ground_nor);
1098                         
1099                         /* level = how many particle sizes above ground */
1100                         level = (pa->prev_state.co[2] - ground_co[2])/(2.0f * pa->size) - 0.5;
1101
1102                         landing_level = - boids->landing_smoothness * pa->prev_state.vel[2] * pa_mass;
1103
1104                         if(pa->prev_state.vel[2] < 0.0f) {
1105                                 if(level < 1.0f) {
1106                                         bbd->wanted_co[0] = bbd->wanted_co[1] = bbd->wanted_co[2] = 0.0f;
1107                                         bbd->wanted_speed = 0.0f;
1108                                         bpa->data.mode = eBoidMode_Falling;
1109                                 }
1110                                 else if(level < landing_level) {
1111                                         bbd->wanted_speed *= (level - 1.0f)/landing_level;
1112                                         bbd->wanted_co[2] *= (level - 1.0f)/landing_level;
1113                                 }
1114                         }
1115                 }
1116
1117                 VECCOPY(old_dir, pa->prev_state.ave);
1118                 new_speed = normalize_v3_v3(wanted_dir, bbd->wanted_co);
1119
1120                 /* first check if we have valid direction we want to go towards */
1121                 if(new_speed == 0.0f) {
1122                         VECCOPY(new_dir, old_dir);
1123                 }
1124                 else {
1125                         float old_dir2[2], wanted_dir2[2], nor[3], angle;
1126                         copy_v2_v2(old_dir2, old_dir);
1127                         normalize_v2(old_dir2);
1128                         copy_v2_v2(wanted_dir2, wanted_dir);
1129                         normalize_v2(wanted_dir2);
1130
1131                         /* choose random direction to turn if wanted velocity */
1132                         /* is directly behind regardless of z-coordinate */
1133                         if(dot_v2v2(old_dir2, wanted_dir2) < -0.99f) {
1134                                 wanted_dir[0] = 2.0f*(0.5f - BLI_frand());
1135                                 wanted_dir[1] = 2.0f*(0.5f - BLI_frand());
1136                                 wanted_dir[2] = 2.0f*(0.5f - BLI_frand());
1137                                 normalize_v3(wanted_dir);
1138                         }
1139
1140                         /* constrain direction with maximum angular velocity */
1141                         angle = saacos(dot_v3v3(old_dir, wanted_dir));
1142                         angle = MIN2(angle, val.max_ave);
1143
1144                         cross_v3_v3v3(nor, old_dir, wanted_dir);
1145                         axis_angle_to_quat( q,nor, angle);
1146                         VECCOPY(new_dir, old_dir);
1147                         mul_qt_v3(q, new_dir);
1148                         normalize_v3(new_dir);
1149
1150                         /* save direction in case resulting velocity too small */
1151                         axis_angle_to_quat( q,nor, angle*dtime);
1152                         VECCOPY(pa->state.ave, old_dir);
1153                         mul_qt_v3(q, pa->state.ave);
1154                         normalize_v3(pa->state.ave);
1155                 }
1156
1157                 /* constrain speed with maximum acceleration */
1158                 old_speed = len_v3(pa->prev_state.vel);
1159                 
1160                 if(bbd->wanted_speed < old_speed)
1161                         new_speed = MAX2(bbd->wanted_speed, old_speed - val.max_acc);
1162                 else
1163                         new_speed = MIN2(bbd->wanted_speed, old_speed + val.max_acc);
1164
1165                 /* combine direction and speed */
1166                 VECCOPY(new_vel, new_dir);
1167                 mul_v3_fl(new_vel, new_speed);
1168
1169                 /* maintain minimum flying velocity if not landing */
1170                 if(level >= landing_level) {
1171                         float len2 = dot_v2v2(new_vel,new_vel);
1172                         float root;
1173
1174                         len2 = MAX2(len2, val.min_speed*val.min_speed);
1175                         root = sasqrt(new_speed*new_speed - len2);
1176
1177                         new_vel[2] = new_vel[2] < 0.0f ? -root : root;
1178
1179                         normalize_v2(new_vel);
1180                         mul_v2_fl(new_vel, sasqrt(len2));
1181                 }
1182
1183                 /* finally constrain speed to max speed */
1184                 new_speed = normalize_v3(new_vel);
1185                 mul_v3_fl(new_vel, MIN2(new_speed, val.max_speed));
1186
1187                 /* get acceleration from difference of velocities */
1188                 sub_v3_v3v3(acc, new_vel, pa->prev_state.vel);
1189
1190                 /* break acceleration to components */
1191                 project_v3_v3v3(tan_acc, acc, pa->prev_state.ave);
1192                 sub_v3_v3v3(nor_acc, acc, tan_acc);
1193         }
1194
1195         /* account for effectors */
1196         pd_point_from_particle(bbd->sim, pa, &pa->state, &epoint);
1197         pdDoEffectors(bbd->sim->psys->effectors, bbd->sim->colliders, bbd->part->effector_weights, &epoint, force, NULL);
1198
1199         if(ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing)) {
1200                 float length = normalize_v3(force);
1201
1202                 length = MAX2(0.0f, length - boids->land_stick_force);
1203
1204                 mul_v3_fl(force, length);
1205         }
1206         
1207         add_v3_v3(acc, force);
1208
1209         /* store smoothed acceleration for nice banking etc. */
1210         VECADDFAC(bpa->data.acc, bpa->data.acc, acc, dtime);
1211         mul_v3_fl(bpa->data.acc, 1.0f / (1.0f + dtime));
1212
1213         /* integrate new location & velocity */
1214
1215         /* by regarding the acceleration as a force at this stage we*/
1216         /* can get better control allthough it's a bit unphysical       */
1217         mul_v3_fl(acc, 1.0f/pa_mass);
1218
1219         VECCOPY(dvec, acc);
1220         mul_v3_fl(dvec, dtime*dtime*0.5f);
1221         
1222         VECCOPY(bvec, pa->prev_state.vel);
1223         mul_v3_fl(bvec, dtime);
1224         add_v3_v3(dvec, bvec);
1225         add_v3_v3(pa->state.co, dvec);
1226
1227         VECADDFAC(pa->state.vel, pa->state.vel, acc, dtime);
1228
1229         if(bpa->data.mode != eBoidMode_InAir)
1230                 bpa->ground = boid_find_ground(bbd, pa, ground_co, ground_nor);
1231
1232         /* change modes, constrain movement & keep track of down vector */
1233         switch(bpa->data.mode) {
1234                 case eBoidMode_InAir:
1235                 {
1236                         float grav[3] = {0.0f, 0.0f, bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f};
1237
1238                         /* don't take forward acceleration into account (better banking) */
1239                         if(dot_v3v3(bpa->data.acc, pa->state.vel) > 0.0f) {
1240                                 project_v3_v3v3(dvec, bpa->data.acc, pa->state.vel);
1241                                 sub_v3_v3v3(dvec, bpa->data.acc, dvec);
1242                         }
1243                         else {
1244                                 VECCOPY(dvec, bpa->data.acc);
1245                         }
1246
1247                         /* gather apparent gravity */
1248                         VECADDFAC(bpa->gravity, grav, dvec, -boids->banking);
1249                         normalize_v3(bpa->gravity);
1250
1251                         /* stick boid on goal when close enough */
1252                         if(bbd->goal_ob && boid_goal_signed_dist(pa->state.co, bbd->goal_co, bbd->goal_nor) <= pa->size * boids->height) {
1253                                 bpa->data.mode = eBoidMode_Climbing;
1254                                 bpa->ground = bbd->goal_ob;
1255                                 boid_find_ground(bbd, pa, ground_co, ground_nor);
1256                                 boid_climb(boids, pa, ground_co, ground_nor);
1257                         }
1258                         /* land boid when belowg ground */
1259                         else if(boids->options & BOID_ALLOW_LAND && pa->state.co[2] <= ground_co[2] + pa->size * boids->height) {
1260                                 pa->state.co[2] = ground_co[2] + pa->size * boids->height;
1261                                 pa->state.vel[2] = 0.0f;
1262                                 bpa->data.mode = eBoidMode_OnLand;
1263                         }
1264                         break;
1265                 }
1266                 case eBoidMode_Falling:
1267                 {
1268                         float grav[3] = {0.0f, 0.0f, bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f};
1269
1270                         /* gather apparent gravity */
1271                         VECADDFAC(bpa->gravity, bpa->gravity, grav, dtime);
1272                         normalize_v3(bpa->gravity);
1273
1274                         if(boids->options & BOID_ALLOW_LAND) {
1275                                 /* stick boid on goal when close enough */
1276                                 if(bbd->goal_ob && boid_goal_signed_dist(pa->state.co, bbd->goal_co, bbd->goal_nor) <= pa->size * boids->height) {
1277                                         bpa->data.mode = eBoidMode_Climbing;
1278                                         bpa->ground = bbd->goal_ob;
1279                                         boid_find_ground(bbd, pa, ground_co, ground_nor);
1280                                         boid_climb(boids, pa, ground_co, ground_nor);
1281                                 }
1282                                 /* land boid when really near ground */
1283                                 else if(pa->state.co[2] <= ground_co[2] + 1.01 * pa->size * boids->height){
1284                                         pa->state.co[2] = ground_co[2] + pa->size * boids->height;
1285                                         pa->state.vel[2] = 0.0f;
1286                                         bpa->data.mode = eBoidMode_OnLand;
1287                                 }
1288                                 /* if we're falling, can fly and want to go upwards lets fly */
1289                                 else if(boids->options & BOID_ALLOW_FLIGHT && bbd->wanted_co[2] > 0.0f)
1290                                         bpa->data.mode = eBoidMode_InAir;
1291                         }
1292                         else
1293                                 bpa->data.mode = eBoidMode_InAir;
1294                         break;
1295                 }
1296                 case eBoidMode_Climbing:
1297                 {
1298                         boid_climb(boids, pa, ground_co, ground_nor);
1299                         //float nor[3];
1300                         //VECCOPY(nor, ground_nor);
1301
1302                         ///* gather apparent gravity to r_ve */
1303                         //VECADDFAC(pa->r_ve, pa->r_ve, ground_nor, -1.0);
1304                         //normalize_v3(pa->r_ve);
1305
1306                         ///* raise boid it's size from surface */
1307                         //mul_v3_fl(nor, pa->size * boids->height);
1308                         //add_v3_v3v3(pa->state.co, ground_co, nor);
1309
1310                         ///* remove normal component from velocity */
1311                         //project_v3_v3v3(v, pa->state.vel, ground_nor);
1312                         //sub_v3_v3v3(pa->state.vel, pa->state.vel, v);
1313                         break;
1314                 }
1315                 case eBoidMode_OnLand:
1316                 {
1317                         /* stick boid on goal when close enough */
1318                         if(bbd->goal_ob && boid_goal_signed_dist(pa->state.co, bbd->goal_co, bbd->goal_nor) <= pa->size * boids->height) {
1319                                 bpa->data.mode = eBoidMode_Climbing;
1320                                 bpa->ground = bbd->goal_ob;
1321                                 boid_find_ground(bbd, pa, ground_co, ground_nor);
1322                                 boid_climb(boids, pa, ground_co, ground_nor);
1323                         }
1324                         /* ground is too far away so boid falls */
1325                         else if(pa->state.co[2]-ground_co[2] > 1.1 * pa->size * boids->height)
1326                                 bpa->data.mode = eBoidMode_Falling;
1327                         else {
1328                                 /* constrain to surface */
1329                                 pa->state.co[2] = ground_co[2] + pa->size * boids->height;
1330                                 pa->state.vel[2] = 0.0f;
1331                         }
1332
1333                         if(boids->banking > 0.0f) {
1334                                 float grav[3];
1335                                 /* Don't take gravity's strength in to account, */
1336                                 /* otherwise amount of banking is hard to control. */
1337                                 negate_v3_v3(grav, ground_nor);
1338
1339                                 project_v3_v3v3(dvec, bpa->data.acc, pa->state.vel);
1340                                 sub_v3_v3v3(dvec, bpa->data.acc, dvec);
1341
1342                                 /* gather apparent gravity */
1343                                 VECADDFAC(bpa->gravity, grav, dvec, -boids->banking);
1344                                 normalize_v3(bpa->gravity);
1345                         }
1346                         else {
1347                                 /* gather negative surface normal */
1348                                 VECADDFAC(bpa->gravity, bpa->gravity, ground_nor, -1.0f);
1349                                 normalize_v3(bpa->gravity);
1350                         }
1351                         break;
1352                 }
1353         }
1354
1355         /* save direction to state.ave unless the boid is falling */
1356         /* (boids can't effect their direction when falling) */
1357         if(bpa->data.mode!=eBoidMode_Falling && len_v3(pa->state.vel) > 0.1*pa->size) {
1358                 normalize_v3_v3(pa->state.ave, pa->state.vel);
1359         }
1360
1361         /* apply damping */
1362         if(ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing))
1363                 mul_v3_fl(pa->state.vel, 1.0f - 0.2f*bbd->part->dampfac);
1364
1365         /* calculate rotation matrix based on forward & down vectors */
1366         if(bpa->data.mode == eBoidMode_InAir) {
1367                 VECCOPY(mat[0], pa->state.ave);
1368
1369                 project_v3_v3v3(dvec, bpa->gravity, pa->state.ave);
1370                 sub_v3_v3v3(mat[2], bpa->gravity, dvec);
1371                 normalize_v3(mat[2]);
1372         }
1373         else {
1374                 project_v3_v3v3(dvec, pa->state.ave, bpa->gravity);
1375                 sub_v3_v3v3(mat[0], pa->state.ave, dvec);
1376                 normalize_v3(mat[0]);
1377
1378                 VECCOPY(mat[2], bpa->gravity);
1379         }
1380         negate_v3(mat[2]);
1381         cross_v3_v3v3(mat[1], mat[2], mat[0]);
1382         
1383         /* apply rotation */
1384         mat3_to_quat_is_ok( q,mat);
1385         copy_qt_qt(pa->state.rot, q);
1386 }
1387
1388 BoidRule *boid_new_rule(int type)
1389 {
1390         BoidRule *rule = NULL;
1391         if(type <= 0)
1392                 return NULL;
1393
1394         switch(type) {
1395                 case eBoidRuleType_Goal:
1396                 case eBoidRuleType_Avoid:
1397                         rule = MEM_callocN(sizeof(BoidRuleGoalAvoid), "BoidRuleGoalAvoid");
1398                         break;
1399                 case eBoidRuleType_AvoidCollision:
1400                         rule = MEM_callocN(sizeof(BoidRuleAvoidCollision), "BoidRuleAvoidCollision");
1401                         ((BoidRuleAvoidCollision*)rule)->look_ahead = 2.0f;
1402                         break;
1403                 case eBoidRuleType_FollowLeader:
1404                         rule = MEM_callocN(sizeof(BoidRuleFollowLeader), "BoidRuleFollowLeader");
1405                         ((BoidRuleFollowLeader*)rule)->distance = 1.0f;
1406                         break;
1407                 case eBoidRuleType_AverageSpeed:
1408                         rule = MEM_callocN(sizeof(BoidRuleAverageSpeed), "BoidRuleAverageSpeed");
1409                         ((BoidRuleAverageSpeed*)rule)->speed = 0.5f;
1410                         break;
1411                 case eBoidRuleType_Fight:
1412                         rule = MEM_callocN(sizeof(BoidRuleFight), "BoidRuleFight");
1413                         ((BoidRuleFight*)rule)->distance = 100.0f;
1414                         ((BoidRuleFight*)rule)->flee_distance = 100.0f;
1415                         break;
1416                 default:
1417                         rule = MEM_callocN(sizeof(BoidRule), "BoidRule");
1418                         break;
1419         }
1420
1421         rule->type = type;
1422         rule->flag |= BOIDRULE_IN_AIR|BOIDRULE_ON_LAND;
1423         strcpy(rule->name, boidrule_type_items[type-1].name);
1424
1425         return rule;
1426 }
1427 void boid_default_settings(BoidSettings *boids)
1428 {
1429         boids->air_max_speed = 10.0f;
1430         boids->air_max_acc = 0.5f;
1431         boids->air_max_ave = 0.5f;
1432         boids->air_personal_space = 1.0f;
1433
1434         boids->land_max_speed = 5.0f;
1435         boids->land_max_acc = 0.5f;
1436         boids->land_max_ave = 0.5f;
1437         boids->land_personal_space = 1.0f;
1438
1439         boids->options = BOID_ALLOW_FLIGHT;
1440
1441         boids->landing_smoothness = 3.0f;
1442         boids->banking = 1.0f;
1443         boids->height = 1.0f;
1444
1445         boids->health = 1.0f;
1446         boids->accuracy = 1.0f;
1447         boids->aggression = 2.0f;
1448         boids->range = 1.0f;
1449         boids->strength = 0.1f;
1450 }
1451
1452 BoidState *boid_new_state(BoidSettings *boids)
1453 {
1454         BoidState *state = MEM_callocN(sizeof(BoidState), "BoidState");
1455
1456         state->id = boids->last_state_id++;
1457         if(state->id)
1458                 sprintf(state->name, "State %i", state->id);
1459         else
1460                 strcpy(state->name, "State");
1461
1462         state->rule_fuzziness = 0.5;
1463         state->volume = 1.0f;
1464         state->channels |= ~0;
1465
1466         return state;
1467 }
1468
1469 BoidState *boid_duplicate_state(BoidSettings *boids, BoidState *state) {
1470         BoidState *staten = MEM_dupallocN(state);
1471
1472         BLI_duplicatelist(&staten->rules, &state->rules);
1473         BLI_duplicatelist(&staten->conditions, &state->conditions);
1474         BLI_duplicatelist(&staten->actions, &state->actions);
1475
1476         staten->id = boids->last_state_id++;
1477
1478         return staten;
1479 }
1480 void boid_free_settings(BoidSettings *boids)
1481 {
1482         if(boids) {
1483                 BoidState *state = boids->states.first;
1484
1485                 for(; state; state=state->next) {
1486                         BLI_freelistN(&state->rules);
1487                         BLI_freelistN(&state->conditions);
1488                         BLI_freelistN(&state->actions);
1489                 }
1490
1491                 BLI_freelistN(&boids->states);
1492
1493                 MEM_freeN(boids);
1494         }
1495 }
1496 BoidSettings *boid_copy_settings(BoidSettings *boids)
1497 {
1498         BoidSettings *nboids = NULL;
1499
1500         if(boids) {
1501                 BoidState *state;
1502                 BoidState *nstate;
1503
1504                 nboids = MEM_dupallocN(boids);
1505
1506                 BLI_duplicatelist(&nboids->states, &boids->states);
1507
1508                 state = boids->states.first;
1509                 nstate = nboids->states.first;
1510                 for(; state; state=state->next, nstate=nstate->next) {
1511                         BLI_duplicatelist(&nstate->rules, &state->rules);
1512                         BLI_duplicatelist(&nstate->conditions, &state->conditions);
1513                         BLI_duplicatelist(&nstate->actions, &state->actions);
1514                 }
1515         }
1516
1517         return nboids;
1518 }
1519 BoidState *boid_get_current_state(BoidSettings *boids)
1520 {
1521         BoidState *state = boids->states.first;
1522
1523         for(; state; state=state->next) {
1524                 if(state->flag & BOIDSTATE_CURRENT)
1525                         break;
1526         }
1527
1528         return state;
1529 }
1530