初始化

This commit is contained in:
SmallMain
2022-06-25 00:23:03 +08:00
commit ef0589e8e5
2264 changed files with 617829 additions and 0 deletions

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,920 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
require('./CCTMXXMLParser');
require('./CCTiledMapAsset');
require('./CCTiledLayer');
require('./CCTiledTile');
require('./CCTiledObjectGroup');
/**
* !#en The orientation of tiled map.
* !#zh Tiled Map 地图方向。
* @enum TiledMap.Orientation
* @static
*/
let Orientation = cc.Enum({
/**
* !#en Orthogonal orientation.
* !#zh 直角鸟瞰地图90°地图
* @property ORTHO
* @type {Number}
* @static
*/
ORTHO: 0,
/**
* !#en Hexagonal orientation.
* !#zh 六边形地图
* @property HEX
* @type {Number}
* @static
*/
HEX: 1,
/**
* Isometric orientation.
* 等距斜视地图斜45°地图
* @property ISO
* @type {Number}
* @static
*/
ISO: 2
});
/**
* The property type of tiled map.
* @enum TiledMap.Property
* @static
*/
let Property = cc.Enum({
/**
* @property NONE
* @type {Number}
* @static
*/
NONE: 0,
/**
* @property MAP
* @type {Number}
* @static
*/
MAP: 1,
/**
* @property LAYER
* @type {Number}
* @static
*/
LAYER: 2,
/**
* @property OBJECTGROUP
* @type {Number}
* @static
*/
OBJECTGROUP: 3,
/**
* @property OBJECT
* @type {Number}
* @static
*/
OBJECT: 4,
/**
* @property TILE
* @type {Number}
* @static
*/
TILE: 5
});
/**
* The tile flags of tiled map.
* @enum TiledMap.TileFlag
* @static
*/
let TileFlag = cc.Enum({
/**
* @property HORIZONTAL
* @type {Number}
* @static
*/
HORIZONTAL: 0x80000000,
/**
* @property VERTICAL
* @type {Number}
* @static
*/
VERTICAL: 0x40000000,
/**
* @property DIAGONAL
* @type {Number}
* @static
*/
DIAGONAL: 0x20000000,
/**
* @property FLIPPED_ALL
* @type {Number}
* @static
*/
FLIPPED_ALL: (0x80000000 | 0x40000000 | 0x20000000 | 0x10000000) >>> 0,
/**
* @property FLIPPED_MASK
* @type {Number}
* @static
*/
FLIPPED_MASK: (~(0x80000000 | 0x40000000 | 0x20000000 | 0x10000000)) >>> 0
});
/**
* !#en The stagger axis of Hex tiled map.
* !#zh 六边形地图的 stagger axis 值
* @enum TiledMap.StaggerAxis
* @static
*/
let StaggerAxis = cc.Enum({
/**
* @property STAGGERAXIS_X
* @type {Number}
* @static
*/
STAGGERAXIS_X : 0,
/**
* @property STAGGERAXIS_Y
* @type {Number}
* @static
*/
STAGGERAXIS_Y : 1
});
/**
* !#en The stagger index of Hex tiled map.
* !#zh 六边形地图的 stagger index 值
* @enum TiledMap.RenderOrder
* @static
*/
let StaggerIndex = cc.Enum({
/**
* @property STAGGERINDEX_ODD
* @type {Number}
* @static
*/
STAGGERINDEX_ODD : 0,
/**
* @property STAGGERINDEX_EVEN
* @type {Number}
* @static
*/
STAGGERINDEX_EVEN : 1
});
/**
* !#en The render order of tiled map.
* !#zh 地图的渲染顺序
* @enum TiledMap.RenderOrder
* @static
*/
let RenderOrder = cc.Enum({
/**
* @property RightDown
* @type {Number}
* @static
*/
RightDown : 0,
/**
* @property RightUp
* @type {Number}
* @static
*/
RightUp : 1,
/**
* @property LeftDown
* @type {Number}
* @static
*/
LeftDown: 2,
/**
* @property LeftUp
* @type {Number}
* @static
*/
LeftUp: 3,
});
/**
* !#en TiledMap Object Type
* !#zh 地图物体类型
* @enum TiledMap.TMXObjectType
* @static
*/
let TMXObjectType = cc.Enum({
/**
* @property RECT
* @type {Number}
* @static
*/
RECT : 0,
/**
* @property ELLIPSE
* @type {Number}
* @static
*/
ELLIPSE : 1,
/**
* @property POLYGON
* @type {Number}
* @static
*/
POLYGON : 2,
/**
* @property POLYLINE
* @type {Number}
* @static
*/
POLYLINE : 3,
/**
* @property IMAGE
* @type {Number}
* @static
*/
IMAGE : 4,
/**
* @property TEXT
* @type {Number}
* @static
*/
TEXT: 5,
});
/**
* !#en Renders a TMX Tile Map in the scene.
* !#zh 在场景中渲染一个 tmx 格式的 Tile Map。
* @class TiledMap
* @extends Component
*/
let TiledMap = cc.Class({
name: 'cc.TiledMap',
extends: cc.Component,
editor: CC_EDITOR && {
executeInEditMode: true,
menu: 'i18n:MAIN_MENU.component.renderers/TiledMap',
},
ctor () {
// store all layer gid corresponding texture info, index is gid, format likes '[gid0]=tex-info,[gid1]=tex-info, ...'
this._texGrids = [];
// store all tileset texture, index is tileset index, format likes '[0]=texture0, [1]=texture1, ...'
this._textures = [];
this._tilesets = [];
this._animations = [];
this._imageLayers = [];
this._layers = [];
this._groups = [];
this._images = [];
this._properties = [];
this._tileProperties = [];
this._mapSize = cc.size(0, 0);
this._tileSize = cc.size(0, 0);
},
statics: {
Orientation: Orientation,
Property: Property,
TileFlag: TileFlag,
StaggerAxis: StaggerAxis,
StaggerIndex: StaggerIndex,
TMXObjectType: TMXObjectType,
RenderOrder: RenderOrder
},
properties: {
_tmxFile: {
default: null,
type: cc.TiledMapAsset
},
/**
* !#en The TiledMap Asset.
* !#zh TiledMap 资源。
* @property {TiledMapAsset} tmxAsset
* @default ""
*/
tmxAsset : {
get () {
return this._tmxFile;
},
set (value, force) {
if (this._tmxFile !== value || (CC_EDITOR && force)) {
this._tmxFile = value;
this._applyFile();
}
},
type: cc.TiledMapAsset
}
},
/**
* !#en Gets the map size.
* !#zh 获取地图大小。
* @method getMapSize
* @return {Size}
* @example
* let mapSize = tiledMap.getMapSize();
* cc.log("Map Size: " + mapSize);
*/
getMapSize () {
return this._mapSize;
},
/**
* !#en Gets the tile size.
* !#zh 获取地图背景中 tile 元素的大小。
* @method getTileSize
* @return {Size}
* @example
* let tileSize = tiledMap.getTileSize();
* cc.log("Tile Size: " + tileSize);
*/
getTileSize () {
return this._tileSize;
},
/**
* !#en map orientation.
* !#zh 获取地图方向。
* @method getMapOrientation
* @return {Number}
* @example
* let mapOrientation = tiledMap.getMapOrientation();
* cc.log("Map Orientation: " + mapOrientation);
*/
getMapOrientation () {
return this._mapOrientation;
},
/**
* !#en object groups.
* !#zh 获取所有的对象层。
* @method getObjectGroups
* @return {TiledObjectGroup[]}
* @example
* let objGroups = titledMap.getObjectGroups();
* for (let i = 0; i < objGroups.length; ++i) {
* cc.log("obj: " + objGroups[i]);
* }
*/
getObjectGroups () {
return this._groups;
},
/**
* !#en Return the TMXObjectGroup for the specific group.
* !#zh 获取指定的 TMXObjectGroup。
* @method getObjectGroup
* @param {String} groupName
* @return {TiledObjectGroup}
* @example
* let group = titledMap.getObjectGroup("Players");
* cc.log("ObjectGroup: " + group);
*/
getObjectGroup (groupName) {
let groups = this._groups;
for (let i = 0, l = groups.length; i < l; i++) {
let group = groups[i];
if (group && group.getGroupName() === groupName) {
return group;
}
}
return null;
},
/**
* !#en enable or disable culling
* !#zh 开启或关闭裁剪。
* @method enableCulling
* @param value
*/
enableCulling (value) {
let layers = this._layers;
for (let i = 0; i < layers.length; ++i) {
layers[i].enableCulling(value);
}
},
/**
* !#en Gets the map properties.
* !#zh 获取地图的属性。
* @method getProperties
* @return {Object[]}
* @example
* let properties = titledMap.getProperties();
* for (let i = 0; i < properties.length; ++i) {
* cc.log("Properties: " + properties[i]);
* }
*/
getProperties () {
return this._properties;
},
/**
* !#en Return All layers array.
* !#zh 返回包含所有 layer 的数组。
* @method getLayers
* @returns {TiledLayer[]}
* @example
* let layers = titledMap.getLayers();
* for (let i = 0; i < layers.length; ++i) {
* cc.log("Layers: " + layers[i]);
* }
*/
getLayers () {
return this._layers;
},
/**
* !#en return the cc.TiledLayer for the specific layer.
* !#zh 获取指定名称的 layer。
* @method getLayer
* @param {String} layerName
* @return {TiledLayer}
* @example
* let layer = titledMap.getLayer("Player");
* cc.log(layer);
*/
getLayer (layerName) {
let layers = this._layers;
for (let i = 0, l = layers.length; i < l; i++) {
let layer = layers[i];
if (layer && layer.getLayerName() === layerName) {
return layer;
}
}
return null;
},
_changeLayer (layerName, replaceLayer) {
let layers = this._layers;
for (let i = 0, l = layers.length; i < l; i++) {
let layer = layers[i];
if (layer && layer.getLayerName() === layerName) {
layers[i] = replaceLayer;
return;
}
}
},
/**
* !#en Return the value for the specific property name.
* !#zh 通过属性名称,获取指定的属性。
* @method getProperty
* @param {String} propertyName
* @return {String}
* @example
* let property = titledMap.getProperty("info");
* cc.log("Property: " + property);
*/
getProperty (propertyName) {
return this._properties[propertyName.toString()];
},
/**
* !#en Return properties dictionary for tile GID.
* !#zh 通过 GID ,获取指定的属性。
* @method getPropertiesForGID
* @param {Number} GID
* @return {Object}
* @example
* let properties = titledMap.getPropertiesForGID(GID);
* cc.log("Properties: " + properties);
*/
getPropertiesForGID (GID) {
return this._tileProperties[GID];
},
__preload () {
if (this._tmxFile) {
// refresh layer entities
this._applyFile();
}
},
onEnable () {
this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this._syncAnchorPoint, this);
},
onDisable () {
this.node.off(cc.Node.EventType.ANCHOR_CHANGED, this._syncAnchorPoint, this);
},
_applyFile () {
let file = this._tmxFile;
if (file) {
let texValues = file.textures;
let texKeys = file.textureNames;
let texSizes = file.textureSizes;
let textures = {};
let textureSizes = {};
for (let i = 0; i < texValues.length; ++i) {
let texName = texKeys[i];
textures[texName] = texValues[i];
textureSizes[texName] = texSizes[i];
}
let imageLayerTextures = {};
texValues = file.imageLayerTextures;
texKeys = file.imageLayerTextureNames;
for (let i = 0; i < texValues.length; ++i) {
imageLayerTextures[texKeys[i]] = texValues[i];
}
let tsxFileNames = file.tsxFileNames;
let tsxFiles = file.tsxFiles;
let tsxMap = {};
for (let i = 0; i < tsxFileNames.length; ++i) {
if (tsxFileNames[i].length > 0) {
tsxMap[tsxFileNames[i]] = tsxFiles[i].text;
}
}
let mapInfo = new cc.TMXMapInfo(file.tmxXmlStr, tsxMap, textures, textureSizes, imageLayerTextures);
let tilesets = mapInfo.getTilesets();
if(!tilesets || tilesets.length === 0)
cc.logID(7241);
this._buildWithMapInfo(mapInfo);
}
else {
this._releaseMapInfo();
}
},
_releaseMapInfo () {
// remove the layers & object groups added before
let layers = this._layers;
for (let i = 0, l = layers.length; i < l; i++) {
layers[i].node.removeFromParent(true);
layers[i].node.destroy();
}
layers.length = 0;
let groups = this._groups;
for (let i = 0, l = groups.length; i < l; i++) {
groups[i].node.removeFromParent(true);
groups[i].node.destroy();
}
groups.length = 0;
let images = this._images;
for (let i = 0, l = images.length; i < l; i++) {
images[i].removeFromParent(true);
images[i].destroy();
}
images.length = 0;
},
_syncAnchorPoint () {
let anchor = this.node.getAnchorPoint();
let leftTopX = this.node.width * anchor.x;
let leftTopY = this.node.height * (1 - anchor.y);
let i, l;
for (i = 0, l = this._layers.length; i < l; i++) {
let layerInfo = this._layers[i];
let layerNode = layerInfo.node;
// Tiled layer sync anchor to map because it's old behavior,
// do not change the behavior avoid influence user's existed logic.
layerNode.setAnchorPoint(anchor);
}
for (i = 0, l = this._groups.length; i < l; i++) {
let groupInfo = this._groups[i];
let groupNode = groupInfo.node;
// Group layer not sync anchor to map because it's old behavior,
// do not change the behavior avoid influence user's existing logic.
groupNode.anchorX = 0.5;
groupNode.anchorY = 0.5;
groupNode.x = groupInfo._offset.x - leftTopX + groupNode.width * groupNode.anchorX;
groupNode.y = groupInfo._offset.y + leftTopY - groupNode.height * groupNode.anchorY;
}
for (i = 0, l = this._images.length; i < l; i++) {
let image = this._images[i];
image.anchorX = 0.5;
image.anchorY = 0.5;
image.x = image._offset.x - leftTopX + image.width * image.anchorX;
image.y = image._offset.y + leftTopY - image.height * image.anchorY;
}
},
_fillAniGrids (texGrids, animations) {
for (let i in animations) {
let animation = animations[i];
if (!animation) continue;
let frames = animation.frames;
for (let j = 0; j < frames.length; j++) {
let frame = frames[j];
frame.grid = texGrids[frame.tileid];
}
}
},
_buildLayerAndGroup () {
let tilesets = this._tilesets;
let texGrids = this._texGrids;
let animations = this._animations;
texGrids.length = 0;
for (let i = 0, l = tilesets.length; i < l; ++i) {
let tilesetInfo = tilesets[i];
if (!tilesetInfo) continue;
cc.TiledMap.fillTextureGrids(tilesetInfo, texGrids, i);
}
this._fillAniGrids(texGrids, animations);
let layers = this._layers;
let groups = this._groups;
let images = this._images;
let oldNodeNames = {};
for (let i = 0, n = layers.length; i < n; i++) {
oldNodeNames[layers[i].node._name] = true;
}
for (let i = 0, n = groups.length; i < n; i++) {
oldNodeNames[groups[i].node._name] = true;
}
for (let i = 0, n = images.length; i < n; i++) {
oldNodeNames[images[i]._name] = true;
}
layers = this._layers = [];
groups = this._groups = [];
images = this._images = [];
let mapInfo = this._mapInfo;
let node = this.node;
let layerInfos = mapInfo.getAllChildren();
let textures = this._textures;
let maxWidth = 0;
let maxHeight = 0;
if (layerInfos && layerInfos.length > 0) {
for (let i = 0, len = layerInfos.length; i < len; i++) {
let layerInfo = layerInfos[i];
let name = layerInfo.name;
let child = this.node.getChildByName(name);
oldNodeNames[name] = false;
if (!child) {
child = new cc.Node();
child.name = name;
node.addChild(child);
}
child.setSiblingIndex(i);
child.active = layerInfo.visible;
if (layerInfo instanceof cc.TMXLayerInfo) {
let layer = child.getComponent(cc.TiledLayer);
if (!layer) {
layer = child.addComponent(cc.TiledLayer);
}
layer._init(layerInfo, mapInfo, tilesets, textures, texGrids);
// tell the layerinfo to release the ownership of the tiles map.
layerInfo.ownTiles = false;
layers.push(layer);
}
else if (layerInfo instanceof cc.TMXObjectGroupInfo) {
let group = child.getComponent(cc.TiledObjectGroup);
if (!group) {
group = child.addComponent(cc.TiledObjectGroup);
}
group._init(layerInfo, mapInfo, texGrids);
groups.push(group);
}
else if (layerInfo instanceof cc.TMXImageLayerInfo) {
let texture = layerInfo.sourceImage;
child.opacity = layerInfo.opacity;
child.layerInfo = layerInfo;
child._offset = cc.v2(layerInfo.offset.x, -layerInfo.offset.y);
let image = child.getComponent(cc.Sprite);
if (!image) {
image = child.addComponent(cc.Sprite);
}
let spf = image.spriteFrame || new cc.SpriteFrame();
spf.setTexture(texture);
image.spriteFrame = spf;
child.width = texture.width;
child.height = texture.height;
images.push(child);
}
maxWidth = Math.max(maxWidth, child.width);
maxHeight = Math.max(maxHeight, child.height);
}
}
let children = node.children;
for (let i = 0, n = children.length; i < n; i++) {
let c = children[i];
if (oldNodeNames[c._name]) {
c.destroy();
}
}
this.node.width = maxWidth;
this.node.height = maxHeight;
this._syncAnchorPoint();
},
_buildWithMapInfo (mapInfo) {
this._mapInfo = mapInfo;
this._mapSize = mapInfo.getMapSize();
this._tileSize = mapInfo.getTileSize();
this._mapOrientation = mapInfo.orientation;
this._properties = mapInfo.properties;
this._tileProperties = mapInfo.getTileProperties();
this._imageLayers = mapInfo.getImageLayers();
this._animations = mapInfo.getTileAnimations();
this._tilesets = mapInfo.getTilesets();
let tilesets = this._tilesets;
this._textures.length = 0;
let totalTextures = [];
for (let i = 0, l = tilesets.length; i < l; ++i) {
let tilesetInfo = tilesets[i];
if (!tilesetInfo || !tilesetInfo.sourceImage) continue;
this._textures[i] = tilesetInfo.sourceImage;
totalTextures.push(tilesetInfo.sourceImage);
}
for (let i = 0; i < this._imageLayers.length; i++) {
let imageLayer = this._imageLayers[i];
if (!imageLayer || !imageLayer.sourceImage) continue;
totalTextures.push(imageLayer.sourceImage);
}
cc.TiledMap.loadAllTextures (totalTextures, function () {
this._buildLayerAndGroup();
}.bind(this));
},
update (dt) {
let animations = this._animations;
let texGrids = this._texGrids;
for (let aniGID in animations) {
let animation = animations[aniGID];
let frames = animation.frames;
let frame = frames[animation.frameIdx];
animation.dt += dt;
if (frame.duration < animation.dt) {
animation.dt = 0;
animation.frameIdx++;
if (animation.frameIdx >= frames.length) {
animation.frameIdx = 0;
}
frame = frames[animation.frameIdx];
}
texGrids[aniGID] = frame.grid;
}
},
});
cc.TiledMap = module.exports = TiledMap;
cc.TiledMap.loadAllTextures = function (textures, loadedCallback) {
let totalNum = textures.length;
if (totalNum === 0) {
loadedCallback();
return;
}
let curNum = 0;
let itemCallback = function () {
curNum ++;
if (curNum >= totalNum) {
loadedCallback();
}
};
for (let i = 0; i < totalNum; i++) {
let tex = textures[i];
if (!tex.loaded) {
tex.once('load', function () {
itemCallback();
});
} else {
itemCallback();
}
}
};
cc.TiledMap.fillTextureGrids = function (tileset, texGrids, texId) {
let tex = tileset.sourceImage;
if (!tileset.imageSize.width || !tileset.imageSize.height) {
tileset.imageSize.width = tex.width;
tileset.imageSize.height = tex.height;
}
let tw = tileset._tileSize.width,
th = tileset._tileSize.height,
imageW = tex.width,
imageH = tex.height,
spacing = tileset.spacing,
margin = tileset.margin,
cols = Math.floor((imageW - margin*2 + spacing) / (tw + spacing)),
rows = Math.floor((imageH - margin*2 + spacing) / (th + spacing)),
count = rows * cols,
gid = tileset.firstGid,
grid = null,
override = texGrids[gid] ? true : false,
texelCorrect = cc.macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL_TMX ? 0.5 : 0;
// Tiledmap may not be partitioned into blocks, resulting in a count value of 0
if (count <= 0) {
count = 1;
}
let maxGid = tileset.firstGid + count;
for (; gid < maxGid; ++gid) {
// Avoid overlapping
if (override && !texGrids[gid]) {
override = false;
}
if (!override && texGrids[gid]) {
break;
}
grid = {
// record texture id
texId: texId,
// record belong to which tileset
tileset: tileset,
x: 0, y: 0, width: tw, height: th,
t: 0, l: 0, r: 0, b: 0,
gid: gid,
};
tileset.rectForGID(gid, grid);
grid.x += texelCorrect;
grid.y += texelCorrect;
grid.width -= texelCorrect*2;
grid.height -= texelCorrect*2;
grid.t = (grid.y) / imageH;
grid.l = (grid.x) / imageW;
grid.r = (grid.x + grid.width) / imageW;
grid.b = (grid.y + grid.height) / imageH;
texGrids[gid] = grid;
}
};
cc.js.obsolete(cc.TiledMap.prototype, 'cc.TiledMap.tmxFile', 'tmxAsset', true);
cc.js.get(cc.TiledMap.prototype, 'mapLoaded', function () {
cc.errorID(7203);
return [];
}, false);

