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