GithubHelp home page GithubHelp logo

pixijs / tilemap Goto Github PK

View Code? Open in Web Editor NEW
273.0 12.0 54.0 36.13 MB

Rectangular tilemap implementation for PixiJS

Home Page: https://pixijs.io/tilemap/docs/

License: MIT License

TypeScript 100.00%
tilemap webgl canvas

tilemap's Introduction

@pixi/tilemap - PixiJS Tilemap Kit

Automation CI

This package provides a low-level rectangular tilemap implementation, optimized for high performance rendering and a out-of-the-box canvas fallback.

Version Compatiblity

PixiJS PixiJS Tilemap Kit
v4.x v1.x
v5.x v2.x
v6.x v3.x
v7.x v4.x
v8.x v5.x

Installation ๐Ÿ“ฆ

npm install --save @pixi/tilemap

You can also use the browser bundle:

<script src="https://cdn.jsdelivr.net/npm/@pixi/tilemap@latest/dist/pixi-tilemap.js"></script>

Usage

In short, the tilemap you create will render each tile texture at the provided position and dimensions. Generally, a spritesheet is used to load the tileset assets:

import { Assets } from 'pixi.js';
import { CompositeTilemap } from '@pixi/tilemap';

Assets.add('atlas', 'atlas.json');
Assets.load(['atlas']).then(() =>
{
    const tilemap = new CompositeTilemap();

    // Render your first tile at (0, 0)!
    tilemap.tile('grass.png', 0, 0);
});

CompositeTilemap is actually a lazy composite of layered Tilemap instances. A Tilemap has a fixed number of tile textures (the tileset) it can render in one go. Usually, CompositeTilemap abstracts away this limitation in a robust enough manner.

Demos

Settings

import { settings } from '@pixi/tilemap';
Setting Description
TEXTURES_PER_TILEMAP Temporarily switched off
TEXTILE_UNITS Temporarily switched off
use32bitIndex There's also a limitation on 16k tiles per one tilemap. If you want to lift it, please use PixiJS v5.1.0 and following setting settings.use32bitIndex = true;

RPGMaker

Canvas fallback is 5x slower than vanilla rpgmaker. WebGL version is faster and doesnt use extra textures.

RPGMaker Demo

More Tutorials

tilemap's People

Contributors

alan01252 avatar bigtimebuddy avatar blurymind avatar cgamesplay avatar dependabot[bot] avatar exponenta avatar finscn avatar hood avatar ivanpopelyshev avatar megabyteceer avatar pixelpicosean avatar sanjosolutions avatar shukantpal avatar smivan avatar spassvogel avatar st-wook avatar steel97 avatar yunyoujun avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tilemap's Issues

Make water shader

We need some killer features. Make a layer that corresponds to water shader.

Npm module

Hi, great work on this plugin. I do have a question, or a request rather. These days most people don't import javascript via <script> tags anymore, instead it turns out it's much more convenient to import npm packages. I was wondering if we could import pixi-tilemap in a similar manner. Thanks!

Cannot read property 'registerPlugin' of undefined (using webpack)

Hello again,

So I'm trying to import pixi-tilemap in a project built using webpack. The following fails :

import 'pixi.js'; 
// `PIXI` now available in global scope
import 'pixi-tilemap';

When I inspect, the error seems to be thrown by this line. Any idea why this fails ? I'm already using this method for other pixi plugins (like pixi-particles).

Here are my libraries versions from yarn.lock :

pixi-tilemap@^1.2.3:
  version "1.2.3"
  resolved "https://registry.yarnpkg.com/pixi-tilemap/-/pixi-tilemap-1.2.3.tgz#63306cb5c1c847279a249f3e1f064140f26e0470"
  dependencies:
    glslify "^5.0.2"
    typescript "^2.2.2"

pixi.js@^4.5.2:
  version "4.5.2"
  resolved "https://registry.yarnpkg.com/pixi.js/-/pixi.js-4.5.2.tgz#22b63b0c42185ac204e01086aff7ebeb60de0e0c"
  dependencies:
    bit-twiddle "^1.0.2"
    earcut "^2.0.7"
    eventemitter3 "^2.0.0"
    ismobilejs "^0.4.0"
    object-assign "^4.0.1"
    pixi-gl-core "^1.0.3"
    remove-array-items "^1.0.0"
    resource-loader "^2.0.6"

