1 package 2 { 3 import com.adobe.utils.AGALMiniAssembler; 4 5 import flash.display.Sprite; 6 import flash.display3D.Context3D; 7 import flash.display3D.Context3DProgramType; 8 import flash.display3D.Context3DVertexBufferFormat; 9 import flash.display3D.IndexBuffer3D;10 import flash.display3D.Program3D;11 import flash.display3D.VertexBuffer3D;12 import flash.events.Event;13 import flash.geom.Matrix3D;14 import flash.geom.Vector3D;15 import flash.utils.getTimer;16 17 public class HelloTriangleColored extends Sprite18 {19 protected var context3D:Context3D;20 protected var program:Program3D;21 protected var vertexbuffer:VertexBuffer3D;22 protected var indexbuffer:IndexBuffer3D;23 24 public function HelloTriangleColored()25 {26 stage.stage3Ds[0].addEventListener( Event.CONTEXT3D_CREATE, initMolehill );27 stage.stage3Ds[0].requestContext3D();28 29 addEventListener(Event.ENTER_FRAME, onRender);30 }31 32 protected function initMolehill(e:Event):void33 {34 context3D = stage.stage3Ds[0].context3D;35 context3D.configureBackBuffer(800, 600, 1, true);//!!!!!!!!!挺重要的36 37 var vertices:Vector.= Vector. ([38 -0.3,-0.3,0, 1, 0, 0, // x, y, z, r, g, b39 -0.3, 0.3, 0, 0, 1, 0,40 0.3, 0.3, 0, 0, 0, 1]);41 42 // Create VertexBuffer3D. 3 vertices, of 6 Numbers each43 vertexbuffer = context3D.createVertexBuffer(3, 6);44 // Upload VertexBuffer3D to GPU. Offset 0, 3 vertices45 vertexbuffer.uploadFromVector(vertices, 0, 3);46 47 var indices:Vector. = Vector. ([0, 1, 2]);48 49 // Create IndexBuffer3D. Total of 3 indices. 1 triangle of 3 vertices50 indexbuffer = context3D.createIndexBuffer(3);51 // Upload IndexBuffer3D to GPU. Offset 0, count 352 indexbuffer.uploadFromVector (indices, 0, 3);53 54 var vertexShaderAssembler : AGALMiniAssembler = new AGALMiniAssembler();55 vertexShaderAssembler.assemble( Context3DProgramType.VERTEX,56 "m44 op, va0, vc0\n" + // pos to clipspace57 "mov v0, va1" // copy color58 );59 60 var fragmentShaderAssembler : AGALMiniAssembler= new AGALMiniAssembler();61 fragmentShaderAssembler.assemble( Context3DProgramType.FRAGMENT,62 63 "mov oc, v0"64 );65 66 program = context3D.createProgram();67 program.upload( vertexShaderAssembler.agalcode, fragmentShaderAssembler.agalcode);68 }69 70 protected function onRender(e:Event):void71 {72 if ( !context3D )73 return;74 75 context3D.clear ( 1, 1, 1, 1 );76 77 // vertex position to attribute register 078 context3D.setVertexBufferAt (0, vertexbuffer, 0, Context3DVertexBufferFormat.FLOAT_3);79 // color to attribute register 180 context3D.setVertexBufferAt(1, vertexbuffer, 3, Context3DVertexBufferFormat.FLOAT_3);81 // assign shader program82 context3D.setProgram(program);83 84 var m:Matrix3D = new Matrix3D();85 m.appendRotation(getTimer()/40, Vector3D.Z_AXIS);86 context3D.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 0, m, true);87 88 context3D.drawTriangles(indexbuffer);89 90 context3D.present();91 }92 }93 }94