Starling Framework help manual Chinese version of "one"

Source: Internet
Author: User
Tags addchild constructor manual

Article transferred from http://www.adobe.com/cn/devnet/flashplayer/articles/introducing_Starling.html

What is Starling

Starling is a 2D image-oriented development framework based on the Stage3D API, developed using ActionScript 3. Starling is primarily designed for game development, but it can also be used in other situations. Stargling allows you to quickly write GPU-accelerated applications without having to touch the underlying Stage3D API.

Why Choose Starling

Most programmers want to use GPU acceleration (through stage 3D) without having to write such a high-level framework and drill down into the underlying Stage3D API. Starling is designed to fully follow the ActionScript API rules and abstract the complexities of low-level Stage3D APIs and allow for easy and intuitive programming for everyone.

Obviously Starling is for ACTIONSCRIPT3 developers, especially those 2D game developers, and of course you need to have a basic understanding of AS3. Through the design of Starling, it can also be applied to other use cases, such as UI programming. This means that anything can be designed to be as intuitive as possible, and programmers like Java and net always want to quickly get tips for terminating the code abnormally.

Philosophy

Intuitive

Starling is very easy to learn. Especially for Flash/flex programmers will feel at home, because it follows most of the ActionScript rules and abstracts the complexities of low-level Stage3D APIs. Starling uses familiar concepts such as the DOM display list, the event model, and familiar APIs such as MovieClip, Sprite, TextField, rather than relying on such things as vertex buffering (vertices buffer), The Perspective matrix (Perspective matrices), the shader program (shader programs), and the combined bytecode (assembly bytecode) are encoded.

Lightweight

Starling is very light in many areas. The number of classes is limited (approximately 80k of code). It has no external dependencies other than Flash Player 11 or AIR 3 (and mobile support used in future releases). These factors make your application small and make your workflow simple.

Free

Starling is free to use and vibrant. It is licensed under the simplified BSD license, so you can use it for free, even in commercial applications. We use it every day and we rely on an active team to constantly refine it.

How it works

In a background operation, Starling uses Stage3D apis-, which are low-level GPU APIs that run on the desktop based on OpenGL ES2 on the mobile device and on the on-screen basis of OpenGL and DirectX. It is important to note that Starling is the ActionScript 3 port of sparrow*, which equates to an ISO library based on OpenGL ES2 APIs (see Figure 1):

Figure 1. Stage3D (Molehill) layered on top of Starling

Starling has re-created many of the APIs that Flash developers are familiar with. The following figure illustrates the graphical element APIs exposed through Starling (see Figure 2).

Figure 2. Starling supports Displayobject inheritance

It may seem odd to create 2D content based on 3D GPU APIs. When it comes to Stage3D APIs, many people think that these APIs are strictly limited to 3D content. This is actually a misunderstanding of the name: if it's called Stage3D, then how can you use it to create 2D elements? The following figure illustrates the issue of drawing MovieClip capabilities using the Drawtriangles API (see Figure 3).

Figure 3. You can create 2D movie clips using the Drawtriangles API.

The GPU is highly efficient and can draw triangles quickly. By using the Drawtriangles API, you can draw two triangles, then pick a texture and apply it to the triangle using a UV map. This creates a four-sided shape with a texture that represents a sprite. By updating the texture of a triangle on each frame, the final result is a MovieClip.

Fortunately, we do not need to use Starling through these details. You just need to provide the number of frames and provide them to a Starling MovieClip, which is all you need to do (see Figure 4).

Figure 4. Using the Drawtriangles API and a textured quad, you can create a 2D graphic


To better understand how Starling reduces complexity, check the code you have to write to make it easy to display simple, textured quads with low-level Stage3D APIs.

Create the vertices var vertices:vector.<number> = vector.<number> ([ -0.5,-0.5,0, 0, 0,//x, Y, Z, u, v-0

.5, 0.5, 0, 0, 1, 0.5, 0.5, 0, 1, 1, 0.5,-0.5, 0, 1, 0]);

Create the buffer to upload the vertices var Vertexbuffer:vertexbuffer3d = Context3d.createvertexbuffer (4, 5);

Upload the vertices vertexbuffer.uploadfromvector (vertices, 0, 4);

Create the buffer to upload the indices var indexbuffer:indexbuffer3d = Context3d.createindexbuffer (6);

Upload the Indices indexbuffer.uploadfromvector (vector.<uint> ([0, 1, 2, 2, 3, 0]), 0, 6);

Create the bitmap texture var bitmap:bitmap = new Texturebitmap ();

Create the texture bitmap to upload the bitmap var texture:texture = context3d.createtexture (Bitmap.bitmapData.width,

Bitmap.bitmapData.height, Context3dtextureformat.bgra, false);

