Texture Optimization in Cocos2d-x optimization, cocos2d-x optimization texture

Source: Internet
Author: User

Texture Optimization in Cocos2d-x optimization, cocos2d-x optimization texture
1. Texture pixel format
Another important indicator of texture optimization is the texture pixel format. To maximize the user's fidelity requirements, select the appropriate pixel format, this greatly improves the processing speed of textures. In addition, the texture pixel format is closely related to hardware.
Next, let's take a look at the format of texture pixels. The main formats include:
RGBA8888. 32-bit color, which is the default pixel format. Each channel has 8 bits, and each pixel has 4 bytes.
BGRA8888. 32-bit color, 8 bits per channel, 4 bytes per pixel.
RGBA4444. 16-bit color. Each channel has four bits, and each pixel has two bytes.
RGB888. 24-bit color, no Alpha channel, so no transparency. Each channel has 8 bits, and each pixel has 3 bytes.
RGB565. 16-bit color, no Alpha channel, so no transparency. The R and B channels are five in each and the G channels are six.
RGB5A1 (or RGBA5551 ). 16-bit color. Each channel has four digits, and the Alpha channel only uses one digit.
PVRTC4. 4-bit PVR compression texture format, which is specially designed for the PowerVR graphics chip on iOS devices. They are very useful on iOS devices, because they can be directly loaded to the graphics card without intermediate computation.
PVRTC4A. 4-bit PVR compressed texture format with Alpha channel.
PVRTC2. 2-bit PVR compression texture format.
PVRTC2A. 2-bit PVR compressed texture format with Alpha channel.


In addition, when the pvrformat is saved, you can still compress gzips and zlibformat, and save the corresponding files as pvr.gz and pvr. ccz. Compressed files will be smaller, and less memory will be used for loading! However, decompression is required when converting to a texture, but it has little impact on CPU usage.


2. asynchronous loading of texture Cache
When starting the game and entering the scenario, the user experience is poor because there are too many resources to load. We can use the texture cache (TextureCache) to asynchronously load texture images. The TextureCache asynchronous loading function is as follows:
Virtual void addImageAsync (const std: string & filepath,
Std: function <void (Texture2D *)> callback
)
The first parameter is the file path, and the second parameter is the callback function. Next we will use an example to introduce the asynchronous loading of the texture cache. There are 200 small images loaded to the texture cache. The loading process will display a progress on the interface, as shown in 20-25.

The main code in the texture cache asynchronously loads the instance HelloWorldScene. cpp is as follows:

Bool HelloWorld: init () {if (! Layer: init () {return false;} Size visibleSize = Director: getInstance ()-> getVisibleSize (); Vec2 origin = Director: getInstance () -> getVisibleOrigin (); auto closeItem = MenuItemImage: create ("CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1 (HelloWorld: menuCloseCallback, this )); closeItem-> setPosition (Vec2 (origin. x + visibleSize. width-closeItem-> getContentSize (). width/2, origin. y + closeItem-> getContentSize (). height/2); auto menu = Menu: create (closeItem, NULL); menu-> setPosition (Vec2: ZERO); this-> addChild (menu, 1 ); _ labelLoading = Label: createWithTTF ("loading... "," fonts/Marker Felt. ttf ", 35); _ labelPercent = Label: createWithTTF (" 0% % "," fonts/Marker Felt. ttf ", 35); _ labelLoading-> setPosition (Vec2 (visibleSize. width/2, visibleSize. height/2-20); _ labelPercent-> setPosition (Vec2 (visibleSize. width/2, visibleSize. height/2 + 20); this-> addChild (_ labelLoading); this-> addChild (_ labelPercent); _ numberOfLoadedSprites = 0; _ imageOffset = 0; auto sharedFileUtils = FileUtils: getInstance (); std: string fullPathForFilename = sharedFileUtils-> fullPathForFilename ("ImageMetaData. plist "); ① ValueVector vec = FileUtils: getInstance ()-> getValueVectorFromFile (fullPathForFilename); ② _ numberOfSprites = vec. size (); ③ // load the texture for (auto & e: vec) ④ {auto row = e. asValueMap (); auto filename = "icons/" + row. at ("filename "). asString (); Director: getInstance ()-> getTextureCache ()-> addImageAsync (filename, CC_CALLBACK_1 (HelloWorld: loadingCallBack, this); ⑤} return true ;} void HelloWorld: loadingCallBack (Texture2D * texture) ⑥ {++ _ numberOfLoadedSprites ;__ String * str =__ String: createWithFormat ("% d %", (int) (float) _ numberOfLoadedSprites/_ numberOfSprites) * 100); ⑦ _ labelPercent-> setString (str-> getCString (); required Size visibleSize = Director :: getInstance ()-> getVisibleSize (); int I = ++ _ imageOffset * 60; auto sprite = Sprite: createWithTexture (texture ); export sprite-> setAnchorPoint (Vec2 (); addChild (sprite,-1); sprite-> setPosition (Vec2 (I % (int) visibleSize. width, (I/(int) visibleSize. width) * 60); if (_ numberOfLoadedSprites = _ numberOfSprites) Then {_ numberOfLoadedSprites = 0 ;}}


Line ① Of the above Code is to obtain the full path of the ImageMetaData. plist file under the Resource Directory. The ImageMetaData. plist file is defined to describe the name of the icon file to be loaded. The file content is as follows:
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0">  <array>    <dict>      <key>filename</key>      <string>01-refresh.png</string>    </dict>    <dict>      <key>filename</key>      <string>02-redo.png</string>    </dict>    <dict>      <key>filename</key>      <string>03-loopback.png</string>    </dict>    <dict>      <key>filename</key>      <string>04-squiggle.png</string>    </dict>   … …    </array></plist>


The ImageMetaData. plist file is an attribute list file and its internal structure is an array type. We can read the value from the getValueVectorFromFile function of the Code FileUtils to the ValueVector type variable vec. Line ③ code _ numberOfSprites = vec. size () is used to obtain the length of the array, and then assign the value to the member Variable _ numberOfSprites to calculate the loading progress.
The Code in line ④ traverses the array cyclically. Each element in the array structure is a key-Value Pair structure, and the structure statement of the obtained key-value pair is auto row = e. asValueMap (). Then, use the statement row. at ("filename"). asString () to retrieve the value corresponding to filename from the key-Value Pair object row.
The fifth line of code calls the addImageAsync function of TextureCache to asynchronously load the image cache. HelloWorld: loadingCallBack is the callback function. this parameter indicates the target object of the callback function.
The sixth line is the implementation of the callback function we have defined. The expression (int) (float) _ numberOfLoadedSprites/_ numberOfSprites) * 100 in line 7 code can count the installation progress. "% d %" indicates the percent sign, % d is used to format the output number. % Is the output %. The preceding % is used as an escape. The code _ labelPercent-> setString (str-> getCString () in the nth line indicates the content of the Progress tag _ labelPercent.

The first line of code auto sprite = Sprite: createWithTexture (texture) is used to create a sprite object through the texture object texture. The first line of code if (_ numberOfLoadedSprites = _ numberOfSprites) is to determine whether the task is completed, _ numberOfLoadedSprites is the number of images already installed, and _ numberOfSprites is the number of all images to be installed.


More content please pay attention to the first domestic Cocos2d-x 3.2 version of the book "Cocos2d-x practice: C ++ volume" book exchange discussion site: http://www.cOcoagame.net
For more exciting video courses, please follow the Cocos course in Zhijie class: http: // v.51wOrk6.com
Welcome to the Cocos2d-x Technology Discussion Group: 257760386 welcome to the knowledge of the iOS classroom public platform


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.