Laya Resource Loading Notes

Source: Internet
Author: User
    • Laya.loader is responsible for the load logic of resources and is managed by Loadermanager.
    • Laya supports the loading of multiple types of resources and also supports custom type loading. Different types of loading methods may be different.
    • The Laya.loader cache has been loaded with resources, reducing the resource duplication load.
    • Provides a cleanup resource interface, which is encapsulated by the Loadermanager interface.
    • Some resource loads include multi-step loading, such as both Atlas and font contain text downloads and picture downloads.
    • Note: Laya.loader is an example of Loadermanager and is a common loading interface for Laya. Laya.loader by Loadermanager Unified Management, under normal circumstances, development is not required to create loader instances themselves.
Built-in types
    • Laya internally supported file types are:
        /** 文本类型,加载完成后返回文本。*/        public static const TEXT:String = "text";        /** JSON 类型,加载完成后返回json数据。*/        public static const JSON:String = "json";        /** XML 类型,加载完成后返回domXML。*/        public static const XML:String = "xml";        /** 二进制类型,加载完成后返回arraybuffer二进制数据。*/        public static const BUFFER:String = "arraybuffer";        /** 纹理类型,加载完成后返回Texture。*/        public static const IMAGE:String = "image";        /** 声音类型,加载完成后返回sound。*/        public static const SOUND:String = "sound";        /** 图集类型,加载完成后返回图集json信息(并创建图集内小图Texture)。*/        public static const ATLAS:String = "atlas";        /** 位图字体类型,加载完成后返回BitmapFont。*/        public static const FONT:String = "font";        /** TTF字体类型,加载完成后返回null。*/        public static const TTF:String = "ttf";        /**@private */        public static const PKM:String = "pkm";
    • LAYA3D Extension Type:
        /**@private 层级文件资源标记。*/        private static const HIERARCHY:String = "SPRITE3DHIERARCHY";        /**@private 网格的原始资源标记。*/        private static const MESH:String = "MESH";        /**@private 材质的原始资源标记。*/        private static const MATERIAL:String = "MATERIAL";        /**@private PBR材质资源标记。*/        private static const PBRMATERIAL:String = "PBRMTL";        /**@private TextureCube原始资源标记。*/        private static const TEXTURECUBE:String = "TEXTURECUBE";        /**@private Terrain原始资源标记。*/        private static const TERRAIN:String = "TERRAIN";
这几种类型通过扩展的方式,在Laya3D初始化时,注册了对应的加载函数。
    • Laya file suffix to file type mapping:
    Laya built-in type {"PNG": "Image", "jpg": "Image", "JPEG": "image", "TXT": "Text", "JSON": "JSON", "XML": "XML", "ALS": "Atlas", "Atlas": "Atlas", "MP3": "Sound", "Ogg": "Sound", "wav": "Sound", "part": "JSON", "FNT": "Font"        , "PKM": "PKM", "TTF": "TTF"}; LAYA3D extension//Add resolution of corresponding type by extension loadermanager.createmap.    Valid only for loadermanager.create methods.    Createmap["LH"] = [Sprite3d, laya3d.hierarchy];    createmap["ls"] = [Scene, laya3d.hierarchy];    createmap["LM"] = [Mesh, Laya3d.mesh];    createmap["Lmat"] = [standardmaterial, laya3d.material];    createmap["LPBR"] = [pbrmaterial, laya3d.material];    createmap["LTC"] = [Texturecube, Laya3d.texturecube];    createmap["jpg"] = [Texture2d, "nativeimage"];    createmap["jpeg"] = [Texture2d, "nativeimage"];    createmap["png"] = [Texture2d, "nativeimage"];    createmap["PKM"] = [texture2d, Loader.buffer];    createmap["Lsani"] = [Animationtemplet, Loader.buffer]; createmap["Lrani"] = [Animationtemplet, Loader.buffER];    createmap["raw"] = [datatexture2d, Loader.buffer];    createmap["mipmaps"] = [datatexture2d, Loader.buffer];    createmap["Thdata"] = [Terrainheightdata, Loader.buffer];    createmap["LT"] = [Terrainres, Laya3d.terrain];    createmap["Lani"] = [Animationclip, Loader.buffer];    createmap["lav"] = [Avatar, Loader.json]; Createmap["ani"] = [Animationtemplet, loader.buffer];//compatible interface