webpack@^2.6.1:
  version "2.6.1"
  resolved "https://registry.yarnpkg.com/webpack/-/webpack-2.6.1.tgz#2e0457f0abb1ac5df3ab106c69c672f236785f07"
  dependencies:
    acorn "^5.0.0"
    acorn-dynamic-import "^2.0.0"
    ajv "^4.7.0"
    ajv-keywords "^1.1.1"
    async "^2.1.2"
    enhanced-resolve "^3.0.0"
    interpret "^1.0.0"
    json-loader "^0.5.4"
    json5 "^0.5.1"
    loader-runner "^2.3.0"
    loader-utils "^0.2.16"
    memory-fs "~0.4.1"
    mkdirp "~0.5.0"
    node-libs-browser "^2.0.0"
    source-map "^0.5.3"
    supports-color "^3.1.0"
    tapable "~0.2.5"
    uglify-js "^2.8.27"
    watchpack "^1.3.1"
    webpack-sources "^0.2.3"
    yargs "^6.0.0"

How to use RPG MV Map

How to use this for RPG MV Map?

RPG MV creates a JSON file including events, bgm, and other data. Is it possible to use RM like a map editor?

What does `TileRenderer.prototype.checkLeaks` do ?

On my device ( iPhone 8 + wechat ) ,
this method (checkLeaks & removeVb) will make the wechat crash .

What does TileRenderer.prototype.checkLeaks do ?
Why remove & destroy the vb & vao every 10 seconds ?

Improper rendering on retina displays

When using a retina display (tested on a MacBook with Chrome), the tilemap example renders even more zoomed out, moves faster, and has small gaps between tiles (visibility of gaps changes as camera moves). lineylines

I add a feature about `addFrame`. Is it useful ?

I make addFrame support texture index , it could provide better performance.

the code :

        addFrame(texture_: PIXI.Texture | String | number, x: number, y: number, animX: number, animY: number) {
            var texture : PIXI.Texture;
            var layer : RectTileLayer = null, ind = 0;
            var children = this.children;

            if (typeof texture_ === "string") {
                texture = PIXI.Texture.fromImage(texture_);
            } else if (typeof texture_ === "number") {
                var childIndex = texture_ / this.texPerChild >> 0;
                ind = texture_ % this.texPerChild;
                layer = children[childIndex] as RectTileLayer;
                texture = layer.textures[ind];
            } else {
                texture = texture_ as PIXI.Texture;

                for (var i = 0; i < children.length; i++) {
                    var child = children[i] as RectTileLayer;
                    var tex = child.textures;
                    for (var j = 0; j < tex.length; j++) {
                        if (tex[j].baseTexture == texture.baseTexture) {
                            layer = child;
                            ind = j;
                            break;
                        }
                    }
                    if (layer) {
                        break;
                    }
                }
            }

            if (!layer) {
                for (i = 0; i < children.length; i++) {
                    var child = children[i] as RectTileLayer;
                    if (child.textures.length < 16) {
                        layer = child;
                        ind = child.textures.length;
                        child.textures.push(texture);
                        break;
                    }
                }
                if (!layer) {
                    children.push(layer = new RectTileLayer(this.zIndex, texture));
                    ind = 0;
                }
            }
            layer.addRect(ind, texture.frame.x, texture.frame.y, x, y, texture.frame.width, texture.frame.height, animX, animY);
            return true;
        };

the example :

        var baseTexture = PIXI.BaseTexture.from(ResourcePool.get('map-tileset'));

        var tileSize = 64;
        var tileTextures = [];
        for (var r = 0; r < 3; r++) {
            for (var c = 0; c < 4; c++) {
                var texture = new PIXI.Texture(baseTexture,
                    new PIXI.Rectangle(c * tileSize, r * tileSize, 64, 64)
                );
                tileTextures.push(texture);
            }
        }
        var groundTiles = new PIXI.tilemap.CompositeRectTileLayer(0, tileTextures, true);

        var indexOfTile = 0;
        for (var r = 0; r < 3; r++) {
            for (var c = 0; c < 4; c++) {
                groundTiles.addFrame(indexOfTile, c * tileSize, r * tileSize);
                indexOfTile++;
            }
        }