View File

@@ -0,0 +1,92 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* Class for tiled map asset handling.
* @class TiledMapAsset
* @extends Asset
*
*/
let TiledMapAsset = cc.Class({
name: 'cc.TiledMapAsset',
extends: cc.Asset,
properties: {
tmxXmlStr: '',
/**
* @property {Texture2D[]} textures
*/
textures: {
default: [],
type: [cc.Texture2D]
},
/**
* @property {String[]} textureNames
*/
textureNames: [cc.String],
/**
* @property {Size[]} textureSizes
*/
textureSizes: {
default: [],
type: [cc.Size]
},
/**
* @property {Texture2D[]} imageLayerTextures
*/
imageLayerTextures: {
default: [],
type: [cc.Texture2D]
},
/**
* @property {String[]} imageLayerTextureNames
*/
imageLayerTextureNames: [cc.String],
tsxFiles: [cc.TextAsset],
tsxFileNames: [cc.String],
},
statics: {
preventDeferredLoadDependents: true
},
createNode: CC_EDITOR && function (callback) {
let node = new cc.Node(this.name);
let tiledMap = node.addComponent(cc.TiledMap);
tiledMap.tmxAsset = this;
return callback(null, node);
}
});
cc.TiledMapAsset = TiledMapAsset;
module.exports = TiledMapAsset;

