phaserjs / phaser-ce

Phaser CE is a fun, free and fast 2D game framework for making HTML5 games for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
http://phaser.io
MIT License
1.34k stars 492 forks source link

RenderTexture can crash if games are created and destroyed in quick succession. #729

Closed timiyay closed 1 year ago

timiyay commented 1 year ago

This Issue is about

let game = newGame() game.destroy() game = newGame()


  * What should happen: the 2nd instantiation of the game should not crash, and should be able to create a `RenderTexture`
  * What happens instead: the code crashes
  * If there's an error:
    * What's the error message? `Uncaught TypeError: Cannot read properties of null (reading 'type')`
    * What's the error trace (expand the error message)?
![crash](https://user-images.githubusercontent.com/1470250/191889268-d1c892e6-1ef5-49a6-ab79-2b6f1876005a.png)

Crash occurs at https://github.com/photonstorm/phaser-ce/blob/1af938320a72ebc0cfbd9cc9101fcf1bf17d9808/src/gameobjects/RenderTexture.js#L86

#### Background

We're using a NextJS/React client to run some Phaser games. We're using [React's effects](https://reactjs.org/docs/hooks-effect.html) inside functional components, since the rendering of a Phaser game is considered a side effect outside of React's control. In development, React has a Strict Mode that will cause these effects to double-render these functional components, in order to help devs identify unintentional side effects in their code

This means our Phaser games are being created, very quickly destroyed, then created again. Some of our games use `RenderTexture`, which isn't resilient to these quick create/destroy/create cycles.

The issue appears to stem from `RenderTexture`'s reliance on global state; specifically, `PIXI.defaultRenderer`.

https://github.com/photonstorm/phaser-ce/blob/1af938320a72ebc0cfbd9cc9101fcf1bf17d9808/src/core/Game.js#L1279

I think what's happening is `Phaser.Game#destroy` will set `PIXI.defaultRenderer` to `null`, which causes a race condition where the 2nd game's `renderer` may or may not be `null`.

I am happy to contribute a PR, once folks have a chance to triage and comment on the issue.
samme commented 1 year ago

I think I have a branch for this.

samme commented 1 year ago

Fixed in https://github.com/photonstorm/phaser-ce/commit/dde4ef24a182ecd7326cfa4607ced8dc5c0389e9

timiyay commented 1 year ago

Thanks! 🙇

timiyay commented 1 year ago

Hi @samme thanks again for the fix for this issue.

Do you have any plans to release it in the near future? It's still affecting us so we may need to consider a fork, or depending directly on this Github repo, in the meantime.

samme commented 1 year ago

I'll make a release soon.

timiyay commented 1 year ago

Thanks @samme 🙇