当前位置:   article > 正文

Unity3D Engine Architecture_unity architecture

unity architecture

原文:http://www.umingo.de/doku.php?id=paper:mechs_and_tanks:section03

Architecture

To better understand the game's software architecture and object model it is useful to get a better look atthe Unity3D Game Engine and editor and it's key principles.

Unity3D Engine

Unity3D is an award winning tool for creating interactive 3D applications on multiple platforms.Unity3D consists of a game engine and an Editor. The engine contains software components for the most common and recurring tasks in game developement. The topics covered by the engine include sound, graphics, physics and network functions. The engine supports C-Sharp, Boo, and JavaScript for script programming.

The other component is the Unity Editor that serves as an integrated development environment with a project panel for scripts and other components, a hierarchical object inspector containing the game scene setup and a game preview window (see figure 4).It also comes with several multi-language script editors and a unique prefab system that will be explained later.

Figure 4: The Unity Editor
Figure 4: The Unity Editor

There are several licenses available for Unity. Unity Basic with limited features is free for PC, MAC and Web development.Other platforms or full feature set require an additional license purchase [15].

Although there are many free and proprietary alternative game engines like the Unreal Engine™ or the C4™ engine the choice fell on Unity for the following reasons:

* It is possible to deploy to Windows, Mac OSX, Web Browser, Wii, iPhone, iPad, Android, XBox 360 and Playstation 3. It is even planned to add Flash and linux deployment in the future. The deployment possbilities offer many possibilities to use the game engine or the games created with the engine for monetizing or further studies. * The Unity community is very supportive and the engine as well as the editor are well documented. * The engine is relatively easy to learn and to work with and supports the idea of rapid software development by providing all tools for quick prototyping and iterating as well as fast script compilation. * The iOS Basic license with possibility to deploy for iPhone, iPad and iPod touch comes at a relatively low price compared to other vendors. Mechs and Tanks was created with Unity 3.0, C-Sharp scripting and the MonoDevelop IDE for development. You can find a Unity Tutorial in Appendix.

Brief History of Unity3D

The following dates illustrate the evolution of the Unity Engine between 2001 and 2011 [16].

  • 2001 Unity Technologies started to develop their game engine in 2001. The main incentive at the time was to create games and to create a good tool as a foundation for these games [1].
  • 2003 In 2003 the company noticed that the resulting engine would be a great product on its own.
  • 2005 In 2005 Unity 1 launched onstage at Apple's WWDC.
  • 2007 Unity 2.0 launched in 2007 and added a terrain engine, real-time dynamic shadows and video playback among others.
  • 2008 In 2008 Unity iPhone launched and the Cartoon Network introduced FusionFall, a game that has been played by more than 8 million people.
  • 2010 In 2010 Unity 3.0 with dozens of new features like asset management and beast lightmapping was released.
  • 2011 Unity surpassed 500 000 developers and 60 million web-player installations.

Game Architecture

Mechs and Tanks' architecture consists of the module- and the Unity scene-architecture.

Main Modules

This section describes the most important modules and their relations.The game's architectural style on a subsystem level is an object network with data capsules.The following UML component diagram illustrates the subsystems and their relations.

Game logic

This module manages the current player and AI configuration the countdown timerand the current game state (paused, waiting for network reply..).

AI

The AI module contains the logic behind unit-, group- and player-AI.The unit AI makes use of diverse steering behaviours for pathfinding or obstacle avoidance and controls a unit's state.The group AI manages a group's behaviour and things like group pathfinding. On a higher level all the player's groups are managed by a player module.

The machine learning AI saves and loads it's data using the interface of the persistant data module.

Persistant data

This module is responsible for saving and loading data that should be available between different game sessions.Among others, it stores lookup tables and graphs for the pathfinding module and manages the machine learning AI's accumulateddata.

Game actors

Game actors are terrains, units or buildings in the game. Their 3D models get passed to the Unity3D rendering pipeline for visualization. Every game actor owns references to the AI modules that control it's behaviour.

Steering behaviours

Steering behaviours calculate forces that influence how and how fast an autonomous game agent should move.They can be used for obstacle avoidance, crowd movement or simple seeking tasks [8].

Pathfinding

This module is responsible for the creation of a pathgrid, gathering of obstacle information and for providing aninterface for various pathfinding requests. For better performance some information is saved to and loaded from the disk.

Input

This module keeps track of the user's input, processes it and generates the feedback.

Network

The network module is responsible for managing all game actor's states in a network game.Another responsibility is to keep the game state consistent on both machines and to avoid jittering in network unit movement.

GUI

The graphical user interface (GUI) displays all buttons, menus, the minimap and the countdown timer. It is also responsible for these element's functionality and interacts heavily with the game logic module for this purpose.

3D rendering

