/* * Player and NPC billboards. See voxel_entities.h and NOTICE.md. */ /* Before global.h, which redefines abs() as a macro over stdlib's prototype. */ #include #include #include #include #include "global.h" #include "fieldmap.h" #include "main.h" #include "sprite.h" #include "event_object_movement.h" #include "field_player_avatar.h" #include "palette.h" #include "constants/field_effects.h" #include "constants/event_object_movement.h" #include "constants/map_types.h" #include "gba/io_reg.h" #include "port_platform.h" #include "3ds_log.h" #include "3ds_video.h" #include "voxel_building.h" #include "voxel_entities.h" #include "voxel_grade.h" #include "voxel_relief.h" #include "voxel_sprite_slots.h" #include "voxel_tree.h" #include "voxel_world.h" #include "voxel_lighting.h" #include "platform/voxel_snapshot.h" bool8 Shop_IsBuyMenuActive(void); /* 16 pixels of sprite is one world tile, as in the reference renderer. */ #define VOXEL_PIXELS_PER_TILE 16.0f /* Largest sprite this atlas can hold, 8bpp: 64*64 bytes of source tiles. */ #define VOXEL_SPRITE_MAX_BYTES (VOXEL_SPRITE_SLOT_DIM * VOXEL_SPRITE_SLOT_DIM) /* Step durations, matching sStepTimes[] in event_object_movement.c. */ static const int32_t sStepFrames[] = { 16, 8, 6, 4, 2 }; /* * What a slot was last decoded from. The animation of a walking object event * rewrites the tiles *behind* a fixed tileNum, so the descriptor alone cannot * detect a frame change: the source bytes and the palette are kept and * compared. That is ~2 KiB of memcmp per object per frame, which is far * cheaper than re-decoding one. */ typedef struct { bool valid; u16 tileNum, paletteNum; /* The ext palette it was drawn with (sprite.c), 0xFF for paletteNum. */ u8 extPalette; u8 shape, size; bool flipX, flipY, color256; int32_t width, height; /* Texels across the atlas cell: `width`, or half of it for a picture * wider than the cell (every second column, VoxelSlots_AtlasWidth). The * card keeps `width` in the world; only its u range is this. */ int32_t atlasWidth; u32 sourceBytes; u8 source[VOXEL_SPRITE_MAX_BYTES]; u16 palette[256]; u32 paletteBytes; /* Extent last written into the atlas cell (atlas texels), so a shrinking * sprite clears exactly what it used to cover instead of the whole 64x64 * slot. */ int32_t drawnWidth, drawnHeight; /* Empty rows under the feet of the standing pose: the art's feet sit this * far up the cell, and the card leaves them out to put them on the * ground (VisibleRows). Measured once per picture table (StandingFootPad). */ int32_t footPad; const struct SpriteFrameImage *footPadImages; /* Measured on the standing pose itself; else, until that picture is in * memory, on the frame the object first showed (StandingFootPad). */ bool footPadExact; } VoxelSpriteSlot; static VoxelSpriteSlot sSlots[VOXEL_SPRITE_SLOTS]; /* The field effect sprite a slot of an unused object event shows, plus one; * 0 for none (VoxelEntities_Emit). */ static u8 sSlotEffect[VOXEL_SPRITE_SLOTS]; /* Slots whose pixels changed since VoxelEntities_TakeDirtySlots last read them. */ static uint32_t sDirtySlots; static int32_t sPlayerVertexFirst = -1; /* The door frame the atlas's door slot holds is not known (FindDoors). */ static bool sDoorStale = true; int32_t VoxelEntities_PlayerVertexFirst(void) { return sPlayerVertexFirst; } void VoxelEntities_Reset(void) { sDoorStale = true; for (uint32_t i = 0; i < VOXEL_SPRITE_SLOTS; ++i) { sSlots[i].valid = false; sSlotEffect[i] = 0; } } /* ── OAM geometry ───────────────────────────────────────────────────────── */ static void GetSpriteDimensions(u8 shape, u8 size, int32_t *w, int32_t *h) { static const u8 square[4][2] = {{8,8},{16,16},{32,32},{64,64}}; static const u8 wide[4][2] = {{16,8},{32,8},{32,16},{64,32}}; static const u8 tall[4][2] = {{8,16},{8,32},{16,32},{32,64}}; const u8 (*table)[2]; if (shape == ST_OAM_SQUARE) table = square; else if (shape == ST_OAM_H_RECTANGLE) table = wide; else if (shape == ST_OAM_V_RECTANGLE) table = tall; else { *w = 16; *h = 32; return; } *w = table[size & 3][0]; *h = table[size & 3][1]; } /* ── Movement interpolation ─────────────────────────────────────────────── */ /* * Sub-tile progress in [0,1]: 0 at previousCoords, 1 at currentCoords. * * sprite->x/y are screen-space and already carry the camera offset, so they * cannot be used for a world position. The step timer can. */ /* * A jump keeps other things in the sprite data a step keeps its speed and * timer in (event_object_movement.c: sDistance, sJumpType, and the timer in * data[6]). Read as a step, a ledge's jump stood still at 0 and the jumper * went from tile to tile as the coordinates did: at the start, half way and * on landing. */ static bool IsJumpAction(u8 action) { return (action >= MOVEMENT_ACTION_JUMP_2_DOWN && action <= MOVEMENT_ACTION_JUMP_2_RIGHT) || (action >= MOVEMENT_ACTION_JUMP_SPECIAL_DOWN && action <= MOVEMENT_ACTION_JUMP_SPECIAL_RIGHT) || (action >= MOVEMENT_ACTION_JUMP_DOWN && action <= MOVEMENT_ACTION_JUMP_IN_PLACE_RIGHT_LEFT) || (action >= MOVEMENT_ACTION_ACRO_WHEELIE_HOP_FACE_DOWN && action <= MOVEMENT_ACTION_ACRO_WHEELIE_JUMP_RIGHT); } /* In the air: the action has set the jump up (sActionFuncId) and not landed. */ static bool IsJumping(const struct ObjectEvent *obj, const struct Sprite *sprite) { return (obj->singleMovementActive || obj->heldMovementActive) && IsJumpAction(obj->movementActionId) && sprite->data[2] == 1; } /* * A jump moves a pixel a frame, a special one a pixel every other frame, and * one of two tiles moves its coordinates on by the second tile half way * (UpdateJumpAnim): past 16 pixels it is that far into the second tile. */ static float GetJumpProgress(const struct ObjectEvent *obj, const struct Sprite *sprite) { float pixels = (float)(u16)sprite->data[6]; if (obj->movementActionId >= MOVEMENT_ACTION_JUMP_SPECIAL_DOWN && obj->movementActionId <= MOVEMENT_ACTION_JUMP_SPECIAL_RIGHT) pixels *= 0.5f; if (pixels >= VOXEL_PIXELS_PER_TILE) pixels -= VOXEL_PIXELS_PER_TILE; return pixels < VOXEL_PIXELS_PER_TILE ? pixels / VOXEL_PIXELS_PER_TILE : 1.0f; } static float GetMovementProgress(const struct ObjectEvent *obj, const struct Sprite *sprite) { int32_t speed, timer, stepLen; float t; /* Idle: ShiftStillObjectEventCoords has made previous == current. */ if (!obj->singleMovementActive && !obj->heldMovementActive) return 1.0f; if (IsJumpAction(obj->movementActionId)) return IsJumping(obj, sprite) ? GetJumpProgress(obj, sprite) : 1.0f; speed = (int32_t)(u16)sprite->data[4]; timer = (int32_t)(u16)sprite->data[5]; if (speed < 0 || speed >= (int32_t)ARRAY_COUNT(sStepFrames)) return 1.0f; stepLen = sStepFrames[speed]; if (stepLen <= 0) return 1.0f; t = (float)timer / (float)stepLen; if (t < 0.0f) t = 0.0f; if (t > 1.0f) t = 1.0f; return t; } static bool GetObjectWorldPos(const struct ObjectEvent *obj, const struct Sprite *sprite, float *outX, float *outZ) { float prevX = (float)(obj->previousCoords.x - MAP_OFFSET); float prevZ = (float)(obj->previousCoords.y - MAP_OFFSET); float curX = (float)(obj->currentCoords.x - MAP_OFFSET); float curZ = (float)(obj->currentCoords.y - MAP_OFFSET); float t = GetMovementProgress(obj, sprite); *outX = prevX + (curX - prevX) * t; *outZ = prevZ + (curZ - prevZ) * t; return true; } /* * How high a bridge's deck lifts an object standing at world (x, z) of its * tile: the Seaside Cycling Road (voxel_bridge.py) carries whoever is up at * the deck's elevation, and lets the ones on the path or the sea pass under. * Tiles; 0 off any deck. */ static float ObjectDeck(const struct ObjectEvent *obj, float worldX, float worldZ) { float cx = worldX + 0.5f, cz = worldZ + 0.5f, lift; const VoxelMapInstance *inst = VoxelWorld_GetInstanceAt((int32_t)floorf(cx), (int32_t)floorf(cz)); return VoxelBuildings_DeckAt(inst, cx, cz, obj->currentElevation, &lift) ? lift : 0.0f; } static VoxelEntitySnapshot sSnapshots[2]; static volatile uint32_t sVisibleSnapshotIdx = 0; static uint32_t sWriteSnapshotIdx = 1; void VoxelEntities_PublishSnapshot(void) { if (Shop_IsBuyMenuActive()) { // Retain the active overworld entity state while the shop buy menu is open sMapMutationLock = 0; return; } VoxelEntitySnapshot *snap = &sSnapshots[sWriteSnapshotIdx]; memcpy(snap->objectEvents, gObjectEvents, sizeof(gObjectEvents)); for (uint32_t i = 0; i < OBJECT_EVENTS_COUNT; ++i) { const struct ObjectEvent *obj = &gObjectEvents[i]; if (obj->active && obj->spriteId < MAX_SPRITES) { snap->sprites[i] = gSprites[obj->spriteId]; snap->extPalettes[i] = GetSpriteExtPalette(&gSprites[obj->spriteId]); } else { snap->extPalettes[i] = 0xFF; } } // Compute player world position atomically on Core 1 from consistent live state const struct ObjectEvent *pObj = &gObjectEvents[gPlayerAvatar.objectEventId]; float px = 0.0f, pz = 0.0f; if (pObj->active && pObj->spriteId < MAX_SPRITES) { GetObjectWorldPos(pObj, &gSprites[pObj->spriteId], &px, &pz); pz += VoxelRelief_ShiftAt(px + 0.5f, pz + 0.5f) + ObjectDeck(pObj, px, pz); } else { VoxelWorld_GetPlayerWorldCoords(&px, &pz); } snap->playerWorldX = px; snap->playerWorldZ = pz; snap->mapGroup = (gSaveBlock1Ptr != NULL) ? (int16_t)gSaveBlock1Ptr->location.mapGroup : (int16_t)-1; snap->mapNum = (gSaveBlock1Ptr != NULL) ? (int16_t)gSaveBlock1Ptr->location.mapNum : (int16_t)-1; snap->frameNum++; __atomic_thread_fence(__ATOMIC_RELEASE); sVisibleSnapshotIdx = sWriteSnapshotIdx; sWriteSnapshotIdx ^= 1; __atomic_thread_fence(__ATOMIC_RELEASE); // Release map mutation lock once the snapshot for the new map state is fully published sMapMutationLock = 0; } const VoxelEntitySnapshot *VoxelEntities_GetVisibleSnapshot(void) { const uint32_t idx = sVisibleSnapshotIdx; __atomic_thread_fence(__ATOMIC_ACQUIRE); return &sSnapshots[idx]; } float VoxelEntities_PlayerDeck(void) { const VoxelEntitySnapshot *snap = VoxelEntities_GetVisibleSnapshot(); const struct ObjectEvent *obj = &snap->objectEvents[gPlayerAvatar.objectEventId]; float x = 0.0f, z = 0.0f; if (!obj->active || obj->spriteId >= MAX_SPRITES) return 0.0f; GetObjectWorldPos(obj, &snap->sprites[gPlayerAvatar.objectEventId], &x, &z); int32_t offX = 0, offY = 0; if (snap != NULL && snap->mapGroup >= 0 && snap->mapNum >= 0) { VoxelWorld_GetInstanceOffset(snap->mapGroup, snap->mapNum, &offX, &offY); } x += (float)offX; z += (float)offY; return ObjectDeck(obj, x, z); } float VoxelEntities_PlayerGround(void) { const VoxelEntitySnapshot *snap = VoxelEntities_GetVisibleSnapshot(); const struct ObjectEvent *obj = &snap->objectEvents[gPlayerAvatar.objectEventId]; float x = 0.0f, z = 0.0f; if (!obj->active || obj->spriteId >= MAX_SPRITES) VoxelWorld_GetPlayerWorldCoords(&x, &z); else { GetObjectWorldPos(obj, &snap->sprites[gPlayerAvatar.objectEventId], &x, &z); int32_t offX = 0, offY = 0; if (snap != NULL && snap->mapGroup >= 0 && snap->mapNum >= 0) { VoxelWorld_GetInstanceOffset(snap->mapGroup, snap->mapNum, &offX, &offY); } x += (float)offX; z += (float)offY; } /* Where the player's card stands (EmitBillboard): on the cell it is in, * not on the one its drawing is shifted south over. */ return VoxelRelief_LiftAt(x + 0.5f, z + 0.5f) + VoxelEntities_PlayerDeck(); } void VoxelEntities_GetPlayerWorldPos(float *worldX, float *worldZ) { const VoxelEntitySnapshot *snap = VoxelEntities_GetVisibleSnapshot(); float px = (snap != NULL) ? snap->playerWorldX : 0.0f; float pz = (snap != NULL) ? snap->playerWorldZ : 0.0f; if (snap != NULL && snap->mapGroup >= 0 && snap->mapNum >= 0) { int32_t offX = 0, offY = 0; if (VoxelWorld_GetInstanceOffset(snap->mapGroup, snap->mapNum, &offX, &offY)) { px += (float)offX; pz += (float)offY; } } if (worldX != NULL) *worldX = px; if (worldZ != NULL) *worldZ = pz; } /* ── Slot decoding ──────────────────────────────────────────────────────── */ /* * Gathers the source tiles of a sprite into `dest`, in reading order, using * the same address arithmetic the 2D compositor uses for OBJ: 1D or 2D * character mapping per DISPCNT bit 6, two VRAM units per tile at 8bpp. */ static u32 GatherSource(const struct Sprite *sprite, int32_t w, int32_t h, bool color256, u8 *dest) { const u8 *vram = VRAM_ + 0x10000; bool mapping1d = (REG_DISPCNT & DISPCNT_OBJ_1D_MAP) != 0; uint32_t bytesPerTile = color256 ? 64u : 32u; u32 written = 0; for (int32_t ty = 0; ty < h / 8; ++ty) { for (int32_t tx = 0; tx < w / 8; ++tx) { uint32_t tile = CtrVideo_ObjTile(sprite->oam.tileNum, (uint32_t)tx, (uint32_t)ty, (uint32_t)w, color256, mapping1d); uint32_t offset = tile * 32; /* OBJ character data is the last 32 KiB of the 96 KiB VRAM bank. */ if (offset + bytesPerTile > 0x8000) offset = 0; memcpy(dest + written, vram + offset, bytesPerTile); written += bytesPerTile; } } return written; } /* The atlas texel of the 8x8 block (bx, by), a block of 64 in Morton order. */ static uint16_t *AtlasBlock(uint16_t *atlas, uint32_t bx, uint32_t by) { return atlas + (by * (VOXEL_SPRITE_ATLAS_W / 8) + bx) * 64u; } /* * Writes the gathered tiles into the slot's 64x64 cell of the atlas. A * sprite's tiles are whole 8x8 blocks of the atlas, flipped or not, so each * goes to one block; the colours are graded once each into a table, not per * pixel out of the 64 KiB grading table (a cache miss a pixel on an ARM11). * The same texels as a pixel at a time through CtrVideo_Texel. */ static void DecodeSlot(VoxelSpriteSlot *slot, uint32_t index, uint16_t *atlas) { static uint8_t morton[64]; static bool mortonReady; uint32_t baseX = (index % VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; uint32_t baseY = (index / VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; uint32_t bytesPerTile = slot->color256 ? 64u : 32u, colours = slot->color256 ? 256u : 16u; int32_t tilesX = slot->width / 8, tilesY = slot->height / 8; /* Clearing only what was drawn before, union the new extent, keeps a * walking sprite's per-frame cost at its own size rather than 64x64. */ int32_t clearW = slot->drawnWidth > slot->atlasWidth ? slot->drawnWidth : slot->atlasWidth; int32_t clearH = slot->drawnHeight > slot->height ? slot->drawnHeight : slot->height; uint16_t graded[256]; if (!mortonReady) { for (uint32_t i = 0; i < 64; ++i) morton[i] = (uint8_t)CtrVideo_Texel(i & 7, i / 8, 8); mortonReady = true; } for (int32_t by = 0; by < (clearH + 7) / 8; ++by) for (int32_t bx = 0; bx < (clearW + 7) / 8; ++bx) memset(AtlasBlock(atlas, baseX / 8 + (uint32_t)bx, baseY / 8 + (uint32_t)by), 0, 64 * sizeof(uint16_t)); slot->drawnWidth = slot->atlasWidth; slot->drawnHeight = slot->height; for (uint32_t c = 1; c < colours; ++c) graded[c] = VoxelGrade_RGBA5551(slot->palette[c]); /* Wider than the cell (the S.S. Tidal): every second column, a texel at * a time. Rare, and re-decoded only when its picture changes. */ if (slot->atlasWidth != slot->width) { for (int32_t y = 0; y < slot->height; ++y) { uint32_t sy = (uint32_t)(slot->flipY ? slot->height - 1 - y : y); for (int32_t x = 0; x < slot->atlasWidth; ++x) { uint32_t sx = VoxelSlots_SourceColumn((uint32_t)x, (uint32_t)slot->atlasWidth, (uint32_t)slot->width, slot->flipX); uint32_t colorIdx = VoxelSlots_TilePixel(slot->source, (uint32_t)slot->width, sx, sy, slot->color256); if (colorIdx != 0) atlas[CtrVideo_Texel(baseX + (uint32_t)x, baseY + (uint32_t)y, VOXEL_SPRITE_ATLAS_W)] = graded[colorIdx]; } } return; } for (int32_t ty = 0; ty < tilesY; ++ty) { for (int32_t tx = 0; tx < tilesX; ++tx) { const u8 *tile = slot->source + (uint32_t)(ty * tilesX + tx) * bytesPerTile; uint32_t ox = (uint32_t)(slot->flipX ? tilesX - 1 - tx : tx); uint32_t oy = (uint32_t)(slot->flipY ? tilesY - 1 - ty : ty); uint16_t *block = AtlasBlock(atlas, baseX / 8 + ox, baseY / 8 + oy); uint32_t flipX = slot->flipX ? 7u : 0u, flipY = slot->flipY ? 7u : 0u; for (uint32_t py = 0; py < 8; ++py) { const uint8_t *row = morton + ((py ^ flipY) * 8); for (uint32_t px = 0; px < 8; ++px) { uint32_t index8 = py * 8 + px; uint32_t colorIdx = slot->color256 ? tile[index8] : ((tile[index8 / 2] >> ((px & 1) * 4)) & 0xF); /* Colour index 0 is transparent; the alpha bit carries it. */ if (colorIdx != 0) block[row[px ^ flipX]] = graded[colorIdx]; } } } } } /* * Empty rows under the feet of an object's standing pose: frame 0 of its * picture table, facing south. Not of the frame showing: the art moves the * whole body between frames, a walk's steps a row lower than the standing * pose and a run's standing pose a row higher than its strides, and that * row is the bob of the walk. Standing on the ground, the pose seen most * meets its shadow; every other frame keeps its offset from it, as on the * GBA (VisibleRows). */ /* Object event pictures are 4bpp, tiles in rows (1D mapping). Bottom up, * the first row with an opaque pixel is the feet. */ static int32_t FootPadOf(const u8 *tiles, int32_t width, int32_t height) { int32_t tilesX = width / 8; for (int32_t y = height - 1; y >= 0; --y) { for (int32_t tx = 0; tx < tilesX; ++tx) { const u8 *row = tiles + (u32)((y / 8) * tilesX + tx) * TILE_SIZE_4BPP + (y % 8) * 4; if (row[0] | row[1] | row[2] | row[3]) return height - 1 - y; } } return 0; } /* * The standing pose is read only if it is in memory already. Its picture is * an asset of its own, and resolving one that is not loaded reads it off the * card - on the render thread, in the middle of the frame: every object that * came into view with a picture the game had not shown yet cost 10-20 ms on * hardware. Until it is, the pad is measured once on the frame the object * first showed (in VRAM already, the slot's own copy): the standing pose, * nearly always, and at worst a row off for as long as it takes the game to * load the picture - it is looked for again every frame. */ static int32_t StandingFootPad(const struct ObjectEventGraphicsInfo *info, const VoxelSpriteSlot *slot, bool *exact) { const struct SpriteFrameImage *frame = &info->images[0]; int32_t tilesX = info->width / 8, tilesY = info->height / 8; u32 size = frame->size; const u8 *tiles = (const u8 *)frame->data; *exact = tiles != NULL; if (tilesX <= 0 || tilesY <= 0) return 0; if (tiles == NULL) { if (slot->color256 || slot->width != info->width || slot->height != info->height || slot->sourceBytes < (u32)(tilesX * tilesY) * TILE_SIZE_4BPP) return 0; return FootPadOf(slot->source, info->width, info->height); } if (size < (u32)(tilesX * tilesY) * TILE_SIZE_4BPP) return 0; return FootPadOf(tiles, info->width, info->height); } /* * The size of a sprite's picture: its OAM's, or an object's own where a table * of subsprites draws it bigger than that - the moving truck is a 32x32 OAM * shown as 48x48 (sOamTable_48x48, its tiles row-major six wide), and its OAM * alone gave the card the truck's top-left corner (#36). The S.S. Tidal * (96x40) and the submarine's shadow (88x32) are wider than a slot: up to * twice as wide, a picture is kept at every second column (DecodeSlot) and * its card at its full width. Their OAM alone was an 8x8 corner (#72). */ static void PictureSize(const struct Sprite *sprite, const struct ObjectEvent *obj, int32_t *w, int32_t *h) { const struct ObjectEventGraphicsInfo *info; GetSpriteDimensions(sprite->oam.shape, sprite->oam.size, w, h); if (obj == NULL || sprite->subspriteTables == NULL) return; info = GetObjectEventGraphicsInfo(obj->graphicsId); if ((info->width > *w || info->height > *h) && VoxelSlots_Fits((uint32_t)info->width, (uint32_t)info->height, sprite->oam.bpp != 0, VOXEL_SPRITE_SLOT_DIM, VOXEL_SPRITE_MAX_BYTES)) { *w = info->width; *h = info->height; } } /* * Brings a slot up to date with its sprite (an object's, or NULL for a field * effect). Returns true if it was re-decoded, which only happens when * something the picture depends on actually changed. */ static bool RefreshSlot(uint32_t index, const struct Sprite *sprite, const struct ObjectEvent *obj, u8 extPalette, uint16_t *atlas) { VoxelSpriteSlot *slot = &sSlots[index]; /* Static, not automatic: this runs in the VBlank handler and 4.5 KiB of * stack frame there is not worth the convenience. */ static u8 source[VOXEL_SPRITE_MAX_BYTES]; static u16 palette[256]; int32_t w, h; bool color256 = sprite->oam.bpp != 0; bool flipX = sprite->oam.affineMode == ST_OAM_AFFINE_OFF && (sprite->oam.matrixNum & 0x08) != 0; bool flipY = sprite->oam.affineMode == ST_OAM_AFFINE_OFF && (sprite->oam.matrixNum & 0x10) != 0; u32 sourceBytes, paletteBytes; bool changed; if (color256) extPalette = 0xFF; PictureSize(sprite, obj, &w, &h); if (!VoxelSlots_Fits((uint32_t)w, (uint32_t)h, color256, VOXEL_SPRITE_SLOT_DIM, VOXEL_SPRITE_MAX_BYTES)) return false; sourceBytes = GatherSource(sprite, w, h, color256, source); paletteBytes = color256 ? 256 * 2 : 16 * 2; /* OBJ palettes are the second half of PLTT; 8bpp uses it as one bank. * One given an ext palette shows that, as the 2D compositor does. * Read from gPlttBufferUnfaded to preserve true colors during screen fades. */ if (extPalette != 0xFF) memcpy(palette, CtrVideo_ExtPalette(extPalette), paletteBytes); else memcpy(palette, &gPlttBufferUnfaded[256 + (color256 ? 0 : sprite->oam.paletteNum * 16)], paletteBytes); changed = !slot->valid || slot->width != w || slot->height != h || slot->color256 != color256 || slot->flipX != flipX || slot->flipY != flipY || slot->tileNum != sprite->oam.tileNum || slot->paletteNum != sprite->oam.paletteNum || slot->extPalette != extPalette || slot->sourceBytes != sourceBytes || memcmp(slot->source, source, sourceBytes) != 0 || memcmp(slot->palette, palette, paletteBytes) != 0; if (!changed) return false; slot->valid = true; slot->width = w; slot->height = h; slot->atlasWidth = (int32_t)VoxelSlots_AtlasWidth((uint32_t)w, VOXEL_SPRITE_SLOT_DIM); slot->color256 = color256; slot->flipX = flipX; slot->flipY = flipY; slot->tileNum = sprite->oam.tileNum; slot->paletteNum = sprite->oam.paletteNum; slot->extPalette = extPalette; slot->shape = sprite->oam.shape; slot->size = sprite->oam.size; slot->sourceBytes = sourceBytes; slot->paletteBytes = paletteBytes; memcpy(slot->source, source, sourceBytes); memcpy(slot->palette, palette, paletteBytes); DecodeSlot(slot, index, atlas); return true; } /* ── Billboards ─────────────────────────────────────────────────────────── */ /* * Rows of the sprite the card shows: all but the standing pose's empty rows * under the feet, so the card ends at the feet and they are on the ground. * Cut off rather than sunk under the ground: a step's feet, a row lower, would * be hidden by the terrain there, and the player's x-ray pass (ctr_voxel.c) * draws exactly what terrain hides. */ static int32_t VisibleRows(const VoxelSpriteSlot *slot) { int32_t pad = slot->footPad < slot->height ? slot->footPad : slot->height - 1; return slot->height - pad; } /* * How far a card standing on (cx, cz) must come towards the camera so the * relief behind it stays behind it. A point of the drawing north of the feet, * dv tiles up the card, lands at depth v + h: on a flight of stairs (h rising * one pixel per pixel) that is exactly the card's own plane, and anything * steeper stands in front of it, so the ground drew over the walker. The card * is then moved along the line of sight (as far up as forward), which leaves * it where it was on screen and only changes what hides what. Flat ground and * walls (a south face lands behind the feet) give nothing. */ #define VOXEL_CARD_CLEAR (1.0f / VOXEL_PIXELS_PER_TILE) static float CardPush(float cx, float cz, float halfW, float height) { const VoxelMapInstance *inst = VoxelWorld_GetInstanceAt((int32_t)floorf(cx), (int32_t)floorf(cz)); float feet, worst = -1.0f; int32_t x0 = (int32_t)floorf(cx - halfW), x1 = (int32_t)floorf(cx + halfW); int32_t y0 = (int32_t)floorf(cz - height), y1 = (int32_t)floorf(cz); bool relief = false; for (int32_t y = y0; y <= y1 && !relief; ++y) for (int32_t x = x0; x <= x1 && !relief; ++x) relief = VoxelRelief_IsSlope(VoxelRelief_Cell(VoxelWorld_GetInstanceAt(x, y), x, y)); if (inst == NULL || !relief) return 0.0f; feet = VoxelRelief_LiftAt(cx, cz); for (int32_t i = -1; i <= 1; ++i) { float x = cx + i * halfW * 0.75f; for (float dv = VOXEL_CARD_CLEAR; dv <= height; dv += 2.0f * VOXEL_CARD_CLEAR) { float over = VoxelRelief_LiftAt(x, cz - dv) - feet - dv; if (over > worst) worst = over; } } return worst > -VOXEL_CARD_CLEAR ? worst + VOXEL_CARD_CLEAR : 0.0f; } /* * Furniture against a room's back wall is modelled from its drawing, and the * drawing comes forward of the wall: half a cell, to the middle of the cell * before it, where a walker's card stands - or further, a Pokemon Center's * PC two pixels past it. Card and model front then share a depth, or the * card is behind, and the model, drawn first, hid the walker in front of it. * The card comes along the line of sight to a pixel in front of the model's * face there, as on the GBA. Under either edge of the card, not only its * middle: walking along the furniture, half the card is over a model's cell * before its middle is, and beside a machine a sliver of it is. * * The bound is on the face, not on the push: a face up to half a tile past * the feet - at most the walker's own cell's south edge - is the furniture's, * and the card goes a pixel past it. Bounding the push instead left out a * face right on the edge, a chair's front with someone seated in it (a face * at 6.0 before feet at 5.5 needs 0.5625), and the seated walker sat inside * the chair, a pixel's push from the fallback (#81). */ #define VOXEL_MODEL_PUSH_MAX 0.5f /* a face further than that is not furniture's front */ #define VOXEL_MODEL_PUSH_HEIGHT 0.25f /* where on the card the face is looked for */ static float ModelPush(float cx, float cz, float halfW) { int32_t y = (int32_t)floorf(cz); float left = cx - halfW + VOXEL_CARD_CLEAR, right = cx + halfW - VOXEL_CARD_CLEAR; int32_t x0 = (int32_t)floorf(left), x1 = (int32_t)floorf(right); float push = 0.0f; for (int32_t x = x0; x <= x1; ++x) { const VoxelMapInstance *inst = VoxelWorld_GetInstanceAt(x, y); float front, need = 0.0f; if (inst == NULL) continue; /* A model's face in the cell, whether or not the cell is the * model's: the PC's foot is drawn on the floor the walker uses it * from, in a cell that is the counter's. */ bool faced = VoxelBuildings_FrontAt(inst, x, y, left, right, VOXEL_MODEL_PUSH_HEIGHT, &front) && VoxelSlots_ModelFacePush(front, cz, VOXEL_CARD_CLEAR, VOXEL_MODEL_PUSH_MAX, &need); if (!faced && VoxelBuildings_CellAt(inst, x, y, NULL, NULL)) need = VOXEL_CARD_CLEAR; if (need > push) push = need; } return push; } /* * A card standing on the ground at (cx, cz), moved (offX, offZ) from there * and raised by `rise`: an object stands on the centre of its tile, feet on * the ground; a field effect that belongs to an object is drawn in that * object's place, moved from it as it is on the GBA screen. */ /* A sprite drawn on an OAM matrix (a visible wild Pokemon growing in, * wild_encounter.c) is that much smaller or larger; the matrix maps the * screen onto the picture, so its size is one over the matrix's. */ static float SpriteScale(const struct Sprite *sprite) { s16 a; if (!(sprite->oam.affineMode & ST_OAM_AFFINE_ON_MASK)) return 1.0f; a = (s16)gOamMatrices[sprite->oam.matrixNum & (OAM_MATRIX_COUNT - 1)].a; return a > 0 ? 256.0f / a : 1.0f; } /* How far the cards lie down this update (VoxelCamera.lay), 0 upright. */ static float sLay; static void EmitBillboard(VoxelBuilder *builder, const VoxelSpriteSlot *slot, uint32_t index, float cx, float cz, float offX, float offZ, float rise, float deck, float rightX, float rightZ, float stretch, float shade, float scale, bool inDoor) { uint32_t baseX = (index % VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; uint32_t baseY = (index / VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; float u0 = baseX / (float)VOXEL_SPRITE_ATLAS_W; float u1 = (baseX + slot->atlasWidth) / (float)VOXEL_SPRITE_ATLAS_W; int32_t rows = VisibleRows(slot); /* Row 0 in memory is v=1, the convention the whole port uses. */ float v0 = 1.0f - baseY / (float)VOXEL_SPRITE_ATLAS_H; float v1 = 1.0f - (baseY + rows) / (float)VOXEL_SPRITE_ATLAS_H; float halfW = slot->width / VOXEL_PIXELS_PER_TILE * 0.5f * scale; float height = rows / VOXEL_PIXELS_PER_TILE * stretch * scale; /* On relief the sprite stands where its cell was lifted to, and rides * the lattice between cells, so a flight of stairs is climbed. */ float lift = VoxelRelief_LiftAt(cx, cz) + rise + deck; float shift = VoxelRelief_ShiftAt(cx, cz) + deck; /* Up on a deck or stepping into an open door, nothing of the ground or of a model's front is before * it: the deck is under its feet, or the doorway is open. */ float push = (deck > 0.0f || inDoor) ? 0.0f : CardPush(cx, cz, halfW, height); float model = (deck > 0.0f || inDoor) ? 0.0f : ModelPush(cx, cz, halfW); if (model > push) push = model; /* Towards the camera: the right vector turned a quarter, unit length. */ float along = push > 0.0f ? push / sqrtf(rightX * rightX + rightZ * rightZ) : 0.0f; float px = cx + offX - rightZ * along, pz = cz + offZ + shift + rightX * along; lift += push; float ax = px - rightX * halfW, az = pz - rightZ * halfW; float bx = px + rightX * halfW, bz = pz + rightZ * halfW; /* Tilting back (sLay) to face the swoop's end camera, square on: the * top of the card swings north by the camera's pitch off vertical. */ float angle = sLay * (90.0f - VOXEL_SWOOP_PITCH) * (3.14159265358979323846f / 180.0f); /* That camera stretches its picture by 1/sin(pitch) to square the * ground and squashes the world's height to VOXEL_SWOOP_HEIGHT * (ctr_voxel.c): a card facing it comes out cos(pitch) x (height + 1) * of its size, so it is made the inverse of that, the 2D sprite, 1:1. */ float pitchRad = VOXEL_SWOOP_PITCH * (3.14159265358979323846f / 180.0f); float squat = 1.0f + sLay * (1.0f / (cosf(pitchRad) * (VOXEL_SWOOP_HEIGHT + 1.0f)) - 1.0f); float topY = height * squat * cosf(angle), topZ = -height * squat * sinf(angle); VoxelBuilder_Quad(builder, &(VoxelVertex){ax, lift, az, u0, v1, shade}, &(VoxelVertex){bx, lift, bz, u1, v1, shade}, &(VoxelVertex){bx, lift + topY, bz + topZ, u1, v0, shade}, &(VoxelVertex){ax, lift + topY, az + topZ, u0, v0, shade}); } /* * A mark on the ground (a ripple, footprints, tyre tracks) lies on it: a * card standing up would be a wall of footprints. The top of the picture is * north, as on the GBA screen. */ #define VOXEL_DECAL_LIFT 0.025f /* over the ground, under cast shadows (0.03) */ static void EmitDecal(VoxelBuilder *builder, const VoxelSpriteSlot *slot, uint32_t index, float cx, float cz, float lift, float shade) { uint32_t baseX = (index % VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; uint32_t baseY = (index / VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; float u0 = baseX / (float)VOXEL_SPRITE_ATLAS_W; float u1 = (baseX + slot->atlasWidth) / (float)VOXEL_SPRITE_ATLAS_W; float v0 = 1.0f - baseY / (float)VOXEL_SPRITE_ATLAS_H; float v1 = 1.0f - (baseY + slot->height) / (float)VOXEL_SPRITE_ATLAS_H; float halfW = slot->width / VOXEL_PIXELS_PER_TILE * 0.5f; float halfH = slot->height / VOXEL_PIXELS_PER_TILE * 0.5f; float y = VoxelRelief_LiftAt(cx, cz) + VOXEL_DECAL_LIFT + lift; float z = cz + VoxelRelief_ShiftAt(cx, cz); VoxelBuilder_Quad(builder, &(VoxelVertex){cx - halfW, y, z + halfH, u0, v1, shade}, &(VoxelVertex){cx + halfW, y, z + halfH, u1, v1, shade}, &(VoxelVertex){cx + halfW, y, z - halfH, u1, v0, shade}, &(VoxelVertex){cx - halfW, y, z - halfH, u0, v0, shade}); } /* * A door opening or closing. The game draws its frames on the tilemap, which * this view does not show: the walker went through a door that stayed shut, * card and all. Here the frame the game draws (field_door.c, the same tiles * it puts on the tilemap) is drawn where the door's drawing is in the world: * up the wall the door is drawn on, by the 45-degree rule that put the model * where its drawing was, or lying on the door's cells where the building is * not modelled and its drawing lies flat. Whoever steps through it is gone * into the dark, as on the GBA they are behind the wall. */ bool8 PortDoor_Get(s16 *x, s16 *y, u8 *width, const u8 **tiles, const u8 **palettes); bool8 PortDoor_GetTwin(s16 *x, s16 *y); /* field_door.c */ #define VOXEL_DOOR_DEPTH 0.03f /* the frame, in front of its wall */ #define VOXEL_DOOR_DUSK 0.5f /* tiles before it over which a walker darkens */ #define VOXEL_DOOR_DARK 0.35f #define VOXEL_DOOR_ROWS 32 /* the frame's pixels down: two metatiles */ /* A multi corridor's (Battle Frontier) second door shows the same frame. */ #define VOXEL_DOORS 2 typedef struct { bool on, upright; int32_t x, y, width; /* world cells: the door's own, the lower of its two */ float z; /* the wall, or the cell's south edge */ } VoxelDoor; /* The wall of a door at (x, y), found once: looking for it reads the whole * model. One remembered for each door. */ static void FindDoorWall(VoxelDoor *door, const VoxelMapInstance *inst, uint32_t which) { static int32_t lastLayout[VOXEL_DOORS] = { -1, -1 }, lastX[VOXEL_DOORS], lastY[VOXEL_DOORS]; static bool lastUpright[VOXEL_DOORS]; static float lastZ[VOXEL_DOORS]; if (lastLayout[which] != inst->layoutId || lastX[which] != door->x || lastY[which] != door->y) { lastLayout[which] = inst->layoutId; lastX[which] = door->x; lastY[which] = door->y; lastZ[which] = (float)door->y + 1.0f; lastUpright[which] = VoxelBuildings_CellAt(inst, door->x, door->y, NULL, NULL); if (lastUpright[which]) VoxelBuildings_DoorWall(inst, door->x, door->y, &lastZ[which]); } door->upright = lastUpright[which]; door->z = lastZ[which]; } /* * The doors showing a frame, and the frame in the atlas's door slot, decoded * again only when it is another: the frame's tiles, the door's palettes or * the map's. Its colours are the tilesets' own, as the atlas the walls were * drawn from has them (voxel_atlas.c): index 0 is the backdrop, opaque, as * the GBA shows it under the door's tiles. Returns whether it was decoded. */ static bool FindDoors(VoxelDoor doors[VOXEL_DOORS], uint16_t *atlas) { static const u8 *lastTiles, *lastPalettes; static const uint16_t *lastPrimary, *lastSecondary; static int32_t lastWidth; const VoxelMapInstance *inst; const uint16_t *primary, *secondary; const u8 *tiles, *palettes; uint32_t baseX = (VOXEL_DOOR_SLOT % VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; uint32_t baseY = (VOXEL_DOOR_SLOT / VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; s16 x, y; u8 width; for (uint32_t d = 0; d < VOXEL_DOORS; ++d) doors[d].on = false; if (VoxelWorld_InstanceCount() == 0 || !PortDoor_Get(&x, &y, &width, &tiles, &palettes)) return false; inst = VoxelWorld_Instance(0); primary = Voxel_ResolvePalettes(inst->primaryTileset); secondary = Voxel_ResolvePalettes(inst->secondaryTileset); if (primary == NULL || secondary == NULL) return false; for (uint32_t d = 0; d < VOXEL_DOORS; ++d) { if (d > 0 && !PortDoor_GetTwin(&x, &y)) break; doors[d].on = true; doors[d].x = x - MAP_OFFSET + inst->originX; doors[d].y = y - MAP_OFFSET + inst->originY; doors[d].width = width; FindDoorWall(&doors[d], inst, d); } if (!sDoorStale && tiles == lastTiles && palettes == lastPalettes && primary == lastPrimary && secondary == lastSecondary && width == lastWidth) return false; sDoorStale = false; lastTiles = tiles; lastPalettes = palettes; lastPrimary = primary; lastSecondary = secondary; lastWidth = width; for (uint32_t py = 0; py < VOXEL_DOOR_ROWS; ++py) for (uint32_t px = 0; px < 32u; ++px) { uint16_t texel = 0; if (px < width * 16u) { uint32_t palette, index = VoxelSlots_DoorPixel(tiles, palettes, px, py, &palette); uint16_t bgr15 = index == 0 ? primary[0] : palette < NUM_PALS_IN_PRIMARY ? primary[palette * 16u + index] : secondary[palette * 16u + index]; texel = VoxelGrade_RGBA5551(bgr15); } atlas[CtrVideo_Texel(baseX + px, baseY + py, VOXEL_SPRITE_ATLAS_W)] = texel; } return true; } /* In a doorway's column: 0 through it, up to 1 a little way before it. */ static float DoorLight(const VoxelDoor doors[VOXEL_DOORS], float cx, float cz) { float light = 1.0f; for (uint32_t d = 0; d < VOXEL_DOORS; ++d) { const VoxelDoor *door = &doors[d]; float t; if (!door->on || cx < (float)door->x || cx >= (float)(door->x + door->width) || cz < (float)door->y || cz >= door->z + VOXEL_DOOR_DEPTH + VOXEL_DOOR_DUSK) continue; if (cz <= door->z + VOXEL_DOOR_DEPTH) return 0.0f; t = (cz - door->z - VOXEL_DOOR_DEPTH) / VOXEL_DOOR_DUSK; t = VOXEL_DOOR_DARK + (1.0f - VOXEL_DOOR_DARK) * t; if (t < light) light = t; } return light; } /* The light a face of the door's turned (nx, ny, nz) gets: the sun's facing * outdoors, as the model's own faces (VoxelLighting_ModelShade). */ static float DoorShade(float nx, float ny, float nz) { #if CTR_VOXEL_LIGHTING if (!VoxelWorld_Instance(0)->indoor) return VoxelLighting_Face(nx, ny, nz); #endif (void)nx; (void)ny; (void)nz; return 1.0f; } /* The rows of the door's drawing from `from` to `to` (world tiles), where * the 45-degree rule puts them against a wall at `wall`. */ static void EmitDoorRows(VoxelBuilder *builder, const VoxelDoor *door, float wall, float from, float to, float shade) { uint32_t baseX = (VOXEL_DOOR_SLOT % VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; uint32_t baseY = (VOXEL_DOOR_SLOT / VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; float u0 = baseX / (float)VOXEL_SPRITE_ATLAS_W; float u1 = (baseX + (uint32_t)door->width * 16u) / (float)VOXEL_SPRITE_ATLAS_W; float top = (float)door->y - 1.0f; float v0 = 1.0f - (baseY + (from - top) * 16.0f) / (float)VOXEL_SPRITE_ATLAS_H; float v1 = 1.0f - (baseY + (to - top) * 16.0f) / (float)VOXEL_SPRITE_ATLAS_H; float x0 = (float)door->x, x1 = (float)(door->x + door->width); float cx = (float)door->x + door->width * 0.5f; float lift = VoxelRelief_LiftAt(cx, (float)door->y + 0.5f); float shift = VoxelRelief_ShiftAt(cx, (float)door->y + 0.5f); float h0, h1, z0, z1; VoxelSlots_DoorRow(from, wall, &h0, &z0); VoxelSlots_DoorRow(to, wall, &h1, &z1); /* Up the wall, just in front of it; on the ground, just over it. */ if (h0 > 0.0f) { z0 += VOXEL_DOOR_DEPTH; z1 += VOXEL_DOOR_DEPTH; } else lift += VOXEL_DECAL_LIFT + 0.01f; VoxelBuilder_Quad(builder, &(VoxelVertex){x0, lift + h1, z1 + shift, u0, v1, shade}, &(VoxelVertex){x1, lift + h1, z1 + shift, u1, v1, shade}, &(VoxelVertex){x1, lift + h0, z0 + shift, u1, v0, shade}, &(VoxelVertex){x0, lift + h0, z0 + shift, u0, v0, shade}); } static void EmitDoor(VoxelBuilder *builder, const VoxelDoor *door) { /* The drawing's rows: the metatile over the door's, then the door's. */ float top = (float)door->y - 1.0f, bottom = (float)door->y + 1.0f; /* A door drawn flat has no wall: all of it lies on the ground. */ float wall = door->upright ? door->z : top; float split = wall < top ? top : wall > bottom ? bottom : wall; if (!door->on) return; if (split > top) EmitDoorRows(builder, door, wall, top, split, DoorShade(0.0f, 0.0f, 1.0f)); if (split < bottom) EmitDoorRows(builder, door, wall, split, bottom, DoorShade(0.0f, 1.0f, 0.0f)); } /* * The billboard's own picture laid on the ground along the sun: the feet stay * where they are and every row of the sprite slides away from the sun by its * height, which is exactly where the fixed sun would put the shadow of a flat * card standing there. Same texture and texels as the sprite, so it walks, * turns and animates with it; one quad per object and no clipping work. * * The strength goes out in `shade`, which the shadow pass reads as alpha * (ctr_voxel.c). An object already in the scenery's shadow has no sun to * cast with, so its shadow fades out with the light it receives. */ #define VOXEL_CAST_SHADOW_ALPHA 0.36f #define VOXEL_CAST_SHADOW_LIFT 0.03f /* over decals (0.02) */ #define VOXEL_CAST_SHADOW_LIT 0.70f /* sample at or below: no sun */ static void EmitCastShadow(VoxelBuilder *shadows, const VoxelSpriteSlot *slot, uint32_t index, float worldX, float worldZ, float rightX, float rightZ, float stretch, float light, float lift, float deck) { if (gVoxelSun.strength == 0.0f) return; uint32_t baseX = (index % VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; uint32_t baseY = (index / VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; float u0 = baseX / (float)VOXEL_SPRITE_ATLAS_W; float u1 = (baseX + slot->atlasWidth) / (float)VOXEL_SPRITE_ATLAS_W; /* The rows the card shows (VisibleRows), from the feet: they meet their * own shadow. */ int32_t rows = VisibleRows(slot); float v0 = 1.0f - baseY / (float)VOXEL_SPRITE_ATLAS_H; float v1 = 1.0f - (baseY + rows) / (float)VOXEL_SPRITE_ATLAS_H; float halfW = slot->width / VOXEL_PIXELS_PER_TILE * 0.5f; float height = rows / VOXEL_PIXELS_PER_TILE * stretch; /* Off the ground by `lift` (riding), the feet's shadow falls that much * further along the sun. */ float cx = worldX + 0.5f + VOXEL_SUN_DX * lift, cz = worldZ + 0.5f + VOXEL_SUN_DZ * lift; float ax = cx - rightX * halfW, az = cz - rightZ * halfW; float bx = cx + rightX * halfW, bz = cz + rightZ * halfW; float sx = VOXEL_SUN_DX * height, sz = VOXEL_SUN_DZ * height; /* Each corner on the ground under it: at a face's foot the ground under * the shadow's far end is not the ground under the feet. */ /* On a deck, on the deck: as high, and as far south (the 45-degree * rule, as the walker). */ float ya = VoxelRelief_LiftAt(ax, az) + VOXEL_CAST_SHADOW_LIFT + deck; float yb = VoxelRelief_LiftAt(bx, bz) + VOXEL_CAST_SHADOW_LIFT + deck; float yc = VoxelRelief_LiftAt(bx + sx, bz + sz) + VOXEL_CAST_SHADOW_LIFT + deck; float yd = VoxelRelief_LiftAt(ax + sx, az + sz) + VOXEL_CAST_SHADOW_LIFT + deck; float za = VoxelRelief_ShiftAt(ax, az) + deck, zb = VoxelRelief_ShiftAt(bx, bz) + deck; float zc = VoxelRelief_ShiftAt(bx + sx, bz + sz) + deck; float zd = VoxelRelief_ShiftAt(ax + sx, az + sz) + deck; float strength = (light - VOXEL_CAST_SHADOW_LIT) / (1.0f - VOXEL_CAST_SHADOW_LIT); if (strength <= 0.0f) return; if (strength > 1.0f) strength = 1.0f; strength *= VOXEL_CAST_SHADOW_ALPHA * gVoxelSun.strength; VoxelBuilder_Quad(shadows, &(VoxelVertex){ax, ya, az + za, u0, v1, strength}, &(VoxelVertex){bx, yb, bz + zb, u1, v1, strength}, &(VoxelVertex){bx + sx, yc, bz + sz + zc, u1, v0, strength}, &(VoxelVertex){ax + sx, yd, az + sz + zd, u0, v0, strength}); } /* * The shadow of something lying flat a little over the ground - the surf mon * on the water: its own picture again on the ground, moved along the sun by * how high it is. Mostly under it, it shows as a dark rim on the far side, * which is what sets it on the water. */ static void EmitDecalShadow(VoxelBuilder *shadows, const VoxelSpriteSlot *slot, uint32_t index, float cx, float cz, float height, float light) { if (gVoxelSun.strength == 0.0f) return; uint32_t baseX = (index % VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; uint32_t baseY = (index / VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; float u0 = baseX / (float)VOXEL_SPRITE_ATLAS_W; float u1 = (baseX + slot->atlasWidth) / (float)VOXEL_SPRITE_ATLAS_W; float v0 = 1.0f - baseY / (float)VOXEL_SPRITE_ATLAS_H; float v1 = 1.0f - (baseY + slot->height) / (float)VOXEL_SPRITE_ATLAS_H; float halfW = slot->width / VOXEL_PIXELS_PER_TILE * 0.5f; float halfH = slot->height / VOXEL_PIXELS_PER_TILE * 0.5f; float x = cx + VOXEL_SUN_DX * height, z0 = cz + VOXEL_SUN_DZ * height; float y = VoxelRelief_LiftAt(x, z0) + VOXEL_CAST_SHADOW_LIFT; float z = z0 + VoxelRelief_ShiftAt(x, z0); float strength = (light - VOXEL_CAST_SHADOW_LIT) / (1.0f - VOXEL_CAST_SHADOW_LIT); if (strength <= 0.0f) return; if (strength > 1.0f) strength = 1.0f; strength *= VOXEL_CAST_SHADOW_ALPHA * gVoxelSun.strength; VoxelBuilder_Quad(shadows, &(VoxelVertex){x - halfW, y, z + halfH, u0, v1, strength}, &(VoxelVertex){x + halfW, y, z + halfH, u1, v1, strength}, &(VoxelVertex){x + halfW, y, z - halfH, u1, v0, strength}, &(VoxelVertex){x - halfW, y, z - halfH, u0, v0, strength}); } /* Require every map cell under the actual, relief-shifted quad to be * reflective. Checking only the first south cell let a long reflection spill * across shorelines into grass. The small AABB is conservative when yawed. */ static bool IsReflectiveFootprint(float ax, float az, float bx, float bz, float length) { float minX = fminf(ax, bx), maxX = fmaxf(ax, bx); float minZ = fminf(az, bz), maxZ = fmaxf(az, bz) + length; int32_t firstX = (int32_t)floorf(minX + 0.0001f); int32_t lastX = (int32_t)floorf(maxX - 0.0001f); int32_t firstZ = (int32_t)floorf(minZ + 0.0001f); int32_t lastZ = (int32_t)floorf(maxZ - 0.0001f); for (int32_t z = firstZ; z <= lastZ; ++z) { for (int32_t x = firstX; x <= lastX; ++x) { if (!VoxelWorld_IsVisibleReflectiveSurface(x, z)) return false; } } return true; } /* A reflected object's quad. Grow only through cells that the world marks as * water or ice; the original ground effect merely says water is nearby. It is * cut across the card in VOXEL_REFLECTION_STRIPS strips, each grown over the * water under it alone: a step onto a one-tile puddle has the reflection come * in with the walker, as the GBA's shows through the water's own pixels, * instead of none until the card is wholly over the puddle and then all of it * at once. Neighbouring strips of one length are one quad. */ static void EmitReflection(VoxelBuilder *reflections, const VoxelSpriteSlot *slot, uint32_t index, float worldX, float worldZ, float rightX, float rightZ, float stretch) { uint32_t baseX = (index % VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; uint32_t baseY = (index / VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; float u0 = baseX / (float)VOXEL_SPRITE_ATLAS_W; float u1 = (baseX + slot->atlasWidth) / (float)VOXEL_SPRITE_ATLAS_W; float v0 = 1.0f - baseY / (float)VOXEL_SPRITE_ATLAS_H; float v1 = 1.0f - (baseY + slot->height) / (float)VOXEL_SPRITE_ATLAS_H; float halfW = slot->width / VOXEL_PIXELS_PER_TILE * 0.5f; float cardLength = slot->height / VOXEL_PIXELS_PER_TILE * stretch; float fullLength = cardLength; float lengths[VOXEL_REFLECTION_STRIPS]; float cx = worldX + 0.5f, nearZ = worldZ + 1.0f; float shift = VoxelRelief_ShiftAt(cx, nearZ + 0.5f); float y = VoxelRelief_LiftAt(cx, nearZ + 0.5f) + 0.035f; const uint32_t strips = VOXEL_REFLECTION_STRIPS; if (fullLength > 1.75f) fullLength = 1.75f; for (uint32_t s = 0; s < strips; ++s) { /* across the card: t = 0 at its left edge (u0), 1 at its right (u1) */ float a = halfW * (2.0f * s / strips - 1.0f), b = halfW * (2.0f * (s + 1) / strips - 1.0f); /* (the water under it by its cells, not where they are drawn) */ float ax = cx + rightX * a, az = nearZ + rightZ * a; float bx = cx + rightX * b, bz = nearZ + rightZ * b; lengths[s] = 0.0f; for (float next = 0.25f; next <= fullLength + 0.0001f; next += 0.25f) { if (!IsReflectiveFootprint(ax, az, bx, bz, next)) break; lengths[s] = next; } } for (uint32_t s = 0, e; s < strips; s = e) { float length = lengths[s]; for (e = s + 1; e < strips && lengths[e] == length; ++e) ; if (length < 0.25f) continue; float t0 = (float)s / strips, t1 = (float)e / strips; float a = halfW * (2.0f * t0 - 1.0f), b = halfW * (2.0f * t1 - 1.0f); float ax = cx + rightX * a, az = nearZ + rightZ * a + shift; float bx = cx + rightX * b, bz = nearZ + rightZ * b + shift; float ua = u0 + (u1 - u0) * t0, ub = u0 + (u1 - u0) * t1; float vFar = v1 + (v0 - v1) * (length / cardLength); VoxelBuilder_Quad(reflections, &(VoxelVertex){ax, y, az, ua, v1, 1.0f}, &(VoxelVertex){bx, y, bz, ub, v1, 1.0f}, &(VoxelVertex){bx, y, bz + length, ub, vFar, 1.0f}, &(VoxelVertex){ax, y, az + length, ua, vFar, 1.0f}); } } /* The part of a cloud whose corner is (left, top) over the world's rectangle * (x0, z0)-(x1, z1), on the water at height y. */ static void EmitCloudPiece(VoxelBuilder *reflections, const VoxelSpriteSlot *slot, uint32_t index, float left, float top, float x0, float z0, float x1, float z1, float y, float shift) { uint32_t baseX = (index % VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; uint32_t baseY = (index / VOXEL_SPRITE_COLUMNS) * VOXEL_SPRITE_SLOT_DIM; float width = slot->width / VOXEL_PIXELS_PER_TILE, height = slot->height / VOXEL_PIXELS_PER_TILE; float u0, u1, v0, v1; x0 = fmaxf(x0, left); x1 = fminf(x1, left + width); z0 = fmaxf(z0, top); z1 = fminf(z1, top + height); if (x1 <= x0 || z1 <= z0) return; u0 = (baseX + slot->atlasWidth * (x0 - left) / width) / (float)VOXEL_SPRITE_ATLAS_W; u1 = (baseX + slot->atlasWidth * (x1 - left) / width) / (float)VOXEL_SPRITE_ATLAS_W; v0 = 1.0f - (baseY + slot->height * (z0 - top) / height) / (float)VOXEL_SPRITE_ATLAS_H; v1 = 1.0f - (baseY + slot->height * (z1 - top) / height) / (float)VOXEL_SPRITE_ATLAS_H; VoxelBuilder_Quad(reflections, &(VoxelVertex){x0, y, z0 + shift, u0, v0, 1.0f}, &(VoxelVertex){x1, y, z0 + shift, u1, v0, 1.0f}, &(VoxelVertex){x1, y, z1 + shift, u1, v1, 1.0f}, &(VoxelVertex){x0, y, z1 + shift, u0, v1, 1.0f}); } /* * A cloud of WEATHER_SUNNY_CLOUDS. The GBA draws it under the ground's * layer, so it shows only through the water, drifting over it: here it lies * on the water's cells alone, with the reflections, and in each only where * the GBA shows it (VoxelWorld_UnderGroundMask): not over a pond's grassy * rim or a puddle's corners. Rows alike are one band, each run of pixels in * it a quad. (left, top): its north-west corner in the world. */ static void EmitCloud(VoxelBuilder *reflections, const VoxelSpriteSlot *slot, uint32_t index, float left, float top) { float right = left + slot->width / VOXEL_PIXELS_PER_TILE; float bottom = top + slot->height / VOXEL_PIXELS_PER_TILE; for (int32_t z = (int32_t)floorf(top); z < (int32_t)ceilf(bottom); ++z) for (int32_t x = (int32_t)floorf(left); x < (int32_t)ceilf(right); ++x) { uint16_t rows[16]; float y, shift; if (!VoxelWorld_IsVisibleReflectiveSurface(x, z)) continue; y = VoxelRelief_LiftAt((float)x + 0.5f, (float)z + 0.5f) + 0.035f; shift = VoxelRelief_ShiftAt((float)x + 0.5f, (float)z + 0.5f); if (!VoxelWorld_UnderGroundMask(x, z, rows)) { EmitCloudPiece(reflections, slot, index, left, top, (float)x, (float)z, (float)x + 1.0f, (float)z + 1.0f, y, shift); continue; } for (uint32_t r0 = 0, r1; r0 < 16; r0 = r1) { uint16_t mask = rows[r0]; for (r1 = r0 + 1; r1 < 16 && rows[r1] == mask; ++r1) ; for (uint32_t a = 0, b; a < 16; a = b) { if (!(mask & (1u << a))) { b = a + 1; continue; } for (b = a + 1; b < 16 && (mask & (1u << b)); ++b) ; EmitCloudPiece(reflections, slot, index, left, top, x + a / 16.0f, z + r0 / 16.0f, x + b / 16.0f, z + r1 / 16.0f, y, shift); } } } } /* * The clouds drift west for ever (UpdateCloudSprite), far off the map: the * GBA shows them because a sprite's place on the screen wraps, every 512 * pixels across and 256 down. So a cloud is a lattice on the map, 32 cells * across by 16 down, laid wherever it meets the camera's view (wider and * deeper to the north than the GBA's screen). */ #define VOXEL_CLOUD_PERIOD_X 32.0f #define VOXEL_CLOUD_PERIOD_Z 16.0f static void EmitClouds(VoxelBuilder *reflections, const VoxelSpriteSlot *slot, uint32_t index, const VoxelCamera *camera, float left, float top) { float width = slot->width / VOXEL_PIXELS_PER_TILE, height = slot->height / VOXEL_PIXELS_PER_TILE; float minX = camera->targetX - 16.0f, maxX = camera->targetX + 16.0f; float minZ = camera->targetZ - 20.0f, maxZ = camera->targetZ + 10.0f; left -= VOXEL_CLOUD_PERIOD_X * floorf((left + width - minX) / VOXEL_CLOUD_PERIOD_X); top -= VOXEL_CLOUD_PERIOD_Z * floorf((top + height - minZ) / VOXEL_CLOUD_PERIOD_Z); for (float z = top; z < maxZ; z += VOXEL_CLOUD_PERIOD_Z) for (float x = left; x < maxX; x += VOXEL_CLOUD_PERIOD_X) EmitCloud(reflections, slot, index, x, z); } /* ── Field effects ──────────────────────────────────────────────────────── */ /* * Every other sprite on the map: the Pokémon the player surfs on, grass * shaking under a step, a trainer's "!", splashes, sand piles. The GBA draws * them over the map at a screen position; here each one is a card like the * objects' own, in an atlas slot no object event is using. * * One drawn over an object belongs to it (the surf mon, the grass, the icon * over a head) and stands in that object's place, moved from it by as much as * on the GBA screen, just in front of it or just behind it as the GBA orders * the two. One drawn behind the object and below its feet is what the object * rides - the surf mon - and lifts it: the rider sits on it as on the GBA, and * the mon floats on the water instead of sinking under it. A sprite on its own * stands where its feet are drawn, placed from the player; a mark on the * ground lies on it (EmitDecal). * * Not here: object shadows and reflections, which this renderer draws its own * way; the weather, drawn over the view (ComposeVoxelOverlay); and sprites * placed on the screen rather than on the map (the mon shown for a field * move, the bird of Fly and its rider), drawn over the view too. */ // bool8 CtrSprite_IsVoxelWeather(const struct Sprite *sprite); /* sprite.c */ // bool8 CtrSprite_IsVoxelCloud(const struct Sprite *sprite); /* sprite.c */ #define VOXEL_EFFECTS_MAX VOXEL_SPRITE_SLOTS /* How far an effect card sits in front of or behind the object it belongs to. */ #define VOXEL_EFFECT_DEPTH 0.04f /* The surf mon lies on the water (the GBA draws it from above, an oval) and * its rider sits on its back this much over it, tiles. */ #define VOXEL_SURF_SEAT 0.04f /* How high the mon's back stands over the water, for its shadow, tiles. */ #define VOXEL_SURF_BODY 0.12f typedef struct { bool drawn; float worldX, worldZ; /* the tile, world */ int32_t screenX; /* GBA screen: centre, */ int32_t top, base, feet; /* top edge, bottom edge, feet (no y2) */ const struct Sprite *sprite; float rise; /* onto what it rides */ float deck; /* up on a bridge's deck, tiles */ float shade; bool outdoor; /* casts a shadow */ } VoxelObjectCard; typedef struct { const struct Sprite *sprite; uint32_t slot; int32_t owner; /* object index, or -1 */ bool front, decal, tile; bool surf; /* the surf mon: lying on the water, ridden */ bool cloud; /* a cloud, laid on the water (EmitCloud) */ } VoxelEffectCard; static bool IsTemplate(const struct SpriteTemplate *template, uint32_t first, uint32_t last) { for (uint32_t i = first; i <= last; ++i) if (template == gFieldEffectObjectTemplatePointers[i]) return true; return false; } /* Grass that rustles where it was stepped on keeps that tile in its data * (field_effect_helpers.c: sX, sY) and stays there while its object walks on: * placed from the object, it floated in the object's plane, off its tile. */ static bool IsTileEffect(const struct SpriteTemplate *template) { return template == gFieldEffectObjectTemplatePointers[FLDEFFOBJ_TALL_GRASS] || template == gFieldEffectObjectTemplatePointers[FLDEFFOBJ_LONG_GRASS]; } static bool IsDecal(const struct SpriteTemplate *template) { return template == gFieldEffectObjectTemplatePointers[FLDEFFOBJ_RIPPLE] || template == gFieldEffectObjectTemplatePointers[FLDEFFOBJ_SAND_FOOTPRINTS] || template == gFieldEffectObjectTemplatePointers[FLDEFFOBJ_DEEP_SAND_FOOTPRINTS] || template == gFieldEffectObjectTemplatePointers[FLDEFFOBJ_BIKE_TIRE_TRACKS]; } /* wild_encounter.c, from the optional visible wild Pokemon (patch 0056); * without it no sprite is one. */ bool8 VisibleWild_IsSprite(u8 spriteId); bool8 __attribute__((weak)) VisibleWild_IsSprite(u8 spriteId) { (void)spriteId; return FALSE; } /* * Which effects get the slots the objects leave (VoxelSlots_Assign): only * those the camera can see, a visible wild Pokemon first and grass rustling * on its tile last, each kept in the slot it had. Taken in sprite order, a * route's grass and the effects of trainers far off the view filled the slots * first, which can starve wild Pokemon of slots as sprites come and go * (a possible contributor to #93). Wide of the 24 tiles the cards are cut at by as much as an effect's * placement can differ from this estimate. */ #define VOXEL_EFFECT_RANGE (24.0f + 2.0f) static u8 EffectPriority(const struct Sprite *sprite, uint32_t id) { if (VisibleWild_IsSprite((u8)id)) return VOXEL_SLOT_PRIORITY_WILD; if (IsTileEffect(sprite->template)) return VOXEL_SLOT_PRIORITY_DECOR; return VOXEL_SLOT_PRIORITY_EFFECT; } /* Drawn over `object` on the GBA screen: sprites come first in OAM, and so * on top, by priority and then subpriority. */ static bool DrawnOver(const struct Sprite *sprite, const struct Sprite *object) { if (sprite->oam.priority != object->oam.priority) return sprite->oam.priority < object->oam.priority; return sprite->subpriority <= object->subpriority; } static int32_t SpriteHeight(const struct Sprite *sprite) { int32_t w, h; GetSpriteDimensions(sprite->oam.shape, sprite->oam.size, &w, &h); return h; } /* The object an effect is drawn over, or -1: its centre inside the object's * picture, the nearest to the object's middle. */ static int32_t EffectOwner(const struct Sprite *sprite, const VoxelObjectCard *objects) { int32_t x = sprite->x + sprite->x2; int32_t y = sprite->y + sprite->y2 + sprite->centerToCornerVecY + SpriteHeight(sprite) / 2; int32_t best = -1, bestDistance = 0x7fff; for (uint32_t i = 0; i < OBJECT_EVENTS_COUNT; ++i) { const VoxelObjectCard *object = &objects[i]; int32_t y2, distance; if (!object->drawn || abs(x - object->screenX) > 8) continue; y2 = object->sprite->y2; if (y < object->top + y2 || y > object->base + y2) continue; distance = abs(y - (object->top + object->base) / 2 - y2); if (distance < bestDistance) { best = (int32_t)i; bestDistance = distance; } } return best; } /* Whether VoxelEntities_Emit may sample the lighting (VoxelEntities_AllowLighting). * While the renderer's chunk worker owns the lighting caches it may not, and an * object keeps the shade it was last given. */ static bool sLightingAllowed = true; static float sLastShade[OBJECT_EVENTS_COUNT]; static bool sLastShadeKnown[OBJECT_EVENTS_COUNT]; void VoxelEntities_AllowLighting(bool allowed) { sLightingAllowed = allowed; } uint32_t VoxelEntities_TakeDirtySlots(void) { const uint32_t dirty = sDirtySlots; sDirtySlots = 0; return dirty; } uint32_t VoxelEntities_Emit(VoxelBuilder *builder, uint16_t *atlas, const VoxelCamera *camera, VoxelBuilder *shadows, VoxelBuilder *reflections) { /* The billboards turn about the vertical axis to face the camera. With the * default yaw of 0 this is (1,0,0), the same plane the reference uses. * The card stands upright and the camera looks down on it, so on screen * its height comes out cos(pitch) short. That is made up half on each * side: the width comes down by sqrt(cos(pitch)) and the height goes up * by as much, so on screen both are sqrt(cos(pitch)) of the sprite's * (0.875 at 40 degrees). The proportions are the sprite's, and so is the * area on screen of the plain card. All of it off the width left the * characters small, all of it on the height big. Still upright, so it * sorts against walls as before. Shadow and reflection are the card's * own, so they take the same size. */ float yawRad = camera->yaw * (3.14159265358979323846f / 180.0f); float narrow = sqrtf(cosf(camera->pitch * (3.14159265358979323846f / 180.0f))); float stretch; /* A card tilted to face the swoop's camera is seen square on: nothing * to make up (upright at a top-down pose it was a hair wide, seven tall). */ sLay = camera->lay; narrow = 1.0f + (narrow - 1.0f) * (1.0f - sLay); stretch = 1.0f / narrow; float rightX = cosf(yawRad) * narrow, rightZ = -sinf(yawRad) * narrow; /* Towards the camera, along the ground. */ float towardX = sinf(yawRad), towardZ = cosf(yawRad); float pixel = stretch / VOXEL_PIXELS_PER_TILE; /* Static, not automatic: this runs in the VBlank handler. */ static VoxelObjectCard objects[OBJECT_EVENTS_COUNT]; static VoxelEffectCard effects[VOXEL_EFFECTS_MAX]; /* Every sprite that could be an effect card this frame, before the * slots are handed out. */ static VoxelEffectCard candidates[MAX_SPRITES]; static VoxelSlotRequest requests[MAX_SPRITES]; static bool objectSprite[MAX_SPRITES]; static u16 objectTiles[OBJECT_EVENTS_COUNT]; bool claimed[VOXEL_SPRITE_SLOTS] = {false}; bool reset[VOXEL_SPRITE_SLOTS] = {false}; uint32_t objectTileCount = 0, effectCount = 0, candidateCount = 0, dropped; uint32_t updates = 0; VoxelDoor doors[VOXEL_DOORS]; sPlayerVertexFirst = -1; /* The lighting caches are the chunks' own, valid until the world * changes (ctr_voxel.c resets them then), so they are not reset here. */ const VoxelEntitySnapshot *snap = VoxelEntities_GetVisibleSnapshot(); int32_t snapOffX = 0, snapOffY = 0; if (snap != NULL && snap->mapGroup >= 0 && snap->mapNum >= 0) { VoxelWorld_GetInstanceOffset(snap->mapGroup, snap->mapNum, &snapOffX, &snapOffY); } memset(objectSprite, 0, sizeof(objectSprite)); for (uint32_t i = 0; i < OBJECT_EVENTS_COUNT; ++i) { const struct ObjectEvent *obj = &snap->objectEvents[i]; const struct Sprite *sprite; VoxelObjectCard *card = &objects[i]; float worldX = 0.0f, worldZ = 0.0f; float shade = 1.0f; bool outdoor = false; card->drawn = false; if (!obj->active) continue; /* An object in use takes its slot back from any field effect. */ claimed[i] = true; if (sSlotEffect[i] != 0) { sSlotEffect[i] = 0; sSlots[i].valid = false; sSlots[i].footPadImages = NULL; } if (obj->spriteId >= MAX_SPRITES) continue; sprite = &snap->sprites[i]; objectSprite[obj->spriteId] = true; objectTiles[objectTileCount++] = sprite->oam.tileNum; /* * Not sprite->invisible: the game also sets that for an object that * has left the 2D field of view (offScreen), and the 3D camera sees * twice as far north. Only the object's own flag hides it here. */ if (obj->invisible) continue; /* Carried on the screen instead of the map - the rider of Fly's * bird - it is drawn with the screen's sprites, over the view. */ if (!sprite->coordOffsetEnabled) continue; GetObjectWorldPos(obj, sprite, &worldX, &worldZ); /* Object coordinates are map-local; transform to inst0 world space via instance offset */ worldX += (float)snapOffX; worldZ += (float)snapOffY; /* Active events may be dozens of tiles beyond the camera, including * across map connections. They cannot appear in this view. * The 3D camera reaches up to 42 tiles north and 16 tiles south. */ if (fabsf(worldX - camera->targetX) > 24.0f || (camera->targetZ - worldZ) > 42.0f || (worldZ - camera->targetZ) > 16.0f) continue; if (!Shop_IsBuyMenuActive()) { if (RefreshSlot(i, sprite, obj, snap->extPalettes[i], atlas)) { ++updates; sDirtySlots |= 1u << i; } } if (!sSlots[i].valid) continue; { const struct ObjectEventGraphicsInfo *info = GetObjectEventGraphicsInfo(obj->graphicsId); bool changed = sSlots[i].footPadImages != info->images; if (changed || !sSlots[i].footPadExact) { bool exact = true; int32_t pad = info->images != NULL ? StandingFootPad(info, &sSlots[i], &exact) : 0; sSlots[i].footPadImages = info->images; /* A provisional pad is taken once, never from each frame of a * walk: that would undo its bob. */ if (changed || exact) sSlots[i].footPad = pad; sSlots[i].footPadExact = exact; } } card->deck = ObjectDeck(obj, worldX, worldZ); { const VoxelMapInstance *inst = VoxelWorld_GetInstanceAt((int32_t)floorf(worldX + 0.5f), (int32_t)floorf(worldZ + 0.5f)); outdoor = inst != NULL && !inst->indoor; #if CTR_VOXEL_LIGHTING /* Where the card stands (EmitBillboard): on its cell's relief and * its map's base, and up on a bridge's deck, the light over the * deck, not under it. At 0.75 over the world's zero, a sprite on * a raised map or a mountain was sampled inside the rock and * drawn in its shadow. One sample, as ever: this runs every * frame. */ if (outdoor) { float cx = worldX + 0.5f, cz = worldZ + 0.5f; if (sLightingAllowed || !sLastShadeKnown[i]) { // (a first sample with the lighting busy is not taken: plain light) if (sLightingAllowed) { shade = VoxelLighting_SampleAlone(cx, VoxelRelief_LiftAt(cx, cz) + 0.75f + card->deck, cz + VoxelRelief_ShiftAt(cx, cz) + card->deck); sLastShade[i] = shade; sLastShadeKnown[i] = true; } } else { shade = sLastShade[i]; } } #endif } card->drawn = true; card->worldX = worldX; card->worldZ = worldZ; card->screenX = sprite->x + sprite->x2; /* A picture bigger than its OAM (PictureSize) is centred on the * sprite as its subsprites are: half the difference higher. */ card->top = sprite->y + sprite->centerToCornerVecY - (sSlots[i].height - SpriteHeight(sprite)) / 2; card->base = card->top + sSlots[i].height; card->feet = card->base - (sSlots[i].height - VisibleRows(&sSlots[i])); card->sprite = sprite; card->rise = 0.0f; card->shade = shade; card->outdoor = outdoor; } if (!Shop_IsBuyMenuActive()) { for (uint32_t id = 0; id < MAX_SPRITES; ++id) { const struct Sprite *sprite = &gSprites[id]; VoxelEffectCard *effect = &candidates[candidateCount]; VoxelSlotRequest *request = &requests[candidateCount]; const VoxelObjectCard *reference; uint32_t t; int32_t w, h; bool inRange = false, cloud; /* sprite->invisible is honoured: an effect hidden on purpose (a * blinking one's off frames) is hidden here too. */ if (!sprite->inUse || sprite->invisible || !sprite->coordOffsetEnabled || objectSprite[id]) continue; cloud = CtrSprite_IsVoxelCloud(sprite); if (IsTemplate(sprite->template, FLDEFFOBJ_SHADOW_S, FLDEFFOBJ_SHADOW_XL) || (CtrSprite_IsVoxelWeather(sprite) && !cloud)) continue; /* A reflection is a copy of its object's picture. */ for (t = 0; t < objectTileCount && objectTiles[t] != sprite->oam.tileNum; ++t) ; if (t < objectTileCount) continue; GetSpriteDimensions(sprite->oam.shape, sprite->oam.size, &w, &h); if (w > (int32_t)VOXEL_SPRITE_SLOT_DIM || h > (int32_t)VOXEL_SPRITE_SLOT_DIM) continue; effect->sprite = sprite; effect->slot = 0; effect->surf = sprite->template == gFieldEffectObjectTemplatePointers[FLDEFFOBJ_SURF_BLOB]; effect->cloud = cloud; effect->decal = IsDecal(sprite->template) || cloud; effect->tile = IsTileEffect(sprite->template); /* A visible wild Pokemon stands on its own tile, never on an object: * a tile south of the player, owned by it, it sank under the ground. */ effect->owner = effect->decal || effect->tile || VisibleWild_IsSprite((u8)id) ? -1 : EffectOwner(sprite, objects); effect->front = effect->owner < 0 || DrawnOver(sprite, objects[effect->owner].sprite); /* Where it will be drawn, near enough to tell whether the camera * can see it (the placement below). */ reference = gPlayerAvatar.objectEventId < OBJECT_EVENTS_COUNT ? &objects[gPlayerAvatar.objectEventId] : NULL; if (effect->tile) { float cx = (float)(sprite->data[1] - MAP_OFFSET) + 0.5f; float cz = (float)(sprite->data[2] - MAP_OFFSET) + 0.5f; if (VoxelWorld_InstanceCount() > 0) { cx += (float)VoxelWorld_Instance(0)->originX; cz += (float)VoxelWorld_Instance(0)->originY; } /* Long grass stands in 3D there (voxel_tree.c): its tuft hides * the walker, and the GBA's picture of it laid on the new floor * was a patch of the old drawing. */ if (sprite->template == gFieldEffectObjectTemplatePointers[FLDEFFOBJ_LONG_GRASS] && VoxelTree_PartAt((int32_t)floorf(cx), (int32_t)floorf(cz)) == VOXEL_TREE_GRASS) continue; inRange = fabsf(cx - camera->targetX) <= VOXEL_EFFECT_RANGE && fabsf(cz - camera->targetZ) <= VOXEL_EFFECT_RANGE; } else if (effect->owner >= 0 && !effect->surf) { /* On a drawn object: that one is in sight. */ inRange = true; } else if (reference != NULL && reference->drawn) { int32_t base = sprite->y + sprite->centerToCornerVecY + h; float cx = reference->worldX + 0.5f + (sprite->x + sprite->x2 - reference->screenX) / VOXEL_PIXELS_PER_TILE; float cz = reference->worldZ + 0.5f + (base - reference->base) / VOXEL_PIXELS_PER_TILE; inRange = fabsf(cx - camera->targetX) <= VOXEL_EFFECT_RANGE && fabsf(cz - camera->targetZ) <= VOXEL_EFFECT_RANGE; } /* A cloud is everywhere its lattice repeats it (EmitClouds). */ if (cloud) inRange = true; request->id = (uint8_t)id; request->priority = EffectPriority(sprite, id); request->inRange = inRange; request->slot = -1; ++candidateCount; } /* All but the door's slot. */ dropped = VoxelSlots_Assign(requests, candidateCount, sSlotEffect, claimed, reset, VOXEL_DOOR_SLOT, OBJECT_EVENTS_COUNT); if (dropped > 0) { /* Not drawn this frame: logged, at most every ten seconds. */ static uint32_t sLastFull; if (sLastFull == 0 || gMain.vblankCounter1 - sLastFull >= 600) { sLastFull = gMain.vblankCounter1 ? gMain.vblankCounter1 : 1; CtrLog_Write(CTR_LOG_VIDEO, "VOXEL sprite slots full: %u in sight left out, lowest priority first", dropped); } } for (uint32_t s = 0; s < VOXEL_SPRITE_SLOTS; ++s) { if (!reset[s]) continue; sSlots[s].valid = false; sSlots[s].footPad = 0; sSlots[s].footPadImages = NULL; } /* In sprite order, as they were drawn before. */ for (uint32_t c = 0; c < candidateCount && effectCount < VOXEL_EFFECTS_MAX; ++c) { VoxelEffectCard *effect = &effects[effectCount]; if (requests[c].slot < 0) continue; *effect = candidates[c]; effect->slot = (uint32_t)requests[c].slot; if (effect->surf) { if (effect->owner >= 0 && !effect->front && VOXEL_SURF_SEAT > objects[effect->owner].rise) objects[effect->owner].rise = VOXEL_SURF_SEAT; effect->decal = true; effect->owner = -1; effect->front = true; } ++effectCount; } /* Slots neither an object nor an effect wants this frame. */ for (uint32_t s = 0; s < VOXEL_SPRITE_SLOTS; ++s) { if (claimed[s]) continue; sSlotEffect[s] = 0; sSlots[s].valid = false; } } if (FindDoors(doors, atlas)) { ++updates; sDirtySlots |= 1u << VOXEL_DOOR_SLOT; } for (uint32_t d = 0; d < VOXEL_DOORS; ++d) EmitDoor(builder, &doors[d]); for (uint32_t i = 0; i < OBJECT_EVENTS_COUNT; ++i) { VoxelObjectCard *card = &objects[i]; float rise, dusk; if (!card->drawn) continue; /* Through an open door: gone, shadow and all. */ dusk = DoorLight(doors, card->worldX + 0.5f, card->worldZ + 0.5f); if (dusk <= 0.0f) continue; /* Riding: up and down with what it rides, as the GBA bobs both. */ rise = card->rise > 0.0f ? card->rise - card->sprite->y2 * pixel : 0.0f; /* Jumping: the arc the GBA draws, over a shadow left on the ground. */ if (IsJumping(&snap->objectEvents[i], card->sprite)) rise -= card->sprite->y2 * pixel; /* Riding, it is off the ground: its shadow falls from its feet, * moved along the sun by how high they are, onto the water past * the mon's back. */ if (shadows != NULL && card->outdoor) EmitCastShadow(shadows, &sSlots[i], i, card->worldX, card->worldZ, rightX, rightZ, stretch, card->shade, card->rise > 0.0f ? rise : 0.0f, card->deck); if (reflections != NULL && snap->objectEvents[i].hasReflection) EmitReflection(reflections, &sSlots[i], i, card->worldX, card->worldZ, rightX, rightZ, stretch); uint32_t first = builder->count; EmitBillboard(builder, &sSlots[i], i, card->worldX + 0.5f, card->worldZ + 0.5f, 0.0f, 0.0f, rise, card->deck, rightX, rightZ, stretch, card->shade * dusk, 1.0f, dusk < 1.0f); if (i == gPlayerAvatar.objectEventId && builder->count == first + 6) sPlayerVertexFirst = (int32_t)first; } for (uint32_t e = 0; e < effectCount; ++e) { const VoxelEffectCard *effect = &effects[e]; const struct Sprite *sprite = effect->sprite; const VoxelObjectCard *reference; int32_t h, x, base; if (RefreshSlot(effect->slot, sprite, NULL, GetSpriteExtPalette(sprite), atlas)) { ++updates; sDirtySlots |= 1u << effect->slot; } if (!sSlots[effect->slot].valid) continue; h = sSlots[effect->slot].height; x = sprite->x + sprite->x2; base = sprite->y + sprite->centerToCornerVecY + h; if (effect->cloud) { /* Placed from the player as a decal is: its picture's bottom * edge 8 px under the middle of the player's tile. */ reference = gPlayerAvatar.objectEventId < OBJECT_EVENTS_COUNT ? &objects[gPlayerAvatar.objectEventId] : NULL; // Ocean routes and underwater maps contain zero reflective puddles/ponds. // Early-skipping EmitClouds on open sea avoids hundreds of fruitless GetRawBlock() checks per frame! const bool isOceanMap = (gMapHeader.mapType == MAP_TYPE_OCEAN_ROUTE || gMapHeader.mapType == MAP_TYPE_UNDERWATER); if (!isOceanMap && reflections != NULL && reference != NULL && reference->drawn) EmitClouds(reflections, &sSlots[effect->slot], effect->slot, camera, reference->worldX + 0.5f + (x - reference->screenX) / VOXEL_PIXELS_PER_TILE - sSlots[effect->slot].width / VOXEL_PIXELS_PER_TILE * 0.5f, reference->worldZ + 0.5f + (base - h - (reference->base - 8)) / VOXEL_PIXELS_PER_TILE); continue; } if (effect->tile) { /* Lying on its own tile over the ground's drawing of it, which it * animates: stood up as a card it read as a flat picture on top * of the tile instead of the tile itself. */ float cx = (float)(sprite->data[1] - MAP_OFFSET) + 0.5f; float cz = (float)(sprite->data[2] - MAP_OFFSET) + 0.5f; float shade = 1.0f; if (gPlayerAvatar.objectEventId < OBJECT_EVENTS_COUNT && objects[gPlayerAvatar.objectEventId].drawn) shade = objects[gPlayerAvatar.objectEventId].shade; if (VoxelWorld_InstanceCount() > 0) { cx += (float)VoxelWorld_Instance(0)->originX; cz += (float)VoxelWorld_Instance(0)->originY; } if (fabsf(cx - camera->targetX) > 24.0f || fabsf(cz - camera->targetZ) > 24.0f) continue; EmitDecal(builder, &sSlots[effect->slot], effect->slot, cx, cz, 0.0f, shade); continue; } if (effect->owner >= 0) { const VoxelObjectCard *object = &objects[effect->owner]; float depth = effect->front ? VOXEL_EFFECT_DEPTH : -VOXEL_EFFECT_DEPTH; float along = (x - object->screenX) / VOXEL_PIXELS_PER_TILE; /* The owner's feet on the ground, lifted by what it rides. */ float rise = object->rise + (object->feet - base - sprite->y2) * pixel; EmitBillboard(builder, &sSlots[effect->slot], effect->slot, object->worldX + 0.5f, object->worldZ + 0.5f, rightX * along + towardX * depth, rightZ * along + towardZ * depth, rise, object->deck, rightX, rightZ, stretch, object->shade, SpriteScale(sprite), false); continue; } /* On its own: placed from the player, whose feet are on the centre of * its tile and whose picture ends at the tile's bottom edge. */ reference = gPlayerAvatar.objectEventId < OBJECT_EVENTS_COUNT ? &objects[gPlayerAvatar.objectEventId] : NULL; if (reference == NULL || !reference->drawn) continue; { float cx = reference->worldX + 0.5f + (x - reference->screenX) / VOXEL_PIXELS_PER_TILE; float cz; if (effect->decal) { /* Its middle on the ground: a tile's middle is 8 px above * its bottom edge. */ cz = reference->worldZ + 0.5f + (base - h / 2 - (reference->base - 8)) / VOXEL_PIXELS_PER_TILE; if (fabsf(cx - camera->targetX) > 24.0f || fabsf(cz - camera->targetZ) > 24.0f) continue; if (effect->surf) { /* Up and down with the GBA's bob, its rider with it. */ float lift = sprite->y2 < 0 ? -sprite->y2 * pixel : 0.0f; /* Under its rider as the GBA draws the two: the rider's * feet a little in front of the oval's middle. Placed as * ground, it lay 8 px south of that - the rider's card * stands on its tile's middle, where the GBA draws feet * at the tile's bottom edge - and the rider sat on its * back rim instead. */ cz -= 8.0f / VOXEL_PIXELS_PER_TILE; EmitDecal(builder, &sSlots[effect->slot], effect->slot, cx, cz, lift, reference->shade); if (shadows != NULL && reference->outdoor) EmitDecalShadow(shadows, &sSlots[effect->slot], effect->slot, cx, cz, lift + VOXEL_SURF_BODY, reference->shade); continue; } EmitDecal(builder, &sSlots[effect->slot], effect->slot, cx, cz, 0.0f, reference->shade); continue; } cz = reference->worldZ + 0.5f + (base - reference->base) / VOXEL_PIXELS_PER_TILE; if (fabsf(cx - camera->targetX) > 24.0f || fabsf(cz - camera->targetZ) > 24.0f) continue; EmitBillboard(builder, &sSlots[effect->slot], effect->slot, cx, cz, 0.0f, 0.0f, -sprite->y2 * pixel, reference->deck, rightX, rightZ, stretch, reference->shade, SpriteScale(sprite), false); } } return updates; }