View File

@@ -0,0 +1,66 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
import InputAssembler from '../renderer/core/input-assembler';
let TiledMapRenderDataList = cc.Class({
name: 'cc.TiledMapRenderDataList',
ctor () {
this._dataList = [];
this._offset = 0;
},
_pushRenderData () {
let renderData = {};
renderData.ia = new InputAssembler();
renderData.nodesRenderList = [];
this._dataList.push(renderData);
},
popRenderData (buffer) {
if (this._offset >= this._dataList.length) {
this._pushRenderData();
}
let renderData = this._dataList[this._offset];
renderData.nodesRenderList.length = 0;
let ia = renderData.ia;
ia._vertexBuffer = buffer._vb;
ia._indexBuffer = buffer._ib;
ia._start = buffer.indiceOffset;
ia._count = 0;
this._offset++;
return renderData;
},
pushNodesList (renderData, nodesList) {
renderData.nodesRenderList.push(nodesList);
},
reset () {
this._offset = 0;
}
});
cc.TiledMapRenderDataList = module.exports = TiledMapRenderDataList;

View File

@@ -0,0 +1,304 @@
/****************************************************************************
Copyright (c) 2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* !#en Renders the TMX object group.
* !#zh 渲染 tmx object group。
* @class TiledObjectGroup
* @extends Component
*/
let TiledObjectGroup = cc.Class({
name: 'cc.TiledObjectGroup',
// Inherits from the abstract class directly,
// because TiledLayer not create or maintains the sgNode by itself.
extends: cc.Component,
/**
* !#en Offset position of child objects.
* !#zh 获取子对象的偏移位置。
* @method getPositionOffset
* @return {Vec2}
* @example
* let offset = tMXObjectGroup.getPositionOffset();
*/
getPositionOffset () {
return this._positionOffset;
},
/**
* !#en List of properties stored in a dictionary.
* !#zh 以映射的形式获取属性列表。
* @method getProperties
* @return {Object}
* @example
* let offset = tMXObjectGroup.getProperties();
*/
getProperties () {
return this._properties;
},
/**
* !#en Gets the Group name.
* !#zh 获取组名称。
* @method getGroupName
* @return {String}
* @example
* let groupName = tMXObjectGroup.getGroupName;
*/
getGroupName () {
return this._groupName;
},
/**
* Return the value for the specific property name
* @param {String} propertyName
* @return {Object}
*/
getProperty (propertyName) {
return this._properties[propertyName.toString()];
},
/**
* !#en
* Return the object for the specific object name. <br />
* It will return the 1st object found on the array for the given name.
* !#zh 获取指定的对象。
* @method getObject
* @param {String} objectName
* @return {Object|Null}
* @example
* let object = tMXObjectGroup.getObject("Group");
*/
getObject (objectName) {
for (let i = 0, len = this._objects.length; i < len; i++) {
let obj = this._objects[i];
if (obj && obj.name === objectName) {
return obj;
}
}
// object not found
return null;
},
/**
* !#en Gets the objects.
* !#zh 获取对象数组。
* @method getObjects
* @return {Array}
* @example
* let objects = tMXObjectGroup.getObjects();
*/
getObjects () {
return this._objects;
},
_init (groupInfo, mapInfo, texGrids) {
const TiledMap = cc.TiledMap;
const TMXObjectType = TiledMap.TMXObjectType;
const Orientation = TiledMap.Orientation;
const StaggerAxis = TiledMap.StaggerAxis;
const TileFlag = TiledMap.TileFlag;
const FLIPPED_MASK = TileFlag.FLIPPED_MASK;
const FLAG_HORIZONTAL = TileFlag.HORIZONTAL;
const FLAG_VERTICAL = TileFlag.VERTICAL;
this._groupName = groupInfo.name;
this._positionOffset = groupInfo.offset;
this._mapInfo = mapInfo;
this._properties = groupInfo.getProperties();
this._offset = cc.v2(groupInfo.offset.x, -groupInfo.offset.y);
this._opacity = groupInfo._opacity;
let mapSize = mapInfo._mapSize;
let tileSize = mapInfo._tileSize;
let width = 0, height = 0;
if (mapInfo.orientation === Orientation.HEX) {
if (mapInfo.getStaggerAxis() === StaggerAxis.STAGGERAXIS_X) {
height = tileSize.height * (mapSize.height + 0.5);
width = (tileSize.width + mapInfo.getHexSideLength()) * Math.floor(mapSize.width / 2) + tileSize.width * (mapSize.width % 2);
} else {
width = tileSize.width * (mapSize.width + 0.5);
height = (tileSize.height + mapInfo.getHexSideLength()) * Math.floor(mapSize.height / 2) + tileSize.height * (mapSize.height % 2);
}
} else if (mapInfo.orientation === Orientation.ISO) {
let wh = mapSize.width + mapSize.height;
width = tileSize.width * 0.5 * wh;
height = tileSize.height * 0.5 * wh;
} else {
width = mapSize.width * tileSize.width;
height = mapSize.height * tileSize.height;
}
this.node.setContentSize(width, height);
let leftTopX = width * this.node.anchorX;
let leftTopY = height * (1 - this.node.anchorY);
let objects = groupInfo._objects;
let aliveNodes = {};
for (let i = 0, l = objects.length; i < l; i++) {
let object = objects[i];
let objType = object.type;
object.offset = cc.v2(object.x, object.y);
let points = object.points || object.polylinePoints;
if (points) {
for (let pi = 0; pi < points.length; pi++) {
points[pi].y *= -1;
}
}
if (Orientation.ISO !== mapInfo.orientation) {
object.y = height - object.y;
} else {
let posIdxX = object.x / tileSize.height;
let posIdxY = object.y / tileSize.height;
object.x = tileSize.width * 0.5 * (mapSize.height + posIdxX - posIdxY);
object.y = tileSize.height * 0.5 * (mapSize.width + mapSize.height - posIdxX - posIdxY);
}
if (objType === TMXObjectType.TEXT) {
let textName = "text" + object.id;
aliveNodes[textName] = true;
let textNode = this.node.getChildByName(textName);
if (!textNode) {
textNode = new cc.Node();
}
textNode.active = object.visible;
textNode.anchorX = 0;
textNode.anchorY = 1;
textNode.angle = -object.rotation;
textNode.x = object.x - leftTopX;
textNode.y = object.y - leftTopY;
textNode.name = textName;
textNode.parent = this.node;
textNode.color = object.color;
textNode.opacity = this._opacity;
textNode.setSiblingIndex(i);
let label = textNode.getComponent(cc.Label);
if (!label) {
label = textNode.addComponent(cc.Label);
}
label.overflow = cc.Label.Overflow.SHRINK;
label.lineHeight = object.height;
label.string = object.text;
label.horizontalAlign = object.halign;
label.verticalAlign = object.valign;
label.fontSize = object.pixelsize;
textNode.width = object.width;
textNode.height = object.height;
}
if (objType === TMXObjectType.IMAGE) {
let gid = object.gid;
let grid = texGrids[(gid & FLIPPED_MASK) >>> 0];
if (!grid) continue;
let tileset = grid.tileset;
let imgName = "img" + object.id;
aliveNodes[imgName] = true;
let imgNode = this.node.getChildByName(imgName);
let imgWidth = object.width || grid.width;
let imgHeight = object.height || grid.height;
let tileOffsetX = tileset.tileOffset.x;
let tileOffsetY = tileset.tileOffset.y;
// Delete image nodes implemented as private nodes
// Use cc.Node to implement node-level requirements
if (imgNode instanceof cc.PrivateNode) {
imgNode.removeFromParent();
imgNode.destroy();
imgNode = null;
}
if (!imgNode) {
imgNode = new cc.Node();
}
if (Orientation.ISO == mapInfo.orientation) {
imgNode.anchorX = 0.5 + tileOffsetX / imgWidth;
imgNode.anchorY = tileOffsetY / imgHeight;
} else {
imgNode.anchorX = tileOffsetX / imgWidth;
imgNode.anchorY = tileOffsetY / imgHeight;
}
imgNode.active = object.visible;
imgNode.angle = -object.rotation;
imgNode.x = object.x - leftTopX;
imgNode.y = object.y - leftTopY;
imgNode.name = imgName;
imgNode.parent = this.node;
imgNode.opacity = this._opacity;
imgNode.setSiblingIndex(i);
let sp = imgNode.getComponent(cc.Sprite);
if (!sp) {
sp = imgNode.addComponent(cc.Sprite);
}
let spf = sp.spriteFrame;
if (!spf) {
spf = new cc.SpriteFrame();
}
if ((gid & FLAG_HORIZONTAL) >>> 0) {
spf.setFlipX(true);
} else {
spf.setFlipX(false);
}
if ((gid & FLAG_VERTICAL) >>> 0) {
spf.setFlipY(true);
} else {
spf.setFlipY(false);
}
spf.setTexture(grid.tileset.sourceImage, cc.rect(grid));
sp.spriteFrame = spf;
sp.setVertsDirty();
// object group may has no width or height info
imgNode.width = imgWidth;
imgNode.height = imgHeight;
}
}
this._objects = objects;
// destroy useless node
let children = this.node.children;
let uselessExp = /^(?:img|text)\d+$/;
for (let i = 0, n = children.length; i < n; i++) {
let c = children[i];
let cName = c._name;
let isUseless = uselessExp.test(cName);
if (isUseless && !aliveNodes[cName]) c.destroy();
}
}
});
cc.TiledObjectGroup = module.exports = TiledObjectGroup;

