game.js 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834
  1. /*
  2. Blocky - game.js
  3. One running world: ties together the world simulation, the player, the
  4. inventory, entities, weather and the day / night cycle, and turns input
  5. into actions (mining, placing, using items, eating).
  6. Time runs at 20 ticks per second; a full day is 24000 ticks (20 real
  7. minutes). Tick 0 is sunrise.
  8. */
  9. import {
  10. B, BLOCKS, ITEMS, I, SHAPE, SOLID, blockDrops, breakSeconds, blockFaceLayer, isOpaqueAt, HDIR, facingFromYaw,
  11. attackDamage, LIGHT_EMIT
  12. } from "./blocks.js";
  13. import { Mobs } from "./mobs.js";
  14. import { Carts } from "./carts.js";
  15. import { Boats } from "./boats.js";
  16. import { Signs } from "./signs.js";
  17. import { WorldEdit } from "./worldedit.js";
  18. import { Machines } from "./machines.js";
  19. import { World, WORLD_H, TE_KINDS } from "./world.js";
  20. import { BIOME, BIOME_NAMES } from "./worldgen.js";
  21. import { Player, DIFFICULTY } from "./player.js";
  22. import { Inventory } from "./inventory.js";
  23. import { Entities, ITEM_HALF } from "./entities.js";
  24. import { moveAxis, regionBlocked } from "./physics.js";
  25. import { selectionBox, collisionBoxes, FACE_DIR, doorHinge } from "./shapes.js";
  26. import { deflateString, mulberry32, clamp, lerp } from "./util.js";
  27. const TICK = 0.05;
  28. const DAY = 24000;
  29. const AUTOSAVE_SECONDS = 120;
  30. const DEATH_TEXT = {
  31. fall: "You hit the ground too hard",
  32. drown: "You drowned",
  33. starve: "You starved to death",
  34. cactus: "You were pricked to death by a cactus",
  35. arrow: "You were shot by a dispenser",
  36. lightning: "You were struck by lightning",
  37. suffocate: "You suffocated in a wall",
  38. lava: "You tried to swim in lava",
  39. fire: "You went up in flames",
  40. burn: "You burned to death",
  41. wolf: "You were mauled by wolves",
  42. bear: "You were mauled by a bear",
  43. command: "You ended it with a command",
  44. void: "You fell out of the world"
  45. };
  46. export class Game {
  47. constructor(app, meta, state) {
  48. this.app = app;
  49. this.renderer = app.renderer;
  50. this.sound = app.sound;
  51. this.ui = app.ui;
  52. this.input = app.input;
  53. this.meta = meta;
  54. this.state = state;
  55. this.rng = mulberry32((Date.now() ^ meta.seed) | 0);
  56. this.paused = false;
  57. this.hideHud = false;
  58. this.debug = false;
  59. this.accum = 0;
  60. this.breaking = null;
  61. this.breakCooldown = 0;
  62. this.useCooldown = 0;
  63. this.eatT = 0;
  64. this.eatSound = 0;
  65. this.swing = 1;
  66. this.equip = 0;
  67. this.lastHeld = -1;
  68. this.lastSelected = -1;
  69. this.stepDist = 0;
  70. this.saving = false;
  71. this.saveTimer = AUTOSAVE_SECONDS;
  72. this.fovNow = 75;
  73. this.frameNo = 0;
  74. this.fps = 0;
  75. this.fpsAcc = 0;
  76. this.fpsFrames = 0;
  77. this.placeOnGround = false;
  78. this.wasInWater = false;
  79. this.pickupSoundAt = 0;
  80. this.hit = null;
  81. //Selection, clipboard and history of the WorldEdit commands (not saved)
  82. this.we = new WorldEdit(this);
  83. }
  84. get settings() {
  85. return this.app.settings;
  86. }
  87. get creative() {
  88. return this.player.creative;
  89. }
  90. /* ---------------- setup ---------------- */
  91. async load(progress) {
  92. const meta = this.meta, state = this.state || {};
  93. this.world = new World(meta.seed, {
  94. onDrop: (x, y, z, id, n, dmg) => this.entities.spawnItem(x, y, z, id, n, dmg || 0),
  95. onFalling: (x, y, z, id, meta2) => this.entities.spawnFalling(x, y, z, id, meta2),
  96. onBlockBroken: (x, y, z, id) => this.blockParticles(x, y, z, id, 0, 10),
  97. onPowerSound: (x, y, z, id, out) => {
  98. if (id === B.PISTON || id === B.STICKY_PISTON) {
  99. this.sound.play("piston", { out });
  100. } else if (id === B.DOOR || id === B.TRAPDOOR) {
  101. this.sound.block("place", "wood");
  102. } else {
  103. this.sound.play("click");
  104. }
  105. },
  106. onPistonPush: (cells, d) => this.pistonPush(cells, d),
  107. onDispense: (x, y, z, face) => this.machines.dispense(x, y, z, face),
  108. onFizz: (x, y, z) => {
  109. this.sound.play("fizz");
  110. this.renderer.spawnParticles(x + 0.5, y + 1, z + 0.5, [200, 200, 200], 12, 0.4, 2);
  111. }
  112. });
  113. this.renderer.attachWorld(this.world);
  114. this.entities = new Entities(this.renderer);
  115. this.mobs = new Mobs(this);
  116. this.carts = new Carts(this);
  117. this.boats = new Boats(this);
  118. this.machines = new Machines(this);
  119. this.signs = new Signs(this);
  120. this.riding = null;
  121. this.boat = null;
  122. this.player = new Player(this.world);
  123. this.inventory = new Inventory();
  124. this.player.creative = meta.mode === "creative";
  125. this.player.difficulty = clamp(meta.difficulty ?? 2, 0, 3);
  126. this.ticks = state.ticks ?? 1000;
  127. //Every session starts with clear skies for 10-20 minutes
  128. this.weather = {
  129. state: "clear",
  130. timer: 12000 + Math.floor(this.rng() * 12000),
  131. rain: 0,
  132. thunder: 0,
  133. strikeIn: 4,
  134. flash: 0
  135. };
  136. this.world.load(state.world);
  137. if (state.spawn) {
  138. this.spawn = state.spawn;
  139. } else {
  140. const s = this.world.gen.findSpawn();
  141. this.spawn = { x: s.x, y: s.h + 1, z: s.z };
  142. }
  143. if (state.player) {
  144. this.player.load(state.player);
  145. } else {
  146. this.player.setPos(this.spawn.x, this.spawn.y, this.spawn.z);
  147. this.player.yaw = Math.PI * 0.75;
  148. this.placeOnGround = true;
  149. }
  150. this.inventory.load(state.inventory);
  151. if (!state.player && this.player.creative) {
  152. //A starter hotbar for creative worlds
  153. [B.GRASS, B.STONE, B.PLANKS, B.LOG, B.GLASS, B.BRICKS, B.TORCH, B.LAMP, B.WORKBENCH].forEach((id, i) => {
  154. this.inventory.slots[i] = { id, count: ITEMS[id].stack, dmg: 0 };
  155. });
  156. }
  157. //Stream the spawn area before showing it
  158. const R = this.settings.renderDistance;
  159. const pcx = Math.floor(this.player.x / 16), pcz = Math.floor(this.player.z / 16);
  160. const need = Math.min(R, 3);
  161. await new Promise((resolve) => {
  162. const step = () => {
  163. const t0 = performance.now();
  164. this.world.stream(pcx, pcz, R, t0 + 40);
  165. this.renderer.updateMeshes(this.world, this.player.x, this.player.z, need, t0 + 60);
  166. let ready = 0, total = 0;
  167. for (let dx = -need; dx <= need; dx++) {
  168. for (let dz = -need; dz <= need; dz++) {
  169. total++;
  170. const c = this.world.chunkAt(pcx + dx, pcz + dz);
  171. if (c && c.meshes && !c.dirty.some((d) => d)) {
  172. ready++;
  173. }
  174. }
  175. }
  176. progress(ready / total);
  177. if (ready >= total) {
  178. resolve();
  179. } else {
  180. setTimeout(step, 0);
  181. }
  182. };
  183. step();
  184. });
  185. if (this.placeOnGround) {
  186. this.dropToGround();
  187. }
  188. this.entities.load(state.entities);
  189. this.carts.load(state.carts);
  190. this.boats.load(state.boats);
  191. this.ui.hudKey = "";
  192. }
  193. //Put the player on top of the column it stands in
  194. dropToGround() {
  195. const x = Math.floor(this.player.x), z = Math.floor(this.player.z);
  196. if (!this.world.isLoaded(x, z)) {
  197. return false;
  198. }
  199. let y = WORLD_H - 2;
  200. while (y > 1 && !SOLID[this.world.getBlock(x, y - 1, z)] && this.world.getBlock(x, y - 1, z) !== B.WATER) {
  201. y--;
  202. }
  203. this.player.setPos(this.player.x, y, this.player.z);
  204. this.placeOnGround = false;
  205. return true;
  206. }
  207. dispose() {
  208. this.entities.clear();
  209. this.mobs.clear();
  210. this.carts.clear();
  211. this.boats.clear();
  212. this.signs.clear();
  213. this.renderer.setRegion(null);
  214. this.renderer.detachWorld();
  215. this.renderer.setHeldItem(0);
  216. this.sound.setRain(0, false);
  217. }
  218. /* ---------------- per frame ---------------- */
  219. frame(dt, now) {
  220. const p = this.player, r = this.renderer, input = this.input;
  221. this.frameNo++;
  222. this.fpsAcc += dt;
  223. this.fpsFrames++;
  224. if (this.fpsAcc >= 0.5) {
  225. this.fps = Math.round(this.fpsFrames / this.fpsAcc);
  226. this.fpsAcc = 0;
  227. this.fpsFrames = 0;
  228. }
  229. this.handleKeys();
  230. const pcx = Math.floor(p.x / 16), pcz = Math.floor(p.z / 16);
  231. const here = this.world.chunkAt(pcx, pcz);
  232. const ready = here && here.lit;
  233. if (!this.paused) {
  234. this.accum += dt;
  235. let n = 0;
  236. while (this.accum >= TICK && n < 5) {
  237. this.tick();
  238. this.accum -= TICK;
  239. n++;
  240. }
  241. if (n === 5) {
  242. this.accum = 0;
  243. }
  244. //Look
  245. const [mx, my] = input.consumeLook();
  246. if (input.locked && !this.ui.isOpen() && !p.dead) {
  247. const s = 0.0022 * this.settings.sensitivity;
  248. p.yaw -= mx * s;
  249. p.pitch -= my * s * (this.settings.invertY ? -1 : 1);
  250. p.pitch = clamp(p.pitch, -1.55, 1.55);
  251. }
  252. if (this.touchLook) {
  253. p.yaw -= this.touchLook[0];
  254. p.pitch = clamp(p.pitch - this.touchLook[1], -1.55, 1.55);
  255. this.touchLook = null;
  256. }
  257. //Move
  258. if (this.placeOnGround && ready) {
  259. this.dropToGround();
  260. }
  261. if (this.sleeping) {
  262. this.updateSleep(dt);
  263. } else if (this.riding || this.boat) {
  264. //The cart or boat carries the player (updates below)
  265. } else if (ready && !this.placeOnGround) {
  266. const mv = this.movementInput();
  267. let rem = Math.min(dt, 0.1);
  268. while (rem > 1e-4) {
  269. const s = Math.min(rem, 1 / 60);
  270. p.update(s, mv);
  271. rem -= s;
  272. }
  273. }
  274. this.handlePlayerEvents();
  275. this.updateInteraction(dt);
  276. this.entities.update(dt, this.world, p, this.inventory, (id, count) => this.onPickup(id, count));
  277. this.mobs.update(dt);
  278. this.carts.update(dt, this.riding ? this.movementInput() : null);
  279. if (this.riding) {
  280. const c = this.riding;
  281. p.x = c.x;
  282. p.y = c.y - 0.25;
  283. p.z = c.z;
  284. p.vx = p.vy = p.vz = 0;
  285. p.fallDistance = 0;
  286. }
  287. this.boats.update(dt, this.boat ? this.movementInput() : null);
  288. if (this.boat) {
  289. [p.x, p.y, p.z] = this.boats.seat(this.boat);
  290. p.vx = p.vy = p.vz = 0;
  291. p.fallDistance = 0;
  292. p.sense();
  293. p.onGround = true;
  294. }
  295. r.updateParticles(dt, this.world);
  296. r.updateLightning(dt);
  297. this.updateWeather(dt);
  298. this.saveTimer -= dt;
  299. if (this.saveTimer <= 0) {
  300. this.saveTimer = AUTOSAVE_SECONDS;
  301. this.save(true);
  302. }
  303. } else {
  304. input.consumeLook();
  305. }
  306. this.we.update();
  307. //Streaming
  308. const R = this.settings.renderDistance;
  309. this.world.stream(pcx, pcz, R, now + 7);
  310. if (this.frameNo % 60 === 0) {
  311. for (const c of this.world.unloadFar(pcx, pcz, R)) {
  312. r.disposeChunk(c);
  313. }
  314. }
  315. this.pendingMeshes = r.updateMeshes(this.world, p.x, p.z, R, performance.now() + 7);
  316. this.updateCamera(dt);
  317. const env = r.applyEnvironment({
  318. time: this.ticks % DAY,
  319. day: Math.floor(this.ticks / DAY),
  320. rain: this.weather.rain,
  321. thunder: this.weather.thunder,
  322. flash: this.weather.flash,
  323. underwater: p.headInWater,
  324. underlava: p.headInLava,
  325. renderDistance: R
  326. });
  327. this.world.skyDarken = Math.round((1 - env.day) * 11 + this.weather.rain * 2);
  328. this.world.raining = this.weather.rain > 0.5;
  329. const exposure = r.updateRain(dt, this.weather.rain, r.camera.position, this.world);
  330. this.sound.setRain(this.paused ? 0 : this.weather.rain * (0.2 + 0.8 * exposure), exposure < 0.25);
  331. //Held item
  332. const held = this.inventory.heldId();
  333. if (held !== this.lastHeld || this.inventory.selected !== this.lastSelected) {
  334. if (this.lastSelected !== -1) {
  335. this.equip = 1;
  336. this.ui.showItemName(held);
  337. }
  338. this.lastHeld = held;
  339. this.lastSelected = this.inventory.selected;
  340. }
  341. this.equip = Math.max(0, this.equip - dt * 6);
  342. this.swing = Math.min(1, this.swing + dt * 4);
  343. //A drawn bow shows its string pulled back with an arrow on it
  344. const pull = held === I.BOW && this.bowDraw > 0 ? Math.min(1, this.bowDraw) : 0;
  345. let heldTile = pull > 0 ? (pull < 0.35 ? "bow_pull_0" : pull < 0.75 ? "bow_pull_1" : "bow_pull_2") : null;
  346. if (held === I.COMPASS) {
  347. heldTile = "compass_" + this.compassStep();
  348. }
  349. r.setHeldItem(held, heldTile);
  350. const ex = Math.floor(p.x), ey = Math.floor(p.eyeY), ez = Math.floor(p.z);
  351. //A torch or other glowing thing in hand lights the area
  352. const glow = p.dead ? 0 : held === I.LAVA_BUCKET ? 15 : held > 0 && held < 256 ? LIGHT_EMIT[held] : 0;
  353. r.dyn.update(this.world, p.x, p.eyeY, p.z, glow, dt);
  354. const bobOn = this.settings.viewBobbing && p.onGround && !p.flying;
  355. const phase = p.walkDist * Math.PI * 0.75;
  356. const amp = bobOn ? Math.min(1, Math.hypot(p.vx, p.vz) / 4.3) : 0;
  357. r.updateHand({
  358. swing: this.swing >= 1 ? 0 : this.swing,
  359. equip: this.equip,
  360. bobX: Math.sin(phase) * 0.03 * amp,
  361. bobY: -Math.abs(Math.cos(phase)) * 0.03 * amp,
  362. eat: this.eatT > 0 ? 1 : 0,
  363. draw: this.bowDraw > 0 ? Math.min(1, this.bowDraw) : 0,
  364. eatT: this.eatT,
  365. sky: this.world.getSky(ex, ey, ez) / 15,
  366. blk: Math.max(this.world.getBlockLight(ex, ey, ez), r.dyn.at(ex, ey, ez)) / 15
  367. });
  368. this.signs.update();
  369. r.render(dt, !this.hideHud && !p.dead && !this.sleeping);
  370. if (this.shotPending) {
  371. //Read the canvas in the same task as the draw, before the
  372. //browser presents (and may clear) the drawing buffer
  373. this.shotPending = false;
  374. this.sound.play("click");
  375. r.canvas.toBlob((blob) => this.app.saveScreenshot(blob), "image/png");
  376. }
  377. this.ui.updateHud(this);
  378. document.getElementById("underwater").classList.toggle("on", p.headInWater);
  379. document.getElementById("hurt").classList.toggle("on", p.hurtTime > 0.3);
  380. document.getElementById("burning").classList.toggle("on", !this.creative && (p.burnTime > 0 || p.inLava));
  381. this.updateDebug();
  382. input.endFrame();
  383. }
  384. movementInput() {
  385. const k = (c) => this.input.down(c);
  386. if (this.ui.isOpen() || this.player.dead || this.paused || this.app.chat.open || this.sleeping) {
  387. return { forward: 0, strafe: 0, jump: false, sneak: false, sprint: false };
  388. }
  389. const t = this.input.touchMove;
  390. let forward = (k("KeyW") || k("ArrowUp") ? 1 : 0) - (k("KeyS") || k("ArrowDown") ? 1 : 0) + t.forward;
  391. let strafe = (k("KeyD") || k("ArrowRight") ? 1 : 0) - (k("KeyA") || k("ArrowLeft") ? 1 : 0) + t.strafe;
  392. if (!k("KeyW") && !k("ArrowUp") && t.forward <= 0.7) {
  393. this.sprintTap = false;
  394. }
  395. return {
  396. forward: clamp(forward, -1, 1),
  397. strafe: clamp(strafe, -1, 1),
  398. jump: k("Space") || this.input.touchJump,
  399. sneak: k("ShiftLeft") || k("ShiftRight") || this.input.touchSneak,
  400. sprint: k("ControlLeft") || k("ControlRight") || this.sprintTap
  401. };
  402. }
  403. handleKeys() {
  404. const input = this.input, ui = this.ui, p = this.player;
  405. for (const code of input.pressed) {
  406. if (code === "KeyE") {
  407. if (ui.isOpen()) {
  408. this.closeScreen();
  409. } else if (!this.paused && !p.dead) {
  410. this.openScreen("inventory");
  411. }
  412. } else if (code === "Escape") {
  413. if (ui.isOpen()) {
  414. this.closeScreen();
  415. }
  416. } else if ((code === "KeyT" || code === "Slash") && !ui.isOpen() && !this.paused && !p.dead) {
  417. this.app.chat.show(code === "Slash" ? "/" : "");
  418. } else if (code.startsWith("Digit")) {
  419. const n = Number(code.slice(5)) - 1;
  420. if (n >= 0 && n < 9) {
  421. if (ui.isOpen()) {
  422. ui.hotkey(n);
  423. } else {
  424. this.inventory.selected = n;
  425. }
  426. }
  427. } else if (code === "KeyQ" && !ui.isOpen() && !this.paused && !p.dead) {
  428. this.dropHeld(input.down("ControlLeft") || input.down("ControlRight"));
  429. } else if (code === "F2") {
  430. //Taken right after the next frame is drawn
  431. this.shotPending = true;
  432. } else if (code === "F3") {
  433. this.debug = !this.debug;
  434. } else if (code === "F1") {
  435. this.hideHud = !this.hideHud;
  436. document.getElementById("hud").classList.toggle("bare", this.hideHud);
  437. }
  438. }
  439. if (input.doubleTaps.has("Space") && this.creative && !ui.isOpen()) {
  440. p.flying = !p.flying;
  441. p.vy = 0;
  442. }
  443. if (input.doubleTaps.has("KeyW")) {
  444. this.sprintTap = true;
  445. }
  446. const wheel = input.consumeWheel();
  447. if (wheel !== 0 && !ui.isOpen()) {
  448. this.inventory.selected = (this.inventory.selected + (wheel > 0 ? 1 : -1) + 9) % 9;
  449. }
  450. }
  451. /* ---------------- ticks ---------------- */
  452. //Pressure plates pressed by the player, animals and (wooden ones only)
  453. //dropped items, carts and boats. A plate senses the bottom quarter of
  454. //its block, inset 1/16 at the sides: feet standing on it, or a body
  455. //passing through (beside a plate on a fence post, say)
  456. pressPlates() {
  457. const w = this.world, U = 1 / 16;
  458. const press = (b, living) => {
  459. for (let by = Math.floor(b[1]); by < b[4]; by++) {
  460. if (b[1] >= by + 0.25) {
  461. continue;
  462. }
  463. for (let bx = Math.floor(b[0]); bx < b[3]; bx++) {
  464. for (let bz = Math.floor(b[2]); bz < b[5]; bz++) {
  465. const id = w.getBlock(bx, by, bz);
  466. if ((id !== B.PLATE_WOOD && id !== B.PLATE_STONE) || (id === B.PLATE_STONE && !living)) {
  467. continue;
  468. }
  469. if (b[3] <= bx + U || b[0] >= bx + 1 - U || b[5] <= bz + U || b[2] >= bz + 1 - U) {
  470. continue;
  471. }
  472. if (w.pressPlate(bx, by, bz)) {
  473. this.sound.play("click");
  474. }
  475. }
  476. }
  477. }
  478. };
  479. const p = this.player;
  480. if (!p.dead) {
  481. press(p.box(), true);
  482. }
  483. for (const m of this.mobs.list) {
  484. press(this.mobs.box(m), true);
  485. }
  486. const h = ITEM_HALF;
  487. for (const e of this.entities.items) {
  488. press([e.x - h, e.y, e.z - h, e.x + h, e.y + 2 * h, e.z + h], false);
  489. }
  490. for (const c of this.carts.list) {
  491. press(this.carts.box(c), false);
  492. }
  493. for (const b of this.boats.list) {
  494. press(this.boats.box(b), false);
  495. }
  496. }
  497. tick() {
  498. this.ticks++;
  499. const p = this.player;
  500. this.world.tick(Math.floor(p.x / 16), Math.floor(p.z / 16));
  501. this.pressPlates();
  502. this.machines.tick();
  503. p.tick();
  504. const w = this.weather;
  505. w.timer--;
  506. if (w.timer <= 0) {
  507. if (w.state === "clear") {
  508. w.state = this.rng() < 0.7 ? "rain" : "thunder";
  509. w.timer = 3600 + Math.floor(this.rng() * 6000);
  510. } else if (w.state === "thunder" && this.rng() < 0.35) {
  511. w.state = "rain";
  512. w.timer = 2400 + Math.floor(this.rng() * 3600);
  513. } else {
  514. w.state = "clear";
  515. w.timer = 6000 + Math.floor(this.rng() * 14000);
  516. }
  517. }
  518. //Containers change while open (furnaces burn, feeders move items)
  519. if (this.ui.isOpen() && this.ui.screen.te && this.ui.screen.te.slots && this.ticks % 2 === 0) {
  520. this.ui.renderScreen(false);
  521. }
  522. }
  523. updateWeather(dt) {
  524. const w = this.weather;
  525. const rainTarget = w.state === "clear" ? 0 : 1;
  526. const thunderTarget = w.state === "thunder" ? 1 : 0;
  527. const step = dt * 0.12;
  528. w.rain += clamp(rainTarget - w.rain, -step, step);
  529. w.thunder += clamp(thunderTarget - w.thunder, -step, step);
  530. w.flash = Math.max(0, w.flash - dt * 3.5);
  531. if (w.state === "thunder" && w.thunder > 0.6) {
  532. w.strikeIn -= dt;
  533. if (w.strikeIn <= 0) {
  534. w.strikeIn = 3 + this.rng() * 14;
  535. this.lightningStrike();
  536. }
  537. }
  538. }
  539. lightningStrike() {
  540. const p = this.player;
  541. const ang = this.rng() * Math.PI * 2, d = 6 + this.rng() * 70;
  542. const x = Math.floor(p.x + Math.cos(ang) * d), z = Math.floor(p.z + Math.sin(ang) * d);
  543. if (!this.world.isLoaded(x, z) || this.world.biomeAt(x, z) === BIOME.DESERT) {
  544. return;
  545. }
  546. const y = this.world.rainTop(x, z);
  547. this.renderer.strikeLightning(x + 0.5, y, z + 0.5);
  548. this.weather.flash = 1;
  549. const dist = Math.hypot(x + 0.5 - p.x, z + 0.5 - p.z, y - p.y);
  550. this.sound.play("thunder", { distance: dist });
  551. if (dist < 3.5) {
  552. p.hurt(5, "lightning");
  553. }
  554. }
  555. setWeather(state) {
  556. this.weather.state = state;
  557. this.weather.timer = state === "clear" ? 12000 : 6000;
  558. if (state === "thunder") {
  559. this.weather.strikeIn = 2;
  560. }
  561. }
  562. setTime(t) {
  563. this.ticks = Math.floor(this.ticks / DAY) * DAY + t + (t < this.ticks % DAY ? DAY : 0);
  564. }
  565. setMode(creative) {
  566. this.player.creative = creative;
  567. if (!creative) {
  568. this.player.flying = false;
  569. }
  570. this.meta.mode = creative ? "creative" : "survival";
  571. this.ui.hudKey = "";
  572. }
  573. setDifficulty(d) {
  574. this.player.difficulty = d;
  575. this.meta.difficulty = d;
  576. }
  577. /* ---------------- interaction ---------------- */
  578. eyeRay() {
  579. const p = this.player;
  580. const cp = Math.cos(p.pitch);
  581. return [p.x, p.eyeY, p.z, -Math.sin(p.yaw) * cp, Math.sin(p.pitch), -Math.cos(p.yaw) * cp];
  582. }
  583. updateInteraction(dt) {
  584. const p = this.player, input = this.input, r = this.renderer;
  585. this.breakCooldown = Math.max(0, this.breakCooldown - dt);
  586. this.useCooldown = Math.max(0, this.useCooldown - dt);
  587. const active = !this.ui.isOpen() && !p.dead && !this.paused && !this.app.chat.open && !this.sleeping && (input.locked || this.touchActive);
  588. if (!active) {
  589. this.breaking = null;
  590. this.eatT = 0;
  591. r.setSelection(null);
  592. r.setCrack(null, 0);
  593. this.hit = null;
  594. return;
  595. }
  596. const [ox, oy, oz, dx, dy, dz] = this.eyeRay();
  597. const reach = this.creative ? 5.5 : 4.5;
  598. const hit = this.world.raycast(ox, oy, oz, dx, dy, dz, reach, (id, m, x, y, z) => selectionBox(id, m, this.world, x, y, z));
  599. this.hit = hit;
  600. //An animal in front of the block under the crosshair takes the click
  601. const mobHit = this.mobs.raycast(ox, oy, oz, dx, dy, dz, this.creative ? 5 : 3.5);
  602. const cartHit = this.carts.raycast(ox, oy, oz, dx, dy, dz, reach);
  603. const near = (h) => h && (!hit || h.t < hit.t);
  604. //A cart wins over the rail it stands on: in a dip the rail's box
  605. //sticks out a little in front of the cart's lower half
  606. const onRail = cartHit && hit && SHAPE[hit.id] === "rail" && cartHit.t < hit.t + 1;
  607. const aimCart = (near(cartHit) || onRail) && (!mobHit || cartHit.t < mobHit.t) ? cartHit.cart : null;
  608. //Boats sit in water, which the block ray passes through
  609. const boatHit = aimCart ? null : this.boats.raycast(ox, oy, oz, dx, dy, dz, reach);
  610. const aimBoat = near(boatHit) && (!mobHit || boatHit.t < mobHit.t) ? boatHit.boat : null;
  611. const aimMob = !aimCart && !aimBoat && near(mobHit) ? mobHit.mob : null;
  612. this.aimMob = aimMob;
  613. r.setSelection(this.hideHud || aimMob || aimCart || aimBoat ? null : hit);
  614. const leftDown = input.buttons.has(0) || this.touchBreak;
  615. const rightDown = input.buttons.has(2);
  616. const rightClick = input.clicked.has(2) || this.touchUse;
  617. if (input.clicked.has(1) && hit) {
  618. this.pickBlock(hit);
  619. }
  620. this.touchUse = false;
  621. //The WorldEdit wand marks the selection's corners instead of mining or placing
  622. if (this.we.wandHeld()) {
  623. for (const n of [1, 2]) {
  624. if (input.clicked.has(n === 1 ? 0 : 2)) {
  625. this.swing = 0;
  626. this.we.wandClick(n, hit);
  627. }
  628. }
  629. this.breaking = null;
  630. r.setCrack(null, 0);
  631. return;
  632. }
  633. //The WorldEdit compass: left click jumps to the block in sight, right
  634. //click passes through the wall within reach (or jumps when none is)
  635. if (this.we.compassHeld()) {
  636. for (const right of [false, true]) {
  637. if (input.clicked.has(right ? 2 : 0)) {
  638. this.swing = 0;
  639. this.we.compassClick(right, hit);
  640. }
  641. }
  642. this.breaking = null;
  643. r.setCrack(null, 0);
  644. return;
  645. }
  646. //Fighting
  647. this.attackCd = Math.max(0, (this.attackCd || 0) - dt);
  648. if (aimMob && (input.clicked.has(0) || (this.touchBreak && this.attackCd === 0))) {
  649. this.swing = 0;
  650. if (this.attackCd === 0) {
  651. this.attackMob(aimMob);
  652. this.attackCd = 0.4;
  653. }
  654. }
  655. if (aimCart && input.clicked.has(0)) {
  656. this.swing = 0;
  657. this.carts.hit(aimCart);
  658. }
  659. if (aimBoat && input.clicked.has(0)) {
  660. this.swing = 0;
  661. this.boats.hit(aimBoat);
  662. }
  663. //After hitting a cart or an animal, holding the button on mines
  664. //nothing until it is let go (the block behind would break next)
  665. if ((aimCart || aimBoat || aimMob) && leftDown) {
  666. this.attackHold = true;
  667. } else if (!leftDown) {
  668. this.attackHold = false;
  669. }
  670. //Mining
  671. if (leftDown && !aimMob && !aimCart && !aimBoat && !this.attackHold) {
  672. if (input.clicked.has(0) || this.swing >= 1) {
  673. this.swing = 0;
  674. }
  675. if (this.creative) {
  676. if (hit && this.breakCooldown <= 0) {
  677. this.breakBlock(hit, false);
  678. this.breakCooldown = 0.22;
  679. }
  680. this.breaking = null;
  681. } else if (!hit) {
  682. this.breaking = null;
  683. } else {
  684. const same = this.breaking && this.breaking.x === hit.x && this.breaking.y === hit.y && this.breaking.z === hit.z && this.breaking.id === hit.id;
  685. if (!same) {
  686. this.breaking = { x: hit.x, y: hit.y, z: hit.z, id: hit.id, progress: 0, sound: 0 };
  687. }
  688. if (this.breakCooldown <= 0) {
  689. const def = BLOCKS[hit.id];
  690. let t = breakSeconds(def, this.inventory.heldId());
  691. if (p.headInWater) {
  692. t *= 5;
  693. }
  694. if (!p.onGround && !p.inWater && !p.onLadder) {
  695. t *= 5;
  696. }
  697. const b = this.breaking;
  698. b.progress = t <= 0 ? 1 : b.progress + dt / t;
  699. b.sound -= dt;
  700. if (b.sound <= 0 && b.progress < 1) {
  701. b.sound = 0.24;
  702. this.sound.block("dig", def.sound);
  703. this.blockParticles(hit.x, hit.y, hit.z, hit.id, hit.meta, 2, hit.point);
  704. }
  705. if (b.progress >= 1) {
  706. this.breakBlock(hit, true);
  707. this.breaking = null;
  708. this.breakCooldown = 0.25;
  709. }
  710. }
  711. }
  712. } else {
  713. this.breaking = null;
  714. }
  715. r.setCrack(hit, this.breaking ? this.breaking.progress : 0);
  716. const held = this.inventory.held;
  717. const heldDef = held && ITEMS[held.id];
  718. //Carts take right clicks before anything held does. The button is
  719. //still down for a few frames after the click: until it is let go
  720. //it must not place the held block where the cart was.
  721. if (!rightDown) {
  722. this.useHold = false;
  723. }
  724. if (aimCart && rightClick) {
  725. this.swing = 0;
  726. this.carts.use(aimCart);
  727. this.useHold = true;
  728. return;
  729. }
  730. if (aimBoat && rightClick) {
  731. this.swing = 0;
  732. this.boats.use(aimBoat);
  733. this.useHold = true;
  734. return;
  735. }
  736. if (this.useHold) {
  737. return;
  738. }
  739. //Bow: hold to draw, let go to shoot
  740. const useBlock = rightClick && hit && BLOCKS[hit.id].interact && !p.sneaking;
  741. if (held && held.id === I.BOW && !useBlock) {
  742. if (rightDown) {
  743. if (this.creative || this.inventory.count(I.ARROW) > 0) {
  744. this.bowDraw = (this.bowDraw || 0) + dt;
  745. }
  746. } else if (this.bowDraw > 0) {
  747. this.fireBow(Math.min(1, this.bowDraw));
  748. this.bowDraw = 0;
  749. }
  750. return;
  751. }
  752. this.bowDraw = 0;
  753. //Eating
  754. if (rightDown && heldDef && heldDef.food && !this.creative && p.food < 20 && !(hit && BLOCKS[hit.id].interact && !p.sneaking)) {
  755. this.eatT += dt;
  756. this.eatSound -= dt;
  757. if (this.eatSound <= 0) {
  758. this.eatSound = 0.22;
  759. this.sound.play("eat");
  760. }
  761. if (this.eatT >= 1.6) {
  762. p.eat(heldDef.food);
  763. this.inventory.consumeHeld(1);
  764. if (heldDef.food.leaves) {
  765. const left = this.inventory.add(heldDef.food.leaves, 1);
  766. if (left) {
  767. this.dropStack({ id: heldDef.food.leaves, count: 1 });
  768. }
  769. }
  770. this.sound.play("burp");
  771. this.eatT = 0;
  772. }
  773. return;
  774. }
  775. this.eatT = 0;
  776. //Using / placing
  777. if (rightClick || (rightDown && this.useCooldown <= 0)) {
  778. if (this.useCooldown <= 0 || rightClick) {
  779. this.useCooldown = 0.25;
  780. this.useItem(hit);
  781. }
  782. }
  783. }
  784. //Where the compass needle points: sixteenths of a turn clockwise from
  785. //straight ahead to the world spawn (it spins while standing on it)
  786. compassStep() {
  787. const p = this.player;
  788. const dx = this.spawn.x - p.x, dz = this.spawn.z - p.z;
  789. if (dx * dx + dz * dz < 1) {
  790. return Math.floor(performance.now() / 90) % 16;
  791. }
  792. const fx = -Math.sin(p.yaw), fz = -Math.cos(p.yaw);
  793. const ahead = dx * fx + dz * fz, right = dx * -fz + dz * fx;
  794. return ((Math.round(Math.atan2(right, ahead) / (Math.PI / 8)) % 16) + 16) % 16;
  795. }
  796. attackMob(m) {
  797. const p = this.player, inv = this.inventory;
  798. const held = inv.heldId();
  799. //A hit while falling lands harder
  800. const crit = !p.onGround && p.vy < -1 && !p.inWater;
  801. const dmg = this.creative ? 100 : attackDamage(held) * (crit ? 1.5 : 1);
  802. this.mobs.damage(m, dmg, [p.x, p.z]);
  803. this.sound.play("hit");
  804. if (crit) {
  805. this.renderer.spawnParticles(m.x, m.y + m.def.h * 0.7, m.z, [255, 240, 160], 10, 0.3, 2);
  806. }
  807. if (!this.creative) {
  808. const it = ITEMS[held];
  809. if (it && it.tool && inv.damageHeld(it.tool.kind === "sword" ? 1 : 2)) {
  810. this.sound.play("toolBreak");
  811. }
  812. p.exhaust(0.1);
  813. }
  814. }
  815. fireBow(power) {
  816. if (power < 0.15) {
  817. return;
  818. }
  819. const inv = this.inventory;
  820. if (!this.creative) {
  821. if (!inv.remove(I.ARROW, 1)) {
  822. return;
  823. }
  824. if (inv.damageHeld(1)) {
  825. this.sound.play("toolBreak");
  826. }
  827. }
  828. const [ox, oy, oz, dx, dy, dz] = this.eyeRay();
  829. const sp = 12 + 30 * power;
  830. this.mobs.shootArrow(ox + dx * 0.5, oy - 0.1 + dy * 0.5, oz + dz * 0.5, dx * sp, dy * sp, dz * sp, Math.round(2 + 7 * power));
  831. this.sound.play("bow");
  832. this.swing = 0;
  833. this.ui.hudKey = "";
  834. }
  835. //Wolves and bears hit the player and knock them back
  836. hurtPlayerBy(amount, cause, fromX, fromZ) {
  837. const p = this.player;
  838. const before = p.health;
  839. p.hurt(amount, cause);
  840. if (p.health < before) {
  841. const ax = p.x - fromX, az = p.z - fromZ;
  842. const l = Math.hypot(ax, az) || 1;
  843. p.vx += ax / l * 6;
  844. p.vz += az / l * 6;
  845. p.vy = Math.max(p.vy, 5);
  846. }
  847. }
  848. isNight() {
  849. const tod = this.ticks % DAY;
  850. return tod >= 12800 && tod <= 23200;
  851. }
  852. //Bone meal: ripens wheat, grows saplings, sprouts grass and flowers
  853. applyBoneMeal(h) {
  854. const w = this.world, rng = this.rng;
  855. if (h.id === B.WHEAT && h.meta < 7) {
  856. w.setBlock(h.x, h.y, h.z, B.WHEAT, Math.min(7, h.meta + 2 + Math.floor(rng() * 3)), false);
  857. } else if (h.id === B.SAPLING) {
  858. if (rng() < 0.45) {
  859. w.growTree(h.x, h.y, h.z);
  860. }
  861. } else if (h.id === B.GRASS && w.getBlock(h.x, h.y + 1, h.z) === B.AIR) {
  862. for (let k = 0; k < 14; k++) {
  863. const x = h.x + Math.floor(rng() * 7) - 3, z = h.z + Math.floor(rng() * 7) - 3;
  864. if (w.getBlock(x, h.y, z) === B.GRASS && w.getBlock(x, h.y + 1, z) === B.AIR) {
  865. const r = rng();
  866. w.setBlock(x, h.y + 1, z, r < 0.8 ? B.TALL_GRASS : r < 0.9 ? B.FLOWER_YELLOW : B.FLOWER_RED, 0);
  867. }
  868. }
  869. } else {
  870. return false;
  871. }
  872. this.renderer.spawnParticles(h.x + 0.5, h.y + 1, h.z + 0.5, [120, 220, 90], 12, 0.5, 1.5);
  873. return true;
  874. }
  875. //Middle click: put the targeted block in hand. Creative fills the
  876. //selected slot; survival swaps it in from the inventory if owned.
  877. pickBlock(hit) {
  878. const PICK = {
  879. [B.DOOR]: I.DOOR, [B.BED]: I.BED, [B.FURNACE_LIT]: B.FURNACE, [B.RETIMER_ON]: B.RETIMER, [B.WALL_SIGN]: B.SIGN, [B.WHEAT]: I.SEEDS, [B.FARMLAND]: B.DIRT
  880. };
  881. const id = PICK[hit.id] ?? hit.id;
  882. if (!ITEMS[id]) {
  883. return;
  884. }
  885. const inv = this.inventory;
  886. const slots = inv.slots;
  887. const hot = slots.findIndex((st, i) => i < 9 && st && st.id === id);
  888. if (hot >= 0) {
  889. inv.selected = hot;
  890. return;
  891. }
  892. if (this.creative) {
  893. slots[inv.selected] = { id, count: ITEMS[id].stack, dmg: 0 };
  894. } else {
  895. const at = slots.findIndex((st, i) => i >= 9 && st && st.id === id);
  896. if (at < 0) {
  897. return;
  898. }
  899. const cur = slots[inv.selected];
  900. slots[inv.selected] = slots[at];
  901. slots[at] = cur;
  902. }
  903. this.ui.hudKey = "";
  904. this.sound.play("pop");
  905. }
  906. blockParticles(x, y, z, id, meta, count, point) {
  907. const tex = this.app.tex;
  908. const layer = blockFaceLayer(id, 4, meta || 0);
  909. const name = tex.names[layer];
  910. let col = tex.avgColor.get(name) || [128, 128, 128];
  911. const def = BLOCKS[id];
  912. if (def.tint) {
  913. col = [col[0] * 0.55, col[1] * 0.9, col[2] * 0.4];
  914. }
  915. const light = Math.max(this.world.getSky(x, y + 1, z) / 15 * this.renderer.shared.uDaylight.value, this.world.getBlockLight(x, y + 1, z) / 15);
  916. const px = point ? point[0] : x + 0.5, py = point ? point[1] : y + 0.5, pz = point ? point[2] : z + 0.5;
  917. this.renderer.spawnParticles(px, py, pz, col, count, point ? 0.08 : 0.4, point ? 2 : 3, Math.max(0.15, light));
  918. }
  919. breakBlock(hit, survival) {
  920. const { x, y, z, id, meta } = hit;
  921. const def = BLOCKS[id];
  922. if (def.hardness < 0 && !this.creative) {
  923. return;
  924. }
  925. if (id === B.BEDROCK && !this.creative) {
  926. return;
  927. }
  928. this.world.setBlock(x, y, z, B.AIR, 0);
  929. this.sound.block("break", def.sound);
  930. this.blockParticles(x, y, z, id, meta, 18);
  931. if (survival) {
  932. const heldId = this.inventory.heldId();
  933. for (const [did, n] of blockDrops(id, meta, this.rng, heldId)) {
  934. this.entities.spawnItem(x + 0.5, y + 0.4, z + 0.5, did, n);
  935. }
  936. const heldTool = ITEMS[heldId] && ITEMS[heldId].tool;
  937. if (def.hardness > 0 && this.inventory.damageHeld(heldTool && heldTool.kind === "sword" ? 2 : 1)) {
  938. this.sound.play("toolBreak");
  939. }
  940. this.player.exhaust(0.005);
  941. }
  942. }
  943. //Tall grass and other loose plants never get in the way: aim through
  944. //them at the top of the block they grow on
  945. throughPlant(hit) {
  946. if (!hit || SHAPE[hit.id] !== "cross" || !BLOCKS[hit.id].replaceable) {
  947. return hit;
  948. }
  949. const w = this.world, y = hit.y - 1;
  950. const id = w.getBlock(hit.x, y, hit.z);
  951. if (id === B.AIR) {
  952. return hit;
  953. }
  954. return {
  955. x: hit.x, y, z: hit.z, id, meta: w.getMeta(hit.x, y, hit.z), face: 2, t: hit.t, box: hit.box,
  956. point: [hit.point[0], y + 1, hit.point[2]], throughPlant: true
  957. };
  958. }
  959. useItem(rawHit) {
  960. const p = this.player, inv = this.inventory, w = this.world;
  961. const held = inv.held;
  962. const it = held && ITEMS[held.id];
  963. if (rawHit && BLOCKS[rawHit.id].interact && !p.sneaking) {
  964. this.interactBlock(rawHit);
  965. return;
  966. }
  967. //An empty bucket scoops up a water or lava source
  968. if (held && held.id === I.BUCKET) {
  969. const [ox, oy, oz, dx, dy, dz] = this.eyeRay();
  970. const wh = w.raycast(ox, oy, oz, dx, dy, dz, 4.5, (bid, m, bx, by, bz) =>
  971. ((bid === B.WATER || bid === B.LAVA) && m === 0 ? [0, 0, 0, 1, 0.875, 1] : selectionBox(bid, m, w, bx, by, bz)));
  972. if (wh && (wh.id === B.WATER || wh.id === B.LAVA) && wh.meta === 0) {
  973. const full = wh.id === B.WATER ? I.WATER_BUCKET : I.LAVA_BUCKET;
  974. w.setBlock(wh.x, wh.y, wh.z, B.AIR, 0);
  975. this.sound.play(wh.id === B.WATER ? "splash" : "fizz");
  976. this.swing = 0;
  977. if (!this.creative) {
  978. inv.consumeHeld(1);
  979. if (inv.held) {
  980. if (inv.add(full, 1)) {
  981. this.dropStack({ id: full, count: 1 });
  982. }
  983. } else {
  984. inv.slots[inv.selected] = { id: full, count: 1, dmg: 0 };
  985. }
  986. }
  987. }
  988. return;
  989. }
  990. if (it && it.boat) {
  991. this.placeBoat();
  992. return;
  993. }
  994. if (!rawHit || !held) {
  995. return;
  996. }
  997. if (held.id === I.BONE_MEAL) {
  998. if (this.applyBoneMeal(rawHit)) {
  999. this.swing = 0;
  1000. if (!this.creative) {
  1001. inv.consumeHeld(1);
  1002. }
  1003. }
  1004. return;
  1005. }
  1006. const hit = this.throughPlant(rawHit);
  1007. if (it.tool && it.tool.kind === "hoe") {
  1008. const above = w.getBlock(hit.x, hit.y + 1, hit.z);
  1009. const free = above === B.AIR || (SHAPE[above] === "cross" && BLOCKS[above].replaceable);
  1010. if ((hit.id === B.GRASS || hit.id === B.DIRT) && hit.face !== 3 && free) {
  1011. if (above !== B.AIR) {
  1012. w.breakNaturally(hit.x, hit.y + 1, hit.z);
  1013. }
  1014. w.setBlock(hit.x, hit.y, hit.z, B.FARMLAND, 0);
  1015. this.sound.block("step", "gravel");
  1016. this.swing = 0;
  1017. if (!this.creative && inv.damageHeld(1)) {
  1018. this.sound.play("toolBreak");
  1019. }
  1020. }
  1021. return;
  1022. }
  1023. if (it.tool && it.tool.kind === "igniter") {
  1024. const [x, y, z] = this.placeTarget(hit);
  1025. if (w.ignite(x, y, z)) {
  1026. this.sound.play("fizz");
  1027. this.swing = 0;
  1028. if (!this.creative && inv.damageHeld(1)) {
  1029. this.sound.play("toolBreak");
  1030. }
  1031. }
  1032. return;
  1033. }
  1034. if (held.id === I.WATER_BUCKET || held.id === I.LAVA_BUCKET) {
  1035. const liquid = held.id === I.WATER_BUCKET ? B.WATER : B.LAVA;
  1036. const [x, y, z] = this.placeTarget(hit);
  1037. const cur = w.getBlock(x, y, z);
  1038. if (y >= 0 && y < WORLD_H && (cur === B.AIR || BLOCKS[cur].replaceable)) {
  1039. if (cur !== B.AIR && cur !== B.WATER && cur !== B.LAVA) {
  1040. w.breakNaturally(x, y, z);
  1041. }
  1042. w.setBlock(x, y, z, liquid, 0);
  1043. w.schedule(x, y, z, 5);
  1044. this.sound.play(liquid === B.WATER ? "splash" : "fizz");
  1045. this.swing = 0;
  1046. if (!this.creative) {
  1047. inv.slots[inv.selected] = { id: I.BUCKET, count: 1, dmg: 0 };
  1048. }
  1049. }
  1050. return;
  1051. }
  1052. if (it.plant) {
  1053. if (hit.id === B.FARMLAND && hit.face === 2 && w.getBlock(hit.x, hit.y + 1, hit.z) === B.AIR) {
  1054. w.setBlock(hit.x, hit.y + 1, hit.z, it.plant, 0);
  1055. this.sound.block("place", "grass");
  1056. this.swing = 0;
  1057. if (!this.creative) {
  1058. inv.consumeHeld(1);
  1059. }
  1060. }
  1061. return;
  1062. }
  1063. if (it.cart) {
  1064. if (SHAPE[rawHit.id] === "rail") {
  1065. //Lined up with the rail, facing the way the player looks
  1066. const [cx, cy, cz] = this.carts.railSeat(rawHit.x, rawHit.y, rawHit.z);
  1067. const yaw = this.carts.railYaw(rawHit.x, rawHit.y, rawHit.z, -Math.sin(this.player.yaw), -Math.cos(this.player.yaw));
  1068. this.carts.spawn(it.cart, cx, cy, cz, { yaw });
  1069. this.sound.block("place", "metal");
  1070. this.swing = 0;
  1071. if (!this.creative) {
  1072. inv.consumeHeld(1);
  1073. }
  1074. }
  1075. return;
  1076. }
  1077. if (held.id === I.DOOR) {
  1078. this.placeDoor(hit);
  1079. return;
  1080. }
  1081. if (held.id === I.BED) {
  1082. this.placeBed(hit);
  1083. return;
  1084. }
  1085. if (it.block) {
  1086. this.placeBlock(hit, it.block);
  1087. }
  1088. }
  1089. //A boat goes onto the water (or ground) under the crosshair, facing the
  1090. //way the player looks
  1091. placeBoat() {
  1092. const w = this.world, p = this.player;
  1093. const [ox, oy, oz, dx, dy, dz] = this.eyeRay();
  1094. const h = w.raycast(ox, oy, oz, dx, dy, dz, 4.5, (bid, m, bx, by, bz) =>
  1095. (bid === B.WATER ? [0, 0, 0, 1, 0.875, 1] : selectionBox(bid, m, w, bx, by, bz)));
  1096. if (!h) {
  1097. return;
  1098. }
  1099. let x = h.point[0], y, z = h.point[2];
  1100. if (h.id === B.WATER || h.face === 2) {
  1101. y = h.point[1];
  1102. } else {
  1103. const [tx, ty, tz] = this.placeTarget(h);
  1104. x = tx + 0.5;
  1105. y = ty;
  1106. z = tz + 0.5;
  1107. }
  1108. if (y < 0 || y >= WORLD_H) {
  1109. return;
  1110. }
  1111. this.boats.spawn(x, y, z, { yaw: p.yaw });
  1112. this.sound.block("place", "wood");
  1113. this.swing = 0;
  1114. this.useHold = true;
  1115. if (!this.creative) {
  1116. this.inventory.consumeHeld(1);
  1117. }
  1118. }
  1119. placeTarget(hit) {
  1120. const def = BLOCKS[hit.id];
  1121. if (def.replaceable && hit.id !== B.WATER && hit.id !== B.LAVA) {
  1122. return [hit.x, hit.y, hit.z];
  1123. }
  1124. const d = FACE_DIR[hit.face];
  1125. return [hit.x + d[0], hit.y + d[1], hit.z + d[2]];
  1126. }
  1127. //Move an entity box out of the cells a piston just filled, along the
  1128. //piston direction d, to the far face of what moved (stopped by blocks
  1129. //beyond). Returns the distance.
  1130. pushOut(box, cells, d) {
  1131. const w = this.world;
  1132. const a = d[0] !== 0 ? 0 : d[1] !== 0 ? 1 : 2, s = d[a];
  1133. const pos = [0, 0, 0];
  1134. let need = 0;
  1135. for (const [cx, cy, cz] of cells) {
  1136. const id = w.getBlock(cx, cy, cz);
  1137. if (!SOLID[id]) {
  1138. continue;
  1139. }
  1140. for (const b of collisionBoxes(id, w.getMeta(cx, cy, cz), w, cx, cy, cz)) {
  1141. pos[0] = cx; pos[1] = cy; pos[2] = cz;
  1142. //The box swept over the block it moved through (the head's
  1143. //plate crosses its whole cell)
  1144. let hit = true;
  1145. for (let k = 0; k < 3 && hit; k++) {
  1146. const lo = pos[k] + b[k] - (k === a && s > 0 ? 1 : 0), hi = pos[k] + b[k + 3] + (k === a && s < 0 ? 1 : 0);
  1147. hit = box[k] < hi - 1e-6 && box[k + 3] > lo + 1e-6;
  1148. }
  1149. if (hit) {
  1150. need = Math.max(need, s > 0 ? pos[a] + b[a + 3] - box[a] : box[a + 3] - (pos[a] + b[a]));
  1151. }
  1152. }
  1153. }
  1154. if (need <= 0) {
  1155. return 0;
  1156. }
  1157. //Straight past the far face when there is room (the moving parts
  1158. //push from behind, so they must not stop it); otherwise as far as
  1159. //the blocks allow, which pins it against the head
  1160. const shift = s * (need + 0.01);
  1161. box[a] += shift;
  1162. box[a + 3] += shift;
  1163. if (!regionBlocked(w, box[0], box[1], box[2], box[3], box[4], box[5])) {
  1164. return Math.abs(shift);
  1165. }
  1166. box[a] -= shift;
  1167. box[a + 3] -= shift;
  1168. return Math.abs(moveAxis(w, box, a, shift));
  1169. }
  1170. //A piston extended: push the player, animals and dropped items out of
  1171. //the head and the blocks it moved, with a little momentum
  1172. pistonPush(cells, d) {
  1173. const p = this.player;
  1174. const box = p.box();
  1175. const moved = this.pushOut(box, cells, d);
  1176. if (moved > 0) {
  1177. p.x = (box[0] + box[3]) / 2;
  1178. p.y = box[1];
  1179. p.z = (box[2] + box[5]) / 2;
  1180. if (d[1] !== 0) {
  1181. p.vy = Math.max(p.vy * d[1], 0) * d[1];
  1182. p.fallDistance = 0;
  1183. p.eyeSmooth -= d[1] * moved;
  1184. } else {
  1185. p.vx = d[0] !== 0 ? d[0] * Math.max(p.vx * d[0], 5) : p.vx;
  1186. p.vz = d[2] !== 0 ? d[2] * Math.max(p.vz * d[2], 5) : p.vz;
  1187. }
  1188. }
  1189. for (const m of this.mobs.list) {
  1190. const mb = this.mobs.box(m);
  1191. if (this.pushOut(mb, cells, d) > 0) {
  1192. m.x = (mb[0] + mb[3]) / 2;
  1193. m.y = mb[1];
  1194. m.z = (mb[2] + mb[5]) / 2;
  1195. m.vx += d[0] * 5;
  1196. m.vz += d[2] * 5;
  1197. m.vy = d[1] !== 0 ? Math.max(m.vy, 0) : m.vy;
  1198. }
  1199. }
  1200. for (const e of this.entities.items) {
  1201. const ib = [e.x - ITEM_HALF, e.y - ITEM_HALF, e.z - ITEM_HALF, e.x + ITEM_HALF, e.y + ITEM_HALF, e.z + ITEM_HALF];
  1202. if (this.pushOut(ib, cells, d) > 0) {
  1203. e.x = (ib[0] + ib[3]) / 2;
  1204. e.y = (ib[1] + ib[4]) / 2;
  1205. e.z = (ib[2] + ib[5]) / 2;
  1206. e.vx += d[0] * 3;
  1207. e.vy = Math.max(e.vy, d[1] * 3);
  1208. e.vz += d[2] * 3;
  1209. }
  1210. }
  1211. }
  1212. //Would this block at (x, y, z) collide with the player?
  1213. blocksPlayer(bid, meta, x, y, z) {
  1214. if (!SOLID[bid]) {
  1215. return false;
  1216. }
  1217. const pb = this.player.box();
  1218. for (const b of collisionBoxes(bid, meta, this.world, x, y, z)) {
  1219. if (pb[0] < x + b[3] && pb[3] > x + b[0] && pb[1] < y + b[4] && pb[4] > y + b[1] && pb[2] < z + b[5] && pb[5] > z + b[2]) {
  1220. return true;
  1221. }
  1222. }
  1223. return false;
  1224. }
  1225. //Clear a replaceable block (a plant) so something can go there
  1226. clearSpot(x, y, z) {
  1227. const cur = this.world.getBlock(x, y, z);
  1228. if (cur !== B.AIR && cur !== B.WATER && cur !== B.LAVA) {
  1229. this.world.breakNaturally(x, y, z);
  1230. }
  1231. }
  1232. placeBlock(hit, bid) {
  1233. const w = this.world, p = this.player;
  1234. const def = BLOCKS[bid];
  1235. const face = hit.face;
  1236. //Completing a slab into a double slab
  1237. if (SHAPE[bid] === "slab" && hit.id === bid && ((hit.meta === 0 && face === 2) || (hit.meta === 1 && face === 3))) {
  1238. this.finishPlace(hit.x, hit.y, hit.z, bid, 2);
  1239. return;
  1240. }
  1241. const t = this.placeTarget(hit);
  1242. const [x, y, z] = t;
  1243. if (y < 0 || y >= WORLD_H) {
  1244. return;
  1245. }
  1246. const cur = w.getBlock(x, y, z);
  1247. const curMeta = w.getMeta(x, y, z);
  1248. let meta = 0;
  1249. if (SHAPE[bid] === "slab") {
  1250. if (cur === bid && curMeta !== 2) {
  1251. this.finishPlace(x, y, z, bid, 2);
  1252. return;
  1253. }
  1254. meta = face === 3 ? 1 : face === 2 ? 0 : (hit.point[1] - hit.y > 0.5 ? 1 : 0);
  1255. }
  1256. if (!BLOCKS[cur].replaceable) {
  1257. return;
  1258. }
  1259. if (bid === B.LEVER || bid === B.BUTTON) {
  1260. meta = face;
  1261. } else if (bid === B.FEEDER) {
  1262. //The spout feeds into the block clicked (down when clicked from
  1263. //above or below)
  1264. meta = face === 2 || face === 3 ? 3 : face ^ 1;
  1265. } else if (bid === B.PISTON || bid === B.STICKY_PISTON || bid === B.DISPENSER) {
  1266. //The pushing (or shooting) face looks back at the player
  1267. const [, , , lx, ly, lz] = this.eyeRay();
  1268. const ax = Math.abs(lx), ay = Math.abs(ly), az = Math.abs(lz);
  1269. if (ay >= ax && ay >= az) {
  1270. meta = ly > 0 ? 3 : 2;
  1271. } else if (ax >= az) {
  1272. meta = lx > 0 ? 1 : 0;
  1273. } else {
  1274. meta = lz > 0 ? 5 : 4;
  1275. }
  1276. } else if (bid === B.SIGN) {
  1277. //On top of a block it stands, turned to face the player; on a
  1278. //side it hangs on the wall
  1279. if (face === 3) {
  1280. return;
  1281. }
  1282. if (face === 2) {
  1283. meta = ((Math.round(p.yaw / (Math.PI / 8)) % 16) + 16) % 16;
  1284. } else {
  1285. bid = B.WALL_SIGN;
  1286. meta = face;
  1287. }
  1288. } else if (bid === B.RETIMER) {
  1289. //Signal runs away from the player
  1290. meta = facingFromYaw(p.yaw);
  1291. } else if (SHAPE[bid] === "rail") {
  1292. meta = Math.abs(Math.sin(p.yaw)) > Math.abs(Math.cos(p.yaw)) ? 1 : 0;
  1293. w.railPreferX = meta === 1;
  1294. w.railAim = face === 2 ? [hit.point[0] - x - 0.5, hit.point[2] - z - 0.5] : null;
  1295. } else if (bid === B.TORCH || bid === B.SPARK_TORCH) {
  1296. if (face === 3) {
  1297. return;
  1298. }
  1299. meta = face;
  1300. } else if (bid === B.LADDER) {
  1301. if (face === 2 || face === 3) {
  1302. return;
  1303. }
  1304. meta = face;
  1305. } else if (bid === B.FENCE_GATE) {
  1306. meta = facingFromYaw(p.yaw);
  1307. } else if (bid === B.TRAPDOOR) {
  1308. //On the side of a block it hinges on that block, in the half
  1309. //clicked; on top of (or under) a block it hinges on the far
  1310. //side, so it swings open away from you
  1311. if (face === 2 || face === 3) {
  1312. meta = facingFromYaw(p.yaw) | (face === 3 ? 8 : 0);
  1313. } else {
  1314. const n = FACE_DIR[face];
  1315. meta = HDIR.findIndex((h) => h[0] === -n[0] && h[1] === -n[2]) | (hit.point[1] - hit.y > 0.5 ? 8 : 0);
  1316. }
  1317. } else if (SHAPE[bid] === "stairs") {
  1318. //The steps climb away from the player; placed under a block or
  1319. //on the upper half of a side they hang upside down
  1320. meta = facingFromYaw(p.yaw);
  1321. if (face === 3 || (face !== 2 && hit.point[1] - hit.y > 0.5)) {
  1322. meta |= 4;
  1323. }
  1324. } else if (def.orient) {
  1325. const lx = -Math.sin(p.yaw), lz = -Math.cos(p.yaw);
  1326. if (Math.abs(lx) > Math.abs(lz)) {
  1327. meta = lx > 0 ? 1 : 0;
  1328. } else {
  1329. meta = lz > 0 ? 5 : 4;
  1330. }
  1331. } else if (bid === B.LEAVES) {
  1332. meta = 1;
  1333. }
  1334. if (def.support && !w.hasSupport(x, y, z, bid, meta)) {
  1335. return;
  1336. }
  1337. if (this.blocksPlayer(bid, meta, x, y, z)) {
  1338. return;
  1339. }
  1340. this.clearSpot(x, y, z);
  1341. this.finishPlace(x, y, z, bid, meta);
  1342. }
  1343. //Doors are two blocks tall and hang on the edge nearest the player
  1344. placeDoor(hit) {
  1345. const w = this.world;
  1346. const [x, y, z] = this.placeTarget(hit);
  1347. if (y < 1 || y + 1 >= WORLD_H) {
  1348. return;
  1349. }
  1350. if (!BLOCKS[w.getBlock(x, y, z)].replaceable || !BLOCKS[w.getBlock(x, y + 1, z)].replaceable) {
  1351. return;
  1352. }
  1353. if (!isOpaqueAt(w.getBlock(x, y - 1, z), w.getMeta(x, y - 1, z))) {
  1354. return;
  1355. }
  1356. let f = (facingFromYaw(this.player.yaw) + 2) & 3;
  1357. //Beside a door facing the same way: become its other half of a
  1358. //double door, hinged on the far side (mirrored when needed). A lone
  1359. //neighbour hinged toward this door turns its hinge outward too.
  1360. for (const side of [(f + 1) & 3, (f + 3) & 3]) {
  1361. const nx = x + HDIR[side][0], nz = z + HDIR[side][1];
  1362. const nm = w.getMeta(nx, y, nz);
  1363. if (w.getBlock(nx, y, nz) !== B.DOOR || (nm & 8) || (nm & 3) !== (f & 3)) {
  1364. continue;
  1365. }
  1366. if (side === ((f + 1) & 3)) {
  1367. f |= 16;
  1368. }
  1369. if (doorHinge(nm) !== side && !w.doorPartner(nx, y, nz)) {
  1370. for (const yy of [y, y + 1]) {
  1371. if (w.getBlock(nx, yy, nz) === B.DOOR) {
  1372. w.setBlock(nx, yy, nz, B.DOOR, w.getMeta(nx, yy, nz) ^ 16, false);
  1373. }
  1374. }
  1375. }
  1376. break;
  1377. }
  1378. if (this.blocksPlayer(B.DOOR, f, x, y, z) || this.blocksPlayer(B.DOOR, f | 8, x, y + 1, z)) {
  1379. return;
  1380. }
  1381. this.clearSpot(x, y, z);
  1382. this.clearSpot(x, y + 1, z);
  1383. w.setBlock(x, y, z, B.DOOR, f, false);
  1384. this.finishPlace(x, y + 1, z, B.DOOR, f | 8);
  1385. }
  1386. //Beds take two blocks: the foot where you click, the head further on
  1387. placeBed(hit) {
  1388. const w = this.world;
  1389. const [x, y, z] = this.placeTarget(hit);
  1390. const f = facingFromYaw(this.player.yaw);
  1391. const hx = x + HDIR[f][0], hz = z + HDIR[f][1];
  1392. if (y < 1 || y >= WORLD_H) {
  1393. return;
  1394. }
  1395. for (const [bx, bz] of [[x, z], [hx, hz]]) {
  1396. if (!BLOCKS[w.getBlock(bx, y, bz)].replaceable || !isOpaqueAt(w.getBlock(bx, y - 1, bz), w.getMeta(bx, y - 1, bz))) {
  1397. this.ui.toast("A bed needs two free blocks on solid ground");
  1398. return;
  1399. }
  1400. if (this.blocksPlayer(B.BED, 0, bx, y, bz)) {
  1401. return;
  1402. }
  1403. }
  1404. this.clearSpot(x, y, z);
  1405. this.clearSpot(hx, y, hz);
  1406. w.setBlock(hx, y, hz, B.BED, f | 4, false);
  1407. this.finishPlace(x, y, z, B.BED, f);
  1408. }
  1409. finishPlace(x, y, z, bid, meta) {
  1410. const w = this.world;
  1411. if (!w.setBlock(x, y, z, bid, meta)) {
  1412. return;
  1413. }
  1414. if (TE_KINDS.has(BLOCKS[bid].interact)) {
  1415. w.createTileEntity(x, y, z, BLOCKS[bid].interact);
  1416. } else if (bid === B.SIGN || bid === B.WALL_SIGN) {
  1417. //Write on it straight away
  1418. this.openScreen("sign", Signs.create(w, x, y, z));
  1419. }
  1420. this.sound.block("place", BLOCKS[bid].sound);
  1421. this.swing = 0;
  1422. if (!this.creative) {
  1423. this.inventory.consumeHeld(1);
  1424. }
  1425. }
  1426. interactBlock(hit) {
  1427. const w = this.world;
  1428. const kind = BLOCKS[hit.id].interact;
  1429. this.swing = 0;
  1430. if (kind === "workbench") {
  1431. this.openScreen("workbench");
  1432. } else if (kind === "door") {
  1433. //(a double door opens and shuts together)
  1434. w.setDoorOpen(hit.x, hit.y, hit.z, !(hit.meta & 4));
  1435. this.sound.block("place", "wood");
  1436. } else if (kind === "lever") {
  1437. w.setBlock(hit.x, hit.y, hit.z, B.LEVER, hit.meta ^ 8);
  1438. this.sound.play("click");
  1439. } else if (kind === "button") {
  1440. if (!(hit.meta & 8)) {
  1441. w.pressButton(hit.x, hit.y, hit.z);
  1442. this.sound.play("click");
  1443. }
  1444. } else if (kind === "sign") {
  1445. const te = w.getTileEntity(hit.x, hit.y, hit.z) || Signs.create(w, hit.x, hit.y, hit.z);
  1446. this.openScreen("sign", te);
  1447. } else if (kind === "retimer") {
  1448. //Next delay: 1 to 4 steps of 2 ticks
  1449. const steps = (((hit.meta >> 2) & 3) + 1) % 4;
  1450. w.setBlock(hit.x, hit.y, hit.z, hit.id, (hit.meta & 3) | (steps << 2));
  1451. this.sound.play("click");
  1452. } else if (kind === "gate") {
  1453. w.setBlock(hit.x, hit.y, hit.z, B.FENCE_GATE, hit.meta ^ 4, false);
  1454. this.sound.block("place", "wood");
  1455. } else if (kind === "trapdoor") {
  1456. w.setBlock(hit.x, hit.y, hit.z, B.TRAPDOOR, hit.meta ^ 4, false);
  1457. this.sound.block("place", "wood");
  1458. } else if (kind === "bed") {
  1459. this.trySleep(hit);
  1460. } else {
  1461. let te = w.getTileEntity(hit.x, hit.y, hit.z);
  1462. if (!te) {
  1463. te = w.createTileEntity(hit.x, hit.y, hit.z, kind);
  1464. }
  1465. this.openScreen(kind, te);
  1466. }
  1467. }
  1468. /* ---------------- sleeping ---------------- */
  1469. trySleep(hit) {
  1470. if (this.mobs.threatNear(this.player.x, this.player.z, 10)) {
  1471. this.ui.toast("You can't sleep now, wild animals are nearby");
  1472. return;
  1473. }
  1474. const tod = this.ticks % DAY;
  1475. if (!(tod >= 12500 && tod <= 23500) && this.weather.state !== "thunder") {
  1476. this.ui.toast("You can only sleep at night or during a thunderstorm");
  1477. return;
  1478. }
  1479. const f = hit.meta & 3, d = HDIR[f];
  1480. const head = hit.meta & 4 ? [hit.x, hit.z] : [hit.x + d[0], hit.z + d[1]];
  1481. const foot = hit.meta & 4 ? [hit.x - d[0], hit.z - d[1]] : [hit.x, hit.z];
  1482. this.spawn = { x: foot[0] + 0.5, y: hit.y + 1, z: foot[1] + 0.5 };
  1483. this.sleeping = { t: 0, head, foot, y: hit.y, f };
  1484. this.breaking = null;
  1485. this.ui.toast("Respawn point set");
  1486. this.app.showSleep(true, 0);
  1487. }
  1488. updateSleep(dt) {
  1489. const s = this.sleeping;
  1490. s.t += dt;
  1491. for (const code of ["ShiftLeft", "ShiftRight", "Space", "KeyW", "KeyA", "KeyS", "KeyD"]) {
  1492. if (this.input.pressed.has(code)) {
  1493. this.wake(false);
  1494. return;
  1495. }
  1496. }
  1497. this.app.showSleep(true, Math.min(1, s.t / 2.2));
  1498. if (s.t >= 3) {
  1499. this.wake(true);
  1500. }
  1501. }
  1502. wake(skipNight) {
  1503. const s = this.sleeping;
  1504. if (!s) {
  1505. return;
  1506. }
  1507. this.sleeping = null;
  1508. if (skipNight) {
  1509. this.ticks = (Math.floor(this.ticks / DAY) + 1) * DAY + 500;
  1510. if (this.weather.state !== "clear") {
  1511. this.setWeather("clear");
  1512. this.weather.rain = 0;
  1513. this.weather.thunder = 0;
  1514. }
  1515. this.ui.toast("Good morning!");
  1516. }
  1517. this.player.setPos(s.foot[0] + 0.5, s.y + 0.5625, s.foot[1] + 0.5);
  1518. this.app.showSleep(false);
  1519. }
  1520. /* ---------------- items ---------------- */
  1521. dropHeld(whole) {
  1522. const inv = this.inventory;
  1523. const s = inv.held;
  1524. if (!s) {
  1525. return;
  1526. }
  1527. const n = whole ? s.count : 1;
  1528. this.dropStack({ id: s.id, count: n, dmg: s.dmg || 0 });
  1529. inv.consumeHeld(n);
  1530. this.swing = 0;
  1531. }
  1532. dropStack(stack) {
  1533. const p = this.player;
  1534. const [, , , dx, dy, dz] = this.eyeRay();
  1535. this.entities.spawnItem(p.x + dx * 0.4, p.eyeY - 0.3, p.z + dz * 0.4, stack.id, stack.count, stack.dmg || 0,
  1536. [dx * 5, dy * 5 + 1.5, dz * 5], 1.5);
  1537. }
  1538. onPickup() {
  1539. const now = performance.now();
  1540. if (now - this.pickupSoundAt > 60) {
  1541. this.pickupSoundAt = now;
  1542. this.sound.play("pop");
  1543. }
  1544. this.ui.hudKey = "";
  1545. if (this.ui.isOpen()) {
  1546. this.ui.renderScreen(false);
  1547. }
  1548. }
  1549. /* ---------------- screens ---------------- */
  1550. openScreen(kind, te = null) {
  1551. this.ui.open(kind, te);
  1552. this.input.unlock();
  1553. }
  1554. closeScreen() {
  1555. this.ui.close();
  1556. this.app.resumePlay();
  1557. }
  1558. /* ---------------- player events ---------------- */
  1559. handlePlayerEvents() {
  1560. const p = this.player;
  1561. for (const e of p.events) {
  1562. if (e.type === "hurt") {
  1563. this.sound.play("hurt");
  1564. } else if (e.type === "death") {
  1565. this.wake(false);
  1566. this.carts.dismount();
  1567. this.boats.dismount();
  1568. this.onDeath(e.cause);
  1569. } else if (e.type === "extinguish") {
  1570. this.sound.play("fizz");
  1571. } else if (e.type === "land" && e.fall > 1.2) {
  1572. const id = this.world.getBlock(Math.floor(p.x), Math.floor(p.y - 0.2), Math.floor(p.z));
  1573. this.sound.block("step", BLOCKS[id].sound);
  1574. }
  1575. }
  1576. p.events.length = 0;
  1577. //Footsteps
  1578. if (p.onGround && !p.sneaking && p.walkDist - this.stepDist > 2.1) {
  1579. this.stepDist = p.walkDist;
  1580. const id = this.world.getBlock(Math.floor(p.x), Math.floor(p.y - 0.2), Math.floor(p.z));
  1581. if (id !== B.AIR) {
  1582. this.sound.block("step", BLOCKS[id].sound);
  1583. }
  1584. } else if (p.walkDist - this.stepDist > 4) {
  1585. this.stepDist = p.walkDist;
  1586. }
  1587. if (p.inWater && !this.wasInWater && p.vy < -3) {
  1588. this.sound.play("splash");
  1589. }
  1590. this.wasInWater = p.inWater;
  1591. }
  1592. onDeath(cause) {
  1593. const p = this.player;
  1594. if (!this.creative) {
  1595. for (const s of this.inventory.slots) {
  1596. if (s) {
  1597. this.entities.spawnItem(p.x, p.y + 1, p.z, s.id, s.count, s.dmg || 0,
  1598. [(this.rng() - 0.5) * 5, 2 + this.rng() * 3, (this.rng() - 0.5) * 5], 1);
  1599. }
  1600. }
  1601. this.inventory.clear();
  1602. }
  1603. this.ui.close();
  1604. this.app.showDeath(DEATH_TEXT[cause] || "You died");
  1605. }
  1606. //Move the player; y null lands on the ground once the terrain is there
  1607. teleport(x, y, z) {
  1608. const p = this.player;
  1609. if (y === null) {
  1610. const fx = Math.floor(x), fz = Math.floor(z);
  1611. const top = this.world.isLoaded(fx, fz) ? this.world.rainTop(fx, fz) : this.world.gen.column(fx, fz).h + 1;
  1612. p.setPos(x, top, z);
  1613. this.placeOnGround = true;
  1614. } else {
  1615. p.setPos(x, y, z);
  1616. }
  1617. this.breaking = null;
  1618. }
  1619. respawn() {
  1620. const p = this.player;
  1621. p.respawn({ x: this.spawn.x, y: this.spawn.y, z: this.spawn.z });
  1622. this.placeOnGround = true;
  1623. this.dropToGround();
  1624. this.ui.hudKey = "";
  1625. }
  1626. /* ---------------- camera ---------------- */
  1627. updateCamera(dt) {
  1628. const p = this.player, cam = this.renderer.camera;
  1629. if (this.sleeping) {
  1630. //Lying on the pillow, looking along the bed toward the foot
  1631. const s = this.sleeping, d = HDIR[s.f];
  1632. cam.position.set(s.head[0] + 0.5 - d[0] * 0.2, s.y + 0.75, s.head[1] + 0.5 - d[1] * 0.2);
  1633. cam.rotation.set(0.45, Math.atan2(d[0], d[1]), 0);
  1634. return;
  1635. }
  1636. let bx = 0, by = 0, roll = 0;
  1637. if (this.settings.viewBobbing && p.onGround && !p.flying) {
  1638. const phase = p.walkDist * Math.PI * 0.75;
  1639. const amp = Math.min(1, Math.hypot(p.vx, p.vz) / 4.3);
  1640. bx = Math.sin(phase) * 0.035 * amp;
  1641. by = -Math.abs(Math.cos(phase)) * 0.06 * amp;
  1642. roll = Math.sin(phase) * 0.006 * amp;
  1643. }
  1644. if (p.hurtTime > 0) {
  1645. roll += Math.sin(p.hurtTime * 40) * 0.04 * p.hurtTime;
  1646. }
  1647. const cos = Math.cos(p.yaw), sin = Math.sin(p.yaw);
  1648. cam.position.set(p.x + cos * bx, p.eyeY + p.eyeSmooth + by, p.z - sin * bx);
  1649. cam.rotation.set(p.pitch, p.yaw, roll);
  1650. let fov = this.settings.fov;
  1651. if (p.sprinting) {
  1652. fov *= p.flying ? 1.15 : 1.1;
  1653. }
  1654. if (this.bowDraw > 0) {
  1655. fov *= 1 - 0.15 * Math.min(1, this.bowDraw);
  1656. }
  1657. if (this.eatT > 0) {
  1658. fov *= 0.98;
  1659. }
  1660. this.fovNow = lerp(this.fovNow, fov, 1 - Math.exp(-10 * dt));
  1661. if (Math.abs(cam.fov - this.fovNow) > 0.01) {
  1662. cam.fov = this.fovNow;
  1663. cam.updateProjectionMatrix();
  1664. }
  1665. }
  1666. updateDebug() {
  1667. const el = document.getElementById("debug");
  1668. const showFps = this.settings.showFps;
  1669. if (!this.debug && !showFps) {
  1670. el.classList.add("hidden");
  1671. return;
  1672. }
  1673. el.classList.remove("hidden");
  1674. if (!this.debug) {
  1675. el.textContent = this.fps + " fps";
  1676. return;
  1677. }
  1678. const p = this.player, w = this.world;
  1679. const bx = Math.floor(p.x), by = Math.floor(p.y), bz = Math.floor(p.z);
  1680. const deg = ((-p.yaw * 180 / Math.PI) % 360 + 360) % 360;
  1681. const facing = ["north (-Z)", "east (+X)", "south (+Z)", "west (-X)"][Math.round(deg / 90) % 4];
  1682. const tod = this.ticks % DAY;
  1683. const hours = Math.floor((tod / 1000 + 6) % 24), mins = Math.floor((tod % 1000) * 0.06);
  1684. const lines = [
  1685. `Blocky - ${this.fps} fps`,
  1686. `XYZ: ${p.x.toFixed(2)} / ${p.y.toFixed(2)} / ${p.z.toFixed(2)}`,
  1687. `Block: ${bx} ${by} ${bz} Chunk: ${bx >> 4} ${bz >> 4}`,
  1688. `Facing: ${facing}`,
  1689. `Biome: ${BIOME_NAMES[w.biomeAt(bx, bz)]}`,
  1690. `Light: sky ${w.getSky(bx, Math.floor(p.eyeY), bz)}, block ${w.getBlockLight(bx, Math.floor(p.eyeY), bz)}`,
  1691. `Day ${Math.floor(this.ticks / DAY) + 1}, ${String(hours).padStart(2, "0")}:${String(mins).padStart(2, "0")}`,
  1692. `Weather: ${this.weather.state} (rain ${this.weather.rain.toFixed(2)})`,
  1693. `Chunks: ${w.chunks.size} loaded, ${this.pendingMeshes || 0} sections queued`,
  1694. `Entities: ${this.entities.items.length} items, ${this.entities.falling.length} falling, ${this.mobs.list.length} animals`,
  1695. `Mode: ${this.creative ? "Creative" : "Survival"} - ${DIFFICULTY[p.difficulty].name}`
  1696. ];
  1697. if (!this.creative) {
  1698. lines.push(`Food ${p.food} Saturation ${p.saturation.toFixed(1)} Exhaustion ${p.exhaustion.toFixed(2)}`);
  1699. }
  1700. if (this.hit) {
  1701. lines.push(`Looking at: ${BLOCKS[this.hit.id].name} (${this.hit.x}, ${this.hit.y}, ${this.hit.z}) meta ${this.hit.meta}`);
  1702. }
  1703. el.textContent = lines.join("\n");
  1704. }
  1705. /* ---------------- saving ---------------- */
  1706. snapshot() {
  1707. return {
  1708. version: 1,
  1709. ticks: this.ticks,
  1710. weather: { state: this.weather.state, timer: this.weather.timer },
  1711. spawn: this.spawn,
  1712. player: this.player.serialize(),
  1713. inventory: this.inventory.serialize(),
  1714. world: this.world.serialize(),
  1715. entities: this.entities.serialize(),
  1716. carts: this.carts.serialize(),
  1717. boats: this.boats.serialize()
  1718. };
  1719. }
  1720. async save(quiet) {
  1721. if (this.saving) {
  1722. return false;
  1723. }
  1724. this.saving = true;
  1725. const ind = document.getElementById("saving");
  1726. ind.classList.remove("hidden");
  1727. try {
  1728. const packed = await deflateString(JSON.stringify(this.snapshot()));
  1729. this.meta.lastPlayed = Date.now();
  1730. this.meta.mode = this.creative ? "creative" : "survival";
  1731. this.meta.difficulty = this.player.difficulty;
  1732. await this.app.storage.save(this.meta, JSON.stringify(packed));
  1733. if (!quiet) {
  1734. this.ui.toast("World saved");
  1735. }
  1736. return true;
  1737. } catch (e) {
  1738. this.ui.toast("Could not save the world: " + e.message);
  1739. return false;
  1740. } finally {
  1741. this.saving = false;
  1742. ind.classList.add("hidden");
  1743. }
  1744. }
  1745. }