In real use case , the index of tiles in tile-set are static.
And in the map.json file , I use index to config the map data, like this:

0,0,0,1,1,2,2,0,0,
1,2,0,0,1,2,3,0,0,

[Bug] When textures.length >= 16 , can't render correctly.

When I create a CompositeRectTileLayer Object like this :

tilemap = new PIXI.tilemap.CompositeRectTileLayer(0, tileTextures, true);

if tileTextures include 16 or more than 16 textures , the map can't be rendered correctly.
The result of rendering is like this :
2017-08-17 8 28 05

the 3 colors are not be included in any tile texture. So strange.

Isometric tiles

Hello there,

not sure if its a dumb question or not, but is it possible to use tilemap to draw a isometric tiles? I have them all in spritesheet/atlas and I draw them manually atm as separate sprites, which is slow.

[QUESTION] Why should I use this plugin ?

Hi, what is the exact use case of this plugin ?
I'm refactoring my TileMap because it takes too much time to render on lowend mobile device.

I'm now studying a solution which will create 20/25 chunks of tiles (each chunk has a different tiles compositon for some diversity) and cache them as bitmap texture to reduce the amount of updateTransforms.

But I'm studying all solutions and I've found this plugin which looks well maintained.

I'm making a isometric 2D game (no Z axis), few tiles, just path, grass, water.

Thnaks for the help

Is there any limit on addFrame count?

I'm rendering map of 400 x 400 grid with size of each grid 16 x 16 pixels.
each grid shares single base texture.
each time player moves, I call addFrame for each grid of area around player.
But after certain point, around 18000 call maybe, addFrame does render nothing.

Is there any limits I'm missing?

Using a RenderTexture crash

I wanted to use a RenderTexture instead and I was getting an error because the source of the base texture is "null".

Specifically it throw an error here.

I was able to get around this with this small modification.

However this fix only works if you use a 2048x2048 RenderTexture. Also not quite sure why it works.

Canvas fallback is too slow

Solution:

  1. ZLayer assigns special ids to all layers, and "subscribes" on their "addXXX" events.
  2. RectTileLayer.renderCanvasTiles(...) method takes tiles list.
  3. RectTileLayer passes all addRect calls to special listener which compares it to previous tilemap.
  4. GraphicsTileLayer overrides drawRect method , does the same.
  5. ZLayer determines which tiles were changed and how (may be they are animated). Or sometimes tile grid is changed, that we need take to account too.

Flipping tiles on an axis?

Tiled allows you to flip tiles along either or both of the x and y axes. Parsing the map file and identifying flipped tiles was trivial, however I'm not seeing any method of rendering the tile on a CompositeRectTileLayer with the transform(s) applied. Is there currently any way to accomplish this?

Issue rendering hover normal

I get some strange bug here , but i don't know where to start for fix this!?
Any ideas are welcome.
normal paralax

If i set normal alpha 0 to a sprite, when hover the BG Clouds (TilingSprite), it render black !
someone would have an idea of what's going on here and why logically this code does not work?

    createBackground() {
        this.clearBackground();
        const dataObj = $objs.BACKGROUND[this._name];
        if(dataObj){
            const C = this.background = $objs.createFrom(dataObj);
            C.child.zOrder = -1;
            C.child.parentGroup = $displayGroup.group[0];
            this.addChildAt(C.child,0);
            this._sceneWidth = C.child.width;
            this._sceneHeight = C.child.height;
            //!extra tilling repeat BG: experimental
            //FIXME: normal see not render correcly hover TilingSprite
            const dataBase  = $loader.DATA2.Tilling1;
            const tilingSprite = new PIXI.extras.TilingSprite( dataBase.textures.cloud1,$app.screen.width,$app.screen.height );
            //tilingSprite.alpha = 0.2;
            tilingSprite.parentGroup = $displayGroup.DiffuseGroup; // BUG, TilingSprite GET BLACK
            $stage.addChildAt(tilingSprite,0);
        }
    };

