본문 바로가기

Cocos2d-x v3.17/고급 기능

[Cocos2d-x 고급기능]그래픽 성능 최적화 및 SQLite

반응형

    그래픽 성능 최적화

    황금 법칙

    28법칙


    프로그램에서 20% 코드가 80% 성능을 잡아먹는다는 뜻이다.우린 끝까지 이런 원칙을 준수해야 할것이다.

     

    이만하면 별차이 없다 원칙

    만약 두종류의 방식으로 어떤 이미지를 렌더링할떄 보기에 어떤 렌더링효과가 더좋은지 잘모르겠을땐 성능소모가 적은 방식을 사용하라.

    우린 RGBA4444 픽셀포맷의 PNG이미지의 질량이 RGBA8888픽셀포맷보다 퀄리티가 떨어지는것을 알고있지만 만약 게임효과에서는 눈으로 보기엔 똑같아보이면 RGBA4444 픽셀포맷을 계속 사용해야 한다.

    왜냐면 메모리문제  대역폭문제의 발생 가능성도 아주 낮기 때문이다.

    오디오 파일도 마찬가지이다

     

    타겟 디바이스와 게임엔진을 이해하기

    목표로한 디바이스의 CPU/GPU 이해해야 한다.

    어떤 성능문제가 어떤 기기에서 발견된다면 찾기어렵지만 이해를 한다면 그것들이 하나의 GPU 공유하는걸 알수있을것이다.

    그다음 면밀하게 분석하여 버그를 고치면 된다.

     

    현재 사용하는 게임엔진을 이해하는것은 굉장히 중요하다.

    만약 엔진의 그래픽 처리 명령이 어떻게 만들어져있는지,어떻게 렌더링과정을 거치는지를 알면 코딩과정에서 많은 함정을 피할수 있다.

     

    분석도구 사용

    많은 툴들이 그래픽성능분석에 사용되고 있다.

    우리가 Android게임의 성능을 최적화하고 싶다면 Xcode 사용하여 디버깅해볼수 있다.

     

    3 모바일 GPU공급 업체이다.그래픽 분석툴도 제공한다.

    만약 당신이 그래픽성능에 문제가 생기면 이런툴들을 사용하면 된다.

    하지만 그전에 먼저 CPU 문제되서 성능문제가 생기는건 아닌지 체크해봐야 한다.

    아무렇게 넘겨짚지 말고 분석하여 결과를 예측하여야 한다.


    병목현상

    경험으로 말하자면 게임의 성능문제는 GPU보다 CPU에서 더욱 많이 발생한다.

     

    CPU성능 최적화

    Draw call 횟수가 많으면 게임루프의 계산량이 너무 커서 CPU성능에 문제가 생길수 있다.

    어떻게든 Draw call 줄이고 Batch drawing 사용하여야 한다.

    Cocos2d-x 자동 Batch Drawing 지원하는 기능이 있다.하지만 자동으로 해주는건 아니기 때문에 작업을  해줘야 한다.

    게임이 돌아갈때 IO작업은 최소한으로 해야한다.

    으로 이미지,음악,TTF폰트등을 pre-loading 하자.

    더욱이 게임루프가 돌아가고 있을때 무거운 계산은 피하자.이것은 프레임당 60번의 많은 계산을 하게되고 성능소모는 무시무시하다.

     

    GPU성능 최적화

    만약 그냥 2D게임을 개발하고 복잡한 Shader 사용되지 않는다면 기본적으로 GPU성능 문제를 일으키진 않는다.

    하지만 over Draw 문제는 여전히 있다.만약 over draw 많다면 많은 대역폭을 사용하게 되고 이로인해 GPU성능이 저하된다

    아무리 현재의 GPU TBDR(타일기반 디퍼드 렌더링)아키텍처가 적용되있지만 PowerVR HSR(숨은공간 삭제)만이 over Draw 문제를 감소시킬수 있다.

    다른 GPU 오직 TBDR  early z test 수행한다.따라서 over Draw 문제는 불투명한 기하도형을 그릴때만 감소된다.

    Cocos2d-x 멀리있는 객체부터 렌더링 명령을 한다.

    이렇게 하면 2D중에서 여러 투명 그래픽이 있어도 혼합되게 그려진다.

     

    Cocos2d-x  성능최적화를 위한 

     

    1. 항상 batch Drawing 하라.같은 레이어에 존재하는 스프라이트 이미지를 하나의  Sprite Sheet 패키징하라.
    2. 경험에 따라서 얘기하자면 Draw call 50 이하로 유지하도록 노력해야 한다.어찌됬든 최소한으로 하면 된다.
    3. 在 原始 32 位(RGBA8888)理上,先使用 16 位(RGBA4444 + 抖)的理方式 RGBA8888 형식의 텍스처에서 16비트 처리방식을 사용해야 한다.
    4. 텍스처 압축을 사용하려면 IOS에선 PVRTC텍스처를 사용하고 Android플랫폼에선 ETC1 사용하라.하지만 ETC1 alpha pass  없기때문에 사용자 정의 쉐이더를 작성하고 알파 채널에 대해 별도의 ETC1 이미지를 제공해야  수도 있다
    5. 시스템폰트를 점수카운트를 표시하기 위해 사용하지 마세요.엄청 느립니다.TTF  BMFont 사용하세요.BMFont 빠릅니다.
    6. 사운드나 다른 게임객체를 사용하기 전에 필요한 파일을 미리 읽어놓으세요.
    7. armabi-v7a 사용하여 Android 프로젝트를 빌드하는것이  좋습니다.
    8. Light bake 사용하고 동적조명을 사용하지 말라.
    9. 복잡한 픽셀Shader 사용하지 말라.
    10. 픽셀Shader에서 alpha test   픽셀 드롭을 사용하지 말라.이것은 HSR최적화에 영향을 줄수있다.

     

    출처: <http://cocos2d-x.org/docs/cocos2d-x/zh/advanced_topics/optimizing.html>

     

    SQLite

    SQLite is a self-contained SQL database engine. This means there is no server involved. SQLite runs while your game is running and you write code to connect to the database and manipulate its contents. This is by no means a comprehensive guide, in fact, we cover 1% of what SQLite can do for you. Please read their website for a lot more detail as to what functionality SQLIte offers developers.

    Getting Started.

    In-order to use SQLite you must download it and add it to your project. Please see the SQLite Downloadspage for more details. For our purposes you will just need sqlite.h and sqlite.c in your project. Add these files to your environment and make sure they are part of your build process.

    How Does SQL Work In A Game?

    Now that you have SQLite you must understand how using a database in your app works. There isn't any automatic benefit, unless you code it. There are no wizards and no functionality for free. This is hand coded, by you, to meet your specific needs. Generally speaking, you will need to evaluate the following:

    • Does your database already exist?
    • Yes? Connect to it.
    • No? Create it, probably using create table queries. Then connect to it.
    • Are you connected to the database?
    • Yes? Issue queries against it to achieve your goals.
    • No? Connect to it, then issue queries against it to achieve your goals.
    • Do you need to update your database based upon player achievements?
    • Yes? Run insert/update queries to change the database.
    • No? Probably select queries are enough to use the database to drive your game play.
    • Is the player done with your game?
    • Yes? Make sure to close the database when your game exists. Failure to do so may corrupt your database and make it unusable.

    Basic Database Creation And Manipulation

    Let's cover how to create a simple database, connect to it and then manipulate it.

    Creating A Simple Database

    In order to use your database, it must exist. SQLite is file based. Simply creating a new file to house your database is sufficient. Notice that we use a .db file extension to help notate that this is indeed our database. It is also important to understand where the database lives on the players device. When you create the database it must be put in a location that the device allows the player to write data to. Cocos2d-x helps make this easy with a file system API called getWriteablePath(). Here is an example:

    sqlite3* pdb;

    pdb = NULL;

    std::string dbPath = cocos2d::FileUtils::getInstance()->getWritablePath() + "mydatabase.db";

    int result = sqlite3_open(dbPath.c_str(), &pdb);

    if(result == SQLITE_OK)

      std::cout << "open database successful!" << std::endl;

    else   

      std::cout << "open database failed!" << std::endl;

    With the database open, you can now use it.

    Creating A Table

    Databases use tables to store data. You need at least one table in your database. The caveat is that you must know what data your table will contain in-order to create it. You can always use the SQL alter tablecommand if at a later tine you need to modify your tables structure. This is outside the scope of this document, however. Creating a simple table:

    int result = 0;

    std::string sql;

    sql = "create table " +

    std::string("Master") +

    std::string(" (id TEXT PRIMARY KEY, value INT);");

    result = sqlite3_exec(pdb, sql.c_str(), NULLNULLNULL);

    if(result == SQLITE_OK)

    {

      // table created successfully

    }

    else

    {

      // table was NOT created successfully

    }

    Querying Data

    When you want information from your database you must execute a select query to get it. A select query is a read-only query. You don't have to worry about accidentally modifying your game data when running these types of queries. An example select query;

    std::string key = "Brown";

    std::string sql = "SELECT NAME " +

    std::string(" FROM ") +

    std::string("Master") +

    std::string(" WHERE id='") +

    std::string(key.c_str()) +

    std::string("' LIMIT 1;");

    sqlite3_stmt* statement;

    if (sqlite3_prepare_v2(&pdb, sql.c_str(), -1, &statement, 0) == SQLITE_OK)

    {

      int result = 0;

    while(true)

      {

          result = sqlite3_step(statement);

    if(result == SQLITE_ROW)

          {

              // do something with the row.

          }

          else

          {

              break;

          }

      }

    }

    Inserting Data

    You may need to insert data into your database to use again at a later time. Use an insert query to do this. Example:

     

    Updating Data

    Closing The Database

     

    출처: <http://cocos2d-x.org/docs/cocos2d-x/zh/advanced_topics/sqlite.html>

     

    출처: http://dygks910910.tistory.com/24?category=295210 [요하네스벅의 블로그]

     

    출처: <http://dygks910910.tistory.com/24?category=295210>

     


반응형