- 画图形,定义模式为GL_SELECT,并为图形创建名字堆栈:
1 /// <summary> 2 /// Draws the rectangles. 3 /// </summary> 4 /// <param name="mode">The selection mode.</param> 5 private static void DrawRects(uint mode) 6 { 7 // The three rectangles are drawn. In selection mode, each rectangle is given 8 // the same name. Note that each rectangle is drawn with a different z value. 9 if (mode == GL_SELECT) 10 { 11 glLoadName(1); 12 } 13 glBegin(GL_QUADS); 14 glColor3f(1.0f, 1.0f, 0.0f); 15 glVertex3i(2, 0, 0); 16 glVertex3i(2, 6, 0); 17 glVertex3i(6, 6, 0); 18 glVertex3i(6, 0, 0); 19 glEnd(); 20 21 if (mode == GL_SELECT) 22 { 23 glLoadName(2); 24 } 25 glBegin(GL_QUADS); 26 glColor3f(0.0f, 1.0f, 1.0f); 27 glVertex3i(3, 2, -1); 28 glVertex3i(3, 8, -1); 29 glVertex3i(8, 8, -1); 30 glVertex3i(8, 2, -1); 31 glEnd(); 32 33 if (mode == GL_SELECT) 34 { 35 glLoadName(3); 36 } 37 glBegin(GL_QUADS); 38 glColor3f(1.0f, 0.0f, 1.0f); 39 glVertex3i(0, 2, -2); 40 glVertex3i(0, 7, -2); 41 glVertex3i(5, 7, -2); 42 glVertex3i(5, 2, -2); 43 glEnd(); 44 }
- 鼠标左键点击选中目标hit select:
1 /// <summary> 2 /// Updates pick selection. 3 /// </summary> 4 private static void PickRects() 5 { 6 private const int BUFSIZE = 512; // sets up selection mode, name stack, and projection matrix for picking. Then the objects are drawn 7 uint[] selectBuf = new uint[BUFSIZE]; 8 int hits; 9 int[] viewport = new int[4]; 10 11 glGetIntegerv(GL_VIEWPORT, viewport); 12 13 glSelectBuffer(BUFSIZE, selectBuf); 14 glRenderMode(GL_SELECT); 15 16 glInitNames(); 17 glPushName(0); 18 19 glMatrixMode(GL_PROJECTION); 20 glPushMatrix(); 21 glLoadIdentity(); 22 // create 5x5 pixel picking region near cursor location 23 gluPickMatrix((double)Model.Mouse.X, (double)(viewport[3] - Model.Mouse.Y), 5.0, 5.0, viewport); 24 glOrtho(0.0f, 8.0f, 0.0f, 8.0f, -0.5f, 2.5f); 25 DrawRects(GL_SELECT); 26 glPopMatrix(); 27 glFlush(); 28 29 hits = glRenderMode(GL_RENDER); 30 ProcessHits(hits, selectBuf); 31 } 32 /// <summary> 33 /// Displays hit data. 34 /// </summary> 35 /// <param name="hits">Number of hits.</param> 36 /// <param name="buffer">The selection buffer.</param> 37 private static void ProcessHits(int hits, uint[] buffer) 38 { 39 uint i, j; 40 uint names; 41 uint[] ptr; 42 43 Console.WriteLine("hits = {0}", hits); 44 ptr = buffer; 45 for (i = 0; i < hits; i++) 46 { // For Each Hit 47 names = ptr[i]; 48 Console.WriteLine(" number of names for hit = {0}", names); 49 i++; 50 Console.WriteLine(" z1 is {0}", (float)ptr[i] / 0x7fffffff); 51 i++; 52 Console.WriteLine(" z2 is {0}", (float)ptr[i] / 0x7fffffff); 53 i++; 54 Console.Write(" the name is "); 55 for (j = 0; j < names; j++) 56 { // For Each Name 57 Console.Write("{0} ", ptr[i]); 58 i++; 59 } 60 Console.Write("\n"); 61 } 62 Console.Write("\n"); 63 }