Skip to content

Commit

Permalink
fix: optimize dynamax code
Browse files Browse the repository at this point in the history
  • Loading branch information
TurtIeSocks committed Sep 10, 2024
1 parent 5b7b58f commit a1cfb57
Show file tree
Hide file tree
Showing 14 changed files with 157 additions and 64 deletions.
9 changes: 6 additions & 3 deletions packages/locales/lib/human/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -788,13 +788,16 @@
"individual_filters": "Partially Filtered",
"data_limit_reached": "You have requested too much data recently and are on cooldown until {{until}}",
"unknown_station": "Unknown Power Spot",
"exclude_battle": "Exclude Battle",
"exclude_battle": "Exclude Max Battle",
"station": "Power Spot",
"stations": "Power Spots",
"stations_options": "Power Spot Options",
"all_stations": "All Power Spots",
"search_battles": "Search Battles",
"search_battles": "Search Max Battles",
"started": "Started",
"ended": "Ended",
"global_search_stations": "Search Power Spots"
"global_search_stations": "Search Power Spots",
"station_timers": "Power Spot Timers",
"station_opacity": "Power Spot Opacity",
"max_battles": "Max Battles"
}
2 changes: 1 addition & 1 deletion server/src/filters/builder/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ function buildDefaultFilters(perms) {
battleTier: perms.dynamax
? defaultFilters.stations.battleTier
: undefined,
battles: perms.stations
maxBattles: perms.stations
? defaultFilters.stations.battles
: undefined,
filter: pokemon.stations,
Expand Down
6 changes: 6 additions & 0 deletions server/src/graphql/typeDefs/map.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@ type Search {
costume: Int
shiny: Int
iv: Float
battle_pokemon_id: Int
battle_pokemon_form: Int
battle_pokemon_gender: Int
battle_pokemon_costume: Int
# battle_pokemon_evolution: Int
battle_pokemon_alignment: Int
}

type SearchLure {
Expand Down
98 changes: 65 additions & 33 deletions server/src/models/Station.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
// @ts-check
const { Model } = require('objection')
const config = require('@rm/config')
const i18next = require('i18next')

const { getAreaSql } = require('../utils/getAreaSql')
const { getEpoch } = require('../utils/getClientTime')
const { state } = require('../services/state')

class Station extends Model {
static get tableName() {
Expand All @@ -19,7 +21,7 @@ class Station extends Model {
*/
static async getAll(perms, args, { isMad }) {
const { areaRestrictions } = perms
const { onlyAreas } = args.filters
const { onlyAreas, onlyAllStations, onlyMaxBattles } = args.filters
const ts = getEpoch()

const select = [
Expand All @@ -38,8 +40,9 @@ class Station extends Model {
.andWhere('end_time', '>', ts)
// .where('is_inactive', false)

if (perms.dynamax) {
if (perms.dynamax && onlyMaxBattles) {
select.push(
'is_battle_available',
'battle_level',
'battle_pokemon_id',
'battle_pokemon_form',
Expand All @@ -48,35 +51,37 @@ class Station extends Model {
'battle_pokemon_alignment',
)

const battleBosses = new Set()
const battleForms = new Set()
const battleLevels = new Set()

Object.keys(args.filters).forEach((key) => {
switch (key.charAt(0)) {
case 'o':
break
case 'j':
battleLevels.add(key.slice(1))
break
default:
{
const [id, form] = key.split('-')
if (id) battleBosses.add(id)
if (form) battleForms.add(form)
}
break
if (!onlyAllStations) {
const battleBosses = new Set()
const battleForms = new Set()
const battleLevels = new Set()

Object.keys(args.filters).forEach((key) => {
switch (key.charAt(0)) {
case 'o':
break
case 'j':
battleLevels.add(key.slice(1))
break
default:
{
const [id, form] = key.split('-')
if (id) battleBosses.add(id)
if (form) battleForms.add(form)
}
break
}
})

if (battleBosses.size) {
query.andWhere('battle_pokemon_id', 'in', [...battleBosses])
}
if (battleForms.size) {
query.andWhere('battle_pokemon_form', 'in', [...battleForms])
}
if (battleLevels.size) {
query.andWhere('battle_level', 'in', [...battleLevels])
}
})

if (battleBosses.size) {
query.andWhere('battle_pokemon_id', 'in', [...battleBosses])
}
if (battleForms.size) {
query.andWhere('battle_pokemon_form', 'in', [...battleForms])
}
if (battleLevels.size) {
query.andWhere('battle_level', 'in', [...battleLevels])
}
}

Expand Down Expand Up @@ -137,19 +142,46 @@ class Station extends Model {
*/
static async search(perms, args, { isMad }, distance, bbox) {
const { areaRestrictions } = perms
const { onlyAreas = [], search = '' } = args
const { onlyAreas = [], search = '', locale } = args
const { searchResultsLimit, stationUpdateLimit } = config.getSafe('api')

const pokemonIds = Object.keys(state.event.masterfile.pokemon).filter(
(pkmn) =>
i18next
.t(`poke_${pkmn}`, { lng: locale })
.toLowerCase()
.includes(search),
)

const select = ['id', 'name', 'lat', 'lon', distance]
if (perms.dynamax) {
select.push(
'battle_level',
'battle_pokemon_id',
'battle_pokemon_form',
'battle_pokemon_costume',
'battle_pokemon_gender',
'battle_pokemon_alignment',
)
}

const query = this.query()
.select(['name', 'id', 'lat', 'lon', distance])
.whereILike('name', `%${search}%`)
.select(select)
.whereBetween('lat', [bbox.minLat, bbox.maxLat])
.andWhereBetween('lon', [bbox.minLon, bbox.maxLon])
.andWhere(
'updated',
'>',
Date.now() / 1000 - stationUpdateLimit * 60 * 60 * 24,
)
.andWhere((builder) => {
if (perms.stations) {
builder.orWhereILike('name', `%${search}%`)
}
if (perms.dynamax) {
builder.orWhereIn('battle_pokemon_id', pokemonIds)
}
})
.limit(searchResultsLimit)
.orderBy('distance')
if (!getAreaSql(query, areaRestrictions, onlyAreas, isMad)) {
Expand Down
10 changes: 5 additions & 5 deletions server/src/ui/clientOptions.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,11 @@ function clientOptions(perms) {
},
stations: {
clustering: { type: 'bool', perm: ['stations', 'dynamax'] },
battleTimers: { type: 'bool', perm: ['dynamax'] },
battleOpacity: { type: 'bool', perm: ['dynamax'] },
opacityTenMinutes: { type: 'number', perm: ['dynamax'] },
opacityFiveMinutes: { type: 'number', perm: ['dynamax'] },
opacityOneMinute: { type: 'number', perm: ['dynamax'] },
stationTimers: { type: 'bool', perm: ['stations', 'dynamax'] },
stationOpacity: { type: 'bool', perm: ['stations', 'dynamax'] },
opacityTenMinutes: { type: 'number', perm: ['stations', 'dynamax'] },
opacityFiveMinutes: { type: 'number', perm: ['stations', 'dynamax'] },
opacityOneMinute: { type: 'number', perm: ['stations', 'dynamax'] },
enableStationPopupCoords: map.misc.enableStationPopupCoordsSelector
? { type: 'bool', perm: ['stations', 'dynamax'] }
: undefined,
Expand Down
2 changes: 1 addition & 1 deletion server/src/ui/drawer.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ function drawer(req, perms) {
(perms.stations || perms.dynamax) && state.db.models.Station
? {
allStations: perms.stations || BLOCKED,
battles: perms.dynamax || BLOCKED,
maxBattles: perms.dynamax || BLOCKED,
}
: BLOCKED,
pokemon:
Expand Down
2 changes: 1 addition & 1 deletion src/features/drawer/Extras.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function ExtrasComponent({ category, subItem }) {
case 'admin':
return <AdminDrawer subItem={subItem} />
case 'stations':
return subItem === 'battles' && <StationsDrawer />
return subItem === 'maxBattles' && <StationsDrawer />
default:
return null
}
Expand Down
15 changes: 9 additions & 6 deletions src/features/drawer/Stations.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// @ts-check
import * as React from 'react'
import Box from '@mui/material/Box'
// import ListItem from '@mui/material/ListItem'
// import ListItemText from '@mui/material/ListItemText'
// import MenuItem from '@mui/material/MenuItem'
Expand Down Expand Up @@ -52,14 +53,16 @@ import { SelectorListMemo } from './components/SelectorList'
// }

function StationsQuickSelect() {
const enabled = useStorage((s) => !!s.filters?.stations?.battles)
const enabled = useStorage((s) => !!s.filters?.stations?.maxBattles)
return (
<CollapsibleItem open={enabled}>
<SelectorListMemo
category="stations"
label="search_battles"
height={350}
/>
<Box px={2}>
<SelectorListMemo
category="stations"
label="search_battles"
height={350}
/>
</Box>
</CollapsibleItem>
)
}
Expand Down
11 changes: 10 additions & 1 deletion src/features/search/OptionImage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ function Misc() {
return <Img src={miscIcon} alt={searchTab} maxHeight={45} maxWidth={45} />
}

/** @param {Partial<import('@rm/types').Quest & { id: string }> | { id: string, url?: string } | Partial<import('@rm/types').Pokemon> | Partial<import('@rm/types').Gym> | Partial<import('@rm/types').Pokestop> | { id: string, nest_pokemon_id: number, nest_pokemon_form?: number } | Partial<import('@rm/types').Invasion> & { id: string }} props */
/** @param {Partial<import('@rm/types').Quest & { id: string }> | { id: string, url?: string } | Partial<import('@rm/types').Pokemon> | Partial<import('@rm/types').Gym> | Partial<import('@rm/types').Pokestop> | { id: string, nest_pokemon_id: number, nest_pokemon_form?: number } | Partial<import('@rm/types').Invasion> & { id: string } | Partial<import('@rm/types').Station} props */
function OptionImage(props) {
if ('url' in props && props.url) return <FortImage url={props.url} />
if ('quest_reward_type' in props) return <QuestImage {...props} />
Expand All @@ -184,6 +184,15 @@ function OptionImage(props) {
if ('lure_id' in props) return <LureImage {...props} />
if ('nest_pokemon_id' in props) return <NestImage {...props} />
if ('grunt_type' in props) return <InvasionImage {...props} />
if ('battle_pokemon_id' in props && props.battle_pokemon_id)
return (
<PokemonImage
pokemon_id={props.battle_pokemon_id}
form={props.battle_pokemon_form}
gender={props.battle_pokemon_gender}
costume={props.battle_pokemon_costume}
/>
)
return <Misc />
}

Expand Down
28 changes: 18 additions & 10 deletions src/features/station/StationPopup.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -182,19 +182,19 @@ function StationMedia({
),
)
const stationImage = useMemory((s) => s.Icons.getStation(true))
const pokemon = useMemory((s) => {
if (!battle_pokemon_id) return null
const types = useMemory((s) => {
if (!battle_pokemon_id) return []
const poke = s.masterfile.pokemon[battle_pokemon_id]
if (poke?.forms?.[battle_pokemon_form]) {
return poke.forms[battle_pokemon_form]
if (poke?.forms?.[battle_pokemon_form]?.types) {
return poke.forms[battle_pokemon_form]?.types || []
}
return poke
return poke?.types || []
})

return battle_pokemon_id ? (
<CardMedia>
<Box className="popup-card-media">
<Box className="flex-center">
<Box className="flex-center" py={2}>
<Img
src={monImage}
alt={t(`${battle_pokemon_id}-${battle_pokemon_form}`)}
Expand All @@ -203,10 +203,12 @@ function StationMedia({
/>
</Box>
<Stack alignItems="center" justifyContent="center" spacing={2}>
{pokemon?.types?.map((type) => (
{types.map((type) => (
<PokeType key={type} id={type} size="medium" />
))}
<GenderIcon gender={battle_pokemon_gender} fontSize="medium" />
{!!battle_pokemon_gender && (
<GenderIcon gender={battle_pokemon_gender} fontSize="medium" />
)}
</Stack>
</Box>
</CardMedia>
Expand All @@ -228,6 +230,7 @@ function StationMedia({
*/
function StationContent({
battle_pokemon_id,
is_battle_available,
battle_pokemon_form,
battle_pokemon_costume,
battle_level,
Expand All @@ -240,9 +243,14 @@ function StationContent({
<CardContent sx={{ p: 0 }}>
<Stack alignItems="center" justifyContent="center" spacing={1}>
{!!battle_level && (
<Rating value={battle_level} max={Math.max(5, battle_level)} />
<Rating
value={battle_level}
max={Math.max(5, battle_level)}
readOnly
size="large"
/>
)}
{!!battle_pokemon_id && (
{!!is_battle_available && (
<Box textAlign="center">
<Typography variant="h6">
{t(`poke_${battle_pokemon_id}`)}
Expand Down
2 changes: 1 addition & 1 deletion src/features/station/useStationMarker.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export function useStationMarker({
opacity: ${getOpacity(0)};
width: ${battleSize}px;
height: ${battleSize}px;
bottom: ${baseSize * 0.4 * battleMod.offsetY}px;
bottom: ${baseSize * 0.8 * battleMod.offsetY}px;
left: ${battleMod.offsetX * 55}%;
transform: translateX(-50%);
"
Expand Down
2 changes: 1 addition & 1 deletion src/pages/map/hooks/usePermCheck.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export function usePermCheck(category) {
case 'stations':
if (
(filters?.allStations && perms?.stations) ||
(filters?.battles && perms?.dynamax)
(filters?.maxBattles && perms?.dynamax)
) {
return true
}
Expand Down
5 changes: 4 additions & 1 deletion src/services/queries/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,14 +144,15 @@ export class Query {
static stations(filters) {
const { perms } = useMemory.getState().auth
let query = 'GET_ALL_STATIONS'
if (filters.battles && perms.dynamax) {
if (filters.maxBattles && perms.dynamax) {
query += '_BATTLE'
}
return stationIndex[query]
}

/** @param {string} category */
static search(category) {
const { perms } = useMemory.getState().auth
switch (category) {
case 'lures':
case 'raids':
Expand All @@ -162,6 +163,8 @@ export class Query {
return searchIndex[category.toUpperCase()]
case 'webhook':
return searchIndex.POI_WEBHOOK
case 'stations':
return perms.dynamax ? searchIndex.MAX_BATTLES : searchIndex.POI
default:
return searchIndex.POI
}
Expand Down
Loading

0 comments on commit a1cfb57

Please sign in to comment.