---
# System prepended metadata

title: Basic
tags: [ctrl]

---

---
title: "Basic"
disqus: hackmd
tags: 'ctrl'
---

## Chapter 1 The Basic Design of the SGC Program

#### 1-1 Cloud Service and the API Object Model

There are four kinds of SGC cloud services, and they cover almost every function it needs to operate a multiplayer game.
(1) For the scene services that are mainly about in-time communication, the main api program is CloudGame and CloudScene.
(2) For the services that are mainly about storing and obtaining data, the main api programs are CloudItem, CloudScore, CloudGuild, and CloudMailbox.
(3) For the services about the system’s operation, the main api program is CloudSystem.
(4) For the services about e-commerce, the main api program is CloudShop.
   
The Cloud API object model has nothing to do with programming languages. In order to explain easily, the API object model reference books that SGC releases are in the C# language.

Since the Cloud API object models are very easy, developers’ difficulties in learning them decrease and for beginners, they are easy to get started with. However, SGC provides services in online game-making and all-around solutions in operating. Therefore, despite the fact that it is easy to learn Cloud API, its coverage and functions are not perfunctory.
         

The Cloud API has eight classes in total, which cover almost every function one needs to operate a multiplayer game:
          
![](https://i.imgur.com/rAhBP2F.png)

The classes are independent of each other with no object-oriented succession relationships. However, they have subsequence order when functioning. Except for CloudGame and CloudScene, the other classes only provide static methods.

- CloudGame
    API’s main category. There must be a CloudGame object before building any other ones, which means there has to be a Game first, and then follow the game’s other functions, such as Scene, Item, Score, Shop, and more.

- CloudScene
  The scene is the foundation of interactions with players. CloudScene is for managing the game’s scenes. Except for sending and receiving messages, CloudScene also contains some functions related to interactions with players.

- CloudItem
  Objects are the player’s personal data when the game is operated, and CloudItem is for managing the data.

- CloudScore
  Recording the game’s score, adding up the score by the server, and creating a Leaderboard.


- CloudShop
  A Server Product Delivery service used in iOS’s in-app purchase and Android’s in-app billing that guarantees the stability and safety of the purchase.

- CloudGuild
  Creating and managing a guild, including data such as the guild’s members, the guild’s basic data, and more.

- CloudMailbox
  The mailbox in the game. This class is for sending and reading offline messages from players and guild groups. The messages are stored in the cloud and occupy the game’s storing capacity.


### 1-2 Asynchronous Non-Blocking API

When it comes to a time-consuming API, SGC uses an asynchronous non-blocking design. When calling, one has to designate a callback function to let API notify the caller by the callback function after finishing its work.
        
A callback is a function designed by the developers themselves and is called by the API work program that functions in the background,, and if API has data to send back after completing its work, the data are considered parameters and are sent back to the developers’ program when calling a callback.
        
![](https://i.imgur.com/a5qGYI5.png)


Send the callback function to API as a parameter, and when the API completes its work, it will call this callback function. Also, the token object will be sent to the callback function and remain unchanged. This design makes the callback function connect to the caller’s program and allows them to deliver data with a shared token object.


There are two function prototypes for the callback function, which are `OnCallCompletion` and `OnCallCompletionWithData`:

- OnCallCompletion


Only send back the integer code of the function’s execution result and execute the result according to the code. The definition of the `OnCallCompletion` function is:

> `void OnCallCompletion(int code, object token);`

- OnCallCompletionWithData


Aside from the result code, the data object’s data are also sent back. Program designers can cast the data object to the correct type according to the API function’s respective definitions, and then have the ability to access the data API obtains after its execution:

> ` void OnCallCompletionWithData(int code, object data, object token)`;


The callback function’s last parameter `token` is an object parameter sent in when calling API. Program designers can input any data into it, and the data will be sent to the callback function and remain unchanged after API completes its execution. Such framework allows program designers to use the same callback function when calling different APIs or calling them several times. Then, the contents of the `token` parameter distinguish which one of the operations initially calls API, and thus decrease the workload of writing callback functions.

### 1-3 Design for Multi-Thread Programs


The Cloud API supports design for multi-thread programs. When it comes to problems with the synchronization of multi-thread programs, please create a CloudGame object in the main thread, and API will trigger an Event in the main thread. 
          

In the previous section, we already introduced that time-consuming API functions under an asynchronous non-blocking design. When the function returns, it does not mean its work is completed. The system will call the callback function with the main thread after the work is completed. Even when API is not called in the main thread at the beginning, the eventual callback will still be executed in the main thread.
        

Also, because the API event and the callback are both called in the main thread, when they are triggered, they can control the app’s UI component directly. In a system that mostly allows the main thread to control the UI component, this is a rather convenient design.

       

Since there are certain connections between the main thread’s operation and the app’s display, program designers should not execute a program that is too time-consuming in the main thread to avoid Lags when operating the app.
     

Some possible program structures are listed below, and please follow the principles when designing your app.

- Processing the event-dealing program is not time-consuming.
  ![](https://i.imgur.com/mJtlELr.png)
- Processing the event-dealing program is time-consuming and cannot be finished immediately.
  ![](https://i.imgur.com/VEeeuwM.png)

- Processing callback is time-consuming and cannot be finished immediately.
  ![](https://i.imgur.com/5eqI6JV.png)

### 1-4 Event Handler

There are two ways to write an event-handler program:

- Override Event Handler
  Program designers design a sub-class succeeding the Cloud API class by themselves, and then rewrite the event-handler function in this class.

```csharp
 ...
 MyCloudGame mag = new MyCloudGame();
 mag.Launch();
 ...
 public class MyCloudGame : CloudGame // MyCloudGame succeeds from CloudGame
 {
  private const string userid = "...";
  private const string passwd = "...";
  private const string gguid = "...";
  public static byte[] cert = { ... };
  public MyCloudGame() : base(userid, passwd, gguid, cert) {}
  protected override void OnCompletion(int code, CloudGame game)
  { // the self-defined event-handler function
  }
}
```

- Assign Eevent Handler
  With the “event function variables” in the object, designate the event-handler function the program designers designed to them. In this way, the Cloud API will execute the event functions defined by the developers.

```csharp
 ...
 private const string userid = "...";
 private const string passwd = "...";
 private const string gguid = "...";
 public static byte[] cert = { ... };
 ...
 CloudGame ag = new CloudGame(userid, passwd, gguid, cert);
 ag.onCompletion += new EventHandler(myCloudGameCompletion,CloudGame game);
 ag.Launch();
 ...
 private void myCloudGameCompletion(int code, CloudGame game)
 { // the self-defined event-handler function
 ...
 }
```


Please be aware that if one neither designates an “event function variable” nor overrides the event-handler function, no program code designated by the program designers will be executed when the event is triggered. Also, the Cloud API will not start any inner operation. In other words, the event fails. Although this does not lead to errors in compiling or executing, program designers should try to avoid making the API event ineffective, for the fact that the Cloud API already simplified much work and all the events it defines should be handled.

### 1-5 Game Management

When using the Cloud API, one has to coordinate with the game management in developers’ backstage and manage the game’s functions, such as the scenes, the objects, the leaderboards, the guilds, the mailboxes, and more, by game.

- Game - When developers decide to make a new game, please go to developers’ backstage to create a new “game developing project,” and then it can be coordinated with the API’s CloudGame class. After inputting the “game’s name” and the “note” when creating a new game, the data in these two columns will be on the player’s website of Cloud. They are also text descriptions for players to know about the game.
- Scene - The game’s scenes can be separated into the “static scenes” and the “active scenes.”

- Static Scenes - The static scenes already exist when the game system is created, so there can be no replica. Players can enter or exit a static scene but cannot delete it.

- Active Scenes - The active scenes do not exist when the game is created, and players can create replicas in the game according to the game’s mechanism. An active scene’s replica that is already built is a scene that already exists in the game, and players can enter or exit it.
  

- Item - The CloudItem class is for managing the items in the game, which are separated into “merchandise,” “attributes,” and “data,” according to their functions. When developers create a new item backstage, the added object must be set to belong to one of the categories based on the needs. “Merchandise” are items that can be sold to players in the game, usually treasures or tools. “Attributes” are for defining the characteristics, measurements, and more, of the game’s characters, scenes, items, and so on. They can also be used to define treasures or tools that are not sold in markets. “Data” are for recording all kinds of players’ data in the game and can also be considered the variables that the players’ game programs stored in the servers.

- Leaderboard - The CloudScore class is for processing the player’s scores in the game, which can also be used to output a player’s score ranking or record a player’s personal scores. The leaderboard is a total, daily, weekly, or monthly ranking, and one can set to execute an item setup after an event is triggered. For example, if we want to give out a certain treasure tool to those top-ranked players, developers only have to set the event trigger of the leaderboard backstage without writing another scheduler program.

- Guild - A guild equals the players’ group in the game, but unlike the scenes, the items, and the leaderboard, a guild does not have a class or an instance’s item structure. Therefore, unlike the scenes, the items, and the scoring board, which need a backstage management class library, a guild still needs the API execution authorization for safety. 

- Mailbox - Mailbox is an offline storage system of the players’ messages. It can send messages to the player one-on-one or to the guild’s members.

### 1-6 Game Data



Game data is stored in the so-called cloud database. SGC already designed special database systems considering the characteristics and needs of multi-player games and separated the systems according to their functions. Developers only have to use the corresponding API access database.

- Personal Data
  The player’s personal data consist of the Item Instances, the personal Score, the Mailbox, the registers (AX, BX, CX, and DX), and the R registers (R1, R2, R3, and R4).
  ![](https://i.imgur.com/rxWP5HA.png)

- Public Data
  The game’s public data consist of the Item Class, the Leaderboard, the Guild, and the G registers (G1, G2, G3, and G4).


A register is a game data with a special function, and only 32-bit integers are allowed. When calling some API to obtain array data, it can designate how the arrays are ordered. There are three kinds of player’s registers, which are the main registers (AX, BX, CX, and DX), the R registers (R1, R2, R3, and R4), and the G registers (G1, G2, G3, and G4). Every player has the main and the R registers, but only players who join a guild get the G registers. 

Since Cloud does not define the functions of register data, developers can define them by themselves. For example, the R1 and R2 registers can be defined as the player’s hit value and experience point. If there is going to be a corresponding Item Instance Attribute in the instances, developers can use CloudItem.SetItemInstanceAttribute() to write in both the item’s attribute and the registers at the same time.

The below picture is a data storage structure of a player in a Cloud game:
![](https://i.imgur.com/BC4lNw5.png)

When there are many players, every player has their own personal data section, and thus forms the data storage structure like the below picture:
![](https://i.imgur.com/00r3zYC.png)

### 1-7  The Server Logic

To ensure the game mechanism’s safety and fairness, developers sometimes have to write a centralized game management program as an extension of the game server’s function. Such a management program is called the game server logic. Cloud uses the Distributed Plugin (or say DP) technology to realize the server logic functions, and therefore we can call the server logic DP.

Normally, the server logic has the below functions:

- System Monitoring and Recording - When every logic control about the game’s procession is sent to DP through the game’s program of the user’s edge, DP records these control messages or monitors abnormality so that the managers can always handle the game players’ situations.
- 
- Scene Control - Scene control is one of the functions in the game lobby, and it includes the creation and deletion of the scene replicas and monitoring the players’ entrance and exit of the game scene, such as controlling the number of players, automatic pairing, managing access authorization, and more.

- Arbitration - Make the logic control programs, which are distributed in the game programs on the user’s edge, function altogether in DP to avoid dis-synchronization in different players’ user-edge programs.

The main reason for designing DP is to extend the game server’s function, and Cloud allows developers to create the game’s own server without having expertise in designing advanced game server programs. Since DP is simply a data-processing program, its design is easier than that of the user-edge game program and the API it uses is the same as that when designing the game program. Also, the account and password that connect DP and the Cloud server is a normal player’s account, for which developers have to apply in the Cloud website. According to the principles of account management, please make DP the account’s only user and do not log into the game with it.
![](https://i.imgur.com/6vR6sco.png)

### 1-8 Super User and Privilege Functions

A Super User, also known as a privileged user, is an account that DP uses to log in to the game. Since DP plays the role of being the central controller of the game, it has to be allowed to have the privilege to obtain other players’ data. To equip DP with this ability, Cloud provides the functions in CloudItem and CloudScore with the authorization on obtaining other players’ data, and these functions are called the “privilege functions.”

The privilege function can only be called when the logged-in account is a super user, or callback will send back an error code that says “not authorized.” The super user function's use and parameter are similar to those of the regular player function. The former function starts with “su,” and if that privilege function aims to operate certain players’ data, there will be an additional parameter “userid” in the function to designate a certain player’s account.

#### The Timing for Using the Privilege Functions

- Reading Data - When the game processes, the user-edge program can read the database at any time, which means reading the player’s data with CloudItem and CloudScore’s static functions. To increase DP’s efficiency, it is allowed to let normal users read the data unless the read data may be related to the game’s fairness. To avoid plug-in distributions, this kind of data should be read by DP.

- Writing in Data - Since writing in data is usually related to the game score, the game result, and the ranking, to avoid hackers’ illegal destruction, it is more adequate to let the DP program do the writing.

#### The Settings and Management of Super Users

Developers can set up all kinds of authorization in the Cloud game management backstage’s “authorization management.”
         
![](https://i.imgur.com/PeOvXmp.jpg)

There are two kinds of authorizations: for Super Users and for normal users:

- Super Users - (1) Designate a “Super User” account and only this account has the complete authorization on obtaining data from the database. (2) Desginate the obtained far-edge IP. For guaranteeing further safety when obtaining data, one can specify that a “Super User” account can only execute the complete data-obtaining from the database with a particular IP. There are three kinds of designated IPs:

|    Type     |                      Notes                     |
| :---------: | :--------------------------------------------: |
|     Any     |           there is no limit and any IP can perform the obtaining            |
| Single host |       designate a single IP and only this IP can perform the obtaining       |
|   Network   | designate a range for the IP and only one within th range can perform the obtaining |

- Normal Users - One can set the normal user’s authorization of obtaining data from the database, which are “no authorization,” “reading only,” “both reading and writing.”

#### Privilege Functions

Among the functions of CloudItem and CloudScore, there are privilege functions that super users can call. The differences between the normal users’ function and the privilege functions are:
          
| | type of users| the range of obtaining|  the way it performs designation |
|:--------------:|:----------:|:--------------:|:--------------:|
|  normal users’ functions| normal users | their own data| (none)|
|  privilege functions|  super users|  other players’ data| other players’ userids|
            
             
For the super users’ functions in CloudItem, please refer to the above API item model => CloudItem => Super Users to view all the functions.
          
For the super users’ functions in CloudScore, please refer to the above API item model => CloudScore => Super Users to view all the functions.   	
        
### 1-9 Downloading API
         
SGC supports the APIs of several programming languages and platforms, and here is the open status of the APIs:

|       platforms      |   programming languages   |  open for download |
| :--------------: | :-----------: | :--------: |
|  Unity3D game engine |      C#       |     V      |
|   MS Visual C#   |      C#       |     V      |
|       iOS        |  Objective-C  |     X      |
|     Android      |     Java      |     X      |
|       Java       |     Java      |     X      |
|      Flash       | Action Script |     X      |

Please go to the SGC developers’ website, log in with a developer’s account, and enter the download area to download API.           