View File

@@ -0,0 +1,151 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* !#en TiledTile can control the specified map tile.
* It will apply the node rotation, scale, translate to the map tile.
* You can change the TiledTile's gid to change the map tile's style.
* !#zh TiledTile 可以单独对某一个地图块进行操作。
* 他会将节点的旋转,缩放,平移操作应用在这个地图块上,并可以通过更换当前地图块的 gid 来更换地图块的显示样式。
* @class TiledTile
* @extends Component
*/
let TiledTile = cc.Class({
name: 'cc.TiledTile',
extends: cc.Component,
editor: CC_EDITOR && {
executeInEditMode: true,
menu: 'i18n:MAIN_MENU.component.renderers/TiledTile',
},
ctor () {
this._layer = null;
},
properties: {
_x: 0,
_y: 0,
/**
* !#en Specify the TiledTile horizontal coordinateuse map tile as the unit.
* !#zh 指定 TiledTile 的横向坐标,以地图块为单位
* @property {Number} x
* @default 0
*/
x: {
get () {
return this._x;
},
set (value) {
if (value === this._x) return;
if (this._layer && this._layer._isInvalidPosition(value, this._y)) {
cc.warn(`Invalid x, the valid value is between [%s] ~ [%s]`, 0, this._layer._layerSize.width);
return;
}
this._resetTile();
this._x = value;
this._updateInfo();
},
type: cc.Integer
},
/**
* !#en Specify the TiledTile vertical coordinateuse map tile as the unit.
* !#zh 指定 TiledTile 的纵向坐标,以地图块为单位
* @property {Number} y
* @default 0
*/
y: {
get () {
return this._y;
},
set (value) {
if (value === this._y) return;
if (this._layer && this._layer._isInvalidPosition(this._x, value)) {
cc.warn(`Invalid y, the valid value is between [%s] ~ [%s]`, 0, this._layer._layerSize.height);
return;
}
this._resetTile();
this._y = value;
this._updateInfo();
},
type: cc.Integer
},
/**
* !#en Specify the TiledTile gid.
* !#zh 指定 TiledTile 的 gid 值
* @property {Number} gid
* @default 0
*/
gid: {
get () {
if (this._layer) {
return this._layer.getTileGIDAt(this._x, this._y);
}
return 0;
},
set (value) {
if (this._layer) {
this._layer.setTileGIDAt(value, this._x, this._y);
}
},
type: cc.Integer
}
},
onEnable () {
let parent = this.node.parent;
this._layer = parent.getComponent(cc.TiledLayer);
this._resetTile();
this._updateInfo();
},
onDisable () {
this._resetTile();
},
_resetTile () {
if (this._layer && this._layer.getTiledTileAt(this._x, this._y) === this) {
this._layer.setTiledTileAt(this._x, this._y, null);
}
},
_updateInfo () {
if (!this._layer) return;
let x = this._x, y = this._y;
if (this._layer.getTiledTileAt(x, y)) {
cc.warn('There is already a TiledTile at [%s, %s]', x, y);
return;
}
this.node.setPosition(this._layer.getPositionAt(x, y));
this._layer.setTiledTileAt(x, y, this);
},
});
cc.TiledTile = module.exports = TiledTile;

