fish.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
  2. import {game} from './game.js';
  3. import {math} from './math.js';
  4. import {visibility} from './visibility.js';
  5. import {OBJLoader} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/loaders/OBJLoader.js';
  6. let _APP = null;
  7. const _NUM_BOIDS = 350;
  8. const _BOID_SPEED = 2.5;
  9. const _BOID_ACCELERATION = _BOID_SPEED / 5.0;
  10. const _BOID_FORCE_MAX = _BOID_ACCELERATION / 10.0;
  11. const _BOID_FORCE_ORIGIN = 8;
  12. const _BOID_FORCE_ALIGNMENT = 10;
  13. const _BOID_FORCE_SEPARATION = 20;
  14. const _BOID_FORCE_COHESION = 10;
  15. const _BOID_FORCE_WANDER = 3;
  16. class LineRenderer {
  17. constructor(game) {
  18. this._game = game;
  19. this._materials = {};
  20. this._group = new THREE.Group();
  21. this._game._graphics.Scene.add(this._group);
  22. }
  23. Reset() {
  24. this._lines = [];
  25. this._group.remove(...this._group.children);
  26. }
  27. Add(pt1, pt2, hexColour) {
  28. const geometry = new THREE.Geometry();
  29. geometry.vertices.push(pt1);
  30. geometry.vertices.push(pt2);
  31. let material = this._materials[hexColour];
  32. if (!material) {
  33. this._materials[hexColour] = new THREE.LineBasicMaterial(
  34. {color: hexColour});
  35. material = this._materials[hexColour];
  36. }
  37. const line = new THREE.Line(geometry, material);
  38. this._lines.push(line);
  39. this._group.add(line);
  40. }
  41. }
  42. class Boid {
  43. constructor(game, params) {
  44. this._mesh = new THREE.Mesh(
  45. params.geometry,
  46. new THREE.MeshStandardMaterial({color: params.colour}));
  47. this._mesh.castShadow = true;
  48. this._mesh.receiveShadow = false;
  49. this._group = new THREE.Group();
  50. this._group.add(this._mesh);
  51. this._group.position.set(
  52. math.rand_range(-50, 50),
  53. math.rand_range(1, 25),
  54. math.rand_range(-50, 50));
  55. this._direction = new THREE.Vector3(
  56. math.rand_range(-1, 1),
  57. 0,
  58. math.rand_range(-1, 1));
  59. this._velocity = this._direction.clone();
  60. const speedMultiplier = math.rand_range(params.speedMin, params.speedMax);
  61. this._maxSteeringForce = params.maxSteeringForce * speedMultiplier;
  62. this._maxSpeed = params.speed * speedMultiplier;
  63. this._acceleration = params.acceleration * speedMultiplier;
  64. const scale = 1.0 / speedMultiplier;
  65. this._radius = scale;
  66. this._mesh.scale.setScalar(scale);
  67. this._mesh.rotateX(-Math.PI / 2);
  68. this._game = game;
  69. game._graphics.Scene.add(this._group);
  70. this._visibilityIndex = game._visibilityGrid.UpdateItem(
  71. this._mesh.uuid, this);
  72. this._wanderAngle = 0;
  73. }
  74. DisplayDebug() {
  75. const geometry = new THREE.SphereGeometry(10, 64, 64);
  76. const material = new THREE.MeshBasicMaterial({
  77. color: 0xFF0000,
  78. transparent: true,
  79. opacity: 0.25,
  80. });
  81. const mesh = new THREE.Mesh(geometry, material);
  82. this._group.add(mesh);
  83. this._mesh.material.color.setHex(0xFF0000);
  84. this._displayDebug = true;
  85. this._lineRenderer = new LineRenderer(this._game);
  86. }
  87. _UpdateDebug(local) {
  88. this._lineRenderer.Reset();
  89. this._lineRenderer.Add(
  90. this.Position, this.Position.clone().add(this._velocity),
  91. 0xFFFFFF);
  92. for (const e of local) {
  93. this._lineRenderer.Add(this.Position, e.Position, 0x00FF00);
  94. }
  95. }
  96. get Position() {
  97. return this._group.position;
  98. }
  99. get Velocity() {
  100. return this._velocity;
  101. }
  102. get Direction() {
  103. return this._direction;
  104. }
  105. get Radius() {
  106. return this._radius;
  107. }
  108. Step(timeInSeconds) {
  109. if (this._displayDebug) {
  110. let a = 0;
  111. }
  112. const local = this._game._visibilityGrid.GetLocalEntities(
  113. this.Position, 15);
  114. this._ApplySteering(timeInSeconds, local);
  115. const frameVelocity = this._velocity.clone();
  116. frameVelocity.multiplyScalar(timeInSeconds);
  117. this._group.position.add(frameVelocity);
  118. const direction = this.Direction;
  119. const m = new THREE.Matrix4();
  120. m.lookAt(
  121. new THREE.Vector3(0, 0, 0),
  122. direction,
  123. new THREE.Vector3(0, 1, 0));
  124. this._group.quaternion.setFromRotationMatrix(m);
  125. this._visibilityIndex = this._game._visibilityGrid.UpdateItem(
  126. this._mesh.uuid, this, this._visibilityIndex);
  127. if (this._displayDebug) {
  128. this._UpdateDebug(local);
  129. }
  130. }
  131. _ApplySteering(timeInSeconds, local) {
  132. const forces = [
  133. this._ApplySeek(new THREE.Vector3(0, 10, 0)),
  134. this._ApplyWander(),
  135. this._ApplyGroundAvoidance(),
  136. this._ApplySeparation(local),
  137. ];
  138. if (this._radius < 5) {
  139. // Only apply alignment and cohesion to similar sized fish.
  140. local = local.filter((e) => {
  141. const ratio = this.Radius / e.Radius;
  142. return (ratio <= 1.35 && ratio >= 0.75);
  143. });
  144. forces.push(
  145. this._ApplyAlignment(local),
  146. this._ApplyCohesion(local),
  147. this._ApplySeparation(local)
  148. )
  149. }
  150. const steeringForce = new THREE.Vector3(0, 0, 0);
  151. for (const f of forces) {
  152. steeringForce.add(f);
  153. }
  154. steeringForce.multiplyScalar(this._acceleration * timeInSeconds);
  155. // Preferentially move in x/z dimension
  156. steeringForce.multiply(new THREE.Vector3(1, 0.25, 1));
  157. // Clamp the force applied
  158. if (steeringForce.length() > this._maxSteeringForce) {
  159. steeringForce.normalize();
  160. steeringForce.multiplyScalar(this._maxSteeringForce);
  161. }
  162. this._velocity.add(steeringForce);
  163. // Clamp velocity
  164. if (this._velocity.length() > this._maxSpeed) {
  165. this._velocity.normalize();
  166. this._velocity.multiplyScalar(this._maxSpeed);
  167. }
  168. this._direction = this._velocity.clone();
  169. this._direction.normalize();
  170. }
  171. _ApplyGroundAvoidance() {
  172. const p = this.Position;
  173. let force = new THREE.Vector3(0, 0, 0);
  174. if (p.y < 10) {
  175. force = new THREE.Vector3(0, 10 - p.y, 0);
  176. } else if (p.y > 30) {
  177. force = new THREE.Vector3(0, p.y - 50, 0);
  178. }
  179. return force.multiplyScalar(_BOID_FORCE_SEPARATION);
  180. }
  181. _ApplyWander() {
  182. this._wanderAngle += 0.1 * math.rand_range(-2 * Math.PI, 2 * Math.PI);
  183. const randomPointOnCircle = new THREE.Vector3(
  184. Math.cos(this._wanderAngle),
  185. 0,
  186. Math.sin(this._wanderAngle));
  187. const pointAhead = this._direction.clone();
  188. pointAhead.multiplyScalar(2);
  189. pointAhead.add(randomPointOnCircle);
  190. pointAhead.normalize();
  191. return pointAhead.multiplyScalar(_BOID_FORCE_WANDER);
  192. }
  193. _ApplySeparation(local) {
  194. if (local.length == 0) {
  195. return new THREE.Vector3(0, 0, 0);
  196. }
  197. const forceVector = new THREE.Vector3(0, 0, 0);
  198. for (let e of local) {
  199. const distanceToEntity = Math.max(
  200. e.Position.distanceTo(this.Position) - 1.5 * (this.Radius + e.Radius),
  201. 0.001);
  202. const directionFromEntity = new THREE.Vector3().subVectors(
  203. this.Position, e.Position);
  204. const multiplier = (
  205. _BOID_FORCE_SEPARATION / distanceToEntity) * (this.Radius + e.Radius);
  206. directionFromEntity.normalize();
  207. forceVector.add(
  208. directionFromEntity.multiplyScalar(multiplier));
  209. }
  210. return forceVector;
  211. }
  212. _ApplyAlignment(local) {
  213. const forceVector = new THREE.Vector3(0, 0, 0);
  214. for (let e of local) {
  215. const entityDirection = e.Direction;
  216. forceVector.add(entityDirection);
  217. }
  218. forceVector.normalize();
  219. forceVector.multiplyScalar(_BOID_FORCE_ALIGNMENT);
  220. return forceVector;
  221. }
  222. _ApplyCohesion(local) {
  223. const forceVector = new THREE.Vector3(0, 0, 0);
  224. if (local.length == 0) {
  225. return forceVector;
  226. }
  227. const averagePosition = new THREE.Vector3(0, 0, 0);
  228. for (let e of local) {
  229. averagePosition.add(e.Position);
  230. }
  231. averagePosition.multiplyScalar(1.0 / local.length);
  232. const directionToAveragePosition = averagePosition.clone().sub(
  233. this.Position);
  234. directionToAveragePosition.normalize();
  235. directionToAveragePosition.multiplyScalar(_BOID_FORCE_COHESION);
  236. return directionToAveragePosition;
  237. }
  238. _ApplySeek(destination) {
  239. const distance = Math.max(0,((
  240. this.Position.distanceTo(destination) - 50) / 250)) ** 2;
  241. const direction = destination.clone().sub(this.Position);
  242. direction.normalize();
  243. const forceVector = direction.multiplyScalar(
  244. _BOID_FORCE_ORIGIN * distance);
  245. return forceVector;
  246. }
  247. }
  248. class FishDemo extends game.Game {
  249. constructor() {
  250. super();
  251. }
  252. _OnInitialize() {
  253. this._entities = [];
  254. this._graphics.Scene.fog = new THREE.FogExp2(
  255. new THREE.Color(0x4d7dbe), 0.01);
  256. this._LoadBackground();
  257. const loader = new OBJLoader();
  258. const geoLibrary = {};
  259. loader.load("./resources/fish.obj", (result) => {
  260. geoLibrary.fish = result.children[0].geometry;
  261. loader.load("./resources/bigfish.obj", (result) => {
  262. geoLibrary.bigFish = result.children[0].geometry;
  263. this._CreateBoids(geoLibrary);
  264. });
  265. });
  266. this._CreateEntities();
  267. }
  268. _LoadBackground() {
  269. const loader = new THREE.TextureLoader();
  270. const texture = loader.load('./resources/underwater.jpg');
  271. this._graphics._scene.background = texture;
  272. }
  273. _CreateEntities() {
  274. const plane = new THREE.Mesh(
  275. new THREE.PlaneGeometry(400, 400, 32, 32),
  276. new THREE.MeshStandardMaterial({
  277. color: 0x837860,
  278. transparent: true,
  279. opacity: 0.5,
  280. }));
  281. plane.position.set(0, -5, 0);
  282. plane.castShadow = false;
  283. plane.receiveShadow = true;
  284. plane.rotation.x = -Math.PI / 2;
  285. this._graphics.Scene.add(plane);
  286. this._visibilityGrid = new visibility.VisibilityGrid(
  287. [new THREE.Vector3(-500, 0, -500), new THREE.Vector3(500, 0, 500)],
  288. [100, 100]);
  289. }
  290. _CreateBoids(geoLibrary) {
  291. const NUM_SMALL = _NUM_BOIDS * 2;
  292. const NUM_MEDIUM = _NUM_BOIDS / 2;
  293. const NUM_LARGE = _NUM_BOIDS / 20;
  294. const NUM_WHALES = 3;
  295. let params = {
  296. geometry: geoLibrary.fish,
  297. speedMin: 3.0,
  298. speedMax: 4.0,
  299. speed: _BOID_SPEED,
  300. maxSteeringForce: _BOID_FORCE_MAX,
  301. acceleration: _BOID_ACCELERATION,
  302. colour: 0x80FF80,
  303. };
  304. for (let i = 0; i < NUM_SMALL; i++) {
  305. const e = new Boid(this, params);
  306. this._entities.push(e);
  307. }
  308. params = {
  309. geometry: geoLibrary.fish,
  310. speedMin: 0.85,
  311. speedMax: 1.1,
  312. speed: _BOID_SPEED,
  313. maxSteeringForce: _BOID_FORCE_MAX,
  314. acceleration: _BOID_ACCELERATION,
  315. colour: 0x8080FF,
  316. };
  317. for (let i = 0; i < NUM_MEDIUM; i++) {
  318. const e = new Boid(this, params);
  319. this._entities.push(e);
  320. }
  321. params = {
  322. geometry: geoLibrary.fish,
  323. speedMin: 0.4,
  324. speedMax: 0.6,
  325. speed: _BOID_SPEED,
  326. maxSteeringForce: _BOID_FORCE_MAX / 4,
  327. acceleration: _BOID_ACCELERATION,
  328. colour: 0xFF8080,
  329. };
  330. for (let i = 0; i < NUM_LARGE; i++) {
  331. const e = new Boid(this, params);
  332. this._entities.push(e);
  333. }
  334. params = {
  335. geometry: geoLibrary.bigFish,
  336. speedMin: 0.1,
  337. speedMax: 0.12,
  338. speed: _BOID_SPEED,
  339. maxSteeringForce: _BOID_FORCE_MAX / 20,
  340. acceleration: _BOID_ACCELERATION,
  341. colour: 0xFF8080,
  342. };
  343. for (let i = 0; i < NUM_WHALES; i++) {
  344. const e = new Boid(this, params);
  345. e._group.position.y = math.rand_range(23, 26);
  346. this._entities.push(e);
  347. }
  348. //this._entities[0].DisplayDebug();
  349. }
  350. _OnStep(timeInSeconds) {
  351. timeInSeconds = Math.min(timeInSeconds, 1 / 10.0);
  352. if (this._entities.length == 0) {
  353. return;
  354. }
  355. // const eye = this._entities[0].Position.clone();
  356. // const dir = this._entities[0].Direction.clone();
  357. // dir.multiplyScalar(5);
  358. // eye.sub(dir);
  359. //
  360. // const m = new THREE.Matrix4();
  361. // m.lookAt(eye, this._entities[0].Position, new THREE.Vector3(0, 1, 0));
  362. //
  363. // const q = new THREE.Quaternion();
  364. // q.setFromEuler(new THREE.Euler(Math.PI / 2, 0, 0));
  365. //
  366. // const oldPosition = this._graphics._camera.position;
  367. // this._graphics._camera.position.lerp(eye, 0.05);
  368. // this._graphics._camera.quaternion.copy(this._entities[0]._group.quaternion);
  369. // //this._graphics._camera.quaternion.multiply(q);
  370. // this._controls.enabled = false;
  371. for (let e of this._entities) {
  372. e.Step(timeInSeconds);
  373. }
  374. }
  375. }
  376. function _Main() {
  377. _APP = new FishDemo();
  378. }
  379. _Main();