Remove a frame / tile ?

Is it possible to remove a single frame or tile without clearing / populating all the CompositeRectTileLayer again ? I have a use case where player actions change the tilemap with small but frequent updates.

I've looked in the sources and did not find any method that seems to do that apart from clear().

About `CompositeRectTileLayer.addRect`

        addRect(num: number, u: number, v: number, x: number, y: number, tileWidth: number, tileHeight: number) {
            if (this.children[num] && (this.children[num] as RectTileLayer).textures)
                (this.children[num] as RectTileLayer).addRect(0, u, v, x, y, tileWidth, tileHeight);
        }

I think this method is useless and can't work correctly , because there is always 0 when call RectTileLayer.addRect.

Could I remove this method ?

pixi.js v5 support

should I use this with pixi.js v5? Should it work there?
I'm using it as npm module and after switching to v5 I'm getting error

index.js:41879 Uncaught ReferenceError: PIXI is not defined
    at pixi_tilemap (index.js:41879)
    at Object.101 (index.js:41880)
    at o (index.js:1)
    at index.js:1
    at Object.43.../components (index.js:1846)
    at o (index.js:1)
    at index.js:1
    at Object.33.../../systems (index.js:1101)
    at o (index.js:1)
    at index.js:1

in this line PIXI.CanvasRenderer.registerPlugin('tilemap', CanvasTileRenderer)

Obviously I have imported PIXI in my bundle with import * as PIXI from 'pixi.js' but seems like this library require PIXI to be in global scope...

Another question is should I use TilingSprite instead of this TileMap. What cons and pros here?

Screen Clipping Off?

Hi, I'm using this for some university coursework. I really don't like how the tiles don't render when they are > 50% offscreen. I can't find where this is being done so is there a way to change this to only cull when a tile is 100% offscreen?

Thanks,
Steppers

texture size limitation

is it possible to somehow hack the 1024x1024 texture limitation?
I'm currently using 2048x3040 and the tiles outside 1024x1024 is just ignored.

[Bug] when use `useSquare==true`, the rendering has a bug in Y axis .

When the map scroll in Y (the viewport moves down) ,

the tiles in the top line (in viewport) will disappear too early ,
and the bottom line (in viewport) will disappear too late.


But X axis never with wrong.
When the map scroll in X (the viewport moves right) , everything is OK.

If not use useSquare==true, everything is also OK.

[REQUEST] A new TileRenderer for `textures with same baseTexture`

I read the code of pixi-tilemap.
I found that , current TileRenderer supports textures with different baseTextures.
It will try to draw 4 tileset images( per image size = 1024*1024 ) to one PIXI.RenderTexture (size = 2048*2048).
And there are 4 PIXI.RenderTextures in TileRenderer.
(that's why pixi-tilemap only support the tileset with max size 1024*1024, and per child could include only 4*4 tiles.)

I know the reason and the good part of this way.

But I think a TileRenderer only for textures with same baseTexture is useful too.
And a TileRenderer only for textures with same baseTexture will with good performance and features.

Rendering artifacts in the WebGL rpgmaker demos

Hi, I was looking at the rpgmaker demos and noticed some artifacts. These do not occur in the canvas version:

On mobile safari on iOS, the tiles are not seemless. There's a very thin (it looks like 1 pixel) black line between tiles. Its not always there, but it flickers in and out as the demo scrolls (seems like a rounding error?). This happens in both the retina and normal demos.

On OSX (tested in both Safari and Chrome), the tiles ARE seamless, however the tiles on the edge of the screen don't draw (I can't tell if they only draw when fully visible, or if a certain amount of them is visible). This seems dependent on the speed of the scrolling, as when I manually pan around the map, it sometimes renders correctly and other times does not.
It seems that this happens consistently in the retina demos, and in the zoomin non-retina demo.

docs

are there docs for this library?

Trying to implement tmx parsing for gdevelop - need help on animated tiles