Resource Loading Basic process
public function load(url:String, type:String = null, cache:Boolean = true, group:String = null, ignoreCache:Boolean = false):void加载资源。加载错误会派发 Event.ERROR 事件,参数为错误信息。Parametersurl:String — 资源地址。 type:String (default = null) — (default = null)资源类型。可选值为:Loader.TEXT、Loader.JSON、Loader.XML、Loader.BUFFER、Loader.IMAGE、Loader.SOUND、Loader.ATLAS、Loader.FONT。如果为null,则根据文件后缀分析类型。 cache:Boolean (default = true) — (default = true)是否缓存数据。 group:String (default = null) — (default = null)分组名称。 ignoreCache:Boolean (default = false) — (default = false)是否忽略缓存,强制重新加载。
    The
    • caches data such as URLs, type, and cache for loading or subsequent loading.
    • If the resource has already been loaded, and the Ignorecache is not set, the complete event is started directly, informing that the load is completed.
    • If you customize the Load method, such as the method registered in Laya3d, it is loaded directly with the corresponding method. The
    • loads the resource based on the type selection corresponding to the Load method, and if no type is passed, the type is determined based on the resource suffix name. After the
    • resource is loaded, the OnLoaded method is triggered, the loaded data is encapsulated by type or subsequently loaded (for example, when the Atlas type loads the resource, the configuration is parsed and the corresponding picture is loaded).
    • calls the complete method, caches data in loader, and then puts the loader into the completion queue. The
    • executes the Endload method, caches the resource, notifies the complete event, and Loadermanager triggers the incoming complete method.
    • if the cumulative callback duration is greater than 100 milliseconds, the delay time is followed by the Endload method for subsequent loader.
        /** * Loading complete.         * @param data loaded.            */protected function complete (data:*): void {this._data = data; if (_customparse) {event (event.loaded, data is Array?)            [Data]: data);                } else {_loaders.push (this);            if (!_isworking) Checknext ();            }}/** @private */private static function Checknext (): void {_isworking = true;            var starttimer:number = Browser.now ();            var thistimer:number = Starttimer;                while (_startindex < _loaders.length) {Thistimer = Browser.now ();                _loaders[_startindex].endload ();                _startindex++;  @ Prevents a single callback event from being too long, the card process if (Browser.now ()-starttimer > Maxtimeout) {console.warn ("Loader        Callback cost a long time: "+ (Browser.now ()-Starttimer) +" url= "+ _loaders[_startindex-1].url);            Laya.timer.frameOnce (1, NULL, checknext);                Return            }} _loaders.length = 0;            _startindex = 0;        _isworking = false;         }/** * End load, handle cache and dispatch complete event <code>Event.COMPLETE</code>.  * @param content loaded data */Public Function endload (content:* = null): void {content &&            (this._data = content);                        if (This._cache) cacheres (This._url, this._data);            Event (event.progress, 1); Event (Event.complete, data is an Array?)                [Data]: data); }
Picture Resource Loading
    • The suffix is PNG, JPG, JPEG, and a resource of type HtmlImage or Nativeimage, which is loaded with the picture type.
    • The load of the picture type is loaded using the Browser.window.Image mode of H5.
      • Creates an instance of a Browser.window.Image.
      • Set the SRC, onload, onerror methods.
      • Use Imgcache to cache image objects to prevent GC from being dropped.
      • When the picture is loaded, the onload callback is triggered, and the onerror and onload methods of the image are cleaned and passed to the subordinate.
    • The nativeimage type of image will pass the image data directly. Other types of pictures wrap the native image data in HtmlImage (canvas mode)/webglimage (in WebGL mode) and then pass it on to subsequent calls.
        /** * @private * load picture resources.         * @param URL resource address.            */protected function _loadimage (url:string): void {url = url.formaturl (URL);            var _this:loader = this;            var image:*;                function clear (): void {image.onload = null;                Image.onerror = null;                Delete Imgcache[url]} var onload:function = Function (): void {clear ();            _this.onloaded (image);            };                var onerror:function = Function (): void {clear ();            _this.event (Event.error, "Load image failed");                } if (_type = = = "Nativeimage") {image = new Browser.window.Image ();                Image.crossorigin = "";                Image.onload = onload;                Image.onerror = onerror;                image.src = URL; Add references to prevent garbage collection Imgcache[url] = Image;                    } else {new Htmlimage.create (URL, {onload:onload, Onerror:onerror, Oncreate:function (img:*): void {                    Image = img;                Add references to prevent garbage collection imgcache[url] = img;            }}); }        }
