<commit_before>/**
 Copyright (C) 2013 by <NAME>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/// <reference path="../interfaces/ITiledMap.ts"/>

module pow2.editor.tiled {

   export class TiledLoader {

      data:JQuery;
      constructor(
         public platform:IAppPlatform,
         public mapName:string,
         data:JQuery){
         this.data = $(data);
      }
   }
   
   
   export class TiledTMX extends TiledLoader {
      $map:JQuery; // The <map> element
      width:number = 0;
      height:number = 0;
      orientation:string = "orthogonal";
      tileheight:number = 16;
      tilewidth:number = 16;
      version:number = 1;
      properties:any = {};
      tilesets:any = {};
      layers:any[] = [];
      objectGroups:any[] = [];



      prepare(done:(res:TiledTMX)=>any) {
         this.$map = getRootNode(this.data,'map');
         this.version = parseInt(getElAttribute(this.$map,'version'));
         this.width = parseInt(getElAttribute(this.$map,'width'));
         this.height = parseInt(getElAttribute(this.$map,'height'));
         this.orientation = getElAttribute(this.$map,'orientation');
         this.tileheight = parseInt(getElAttribute(this.$map,'tileheight'));
         this.tilewidth = parseInt(getElAttribute(this.$map,'tilewidth'));
         this.properties = tiled.readTiledProperties(this.$map);
         var tileSetDeps = [];
         var tileSets = getChildren(this.$map,'tileset');
         _.each(tileSets,(ts) => {
            var source:string = getElAttribute(ts,'source');
            if(source){
               tileSetDeps.push({
                  source:this.platform.getDirName(this.mapName) + '/' + source,
                  firstgid:parseInt(getElAttribute(ts,'firstgid') || "-1")
               });
            }
            // TODO: IF no source then create a resource with the given data.
         });

         // Extract tile <layer>s
         var layers = getChildren(this.$map,'layer');
         _.each(layers,(layer) => {
            var tileLayer = <tiled.ITiledLayer>tiled.readITiledLayerBase(layer);
            this.layers.push(tileLayer);

            // Take CSV and convert it to JSON array, then parse.
            var data:any = getChild(layer,'data');
            if(data){
               var encoding:string = getElAttribute(data,'encoding');
               if(!encoding || encoding.toLowerCase() !== 'csv'){
                  throw new Error("Pow2 only supports CSV maps.  Edit the Map Properties in Tiled to use the CSV option when saving.");
               }
               tileLayer.data = JSON.parse('[' + $.trim(data.text()) + ']');
            }
         });

         // Extract tile <objectgroup>s
         var objectGroups = getChildren(this.$map,'objectgroup');
         _.each(objectGroups,($group) => {

            // Base layer properties.
            var objectGroup = <tiled.ITiledObjectGroup>tiled.readITiledLayerBase($group);
            objectGroup.objects = [];
            var color:string = getElAttribute($group,'color');
            if(color){
               objectGroup.color = color;
            }
            // Read any objects
            var objects = getChildren($group,'object');
            _.each(objects,(object) => {
               objectGroup.objects.push(<tiled.ITiledObject>tiled.readITiledLayerBase(object));
            });
            this.objectGroups.push(objectGroup);
         });


         // Load any source references.
         var _next = ():any => {
            if(tileSetDeps.length <= 0){
               return done(this);
            }
            var dep = tileSetDeps.shift();
            return this.platform.readFile(dep.source,(data:any) => {
               var tsr:TiledTSX = new TiledTSX(this.platform,dep.source,data);
               tsr.prepare(() => {
                  this.tilesets[tsr.name] = tsr;
                  tsr.firstgid = dep.firstgid;
                  _next();
               });
            });
         };
         _next();
      }
   }


   export class TilesetTile {
      id:number;
      properties:any = {};
      constructor(id:number){
         this.id = id;
      }
   }
   /**
    * A Tiled TSX tileset resource
    */
   export class TiledTSX extends TiledLoader {
      name:string = null;
      tilewidth:number = 16;
      tileheight:number = 16;
      imageWidth:number = 0;
      imageHeight:number = 0;
      image:HTMLImageElement = null;
      url:string;
      firstgid:number = -1;
      tiles:any[] = [];

      prepare(done:(res:TiledTSX)=>any) {
         var tileSet = getRootNode(this.data,'tileset');<commit_msg>feat(tiledLoader): support inline tile sets<commit_after>/**
 Copyright (C) 2013 by <NAME>

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

/// <reference path="../interfaces/ITiledMap.ts"/>

module pow2.editor.tiled {

   export class TiledLoader {

      data:JQuery;
      constructor(
         public platform:IAppPlatform,
         public mapName:string,
         data:JQuery){
         this.data = $(data);
      }
   }

   interface TileSetDependency {
      source?:string; // Path to URL source from which to load data.
      data?:any; // Data instead of source.
      firstgid:number; // First global id.
   }


   export class TiledTMX extends TiledLoader {
      $map:JQuery; // The <map> element
      width:number = 0;
      height:number = 0;
      orientation:string = "orthogonal";
      tileheight:number = 16;
      tilewidth:number = 16;
      version:number = 1;
      properties:any = {};
      tilesets:any = {};
      layers:any[] = [];
      objectGroups:any[] = [];



      prepare(done:(res:TiledTMX)=>any) {
         this.$map = getRootNode(this.data,'map');
         this.version = parseInt(getElAttribute(this.$map,'version'));
         this.width = parseInt(getElAttribute(this.$map,'width'));
         this.height = parseInt(getElAttribute(this.$map,'height'));
         this.orientation = getElAttribute(this.$map,'orientation');
         this.tileheight = parseInt(getElAttribute(this.$map,'tileheight'));
         this.tilewidth = parseInt(getElAttribute(this.$map,'tilewidth'));
         this.properties = tiled.readTiledProperties(this.$map);
         var tileSetDeps:TileSetDependency[] = [];
         var tileSets = getChildren(this.$map,'tileset');
         _.each(tileSets,(ts) => {
            var source:string = getElAttribute(ts,'source');
            if(source){
               tileSetDeps.push({
                  source:this.platform.getDirName(this.mapName) + '/' + source,
                  firstgid:parseInt(getElAttribute(ts,'firstgid') || "-1")
               });
            }
            // Tileset element is inline, load from the existing XML and
            // assign the source (used for relative image loading) to be
            // the .tmx file.
            else {
               tileSetDeps.push({
                  data:ts,
                  source:this.mapName,
                  firstgid:parseInt(getElAttribute(ts,'firstgid') || "-1")
               })
            }
            // TODO: IF no source then create a resource with the given data.
         });

         // Extract tile <layer>s
         var layers = getChildren(this.$map,'layer');
         _.each(layers,(layer) => {
            var tileLayer = <tiled.ITiledLayer>tiled.readITiledLayerBase(layer);
            this.layers.push(tileLayer);

            // Take CSV and convert it to JSON array, then parse.
            var data:any = getChild(layer,'data');
            if(data){
               var encoding:string = getElAttribute(data,'encoding');
               if(!encoding || encoding.toLowerCase() !== 'csv'){
                  throw new Error("Pow2 only supports CSV maps.  Edit the Map Properties in Tiled to use the CSV option when saving.");
               }
               tileLayer.data = JSON.parse('[' + $.trim(data.text()) + ']');
            }
         });

         // Extract tile <objectgroup>s
         var objectGroups = getChildren(this.$map,'objectgroup');
         _.each(objectGroups,($group) => {

            // Base layer properties.
            var objectGroup = <tiled.ITiledObjectGroup>tiled.readITiledLayerBase($group);
            objectGroup.objects = [];
            var color:string = getElAttribute($group,'color');
            if(color){
               objectGroup.color = color;
            }
            // Read any objects
            var objects = getChildren($group,'object');
            _.each(objects,(object) => {
               objectGroup.objects.push(<tiled.ITiledObject>tiled.readITiledLayerBase(object));
            });
            this.objectGroups.push(objectGroup);
         });


         // Load any source references.
         var _next = ():any => {
            if(tileSetDeps.length <= 0){
               return done(this);
            }
            var dep = tileSetDeps.shift();
            var loadTileset = (data:any) => {
               var tsr:TiledTSX = new TiledTSX(this.platform,dep.source,data);
               tsr.prepare(() => {
                  this.tilesets[tsr.name] = tsr;
                  tsr.firstgid = dep.firstgid;
                  _next();
               });
            };
            if(dep.data) {
               loadTileset(dep.data);
            }
            else if(dep.source){
               this.platform.readFile(dep.source,(data:any) => {
                  loadTileset(data);
               });
            }
            else {
               throw new Error("Unknown type of tile set data");
            }
         };
         _next();
      }
   }


   export class TilesetTile {
      id:number;
      properties:any = {};
      constructor(id:number){
         this.id = id;
      }
   }
   /**
    * A Tiled TSX tileset resource
    */
   export class TiledTSX extends TiledLoader {
      name:string = null;
      tilewidth:number = 16;
      tileheight:number = 16;
      imageWidth:number = 0;
      imageHeight:number = 0;
      image:HTMLImageElement = null;
      url:string;
      firstgid:number = -1;
      tiles:any[] = [];

      prepare(done:(res:TiledTSX)=>any) {
         var tileSet = getRootNode(this.data,'tileset');
{'fraction_non_alphanumeric': 0.12345235959088462, 'fraction_numerical': 0.004755069083079132, 'mean_word_length': 1.956763925729443, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 38, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '753030', 'n_tokens_mistral': 3108, 'n_tokens_neox': 2998, 'n_words': 703}