View File

@@ -0,0 +1,19 @@
<link rel="import" href="packages://inspector/share/meta-header.html">
<dom-module id="tiled-map-inspector">
<link rel="import" type="css" href="packages://inspector/share/common.css">
<template>
<inspector-meta-header
target="[[target]]"
icon="unpack://engine/cocos2d/tilemap/editor/tiled-map.png"
dirty="{{dirty}}"
>
</inspector-meta-header>
</template>
<script>
Editor.registerElement({
});
</script>
</dom-module>

View File

@@ -0,0 +1,200 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
'use strict';
const CustomAssetMeta = Editor.metas['custom-asset'];
const Fs = require('fire-fs');
const Path = require('fire-path');
const Url = require('fire-url');
const DOMParser = require('xmldom').DOMParser;
const TMX_ENCODING = { encoding: 'utf-8' };
const Sharp = require(Editor.url('app://editor/share/sharp'));
async function searchDependFiles(tmxFile, tmxFileData, cb) {
var doc = new DOMParser().parseFromString(tmxFileData);
if (!doc) {
return cb(new Error(cc.debug.getError(7222, tmxFile)));
}
var imageLayerTextures = [];
var imageLayerTextureNames = [];
var textures = [];
var tsxFiles = [];
var textureNames = [];
var textureSizes = [];
async function parseTilesetImages(tilesetNode, sourcePath) {
var images = tilesetNode.getElementsByTagName('image');
for (var i = 0, n = images.length; i < n ; i++) {
var imageCfg = images[i].getAttribute('source');
if (imageCfg) {
var imgPath = Path.join(Path.dirname(sourcePath), imageCfg);
textures.push(imgPath);
// Since it is possible to compress the texture at build time, meta file must save the original size of the texture when importing it
if (Fs.existsSync(imgPath)) {
let metaData = await Sharp(imgPath).metadata();
textureSizes.push(cc.size(
metaData.width,
metaData.height
));
} else {
// The image file does not exist
textureSizes.push(cc.size(0,0));
Editor.warn("Can not find image file %s", imgPath);
}
let textureName = Path.relative(Path.dirname(sourcePath), imgPath);
textureName = textureName.replace(/\\/g, '\/');
textureNames.push(textureName);
}
}
}
var rootElement = doc.documentElement;
var tilesetElements = rootElement.getElementsByTagName('tileset');
for (var i = 0, n = tilesetElements.length; i < n; i++) {
var tileset = tilesetElements[i];
var sourceTSX = tileset.getAttribute('source');
if (sourceTSX) {
var tsxPath = Path.join(Path.dirname(tmxFile), sourceTSX);
if (Fs.existsSync(tsxPath)) {
tsxFiles.push(sourceTSX);
var tsxContent = Fs.readFileSync(tsxPath, 'utf-8');
var tsxDoc = new DOMParser().parseFromString(tsxContent);
if (tsxDoc) {
await parseTilesetImages(tsxDoc, tsxPath);
} else {
Editor.warn('Parse %s failed.', tsxPath);
}
}
}
// import images
await parseTilesetImages(tileset, tmxFile);
}
var imageLayerElements = rootElement.getElementsByTagName('imagelayer');
for (var ii = 0, nn = imageLayerElements.length; ii < nn; ii++) {
var imageLayer = imageLayerElements[ii];
var imageInfos = imageLayer.getElementsByTagName('image');
if (imageInfos && imageInfos.length > 0) {
var imageInfo = imageInfos[0];
var imageSource = imageInfo.getAttribute('source');
var imgPath = Path.join(Path.dirname(tmxFile), imageSource);
if (Fs.existsSync(imgPath)) {
imageLayerTextures.push(imgPath);
let imgName = Path.relative(Path.dirname(tmxFile), imgPath);
imgName = imgName.replace(/\\/g, '\/');
imageLayerTextureNames.push(imgName);
} else {
Editor.warn('Parse %s failed.', imgPath);
}
}
}
cb(null, { textures, tsxFiles, textureNames, textureSizes, imageLayerTextures, imageLayerTextureNames});
}
const AssetRootUrl = 'db://assets/';
class TiledMapMeta extends CustomAssetMeta {
constructor (assetdb) {
super(assetdb);
this._tmxData = '';
this._textures = [];
this._tsxFiles = [];
this._textureNames = [];
this._textureSizes = [];
this._imageLayerTextures = [];
this._imageLayerTextureNames = [];
}
static version () { return '2.0.5'; }
static defaultType() { return 'tiled-map'; }
import (fspath, cb) {
Fs.readFile(fspath, TMX_ENCODING, (err, data) => {
if (err) {
return cb(err);
}
this._tmxData = data;
searchDependFiles(fspath, data, (err, info) => {
if (err) {
return cb(err);
}
this._textures = info.textures;
this._tsxFiles = info.tsxFiles;
this._textureNames = info.textureNames;
this._textureSizes = info.textureSizes;
this._imageLayerTextures = info.imageLayerTextures;
this._imageLayerTextureNames = info.imageLayerTextureNames;
cb();
});
});
}
postImport ( fspath, cb ) {
var db = this._assetdb;
var asset = new cc.TiledMapAsset();
asset.name = Path.basenameNoExt(fspath);
asset.tmxXmlStr = this._tmxData;
asset.textures = this._textures.map(p => {
var uuid = db.fspathToUuid(p);
return uuid ? Editor.serialize.asAsset(uuid) : null;
});
asset.textureNames = this._textureNames;
asset.textureSizes = this._textureSizes;
asset.imageLayerTextures = this._imageLayerTextures.map(p => {
var uuid = db.fspathToUuid(p);
return uuid ? Editor.serialize.asAsset(uuid) : null;
});
asset.imageLayerTextureNames = this._imageLayerTextureNames;
asset.tsxFiles = this._tsxFiles.map(p => {
var tsxPath = Path.join(Path.dirname(fspath), p);
var uuid = db.fspathToUuid(tsxPath);
if (uuid) {
asset.tsxFileNames.push(p);
return Editor.serialize.asAsset(uuid);
} else {
Editor.error(`Can not find file ${tsxPath}`);
asset.tsxFileNames.push('');
}
return null;
});
db.saveAssetToLibrary(this.uuid, asset);
cb();
}
}
module.exports = TiledMapMeta;

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