Text type loading
    • Simple types such as JSON, buffer, etc., are downloaded directly through HTTP requests.
    • Atlas/font type, the configuration file is downloaded in this manner before performing subsequent operations.
            var contentType:String;            switch (type) {            case ATLAS:                 contentType = JSON;                break;            case FONT:                 contentType = XML;                break;            case PKM:                 contentType = BUFFER;                break            default:                 contentType = type;            }            if (preLoadedMap[url])            {                onLoaded(preLoadedMap[url]);            }else            {                if (!_http)                 {                    _http = new HttpRequest();                    _http.on(Event.PROGRESS, this, onProgress);                    _http.on(Event.ERROR, this, onError);                    _http.on(Event.COMPLETE, this, onLoaded);                }                _http.send(url, null, "get", contentType);            }            
Sound type Loading
    The
    • loads the sound resource, which is Laya encapsulated inside the sounds class. Laya supports three types of sound: H5, Web Audio API, and mini-game mode. The
    • H5 mode uses the native audio tag to load the sound. The
    • Web audio method is downloaded through an HTTP request. The
    • mini-game is available as a downloadable method. When the
    • sound is loaded, external data is accepted as the audio object, not the voice.
        /**         * @private         * 加载声音资源。         * @param   url 资源地址。         */        protected function _loadSound(url:String):void {            var sound:Sound = (new SoundManager._soundClass()) as Sound;            var _this:Loader = this;                        sound.on(Event.COMPLETE, this, soundOnload);            sound.on(Event.ERROR, this, soundOnErr);            sound.load(url);                        function soundOnload():void {                clear();                _this.onLoaded(sound);            }            function soundOnErr():void {                clear();                sound.dispose();                _this.event(Event.ERROR, "Load sound failed");            }            function clear():void {                sound.offAll();            }        }
Atlas Loading
    The
    • Atlas type typically contains one copy of the profile and one or more post plots. The
    • first downloads the configuration file in HTTP mode. and set the current type to Atlas type.
    • When the profile download is complete, parse the Meta field, get the image address you want to download, and download the picture using the download image.
    • After all the pictures have been downloaded, parse the frames of the configuration, parse the picture information contained within the atlas, create a texture for each picture, and place the texture in Loadedmap, key is the original path to the picture. Even if the picture is in the gallery, you can get the picture resource by setting the URL of the single picture. The
    • stores the URL of all pictures in the atlas as an array of atlasmap, and key is the Atlas address.