Hi, I am one of the devs on gdevelop and we are currently looking into adding support for tilemaps and specifically for tiled tile support

I understand that this is a "in progress" feature on this project and I was wondering if you have made any progress on it.
I couldn't find any test branches or commits trying to add tmx parsing.

Currently we are trying to evaluate whether to use this library vs another one and so far I have found the following pros and cons:

pros:

  • pixi-tilemap is actively developed
  • designed to be performant
  • battle tested on another game engine (rpg maker mv)

cons:

  • It does not support isometric maps or anything other than top down (do you plan on adding support for other map types?)
  • I have to parse the tmx data myself and turn it into something pixi-tilemap will like (i made some progress on that, but can you share any of your progress if you have some?)
  • The way it handles animated tiles is very tied with the image resource that the tileset is using, leading to a real challenge in parsing them properly

Please correct me if you have anything on these points.

In any ways, I am interested to get some feedback from the devs here on potentially making some progress in parsing tmx data properly to this renderer.
Here is the issue at gdevelop's git
4ian/GDevelop#503

I will also publish my test project, which so far can parse most of the tmx data to pixi-tilemap but only for topdown maps and with animated tiles having issues
objectsRendered

Right now I am struggling with how pixi-tilemap requires animated tiles to always have their frame laid one next to each other in the correct order, where as tmx data that comes from tiled lets the developer arrange frames in any order and take them from any position on the atlas. This leads to problems like this:
neckPainTiles

with an atlas like
painAtlas

And this is what pixi-tilemap is expecting to get
https://github.com/Alan01252/pixi-tilemap-tutorial/blob/master/imgs/imgBuildings.png

Do you have any ideas on ways to get around that?
I am getting really close to having the entire tmx data properly parsed to pixi-tilemap with this being the last stumbling block

One idea I had is to make my parser create another tilemap image resource for animated ones, but that could potentially lead to zordering problems

Isometric view

I'm trying to figure out if this plugin would be good to use for isometric projects. I'm guessing that in principle it's possible to use, we just have to calculate the position of each tile properly.

But then how to deal with z-axis occlusion?

Make Tiled demo

Choose some Tiled maps and try to show them with that renderer.

[QUESTION] Catch tile event

Hi ! Does anyone have a solution for catching tile events? I did not find anything that allows me to catch a click on a tile for example. Thx !

[REQUEST]Let pixi-tilemap supports pixi-projection

If pixi-tilemap supports pixi-projection , we could do something like these :

2017-10-07 4 30 28

2017-10-07 4 30 16

2017-10-07 4 29 53

I know the game in the images is created by real 3D Engine , but if we just need projection , I think pixi.js could do it.

tile rotations

In the demo atlas.json I can see a rotated property for each frame. However I can't find any more mentions of rotated in this repo. So my questions is - is it used somehow? How can I have rotated tile?
Also where I can found full description of format used in atlas.json?

Where is atlas_image taken from

Hello there,

I am trying to understand and apply what you are showing in the demo in my code and I don't understand what you're trying to access. This is the following line I am struggling with.

var tilemap = new PIXI.tilemap.CompositeRectTileLayer(0, [resources['atlas_image'].texture], true);

In particular where the atlas_image is being set-up or how it is being called. I can see in the repo that atlas.json is a TexturePacker json file which you load right at the very beginning with loader.add('atlas', 'basic/atlas.json'); but I cannot see the connection between the two.

Maybe once I understand this I might be able to help to improve the documentation to help other people understand it too?

Glitches with boundCountPerBuffer: 1

When using boundCountPerBuffer: 1 (using maxTextures: 1 can help the reproduction be 100%) and the tilemap textures aren't the same size, glitches start to occur. I was able to track down the issue and fix it by adding this line at the end of TileRenderer.bindTexturesWithoutRT:

renderer.shader.bind(shader, false);

The issue seems to be related to how CompositeTileRectLayer renders TileRectLayer instances, but doesn't compensate for changed uSamplerSize between the textures used in the different TileRectLayer children.

Can this issue be confirmed and the fix (or an alternate, better fix) be integrated into the codebase?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.