|
1 | 1 | // SPDX-License-Identifier: Apache-2.0
|
2 |
| -import type { FnU2 } from "@thi.ng/api"; |
| 2 | +import type { Predicate2 } from "@thi.ng/api"; |
3 | 3 | import type { Vec } from "@thi.ng/vectors";
|
4 | 4 | import type { IBoidBehavior, ScalarOrField } from "../api.js";
|
5 | 5 | import type { Boid } from "../boid.js";
|
6 | 6 | import { __ensureFn } from "../internal/ensure.js";
|
7 | 7 |
|
| 8 | +/** |
| 9 | + * Cohesion behavior. Attempts to move boid towards centroid of neighboring |
| 10 | + * boids within `maxDist`. The behavior itself can be weighted via `weight`. |
| 11 | + * Neighbors can be filtered via optional `filter` predicate, which receives |
| 12 | + * current boid as first arg and current neighbor as second. By default all |
| 13 | + * neighbors are considered. |
| 14 | + * |
| 15 | + * @param maxDist |
| 16 | + * @param weight |
| 17 | + * @param pred |
| 18 | + */ |
8 | 19 | export const cohesion = (
|
9 | 20 | maxDist: ScalarOrField,
|
10 | 21 | weight: ScalarOrField = 1,
|
11 |
| - amp?: FnU2<Boid, number> |
| 22 | + pred: Predicate2<Boid> = () => true |
12 | 23 | ): IBoidBehavior => {
|
13 | 24 | const $maxDist = __ensureFn(maxDist);
|
14 | 25 | const centroid: Vec = [];
|
15 | 26 | return {
|
16 | 27 | weight: __ensureFn(weight),
|
17 | 28 | update: (boid) => {
|
18 |
| - const { add, maddN, mulN, setN } = boid.api; |
| 29 | + const { add, mulN, setN } = boid.api; |
19 | 30 | const neighbors = boid.neighbors($maxDist(boid), boid.pos.curr);
|
20 | 31 | const num = neighbors.length;
|
21 | 32 | setN(centroid, 0);
|
22 | 33 | for (let i = 0; i < num; i++) {
|
23 | 34 | const n = neighbors[i];
|
24 |
| - if (n !== boid) { |
25 |
| - amp |
26 |
| - ? maddN(centroid, n.pos.curr, amp(boid, n), centroid) |
27 |
| - : add(centroid, centroid, n.pos.curr); |
28 |
| - } |
| 35 | + if (n !== boid && pred(boid, n)) |
| 36 | + add(centroid, centroid, n.pos.curr); |
29 | 37 | }
|
30 | 38 | return num > 1
|
31 | 39 | ? boid.steerTowards(mulN(centroid, centroid, 1 / (num - 1)))
|
|
0 commit comments