This module is mainly managed by Unity3D. The scene's main camera determines the objects that need to be rendered and sends them through the rendering pipeline. Unity3D encapsulates most rendering details but also offers access through pixel and vertex shaders.

Unity Scene Setup

Every map in the game is represented by a Unity3D scene. Here is what a typical scene setup in the Unity Hierarchy (a) and in the scene window (b) looks like:

A map in the Unity Hierarchy
A map in the Unity Hierarchy

A map in the Scene View
A map in the Scene View

Now all game objects from the top to the bottom of the panel will be described.

CWalls

This object contains custom drawn wall nodes and wall edges. The alternative to using custom drawn walls is to calculatethem depending on the map's geometry.

Directional light

This light is only used to calculate the terrain lightmap. It is turned off afterwards due to performance reasons.

Game Music

Holds the game's main music and plays it on scene start.

GameController

The GameController GameObject holds and administers all GameObjects that manage the game's logic. It consists of the following objects:

CursorController

Manages the look and the logic behind the cursor.

GameInstantiator

This important GameObject is responsible for instantiating other objects that need to be created in aspecific order.

GameInstantiator in the InspectorGameInstantiator in the Inspector

GameController in the HierarchyGameController in the Hierarchy

The GameInstantiator holds referenes to the buildings on the map, the PathCreator for path creation and obstacle management, the Player GameObject that manages player-configuration and -settings, the InputControl GameObject that is used to process user input, and a reference to the PlayArea GameObject that defines the playable area of a map.

It also contains references to the player's spawn points and custom paths and walls.

GUI

Holds all the map's GUI objects.

MachineLearningController

This GameObject controls all functionality that is needed for machine learning.

spawn1, spawn2

The actual player spawn points. Spawn points are marked by green cubes in the Scene View.

HPaths

Custom path nodes and edges of the map. Custom nodes are labeled in the scene editor and outlined with red lines.

Main Camera

The scene's main camera and audio listener. All 3D sounds are observed from the camera's perspective.

PlayArea

Defines the actual playable area of a map.

Base Prefabs

The buildings that are scattered on the map.

Terrain

The Unity terrain object.

TestRunner

A GameObject that is used to run unit tests made with the Unity3D unit testingframework SharpUnit [17].

MVC Pattern

The design of the Unity Engine encourages MVC (Model View Controller) oriented engineering.In my case the structure looks like this:

Figure 5: MVC pattern representation of the architecture
 
Figure 5: MVC pattern representation of the architecture

The model contains all GameObjects, their components and data files. It has access to the GameObject's renderers and the camera object.

The view renders the models and is mainly managed by the Unity3D Engine's renderers. It needs to accessthe 3D models, textures, materials and effects that are held by the model. It also has influence on what input options are available.

The controller receives user input and reacts by calling methods on model objects. It is represented by the Input subsystem in my game. The user can influence the view with his input.

Multiplatform Development

Unity allows to deploy a project on different platforms with minor changes.The presentation and functionality is largely maintained depending on the platform's capabilities.However, there are major differences in some areas like the input mechanisms on different devices.

The abstract factory design pattern was applied to design these components.

The Abstract Factory Pattern

Figure 6: Abstract factory pattern
Figure 6: Abstract factory pattern

The abstract factory pattern (see figure 6) protects a client from different platforms that implement the same concept in different ways.A platform is a set of AbstractProduct classes. These classes represent a concept that is supported on all platforms.An AbstractFactory class declares operations for creating single products, ConcreteFactory classes represent a specific platform.

The client only uses abstract factory and abstract product methods and is therefore protected from a platform's concrete implementation.

Input and Persistant Data

The two main aspects of the game that ask for different implementation are the input-mechanisms and the usageof persistant file data. Unity3D does not support cross-plattform databases. That is why Mechs and Tanks uses persistant data as binary files on the disk. All platforms got their own implementation in respect to their capabilities and supported file formats.

In order to maintain readability and flexibility the following adaption of the abstract factory pattern for cross-platform input processing was used:

Figure 7: Excerpt of the Input subsystem structure
Figure 7: Excerpt of the Input subsystem structure

This is only a little excerpt of all the involved platforms and commands, chosen for demonstration purposes.

The InputManager gets attached to the InputControl GameObject in the scene. It calls the CommandImplementor's Execute method every frame inside the Update function. The Execute method of a CommandImplementor iterates through all added commands, checks if their execute condition is satisfied and calls their Execute method, if so.

These are the components of the Input subsystems's diagram in respect to the abstract factory pattern:

 Component in the input subsystem
ClientInputManager
AbstractFactoryCommandImplementor
ConcreteFactoryCommandImplementorWindows, CommandImplementorIphone
AbstractProductCommand, InputMoveCamera, InputHover, InputMultiselect
ConcreteProductInputWindowsMoveCamera, InputIphoneMoveCamera InputWindowsHover, InputIphoneHover,InputWindowsMultiSelect, InputIphoneMultiSelect

