Pular para o conteúdo
Skillpedia
Código em geral6,4 mil · #14209

melonjs-performance

O que ela faz

Explica como medir o desempenho de um jogo melonJS e as principais mudanças que o aceleram. É para desenvolvedores de jogos cujo jogo trava ou perde quadros.

Quando usar

  • ✓Quando o jogo de um desenvolvedor perde quadros com muitos objetos na tela.
  • ✓Quando o jogo de um desenvolvedor gagueja porque cria muitos objetos a cada quadro.
  • ✓Quando um desenvolvedor quer medir chamadas de desenho e tempo de quadro antes de otimizar.

Link da skill

https://github.com/melonjs/melonJS/blob/master/packages/melonjs/skills/melonjs-performance/SKILL.md

Copie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.

Como usar

O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.

Mensagem pronta para colar

Use esta skill para me ajudar: https://github.com/melonjs/melonJS/blob/master/packages/melonjs/skills/melonjs-performance/SKILL.md Leia o arquivo SKILL.md desse link e siga as instruções dele na minha tarefa.
Quer que a sua IA encontre skills como esta sozinha?Instale o MCP grátis do Skillpedia: uma linha, e ela pesquisa entre 15.000+ skills antes de cada tarefa.Instalar em 1 minuto →

Exemplo do que pedir para a IA

“Meu jogo melonJS trava quando há muitos inimigos na tela. Como posso acelerá-lo?”

5 skills novas por semana. 1 minuto de leitura.

Como funciona

A skill orienta a IA a adicionar o painel de depuração e ler os números primeiro, depois sugere correções como usar um atlas de texturas, agrupar por modo de mesclagem e reutilizar objetos.

Conteúdo técnico (SKILL.md original)

Texto original do autor, em inglês, direto do GitHub.

Performance

Measure first

Register the debug plugin and read the numbers before changing anything:

import { plugin } from "melonjs";
import { DebugPanelPlugin } from "@melonjs/debug-plugin";

await app.init();
plugin.register(DebugPanelPlugin, "debugPanel");

It reports frame time, draw calls, object counts, and can overlay collision shapes and bounds. Draw calls is usually the number that matters.

Batching: the biggest lever

Both GPU backends batch across textures, not just within one: the quad batcher assigns each source image a texture unit and embeds the unit in the vertex data, so several different images still flush as a single draw. The pool is finite — the WebGL batcher gets renderer.maxTextures units (the maxTextures application setting, "auto" = the device limit capped at 32), the WebGPU batcher eight per segment. Overflow the pool and the batch flushes.

So the goal is not "one image" but "few state changes". What actually ends a batch:

  • Overflowing the texture-unit pool — pack sprites into a TextureAtlas and prefer one large tileset over several small ones, so a screenful of sprites fits inside the pool with room to spare.
  • Changing blendMode — setBlendMode flushes before it touches GL state. Group by blend mode where you can.
  • Switching batcher — interleaving primitives (strokeRect, fillRect, debug shapes) or meshes between sprites flushes the quad batcher and rebinds. Draw all the sprites, then all the primitives.
  • Binding a custom shader — a ShaderEffect on the quad batcher also turns multi-texture batching off for the duration, dropping you back to one texture per draw.

The advanced blend modes are the expensive ones: overlay, difference, hard-light, soft-light, color-dodge, color-burn, darken and lighten cannot be expressed as fixed-function blending, so each such draw is bracketed on its own — capture the destination, redraw offscreen, composite through a shader. Right for accents, wrong for hundreds of objects. normal, additive, multiply, screen and exclusion are plain fixed-function state and cost nothing extra.

Pooling

Anything spawned frequently — bullets, particles, pickups, damage numbers — should be pooled rather than allocated:

import { createPool } from "melonjs";

const bulletPool = createPool((x, y) => {
    const instance = new Bullet(x, y);
    return { instance, reset: (x, y) => instance.onResetEvent(x, y) };
});

const b = bulletPool.get(x, y);   // recycled: reset(x, y)
                                  // fresh:    new Bullet(x, y)
world.removeChild(b);             // returns to bulletPool automatically

The container returns a child to whichever pool built it, so removal is enough; you only call release() yourself for something that was never added to the world.

me.pool is the older, string-keyed version and is deprecated since 18.0.0. pool.register(name, Class, true) / pool.pull(name) still work and print a one-off console notice, but a recycled object is no longer returned on removal, so pooling through it now costs an allocation per spawn. To register a class so a Tiled map can name it, use registerTiledObjectClass — that is a separate registry and is not deprecated.

Two rules that cause subtle bugs when missed:

  • onResetEvent must restore everything the object's lifetime mutates — alpha, tint, scale, animation, velocity. Anything you forget carries into the next use, which looks like a random visual glitch.

  • Pooled objects do not fire onDestroyEvent on removal. Removal always calls onDeactivateEvent, then tries to return the object to the pool that built it; only when nothing owns it does it fall through to destroy(), which is what calls onDestroyEvent. So a successfully recycled object never sees it. Pair event subscriptions with onActivateEvent / onDeactivateEvent instead, or you leak handlers.

  • removeChild is DEFERRED, which breaks a pool you re-lend in the same frame. The removal is queued and runs after the update and draw stack has unwound, so an object you remove and immediately hand out again is torn out from under its new owner when the queue drains: it vanishes, and the frame after that the removal throws Child is not mine. Take it out immediately instead, keeping the instance alive for reuse:

    world.removeChildNow(bullet, true);   // keepalive: do NOT destro
    
Perguntas frequentes

O que devo medir primeiro?

A skill recomenda o painel de depuração, que mostra o tempo de quadro e as chamadas de desenho.

O que é batching?

Batching combina muitos sprites em menos chamadas de desenho, geralmente o maior ganho de velocidade.

Por que mudar o modo de mesclagem deixa tudo mais lento?

A skill diz que mudar o modo de mesclagem encerra um lote, por isso agrupar sprites pelo modo de mesclagem ajuda.

Detalhes

Descrição original do autor

Use this skill when a melonJS game drops frames, allocates heavily, or needs to scale to many objects. Covers object pooling, draw-call batching, atlases, baking with CanvasRenderTarget, instancing, culling and alwaysUpdate, the debug plugin, and where the real costs are. Triggers on: performance, slow, frame rate, fps, lag, pool, pool.register, pool.pull, batching, draw calls, InstancedMesh, culling, alwaysUpdate, inViewport, CanvasRenderTarget, optimise, profiling, debug plugin, memory, render targets, hdr.

repo: melonjs/melonJS

Popularidade

Estrelas no GitHub
6,4 mil
Posição no ranking
#14209
Licença
MIT
Atualizada em
02/11/2026

Essa skill é útil?

0

Entre para votar.

Comentários

  • …

Mais skills deste repositório

Skills parecidas