@@ -0,0 +1,29 @@
/****************************************************************************
Copyright (c) 2018 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
require('./CCTiledMap');
require('./CCTiledMapRenderDataList');
require('./tiledmap-buffer');
require('./tmx-layer-assembler');

View File

@@ -0,0 +1,45 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
let TiledMapBuffer = cc.Class({
name: 'cc.TiledMapBuffer',
extends: require('../core/renderer/webgl/quad-buffer'),
_updateOffset () {
let offsetInfo = this._offsetInfo;
offsetInfo.vertexOffset = this.vertexOffset;
offsetInfo.indiceOffset = this.indiceOffset;
offsetInfo.byteOffset = this.byteOffset;
},
adjust (vertexCount, indiceCount) {
this.vertexOffset += vertexCount;
this.indiceOffset += indiceCount;
this.indiceStart = this.indiceOffset;
this.byteOffset = this.byteOffset + vertexCount * this._vertexBytes;
this._dirty = true;
}
});
cc.TiledMapBuffer = module.exports = TiledMapBuffer;

View File

@@ -0,0 +1,478 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
import Assembler from '../core/renderer/assembler';
const TiledLayer = require('./CCTiledLayer');
const TiledMap = require('./CCTiledMap');
const TileFlag = TiledMap.TileFlag;
const FLIPPED_MASK = TileFlag.FLIPPED_MASK;
const renderer = require('../core/renderer/');
const vfmtPosUvColor = require('../core/renderer/webgl/vertex-format').vfmtPosUvColor;
const MaxGridsLimit = parseInt(65535 / 6);
const RenderOrder = TiledMap.RenderOrder;
import { Mat4, Vec3 } from '../core/value-types';
const RenderFlow = require('../core/renderer/render-flow');
let _mat4_temp = cc.mat4();
let _vec3_temp = cc.v3();
let _leftDown = {row:0, col:0};
let _uva = {x:0, y:0};
let _uvb = {x:0, y:0};
let _uvc = {x:0, y:0};
let _uvd = {x:0, y:0};
let _renderData = null, _ia = null, _fillGrids = 0,
_vfOffset = 0, _moveX = 0, _moveY = 0, _layerMat = null,
_renderer = null, _renderDataList = null, _buffer = null,
_curMaterial = null, _comp = null, _vbuf = null, _uintbuf = null;
function _visitUserNode (userNode) {
if (CC_NATIVERENDERER) return;
userNode._updateLocalMatrix();
Mat4.mul(userNode._worldMatrix, _layerMat, userNode._matrix);
userNode._renderFlag &= ~(RenderFlow.FLAG_TRANSFORM | RenderFlow.FLAG_BREAK_FLOW);
RenderFlow.visitRootNode(userNode);
userNode._renderFlag |= RenderFlow.FLAG_BREAK_FLOW;
}
function _flush () {
if (_ia._count === 0) {
return;
}
_renderer.material = _renderData.material;
_renderer.node = _comp.node;
_renderer._flushIA(_renderData.ia);
let needSwitchBuffer = (_fillGrids >= MaxGridsLimit);
if (needSwitchBuffer) {
_buffer.uploadData();
_buffer.switchBuffer();
_vbuf = _buffer._vData;
_uintbuf = _buffer._uintVData;
_renderData = _renderDataList.popRenderData(_buffer);
_ia = _renderData.ia;
_vfOffset = 0;
_fillGrids = 0;
} else {
_renderData = _renderDataList.popRenderData(_buffer);
_ia = _renderData.ia;
}
_renderData.material = _curMaterial;
}
function _renderNodes (nodeRow, nodeCol) {
let nodesInfo = _comp._getNodesByRowCol(nodeRow, nodeCol);
if (!nodesInfo || nodesInfo.count == 0) return;
let nodesList = nodesInfo.list;
let newIdx = 0, oldIdx = 0;
// flush map render data
_flush();
_renderer.worldMatDirty++;
// begin to render nodes
for (; newIdx < nodesInfo.count; ) {
let dataComp = nodesList[oldIdx];
oldIdx++;
if (!dataComp) continue;
_visitUserNode(dataComp.node);
if (newIdx !== oldIdx) {
nodesList[newIdx] = dataComp;
dataComp._index = newIdx;
}
newIdx++;
}
nodesList.length = newIdx;
_renderer.worldMatDirty--;
_renderDataList.pushNodesList(_renderData, nodesList);
// flush user nodes render data
_renderer._flush();
_renderer.node = _comp.node;
}
/*
texture coordinate
a b
c d
*/
function _flipTexture (inGrid, gid) {
_uva.x = inGrid.l;
_uva.y = inGrid.t;
_uvb.x = inGrid.r;
_uvb.y = inGrid.t;
_uvc.x = inGrid.l;
_uvc.y = inGrid.b;
_uvd.x = inGrid.r;
_uvd.y = inGrid.b;
let tempVal = null;
// vice
if ((gid & TileFlag.DIAGONAL) >>> 0) {
tempVal = _uvb;
_uvb = _uvc;
_uvc = tempVal;
}
// flip x
if ((gid & TileFlag.HORIZONTAL) >>> 0) {
tempVal = _uva;
_uva = _uvb;
_uvb = tempVal;
tempVal = _uvc;
_uvc = _uvd;
_uvd = tempVal;
}
// flip y
if ((gid & TileFlag.VERTICAL) >>> 0) {
tempVal = _uva;
_uva = _uvc;
_uvc = tempVal;
tempVal = _uvb;
_uvb = _uvd;
_uvd = tempVal;
}
};
export default class TmxAssembler extends Assembler {
updateRenderData (comp) {
if (!comp._renderDataList) {
comp._buffer = new cc.TiledMapBuffer(renderer._handle, vfmtPosUvColor);
comp._renderDataList = new cc.TiledMapRenderDataList();
}
}
fillBuffers (comp, renderer) {
let vertices = comp._vertices;
if (vertices.length === 0 ) return;
comp._updateCulling();
let layerNode = comp.node;
_moveX = comp._leftDownToCenterX;
_moveY = comp._leftDownToCenterY;
_layerMat = layerNode._worldMatrix;
_renderer = renderer;
_comp = comp;
_renderDataList = comp._renderDataList;
_buffer = comp._buffer;
if (comp._isCullingDirty() || comp._isUserNodeDirty() || comp._hasAnimation() || comp._hasTiledNode()) {
_buffer.reset();
let leftDown, rightTop;
if (comp._enableCulling) {
let cullingRect = comp._cullingRect;
leftDown = cullingRect.leftDown;
rightTop = cullingRect.rightTop;
} else {
leftDown = _leftDown;
rightTop = comp._rightTop;
}
let maxRows = rightTop.row - leftDown.row + 1;
let maxCols = rightTop.col - leftDown.col + 1;
let maxGrids = maxRows * maxCols;
if (maxGrids > MaxGridsLimit) {
maxGrids = MaxGridsLimit;
}
_buffer.request(maxGrids * 4, maxGrids * 6);
switch (comp._renderOrder) {
// left top to right down, col add, row sub,
case RenderOrder.RightDown:
this.traverseGrids(leftDown, rightTop, -1, 1);
break;
// right top to left down, col sub, row sub
case RenderOrder.LeftDown:
this.traverseGrids(leftDown, rightTop, -1, -1);
break;
// left down to right up, col add, row add
case RenderOrder.RightUp:
this.traverseGrids(leftDown, rightTop, 1, 1);
break;
// right down to left up, col sub, row add
case RenderOrder.LeftUp:
this.traverseGrids(leftDown, rightTop, 1, -1);
break;
}
comp._setCullingDirty(false);
comp._setUserNodeDirty(false);
} else if (!CC_NATIVERENDERER) {
let renderData = null;
let nodesRenderList = null;
let nodesList = null;
for (let i = 0; i < _renderDataList._offset; i++) {
renderData = _renderDataList._dataList[i];
nodesRenderList = renderData.nodesRenderList;
if (nodesRenderList.length > 0) {
renderer.worldMatDirty++;
for (let j = 0; j < nodesRenderList.length; j++) {
nodesList = nodesRenderList[j];
if (!nodesList) continue;
for (let idx = 0; idx < nodesList.length; idx++) {
let dataComp = nodesList[idx];
if (!dataComp) continue;
_visitUserNode(dataComp.node);
}
}
renderer.worldMatDirty--;
renderer._flush();
}
if (renderData.ia._count > 0) {
renderer.material = renderData.material;
renderer.node = layerNode;
renderer._flushIA(renderData.ia);
}
}
}
_renderData = null;
_ia = null;
_layerMat = null;
_renderer = null;
_renderDataList = null;
_buffer = null;
_curMaterial = null;
_comp = null;
_vbuf = null;
_uintbuf = null;
}
// rowMoveDir is -1 or 1, -1 means decrease, 1 means increase
// colMoveDir is -1 or 1, -1 means decrease, 1 means increase
traverseGrids (leftDown, rightTop, rowMoveDir, colMoveDir) {
_renderDataList.reset();
// show nothing
if (rightTop.row < 0 || rightTop.col < 0) return;
_renderData = _renderDataList.popRenderData(_buffer);
_ia = _renderData.ia;
_vbuf = _buffer._vData;
_uintbuf = _buffer._uintVData;
_fillGrids = 0;
_vfOffset = 0;
_curMaterial = null;
let layerNode = _comp.node;
let pOpacity = layerNode.parent ? layerNode.parent._opacity / 255 : 1.0;
let opacity = pOpacity * layerNode._opacity;
layerNode._color._fastSetA(opacity);
let color = layerNode._color._val;
let tiledTiles = _comp._tiledTiles;
let texGrids = _comp._texGrids;
let tiles = _comp._tiles;
let texIdToMatIdx = _comp._texIdToMatIndex;
let mats = _comp._materials;
let vertices = _comp._vertices;
let rowData, col, cols, row, rows, colData, tileSize, grid = null, gid = 0;
let left = 0, bottom = 0, right = 0, top = 0; // x, y
let tiledNode = null, curTexIdx = -1, matIdx;
let colNodesCount = 0, checkColRange = true;
if (rowMoveDir == -1) {
row = rightTop.row;
rows = leftDown.row;
} else {
row = leftDown.row;
rows = rightTop.row;
}
// traverse row
for (; (rows - row) * rowMoveDir >= 0; row += rowMoveDir) {
rowData = vertices[row];
colNodesCount = _comp._getNodesCountByRow(row);
checkColRange = (colNodesCount == 0 && rowData != undefined);
// limit min col and max col
if (colMoveDir == 1) {
col = checkColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col;
cols = checkColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col;
} else {
col = checkColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col;
cols = checkColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col;
}
// traverse col
for (; (cols - col) * colMoveDir >= 0; col += colMoveDir) {
colData = rowData && rowData[col];
if (!colData) {
// only render users nodes because map data is empty
if (colNodesCount > 0) _renderNodes(row, col);
continue;
}
gid = tiles[colData.index];
grid = texGrids[(gid & FLIPPED_MASK) >>> 0];
if (!grid) continue;
// check init or new material
if (curTexIdx !== grid.texId) {
// need flush
if (curTexIdx !== -1) {
_flush();
}
// update material
curTexIdx = grid.texId;
matIdx = texIdToMatIdx[curTexIdx];
_curMaterial = mats[matIdx];
_renderData.material = _curMaterial;
}
if (!_curMaterial) continue;
// calc rect vertex
left = colData.left - _moveX;
bottom = colData.bottom - _moveY;
tileSize = grid.tileset._tileSize;
right = left + tileSize.width;
top = bottom + tileSize.height;
// begin to fill vertex buffer
tiledNode = tiledTiles[colData.index];
if (!tiledNode) {
// tl
_vbuf[_vfOffset] = left;
_vbuf[_vfOffset + 1] = top;
_uintbuf[_vfOffset + 4] = color;
// bl
_vbuf[_vfOffset + 5] = left;
_vbuf[_vfOffset + 6] = bottom;
_uintbuf[_vfOffset + 9] = color;
// tr
_vbuf[_vfOffset + 10] = right;
_vbuf[_vfOffset + 11] = top;
_uintbuf[_vfOffset + 14] = color;
// br
_vbuf[_vfOffset + 15] = right;
_vbuf[_vfOffset + 16] = bottom;
_uintbuf[_vfOffset + 19] = color;
} else {
if(tiledNode.node.active) {
tiledNode.node._color._fastSetA(tiledNode.node._opacity * opacity / 255);
this.fillByTiledNode(tiledNode.node, _vbuf, _uintbuf, left, right, top, bottom);
}
}
_flipTexture(grid, gid);
// tl -> a
_vbuf[_vfOffset + 2] = _uva.x;
_vbuf[_vfOffset + 3] = _uva.y;
// bl -> c
_vbuf[_vfOffset + 7] = _uvc.x;
_vbuf[_vfOffset + 8] = _uvc.y;
// tr -> b
_vbuf[_vfOffset + 12] = _uvb.x;
_vbuf[_vfOffset + 13] = _uvb.y;
// br -> d
_vbuf[_vfOffset + 17] = _uvd.x;
_vbuf[_vfOffset + 18] = _uvd.y;
// modify buffer all kinds of offset
_vfOffset += 20;
_buffer.adjust(4, 6);
_ia._count += 6;
_fillGrids++;
// check render users node
if (colNodesCount > 0) _renderNodes(row, col);
// vertices count exceed 66635, buffer must be switched
if (_fillGrids >= MaxGridsLimit) {
_flush();
}
}
}
// upload buffer data
_buffer.uploadData();
// last flush
if (_ia._count > 0) {
_renderer.material = _renderData.material;
_renderer.node = _comp.node;
_renderer._flushIA(_renderData.ia);
}
}
fillByTiledNode (tiledNode, vbuf, uintbuf, left, right, top, bottom) {
tiledNode._updateLocalMatrix();
Mat4.copy(_mat4_temp, tiledNode._matrix);
Vec3.set(_vec3_temp, -(left + _moveX), -(bottom + _moveY), 0);
Mat4.transform(_mat4_temp, _mat4_temp, _vec3_temp);
let m = _mat4_temp.m;
let a = m[0];
let b = m[1];
let c = m[4];
let d = m[5];
let tx = m[12];
let ty = m[13];
let color = tiledNode._color._val;
// tl
vbuf[_vfOffset] = left * a + top * c + tx;
vbuf[_vfOffset + 1] = left * b + top * d + ty;
uintbuf[_vfOffset + 4] = color;
// bl
vbuf[_vfOffset + 5] = left * a + bottom * c + tx;
vbuf[_vfOffset + 6] = left * b + bottom * d + ty;
uintbuf[_vfOffset + 9] = color;
// tr
vbuf[_vfOffset + 10] = right * a + top * c + tx;
vbuf[_vfOffset + 11] = right * b + top * d + ty;
uintbuf[_vfOffset + 14] = color;
// br
vbuf[_vfOffset + 15] = right * a + bottom * c + tx;
vbuf[_vfOffset + 16] = right * b + bottom * d + ty;
uintbuf[_vfOffset + 19] = color;
}
}
Assembler.register(TiledLayer, TmxAssembler);