if (type = = = ATLAS) {//Process Atlas if (!DATA.SRC &&!data._setcontext) {                        @ process. atlas file if (!_data) {this._data = data;                            Construct Load picture information if (Data.meta && data.meta.image) {//type with picture information                            var Toloadpics:array = Data.meta.image.split (","); var split:string = _url.indexof ("/") >= 0?                            "/" : "\\";                            var idx:int = _url.lastindexof (split); var folderpath:string = idx >= 0?                            _URL.SUBSTR (0, idx + 1): "";                            IDX = _url.indexof ("?");                            var ver:string; ver = idx >= 0?                            _URL.SUBSTR (IDX): ""; for (var i:int = 0, len:int = toloadpics.length; i < Len; i++) {Toloadpics[i] = Folderp Ath + Toloadpics[i]; }} else {//without picture information toloadpics = [_url.replac                        E (". JSON", ". png")];                        }//ensure the positive sequence loading of the Atlas Toloadpics.reverse ();                        Data.toloads = Toloadpics;                    Data.pics = [];                    } event (Event.progress, 0.3 + 1/toloadpics.length * 0.6);                Return _loadimage (Toloadpics.pop ());                    } else {//Process picture _data.pics.push (data);                        if (_data.toloads.length > 0) {event (event.progress, 0.3 + 1/_data.toloads.length * 0.6);                    There is a picture that does not load return _loadimage (_data.toloads.pop ());                    } var frames:object = This._data.frames; var Cleanurl:string = This._url.split ("?")                    [0]; var directory:string = (This._data.meta && this._data.meta.prefix)?                    This._data.meta.prefix:cleanurl.substring (0, Cleanurl.lastindexof (".")) + "/";                    var pics:array = _data.pics;                    var atlasurl:string = Url.formaturl (This._url); var map:array = Atlasmap[atlasurl] | |                    (Atlasmap[atlasurl] = []);                    Map.dir = Directory;                    var scalerate:number = 1;                        if (This._data.meta && this._data.meta.scale && This._data.meta.scale! = 1) {                        Scalerate = parsefloat (This._data.meta.scale);                            for (var name:string in frames) {var obj:object = frames[name];//take the corresponding graph var tpic:object = Pics[obj.frame.idx? obj.frame.idx:0];//whether to release var url:string = Url.forma                 Turl (directory + name);           Tpic.scalerate = scalerate; Cacheres (URL, texture.create (TPic, obj.frame.x, Obj.frame.y, OBJ.FRAME.W, Obj.frame.h, obj.spritesourcesize.x,                            Obj.spritesourcesize.y, OBJ.SOURCESIZE.W, obj.sourcesize.h));                            Loadedmap[url].url = URL;                        Map.push (URL); }}else{for (name in frames) {obj = frames[name];// Take the corresponding figure TPic = Pics[obj.frame.idx? obj.frame.idx:0];//whether to release URL = UR                            L.formaturl (directory + name); Cacheres (URL, texture.create (TPic, obj.frame.x, Obj.frame.y, OBJ.FRAME.W, Obj.frame.h, obj.spritesourcesize.x,                            Obj.spritesourcesize.y, OBJ.SOURCESIZE.W, obj.sourcesize.h));                            Loadedmap[url].url = URL;                        Map.push (URL); }} Delete _Data.pics;                    /*[if-flash]*/Map.sort ();                Complete (this._data); }
Font resources
    • Laya has two fonts, one is TTF font and one is Bitmapfont.
    • Loading the Bitmapfont is to load the configuration file before changing the. fnt to. png to load the image. Once the resources are complete, use Bitmapfont to parse the Atlas font information.
    • TTF fonts use Ttfloader to load, through a variety of loading methods depending on the situation, there are ways to use fontface, but also through CSS and so on.
            var tArr:Array = fontPath.split(".ttf")[0].split("/");            fontName = tArr[tArr.length - 1];            if (Browser.window.conch)            {                _loadConch();            }else            if (Browser.window.FontFace) {                this._loadWithFontFace()            }            else {                this._loadWithCSS();            }
Resource Cleanup methods
        /** * Clears the cache for the specified resource address.         * If it is texture, it is destroyed by reference counting, "note" If the picture itself in the auto-collection (the default image is less than 512*512), memory cannot be destroyed, this image will be managed by the large Image collection Manager * @param URL resource address. * @param Forcedispose is forced to destroy, some resources are destroyed by reference counting method, if forcedispose=true, ignore reference count, directly destroy, such as texture, default is false */Publi            C static function Clearres (url:string, Forcedispose:boolean = false): void {url = url.formaturl (URL);            Delete Atlas var arr:array = Getatlas (URL); if (arr) {for (var i:int = 0, n:int = arr.length; i < n; i++) {var resurl:string =                    Arr[i];                    var tex:texture = getres (Resurl);                    Delete Loadedmap[resurl];                                    if (Tex) Tex.destroy (Forcedispose);                } arr.length = 0;                Delete Atlasmap[url];            Delete Loadedmap[url];                } else {var res:* = Loadedmap[url];                 if (res) {   Delete Loadedmap[url];                               If (res is Texture && res.bitmap) Texture (res). Destroy (Forcedispose);         }}}/** * Destroy the image resources used by texture, keep the texture shell, if the next time you render, find that the image resource used by texture does not exist, it will automatically recover * Compared to clearres,cleartextureres just clean texture inside the use of the image resources, do not destroy texture, re-use will automatically restore the picture resources * and clearres will completely destroy texture, resulting in no longer use Cleartextureres can ensure that image resources are destroyed immediately without fear of destroying errors, and Clearres is destroyed by reference counting. * "Note" If the picture itself is in the auto-collection (the default image is less than 512*512), the memory cannot be destroyed, This picture is managed by the large Atlas collection manager * @param URL Atlas address or texture address, such as Loader.cleartextureres ("Res/atlas/comp.atlas");            Loader.cleartextureres ("hall/bg.jpg");            */public static function Cleartextureres (url:string): void {url = url.formaturl (URL);            Delete Atlas var arr:array = Loader.getatlas (URL); var res:* = (arr && arr.length>0)?            Loader.getres (Arr[0]): loader.getres (URL); if (res && res.bitmap) {if (Render.isconchapp) {//compatible with old version if (res.bitmap.source.releaseTexture) {                    Res.bitmap.source.releaseTexture ();                }} else if (Res.bitmap._atlaser = = null) {Res.bitmap.releaseResource (true); }            }        }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.