Upload the bitmap texture.uploadfrombitmapdata (bitmap.bitmapdata); Create the Mini assembler var vertexshaderassembler:agalminiassembler = new AgalminiassemBler (); Assemble the vertex shader vertexshaderassembler.assemble (Context3dprogramtype.vertex, "M44 op, Va0, vc0\n" +//POS

To Clipspace "mov v0, VA1"//copy UV); Assemble the fragment shader fragmentshaderassembler.assemble (Context3dprogramtype.fragment, "Tex Ft1, V0, Fs0 <2d

, linear, nomip>;\n "+" mov oc, ft1 ");

Create the shader program var program:program3d = Context3d.createprogram (); Upload the vertex and fragment shaders Program.upload (Vertexshaderassembler.agalcode,

Fragmentshaderassembler.agalcode);

Clear the buffer context3d.clear (1, 1, 1, 1);
Set the vertex buffer Context3d.setvertexbufferat (0, vertexbuffer, 0, context3dvertexbufferformat.float_3);

Context3d.setvertexbufferat (1, VertexBuffer, 3, context3dvertexbufferformat.float_2);

Set the texture context3d.settextureat (0, texture);

Set the shaders program Context3d.setprogram;

Create a 3D matrix var m:matrix3d = new Matrix3D (); Apply rotation to the MatrIX to rotate vertices along the Z axis m.appendrotation (Gettimer ()/50, Vector3d.z_axis); Set the program constants (matrix here) Context3d.setprogramconstantsfrommatrix (Co Ntext3dprogramtype.vertex, 0, M, tr

UE);

Draw the Triangles context3d.drawtriangles (indexbuffer); Present the pixels to the screen context3d.present ();


The code in the example above creates a 2D instance of a square (see Figure 5):

Figure 5. Using the Drawtriangles API and a textured quad to create a 2D object result

The code shown in the example above is undoubtedly very complex. That's a price to pay for accessing low-level APIs. On the other hand, you can control many aspects, but it requires a lot of code to set everything up.

With Starling, you can write the following code to replace the above code:

Create a Texture object out of a embedded bitmap
var texture:texture = texture.frombitmap (New Embeddedbitmap ()) ;

Create an Image object our of the Texture
var image:image = new Image (Texture);

Set the properties
Quad.pivotx =;
Quad.pivoty =;
Quad.x = +;
Quad.y =.
Quad.rotation = Math.pi/4;

Display it
addChild (quad);


As an ActionScript 3 developer who knows how to use Flash APIs, you can start working immediately with these exposed APIs, while all the complex parts of the Stage3D APIs can be processed in the background.

If you experiment with the redraw area (redraw regions) feature, the Starling will render everything on stage3d rather than on the expected traditional display list. The screenshot below illustrates this behavior. The quadrilateral rotates on each frame, and the redraw area (redraw regions) displays only the FTP counters, not the contents of the Stage3D (see Figure 6):


Figure 6. Example of rendering content using Stage3D

It is necessary to remember that when using the Stage 3D architecture, the corresponding content can be completely rendered and synthesized by the GPU. Therefore, the redraw area (redraw regions) feature that is running on the GPU for displaying lists is not available.

Layering Limits

When you use Starling (and stage 3D), remember that there is a limit to the development content. As mentioned earlier, Stage3D is completely new to the rendering architecture embedded in Flash Player. The GPU surface is placed below the display list, which means that any content running in the display list will be placed on top of the Stage3D content. When writing this article, the content running in the display list still cannot be placed under the Stage3D hierarchy (see Figure 7).

Figure 7. Stacking order of content rendered using Stage3D

Also, be aware that the Stage3D object is not transparent. If this is possible, you can use Stage video technology (the features introduced by Flash Player 10.2) to play the video and overlay the video with content rendered through Stage3D. This feature is expected to be supported in future Flash Player editions.


As an ActionScript 3 developer who knows how to use Flash APIs, you can start working immediately with these exposed APIs, while all the complex parts of the Stage3D APIs can be processed in the background.

If you experiment with the redraw area (redraw regions) feature, the Starling will render everything on stage3d rather than on the expected traditional display list. The screenshot below illustrates this behavior. The quadrilateral rotates on each frame, and the redraw area (redraw regions) displays only the FTP counters, not the contents of the Stage3D (see Figure 6):


Figure 6. Example of rendering content using Stage3D

It is necessary to remember that when using the Stage 3D architecture, the corresponding content can be completely rendered and synthesized by the GPU. Therefore, the redraw area (redraw regions) feature that is running on the GPU for displaying lists is not available.

Layering Limits

When you use Starling (and stage 3D), remember that there is a limit to the development content. As mentioned earlier, Stage3D is completely new to the rendering architecture embedded in Flash Player. The GPU surface is placed below the display list, which means that any content running in the display list will be placed on top of the Stage3D content. When writing this article, the content running in the display list still cannot be placed under the Stage3D hierarchy (see Figure 7).

Figure 7. Stacking order of content rendered using Stage3D

Also, be aware that the Stage3D object is not transparent. If this is possible, you can use Stage video technology (the features introduced by Flash Player 10.2) to play the video and overlay the video with content rendered through Stage3D. This feature is expected to be supported in future Flash Player editions.


set up the project

You can visit the official GitHub page to download Starling. In addition, you may find it rewarding to visit the Starling website.

Starling is licensed under the simplified BSD license, so you can use Starling on any type of commercial or non-commercial project. If you need more information, you can contact the Starling Framework team.

After you download Starling, you can refer to the Starling Library as you would reference other AS3 libraries. In order to use the new version of Flash Player one-time beta, you must target SWF version 13, which is implemented by passing additional compiler parameters,-swf-version=13, to the Flex compiler. If you are using the Adobe Flex SDK, follow these steps: Download the new PLAYERGLOBAL.SWC for Flash Player 11. Download the Flex 4.5 SDK (4.5.0.20967) from the Flex 4.5 SDK table. Install the appropriate version into your development environment. In Flash Builder, create a new ActionScript project by selecting File > New > ActionScript projects. Open Property Inspector (right-click and select the Properties option). In the menu list on the left, select ActionScript Compiler. Use the Configure Flex SDK option in the upper-right corner to point your project to flex build 20967. Click OK. Set your project target to SWF version 13. Open Property Inspector and select ActionScript Compiler from the menu list on the left. Add -swf-version=13 to the ' Additional compiler arguments ' input. This ensures that the output SWF will take SWF version 13 as the target version. If you do not compile in Flash Builder at the command line, you must add the same compiler parameters. Verify that you have installed the new Flash Player 11 version in your browser. setting up a scene

After you have prepared your development environment, you can delve into the code and see how you can make the most of this framework. Using Starling is very simple, you just need to create a Starling object and add it to your main class. In this article, when it comes to things like MovieClip, sprites, and other objects, I mean the Starling APIs, not the local objects from Flash Player.

First, the Starling constructor (constructor) requires multiple arguments. Here is the signature:

Public Function Starling (Rootclass:class, Stage:flash.display.Stage, 
                         viewport:rectangle=null, stage3d:stage3d= NULL,
                         rendermode:string= "Auto")

In fact, only the first 3 are often used. The associated Rootclass parameter requires a reference to the class that extends Starling.display.Sprite, and the second parameter is our stage, then a Stage3D object:

Package 
{
    import flash.display.Sprite;
    Import flash.display.StageAlign;
    Import Flash.display.StageScaleMode;
    Import starling.core.Starling;
    
    [SWF (width= ", height=" 752 ", framerate=", backgroundcolor= "#002143")]
    public class Startup extends Sprite
    {
        private var mstarling:starling;
        
        Public Function Startup ()
        {
        	//stats class for FPS
	addChild (new stats ());
			
	Stage.align = Stagealign.top_left;
	Stage.scalemode = Stagescalemode.no_scale;
		
	Create our Starling instance
            	mstarling = new Starling (Game, stage);

           	Set anti-aliasing (higher is better quality but slower   		    performance)
               mstarling.antialiasing = 1;

           	Start it!
	Mstarling.start ();}}}

In the following code, the game class can create a simple quadrilateral when it is added to the Stage:

Package 
{
    import starling.display.Quad;
    Import Starling.display.Sprite;
    Import starling.events.Event;

    public class Game extends Sprite
    {
	private var Q:quad;
		
        Public Function Game ()
        {	
	AddEventListener (event.added_to_stage, onadded);
        }
		
		Private Function onadded (e:event): void
            {
	q = new Quad (.);
	Q.setvertexcolor (0, 0x000000);
	Q.setvertexcolor (1, 0xaa0000);
	Q.setvertexcolor (2, 0x00FF00);
	Q.setvertexcolor (3, 0x0000FF);
	AddChild (q);}}

The code above adds a listener to the Event.added_to_stage event and initializes the application in the event handler. This allows you to safely access the Stage.

Note: Take a look at this subtle detail: the Game class described above extends the Sprite class from the Starling.display package, not from the Flash.display package. You must check your import statements and make sure that you are not using the local API to replace the Starling API.

As expected in Flash, the objects in Starling have a default location of 0,0. So add a few lines of command so that the quads are in the center of the Stage:

q.x = stage.stagewidth-q.width >> 1; Q.Y = stage.stageheight-q.height >> 1;

Now, test the project to make it easier to observe the corresponding results (see Figure 8):

Figure 8. The quadrilateral is in the center of the stage

Note the Sawtooth elimination feature (anti-aliasing) value allows you to set the type required for the anti-aliasing feature. In general, a value of 1 is basically acceptable, but you can choose a different value. The framework supports a change in the range of antialiasing (anti-aliasing) values from 0 to 16, but the following list gives the most common values: 0: No-aliasing elimination (anti-aliasing). 2: Minimal sawtooth elimination (anti-aliasing). 4: High-quality sawtooth elimination (anti-aliasing). 16: Extremely high-quality sawtooth elimination (anti-aliasing).

You rarely need to use more than 2 of the settings, especially for 2D content. However, depending on your project requirements, you will need to make the appropriate decisions for your specific situation. In Figure 9, compare the two screenshots to see the subtle differences between the two sawtooth elimination (anti-aliasing) VALUES (1 and 4).

Figure 9. Compare the visual differences between 1 (left) and 4 (right) of the sawtooth Elimination (anti-aliasing) value

Try using a value above 2 to set the desired quality for your project. Of course, choosing a higher value can affect performance. Note Stage3D is not affected by the Stage quality of the SWF file.

The following is a description of the other APIs that can be used with the Starling object: enableerrorchecking: allows you to enable or disable error checking. Specifies whether to report problems encountered by the renderer to the application. When Enableerrorchecking is set to Ture, the clear () and Drawtriangles () methods that are called internally by Starling are synchronous and can throw errors. When Enableerrorchecking is set to False, the clear () and Drawtriangles () methods are asynchronous and do not report an error. Enabling error checking will weaken rendering performance. The error checking feature is enabled only when the project is debugged, and is not enabled until the final version is deployed. isstarted: Indicates whether start is called. juggler: juggler is a simple object. It only holds a list of objects that perform ianimatable, and in the case of being required to do so, advance their time (by calling its own AdvanceTime: method). When an animation is complete, it will discard it. Start : Start Rendering and event handling. Stop : stops rendering and event handling. Use this method to stop rendering when the game enters the background running state to conserve resources. Dispose: This method is called when you want to handle everything that has been rendered on the current GPU memory. The API is able to handle everything inside it (such as a shader (shader programs), textures, and everything else).

Once you have created your Starling object, the debug record is automatically output to display information about the rendering. By default, when a SWF file is correctly embedded in a page or when tested in a standalone Flash Player, Starling outputs the following code:

[Starling] Initialization complete.
[Starling] Display Driver:opengl vendor=nvidia Corporation version=2.1 NVIDIA-7.2.9 renderer=nvidia GeForce GT 330M OpenGL Engine GLS l=1.20 (Direct blitting)

Of course, specific hardware details will change depending on your configuration. The above information indicates that GPU acceleration has been used because it includes the details of the driver version. For debugging purposes, you might want to be able to force the software fallback used within Flash Player to understand how it behaves when your content is running on the software.

Add the following code to make it easier to notify Starling that you want to use the software fallback feature (software rasterizer):

mstarling = new Starling (Game, stage, NULL, NULL, context3drendermode.software);

When you use the software, the output information confirms that you are using Software mode:

[Starling] Initialization complete.
[Starling] Display Driver:software (Direct blitting)


Make sure you also test your content in software mode to better understand its performance in this mode. If the user's configuration uses an older version of the driver (for consistency, all drivers prior to 2009 are included in the blacklist), then your content may fall back to the software.

In the next section, when you embed your SWF file in the page, you need to look at the stage3d requirements. Wmode Requirements

You must remember that in order to enable the stage and GPU acceleration features, you must use Wmode=direct as the embedding mode in the page. If you do not specify any value or choose a value other than "direct", such as "Transparent", "opaque", or "window", then stage 3D will not be available. Conversely, when Requestcontext3d Onstage3d is called, you will be prompted with a run-time exception that tells you that the creation of the Context3d object failed.

The following illustration lists a dialog box for a run-time exception:

Figure Ten. Run-time Exception dialog box when Context3d is not available

If your application is embedded with the wrong wmode, you must handle this situation with care. You need to give a reasonable response by displaying a message explaining the problem. Fortunately, Starling automatically handles this problem for you and displays the following information:

figure one. Warnings displayed when an application is not embedded correctly

Stage Quality

As a flash developer, the concept of stage quality is no stranger to you. Remember that stage quality does not affect performance when using Stage3D and Starling as a result.

Progressive Enhancements

When the GPU Acceleration feature does not work, Stage3D will fall back into the software and will internally use a software fallback engine called Swiftshader (transgaming). To ensure that your content is working properly in this situation, you need to detect when you should be running in software mode and remove the potential impact that may slow down in software mode.

In a 2D content environment, the software fallback function can handle many objects and provide good performance, but to detect this, you can still read the Context3d object from the Starling object using a static property environment:

Are we running hardware or software?
var Ishw:boolean = Starling.context.driverInfo.toLowerCase (). IndexOf ("software") = =-1;



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.