iOS+Unity

Mechs and Tanks was created with a process of iterative development, which is the reason why the game was already playable before any adjustments for the iPad™ were made.

This chapter describes and analyses the challenges and solutions of porting Mechs and Tanks to the iPad™ .

Maximum Polygon Count

One of the most obvious restrictions for iPad™ games is the number of polygons the graphics chip is able to render each frame.It turned out that more than 30 000 polygons per frame started to drop the framerate below 25 FPS on the iPad™ . After reducing the polygon count inside a 3D modeling software by manually removing edges and applying pre-defined algorithms for polygon reduction and even rebuiilding some models from the start, the current polygon counts on all platforms are:

 MechTankRunnerBuilding
Polygon count350226356385

The average polygon count is about 300 per unit. If all 24 enemy and player units are captured by the camera in one frame the resulting polygon count would be 7200 on average and about 8500 in the worst case of 24 runners.Adding the maximum 4000 terrain polygons (the rest of the terrain gets frustum culled), the heaviest frame would give the GPU about 12 500 polygons to render.

Draw Call Reduction and Lights

Even more important for decent performance on mobile devices is the number of draw calls per frame. A draw call is issued to the GPU every time a model is drawn. If the model has n submeshes it will cause at least n draw calls.Every GUI texture, selection plane and health bar adds one draw call to the scene.

Another source for additional draw calls is per pixel lighting that causes an additional draw call for every light pass.That is why all submeshes in a model were combined into one and models don't use dynamic lighting at all. The lights for all model and terrain textures are baked in. Light and shadow baking calculates the brightness for each texel that gets illuminated by static light sources and lays a lightmap over the texture. The models look as if they are effected by lights although no calculations are made. Figure 8 shows a few models without lightmaps or light effects.

Figure 8: Screenshot with Unlit Texture material shader and no light baking for models
Figure 8: Screenshot with Unlit Texture material shader and no light baking for models

Figure 9: Game view with expanded stats window in the top right corner
Figure 9: Game view with expanded stats window in the top right corner

It is to say that Unity can combine a number of objects, sharing the same material, at run-time and draw them together in a single draw call. This method is called dynamic batching [18].Figure 9 shows a scene with 66 draw calls that are caused by the following sources:

GUI

8 draw calls for buttons, minmap, countdown and countdown text + 24 unit map spots + 8 building map spots + 1 camera map spot. Sums up to 41 GUI caused draw calls.

Terrain

4 draw calls. One for each texture.

Visible Models

14 draw calls. Each model would cause 3 draw calls on its own. One for the unit mesh, one for the healthbar mesh and one for the selection plane mesh. The low number can be explained with Unity's dynamic batching.

Terrains

Unity3D did not support terrains for iOS until Unity 3.4 was released in July 2011 [19].In order to find the best solution for Mechs and Tanks, two alternative ways for terrain implementation have been tested: * Modelling terrains in a 3D program: Creating a terrain in a 3D modeling program and segmenting it into different parts (see figure 10).The partitioning has the effect that most segments are frustum culled by Unity. That meansthat only the segments that are at least partly visible get rendered.

Figure 10: Modelled terrain with highlighted parts
Figure 10: Modelled terrain with highlighted parts

This technique was discarded because the process of creating new terrains gets very complicatedcompared to the Unity terrain system and the texture size is either very large or the quality suffers. * Terrain for mobile systems: Terrain for mobile systems is a solution that is available on the Unity Asset store and can convert Unity terrains to T4M terrains whichcan be used on mobile devices. It turned out that the performance of this solution was not sufficient for the game.

The final terrain solution was using the Unity terrain engine with very low quality settings. That was only possible after Unity 3.4 was released in July 2011 and added support for Unity terrains on mobile systems.

GUI-Optimization

The Unity engine offers two ways to implement the GUI. One way is to use Unity's GUI system UnityGUI that needs it's functions to be calledinside a special function called OnGUI(), that is executed twice every frame and onceevery event. This system is only used for the main menu and the pause menu, where allvalues needed are calculated outside the OnGUI function.

GUI Textures are used for all other GUI elements like GUI buttons and the minimap to sustain performance. GUI Textures are flat images that are displayed in 2D and only rendered once per frame.

Script-Optimizations

In order to grant high script performance the most expensive methods were tracked with a profiler.It turned out that the most expensive methods are called either by the pathfinding or the steering behaviour subsystem. Pathfinding has been optimized as described below in the AI section. It was also made sure that costly functions like steering behaviours and other AI routines don't get called every single frame.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/118118
推荐阅读
相关标签
  

闽ICP备14008679号