예제 #1
0
void CRenderingContext::Finish()
{
	glFinish();
}
예제 #2
0
//---------------------------------------------------------------------------
void CFabAtHomeView::DrawScene(void)
//---------------------------------------------------------------------------
{// draw the scene

	m_bDrawing = true;
	CFabAtHomeDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	CSingleLock lockModel(&pDoc->model.m_mutAccess);
	lockModel.Lock(100);
	if(!lockModel.IsLocked()) return;
	CFabAtHomeApp *pApp = (CFabAtHomeApp *) AfxGetApp();
	CVec platetop(0,0,0);
	//get the graphics position (offset by PrinterComponent home from the hardware home (0,0,0).
	if (pApp->printer.IsDefined())
		platetop = pApp->printer.component[3].GetGraphicsRTPos() + pApp->printer.component[3].pmax;

	// background

	glClearColor(1,1,1,1);
	ReportGLError(CString("ClearColor"));
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	ReportGLError(CString("Clear"));
	
	// lighting

	SetLighting();

	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	ReportGLError(CString("PolygonMode"));

	// draw

    glPushMatrix();
	ReportGLError(CString("PushMatrix1"));
	
	if(bPanning)
	{
		view.x=(eye.x+view.z)/view.z;
		view.y=(eye.y+view.z)/view.z;
	}
	gluLookAt(eye.x, eye.y, eye.z, view.x, view.y, view.z, up.x, up.y, up.z);
	ReportGLError(CString("gluLookAt"));

	glMultMatrixd(rotmat);
	ReportGLError(CString("MultMatrix"));
	glPushMatrix();
	ReportGLError(CString("PushMatrix2"));

	
	glEnable(GL_NORMALIZE);
	ReportGLError(CString("Enable"));

	if(bShowPrinter)
	{
		((CFabAtHomeApp*) AfxGetApp())->printer.Draw();
		ReportGLError(CString("printer.Draw"));
	}

	// model

	glPushMatrix();
	ReportGLError(CString("PushMatrix3"));
	glTranslated(0,0,platetop.z);
	ReportGLError(CString("Translate"));
	DrawMainAxes(20);
	ReportGLError(CString("DrawAxes"));

	glPushName(1);
	ReportGLError(CString("PushName1"));
	glLoadName(NAMESTACK_CHUNK);
	ReportGLError(CString("LoadName1"));
	glPushName(NAMESTACK_CHUNK);
	ReportGLError(CString("PushName"));

	if (bShowModel) {
		glColor3d(0.4,0.8,0.2);
		for (int i=0; i<pDoc->model.chunk.GetSize(); i++) {
			glLoadName(i);
			ReportGLError(CString("LoadName2"));

			pDoc->model.chunk[i].Draw(&pDoc->model, bModelNormals, bShaded);

			ReportGLError(CString("DrawChunk"));
		}
	}
	glPopName();
	ReportGLError(CString("PopName1"));
	
	// paths
	
	if(bFollowCurrentLayer) 
	{
		UpdateCurrentLayer();
	}
	pDoc->model.fab.DrawLayers(&pDoc->model, firstlayer, lastlayer, bShowPaths, bShowTrace);

	ReportGLError(CString("DrawLayers"));

	glColor3d(1,1,1);
	ReportGLError(CString("Color3d"));
	glLineWidth(5);
	ReportGLError(CString("LineWidth1"));
	glLineWidth(1);
	ReportGLError(CString("LineWidth2"));

	glPopName();
	ReportGLError(CString("PopName2"));
	glPopMatrix();
	ReportGLError(CString("PopMatrix1"));
	glPopMatrix();
	ReportGLError(CString("PopMatrix2"));

	// end

	glDisable(GL_COLOR_MATERIAL);
	ReportGLError(CString("Disable"));
	
    glPopMatrix();
	ReportGLError(CString("PopMatrix3"));
	glFinish();
	ReportGLError(CString("Finish"));
	HDC localDC = wglGetCurrentDC();
	ASSERT(localDC != NULL);
	SwapBuffers(localDC);
	ReportGLError(CString("SwapBuffers"));
	m_bDrawing = false;
}
예제 #3
0
bool CoreTexture::RebuildCubemap(JSContext* cx, OVR::String pathStr) {
  OVR::FreeTexture(texture);

  if (pathStr.IsEmpty()) {
    return true;
  }

  // Get the file extension, and a copy of the path with no extension
  OVR::String ext = pathStr.GetExtension();
  OVR::String noExt(pathStr);
  noExt.StripExtension();

  // Create some membuffers for the files we're going to open
  OVR::MemBufferFile mbfs[6] = { 
    OVR::MemBufferFile(OVR::MemBufferFile::NoInit), 
    OVR::MemBufferFile(OVR::MemBufferFile::NoInit),
    OVR::MemBufferFile(OVR::MemBufferFile::NoInit),
    OVR::MemBufferFile(OVR::MemBufferFile::NoInit),
    OVR::MemBufferFile(OVR::MemBufferFile::NoInit),
    OVR::MemBufferFile(OVR::MemBufferFile::NoInit) 
  };
  
  // Load all of them up
  const char* const cubeSuffix[6] = {"_px", "_nx", "_py", "_ny", "_pz", "_nz"};
  for (int side = 0; side < 6; ++side) {
    OVR::String sidePath = noExt + OVR::String(cubeSuffix[side]) + ext;
    if (CURRENT_BASE_DIR.IsEmpty()) {
      if (!OVR::ovr_ReadFileFromApplicationPackage(sidePath.ToCStr(), mbfs[side])) {
        JS_ReportError(cx, "Could not load cube file");
        return false;
      }
    } else {
      OVR::String fullFileStr = FullFilePath(sidePath);
      if (!mbfs[side].LoadFile(fullFileStr.ToCStr())) {
        JS_ReportError(cx, "Could not load cube file");
        return false;
      }
    }
    
    
  }

  unsigned char* data[6];
  int comp, imgWidth, imgHeight;
  // For each side of the cube
  for (int i = 0; i < 6; ++i) {
    // Load the image
    data[i] = (unsigned char *)stbi_load_from_memory(
      (unsigned char *)mbfs[i].Buffer, mbfs[i].Length, &imgWidth, &imgHeight, &comp, 4);

    // Sanity check image dimensions
    if (imgWidth != width) {
      JS_ReportError(cx, "Cubemap has mismatched image width");
      return false;
    }
    if (imgHeight != height) {
      JS_ReportError(cx, "Cubemap has mismatched image height");
      return false;
    }
    if (imgWidth <= 0 || imgWidth > 32768 || imgHeight <= 0 || imgHeight > 32768) {
      JS_ReportError(cx, "Invalid texture size");
      return false;
    }
  }

  GLenum glFormat;
  GLenum glInternalFormat;
  if (!TextureFormatToGlFormat(OVR::Texture_RGBA, true, glFormat, glInternalFormat)) {
    JS_ReportError(cx, "Invalid texture format OVR::Texture_RGBA");
    return false;
  }

  GLuint texId;
  glGenTextures(1, &texId);
  glBindTexture(GL_TEXTURE_CUBE_MAP, texId);

  // Get the total size (GetOvrTextureSize(OVR::Texture_RGBA, width, height) * 6)
  // size_t totalSize = (((width + 3) / 4) * ((height + 3) / 4) * 8) * 6;

  for (int i = 0; i < 6; ++i) {
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, width, height, 0, glFormat, GL_UNSIGNED_BYTE, data[i]);
  }

  // Generate mipmaps and bind the texture
  glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
  glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

  // Construct our actual texture object
  texture = OVR::GlTexture(texId, GL_TEXTURE_CUBE_MAP);

  // Free our image data
  for (int i = 0; i < 6; ++i) {
    free(data[i]);
  }

  // Wait for the upload to complete.
  glFinish();
  return true;
}
예제 #4
0
CGImageRef grabViaOpenGL(CGDirectDisplayID display, CGRect srcRect)
{
    CGContextRef bitmap;
    CGImageRef image;
    void * data;
    long bytewidth;
    GLint width, height;
    long bytes;

    CGLContextObj    glContextObj;
    CGLPixelFormatObj pixelFormatObj ;
    GLint numPixelFormats ;
    CGLPixelFormatAttribute attribs[] =
    {
        kCGLPFAFullScreen,
        kCGLPFADisplayMask,
        (CGLPixelFormatAttribute) 0,    /* Display mask bit goes here */
        (CGLPixelFormatAttribute) 0
    } ;


    if ( display == kCGNullDirectDisplay )
        display = CGMainDisplayID();
    attribs[2] = (CGLPixelFormatAttribute) CGDisplayIDToOpenGLDisplayMask(display);


    /* Build a full-screen GL context */
    CGLChoosePixelFormat( attribs, &pixelFormatObj, &numPixelFormats );
    if ( pixelFormatObj == NULL )    // No full screen context support
        return NULL;
    CGLCreateContext( pixelFormatObj, NULL, &glContextObj ) ;
    CGLDestroyPixelFormat( pixelFormatObj ) ;
    if ( glContextObj == NULL )
        return NULL;


    CGLSetCurrentContext( glContextObj ) ;
    CGLSetFullScreen( glContextObj ) ;


    glReadBuffer(GL_FRONT);


    width = (GLint)srcRect.size.width;
    height = (GLint)srcRect.size.height;


    bytewidth = width * 4; // Assume 4 bytes/pixel for now
    bytewidth = (bytewidth + 3) & ~3; // Align to 4 bytes
    bytes = bytewidth * height; // width * height

    /* Build bitmap context */
    data = malloc(height * bytewidth);
    if ( data == NULL )
    {
        CGLSetCurrentContext( NULL );
        CGLClearDrawable( glContextObj ); // disassociate from full screen
        CGLDestroyContext( glContextObj ); // and destroy the context
        return NULL;
    }
    bitmap = CGBitmapContextCreate(data, width, height, 8, bytewidth,
                                   wxMacGetGenericRGBColorSpace(), kCGImageAlphaNoneSkipFirst /* XRGB */);


    /* Read framebuffer into our bitmap */
    glFinish(); /* Finish all OpenGL commands */
    glPixelStorei(GL_PACK_ALIGNMENT, 4); /* Force 4-byte alignment */
    glPixelStorei(GL_PACK_ROW_LENGTH, 0);
    glPixelStorei(GL_PACK_SKIP_ROWS, 0);
    glPixelStorei(GL_PACK_SKIP_PIXELS, 0);

    /*
     * Fetch the data in XRGB format, matching the bitmap context.
     */
    glReadPixels((GLint)srcRect.origin.x, (GLint)srcRect.origin.y, width, height,
                 GL_BGRA,
#ifdef __BIG_ENDIAN__
                 GL_UNSIGNED_INT_8_8_8_8_REV, // for PPC
#else
                 GL_UNSIGNED_INT_8_8_8_8, // for Intel! http://lists.apple.com/archives/quartz-dev/2006/May/msg00100.html
#endif
                 data);
    /*
     * glReadPixels generates a quadrant I raster, with origin in the lower left
     * This isn't a problem for signal processing routines such as compressors,
     * as they can simply use a negative 'advance' to move between scanlines.
     * CGImageRef and CGBitmapContext assume a quadrant III raster, though, so we need to
     * invert it. Pixel reformatting can also be done here.
     */
    swizzleBitmap(data, bytewidth, height);


    /* Make an image out of our bitmap; does a cheap vm_copy of the bitmap */
    image = CGBitmapContextCreateImage(bitmap);

    /* Get rid of bitmap */
    CFRelease(bitmap);
    free(data);


    /* Get rid of GL context */
    CGLSetCurrentContext( NULL );
    CGLClearDrawable( glContextObj ); // disassociate from full screen
    CGLDestroyContext( glContextObj ); // and destroy the context

    /* Returned image has a reference count of 1 */
    return image;
}
예제 #5
0
void
clutter_stage_glx_redraw (ClutterStageGLX *stage_glx,
                          ClutterStage *stage)
{
  ClutterBackend    *backend;
  ClutterBackendX11 *backend_x11;
  ClutterBackendGLX *backend_glx;
  ClutterStageX11   *stage_x11;
  GLXDrawable        drawable;
  unsigned int       video_sync_count;
  CLUTTER_STATIC_TIMER (painting_timer,
                        "Redrawing", /* parent */
                        "Painting actors",
                        "The time spent painting actors",
                        0 /* no application private data */);
  CLUTTER_STATIC_TIMER (swapbuffers_timer,
                        "Redrawing", /* parent */
                        "glXSwapBuffers",
                        "The time spent blocked by glXSwapBuffers",
                        0 /* no application private data */);
  CLUTTER_STATIC_TIMER (blit_sub_buffer_timer,
                        "Redrawing", /* parent */
                        "glx_blit_sub_buffer",
                        "The time spent in _glx_blit_sub_buffer",
                        0 /* no application private data */);

  backend     = clutter_get_default_backend ();
  backend_x11 = CLUTTER_BACKEND_X11 (backend);
  backend_glx = CLUTTER_BACKEND_GLX (backend);

  stage_x11 = CLUTTER_STAGE_X11 (stage_glx);

  CLUTTER_TIMER_START (_clutter_uprof_context, painting_timer);

  if (backend_glx->can_blit_sub_buffer &&
      /* NB: a degenerate redraw clip width == full stage redraw */
      (stage_glx->bounding_redraw_clip.width != 0) &&
      G_LIKELY (!(clutter_paint_debug_flags &
                  CLUTTER_DEBUG_DISABLE_CLIPPED_REDRAWS)))
    {
      cogl_clip_push_window_rectangle (stage_glx->bounding_redraw_clip.x,
                                       stage_glx->bounding_redraw_clip.y,
                                       stage_glx->bounding_redraw_clip.width,
                                       stage_glx->bounding_redraw_clip.height);
      clutter_actor_paint (CLUTTER_ACTOR (stage));
      cogl_clip_pop ();
    }
  else
    clutter_actor_paint (CLUTTER_ACTOR (stage));

  cogl_flush ();
  CLUTTER_TIMER_STOP (_clutter_uprof_context, painting_timer);

  if (stage_x11->xwin == None)
    return;

  drawable = stage_glx->glxwin ? stage_glx->glxwin : stage_x11->xwin;

  /* If we might ever use _clutter_backend_glx_blit_sub_buffer then we
   * always need to keep track of the video_sync_count so that we can
   * throttle blits.
   *
   * Note: we get the count *before* we issue any glXCopySubBuffer or
   * blit_sub_buffer request in case the count would go up before
   * returning control to us.
   */
  if (backend_glx->can_blit_sub_buffer && backend_glx->get_video_sync)
    backend_glx->get_video_sync (&video_sync_count);

  /* push on the screen */
  if (backend_glx->can_blit_sub_buffer &&
      /* NB: a degenerate redraw clip width == full stage redraw */
      (stage_glx->bounding_redraw_clip.width != 0) &&
      G_LIKELY (!(clutter_paint_debug_flags &
                  CLUTTER_DEBUG_DISABLE_CLIPPED_REDRAWS)))
    {
      ClutterGeometry *clip = &stage_glx->bounding_redraw_clip;
      ClutterGeometry copy_area;

      CLUTTER_NOTE (BACKEND,
                    "_glx_blit_sub_buffer (window: 0x%lx, "
                                          "x: %d, y: %d, "
                                          "width: %d, height: %d)",
                    (unsigned long) drawable,
                    stage_glx->bounding_redraw_clip.x,
                    stage_glx->bounding_redraw_clip.y,
                    stage_glx->bounding_redraw_clip.width,
                    stage_glx->bounding_redraw_clip.height);

      if (clutter_paint_debug_flags & CLUTTER_DEBUG_REDRAWS)
        {
          static CoglHandle outline = COGL_INVALID_HANDLE;
          CoglHandle vbo;
          float x_1 = clip->x;
          float x_2 = clip->x + clip->width;
          float y_1 = clip->y;
          float y_2 = clip->y + clip->height;
          float quad[8] = {
            x_1, y_1,
            x_2, y_1,
            x_2, y_2,
            x_1, y_2
          };

          if (outline == COGL_INVALID_HANDLE)
            {
              outline = cogl_material_new ();
              cogl_material_set_color4ub (outline, 0xff, 0x00, 0x00, 0xff);
            }

          vbo = cogl_vertex_buffer_new (4);
          cogl_vertex_buffer_add (vbo,
                                  "gl_Vertex",
                                  2, /* n_components */
                                  COGL_ATTRIBUTE_TYPE_FLOAT,
                                  FALSE, /* normalized */
                                  0, /* stride */
                                  quad);
          cogl_vertex_buffer_submit (vbo);

          cogl_set_source (outline);
          cogl_vertex_buffer_draw (vbo, COGL_VERTICES_MODE_LINE_LOOP,
                                   0 , 4);
          cogl_flush ();
        }

      /* XXX: It seems there will be a race here in that the stage
       * window may be resized before glXCopySubBufferMESA is handled
       * and so we may copy the wrong region. I can't really see how
       * we can handle this with the current state of X but at least
       * in this case a full redraw should be queued by the resize
       * anyway so it should only exhibit temporary artefacts.
       */
      copy_area.y = clutter_actor_get_height (CLUTTER_ACTOR (stage))
        - clip->y - clip->height;
      copy_area.x = clip->x;
      copy_area.width = clip->width;
      copy_area.height = clip->height;

      /* glXCopySubBufferMESA and glBlitFramebuffer are not integrated
       * with the glXSwapIntervalSGI mechanism which we usually use to
       * throttle the Clutter framerate to the vertical refresh and so
       * we have to manually wait for the vblank period...
       */

      /* Here 'is_synchronized' only means that the blit won't cause a
       * tear, ie it won't prevent multiple blits per retrace if they
       * can all be performed in the blanking period. If that's the
       * case then we still want to use the vblank sync menchanism but
       * we only need it to throttle redraws.
       */
      if (!backend_glx->blit_sub_buffer_is_synchronized)
        {
          /* XXX: note that glXCopySubBuffer, at least for Intel, is
           * synchronized with the vblank but glBlitFramebuffer may
           * not be so we use the same scheme we do when calling
           * glXSwapBuffers without the swap_control extension and
           * call glFinish () before waiting for the vblank period.
           *
           * See where we call glXSwapBuffers for more details.
           */
          glFinish ();
          wait_for_vblank (CLUTTER_BACKEND_GLX (backend));
        }
      else if (backend_glx->get_video_sync)
        {
          /* If we have the GLX_SGI_video_sync extension then we can
           * be a bit smarter about how we throttle blits by avoiding
           * any waits if we can see that the video sync count has
           * already progressed. */
          if (backend_glx->last_video_sync_count == video_sync_count)
            wait_for_vblank (CLUTTER_BACKEND_GLX (backend));
        }
      else
        wait_for_vblank (CLUTTER_BACKEND_GLX (backend));

      CLUTTER_TIMER_START (_clutter_uprof_context, blit_sub_buffer_timer);
      _clutter_backend_glx_blit_sub_buffer (backend_glx,
                                            drawable,
                                            copy_area.x,
                                            copy_area.y,
                                            copy_area.width,
                                            copy_area.height);
      CLUTTER_TIMER_STOP (_clutter_uprof_context, blit_sub_buffer_timer);
    }
  else
    {
      CLUTTER_NOTE (BACKEND, "glXSwapBuffers (display: %p, window: 0x%lx)",
                    backend_x11->xdpy,
                    (unsigned long) drawable);

      /* If we have GLX swap buffer events then glXSwapBuffers will return
       * immediately and we need to track that there is a swap in
       * progress... */
      if (clutter_feature_available (CLUTTER_FEATURE_SWAP_EVENTS))
        stage_glx->pending_swaps++;

      if (backend_glx->vblank_type != CLUTTER_VBLANK_GLX_SWAP &&
          backend_glx->vblank_type != CLUTTER_VBLANK_NONE)
        {
          /* If we are going to wait for VBLANK manually, we not only
           * need to flush out pending drawing to the GPU before we
           * sleep, we need to wait for it to finish. Otherwise, we
           * may end up with the situation:
           *
           *        - We finish drawing      - GPU drawing continues
           *        - We go to sleep         - GPU drawing continues
           * VBLANK - We call glXSwapBuffers - GPU drawing continues
           *                                 - GPU drawing continues
           *                                 - Swap buffers happens
           *
           * Producing a tear. Calling glFinish() first will cause us
           * to properly wait for the next VBLANK before we swap. This
           * obviously does not happen when we use _GLX_SWAP and let
           * the driver do the right thing
           */
          glFinish ();

          wait_for_vblank (CLUTTER_BACKEND_GLX (backend));
        }

      CLUTTER_TIMER_START (_clutter_uprof_context, swapbuffers_timer);
      glXSwapBuffers (backend_x11->xdpy, drawable);
      CLUTTER_TIMER_STOP (_clutter_uprof_context, swapbuffers_timer);
    }

  backend_glx->last_video_sync_count = video_sync_count;

  /* reset the redraw clipping for the next paint... */
  stage_glx->initialized_redraw_clip = FALSE;
}
예제 #6
0
파일: ximage.c 프로젝트: 0x0all/ROOT
Bool
asimage2drawable_gl(	ASVisual *asv, Drawable d, ASImage *im,
                  		int src_x, int src_y, int dest_x, int dest_y,
        		  		int width, int height, int d_width, int d_height, 
						Bool force_direct )
{
	if( im != NULL && get_flags( asv->glx_support, ASGLX_Available ) && d != None )
	{
#ifdef HAVE_GLX
		int glbuf_size = (get_flags( asv->glx_support, ASGLX_RGBA )? 4 : 3 ) * width * height;
		CARD8 *glbuf = NULL;
		ASImageDecoder *imdec  = NULL ;
		GLXPixmap glxp = None;
		
		if ((imdec = start_image_decoding( asv, im, 
									   	get_flags( asv->glx_support, ASGLX_RGBA )?SCL_DO_ALL:SCL_DO_COLOR, 
									   	src_x, src_y, width, height, NULL)) != NULL )
		{	 
			int i, l = glbuf_size;
			glbuf = safemalloc( glbuf_size );
			for (i = 0; i < (int)height; i++)
			{	
				int k = width;
				imdec->decode_image_scanline( imdec ); 
				if( get_flags( asv->glx_support, ASGLX_RGBA ) ) 
				{	  
					while( --k >= 0 ) 
					{
						glbuf[--l] = imdec->buffer.alpha[k] ;
						glbuf[--l] = imdec->buffer.blue[k] ;
						glbuf[--l] = imdec->buffer.green[k] ;
						glbuf[--l] = imdec->buffer.red[k] ;
					}	 
				}else
				{	
					while( --k >= 0 ) 
					{
						glbuf[--l] = imdec->buffer.blue[k] ;
						glbuf[--l] = imdec->buffer.green[k] ;
						glbuf[--l] = imdec->buffer.red[k] ;
					}	 
				}
			}
			stop_image_decoding( &imdec );
		}else
			return False;

		if( !force_direct ) 
		{	
			glxp = glXCreateGLXPixmap( asv->dpy, &(asv->visual_info), d);
			/* d is either invalid drawable or is a window */
			if( glxp == None ) 
				force_direct = True ; 
		}                      
		if( glxp == None ) 
		{
			if( asv->glx_scratch_gc_direct	!= NULL )
				glXMakeCurrent (asv->dpy, d, asv->glx_scratch_gc_direct);
			else
				glXMakeCurrent (asv->dpy, d, asv->glx_scratch_gc_indirect);
		}else
			glXMakeCurrent (asv->dpy, glxp, asv->glx_scratch_gc_indirect);
		
		if( glGetError() != 0 ) 
			return False;

  		if ( get_flags( asv->glx_support, ASGLX_DoubleBuffer ) ) 
   			glDrawBuffer (GL_FRONT);

		glDisable(GL_BLEND);		/* optimize pixel transfer rates */
	  	glDisable (GL_DEPTH_TEST);
	  	glDisable (GL_DITHER);
	  	glDisable (GL_FOG);
	  	glDisable (GL_LIGHTING);

		glViewport( 0, 0, d_width, d_height);
		glMatrixMode (GL_PROJECTION);
		glLoadIdentity ();
		/* gluOrtho2D (0, d_width, 0, d_height); */
		glMatrixMode (GL_MODELVIEW);
		glLoadIdentity ();
		glTranslatef (0.375, 0.375, 0.0);


#if 1
		if( !IS_POWER_OF2(width) || !IS_POWER_OF2(height))
		{
			/* now put pixels on */
			glRasterPos2i( dest_x, d_height - (dest_y+height) );
			glDrawPixels(   width, height, 
							get_flags( asv->glx_support, ASGLX_RGBA )?GL_RGBA:GL_RGB, 
							GL_UNSIGNED_BYTE, glbuf );
		}else
#endif		
		{ /* this stuff might be faster : */
			GLuint texture ;

#define TARGET_TEXTURE_ID GL_TEXTURE_2D

#if TARGET_TEXTURE_ID!=GL_TEXTURE_2D
			glEnable(GL_TEXTURE_2D);
#endif			
			glEnable(TARGET_TEXTURE_ID);
			glGenTextures(1, &texture);

			glBindTexture(TARGET_TEXTURE_ID, texture);
	    	glTexParameteri(TARGET_TEXTURE_ID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	     	glTexParameteri(TARGET_TEXTURE_ID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
			glTexImage2D(TARGET_TEXTURE_ID, 0, get_flags( asv->glx_support, ASGLX_RGBA )?GL_RGBA:GL_RGB, 
					      /* width and height must be the power of 2 !!! */
						  width, height, 
						  0, GL_RGBA, GL_UNSIGNED_BYTE, glbuf);

		 	glBegin(GL_QUADS);
			/* bottom-left */
		   	glTexCoord2d(0., 0.); glVertex2i(dest_x, d_height - (dest_y+height) );
			/* bottom-right */
		   	glTexCoord2d(1.0, 0.0); glVertex2i(dest_x+width, d_height - (dest_y+height));
			/* top-right */
		   	glTexCoord2d(1.0, 1.0); glVertex2i(dest_x+width, d_height - dest_y);    
			/* top-left */ 
		   	glTexCoord2d(0.0, 1.0); glVertex2i(dest_x, d_height - dest_y);
		   	glEnd();

			glBindTexture(TARGET_TEXTURE_ID, 0);
			glFinish();
		}							

		free( glbuf );
		glXMakeCurrent (asv->dpy, None, NULL);	  
		if( glxp ) 
			glXDestroyGLXPixmap( asv->dpy, glxp);
		glFinish(); 				   
		return True;
#endif /* #ifdef HAVE_GLX */
	}
	{
		static Bool warning_shown = False ; 
		if( !warning_shown ) 
		{
			warning_shown = True ;
			show_warning( "Support for GLX is unavailable.");
		}
	}
	return False;
}
EGLBoolean eglSwapBuffers(EGLDisplay display, EGLSurface surface_)
{
    struct context *current_context = brcm_egl_get_current();
    struct surface *surface = (struct surface *)surface_;

    if( !current_context )
    {
       LOGE("eglSwapBuffers() - TODO - function called but no current context is valid");
	   return false;
    }

    //nothing bound?
    if(surface_ == EGL_NO_SURFACE)
    {
        LOGE("eglSwapBuffers(%p) error: EGL_BAD_SURFACE Thread: %d", current_context, gettid());
        return EGL_FALSE;
    }

    //do we have an android native window already assigned to our egl context?
    if(surface->window)
    {

        //check that the context wasn't deleted
        //TODO - explain why this could occur
#if 0
        if(egl_is_context_lost(thread))
        {
            thread->error = EGL_CONTEXT_LOST;
            LOGE("eglSwapBuffers(%p) error: EGL_CONTEXT_LOST, Thread: %d", current_context, gettid());
            return EGL_FALSE;
        }
#endif

        LOGD_IF(current_context->profiling, "eglSwapBuffers(%d, %p) %d", (int)display, (void *)surface, gettid());

        //todo - add in invalidates here
#ifndef BRCM_V3D_OPT
        glFinish();
#else
        glFinish();
        glFlush();
		if(surface->buffer->format == HAL_PIXEL_FORMAT_YCbCr_422_I)
			convert_to_yuv(current_context->composer,surface->buffer);
#endif
        //TODO - if we don't get a buffer below, then v3d will have a pointer to memory that it can't write to anymore

		EGLint res = glGetError();
		if (res == GL_OUT_OF_MEMORY)
			{
			LOGE("eglSwapBuffers Error 0x%x",res);
			return false;
			}
        //send the current buffer out
        surface_enqueue_buffer( surface);

		sync_composer(current_context->composer);

        //grab a new buffer and bind it to V3D
        if( !surface_dequeue_buffer(surface) )
           LOGE("surface_dequeue_buffer FATAL error - no buffer to attach");

         attach_buffer(display, surface);

        return EGL_TRUE;
    }
    else
    {
       LOGE("eglSwapBuffers called but no window bound!" );
    }
    return EGL_FALSE;
}
예제 #8
0
파일: tronbit.c 프로젝트: Zygo/xscreensaver
ENTRYPOINT void
draw_bit (ModeInfo *mi)
{
  bit_configuration *bp = &bps[MI_SCREEN(mi)];
  Display *dpy = MI_DISPLAY(mi);
  Window window = MI_WINDOW(mi);
  int wire = MI_IS_WIREFRAME(mi);

  if (!bp->glx_context)
    return;

  glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *bp->glx_context);

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  if (!wire)
    {
      GLfloat pos[4] = {1.0, 1.0, 1.0, 0.0};
      GLfloat amb[4] = {0.0, 0.0, 0.0, 1.0};
      GLfloat dif[4] = {1.0, 1.0, 1.0, 1.0};
      GLfloat spc[4] = {0.0, 1.0, 1.0, 1.0};

      glEnable(GL_LIGHTING);
      glEnable(GL_LIGHT0);
      glLightfv(GL_LIGHT0, GL_POSITION, pos);
      glLightfv(GL_LIGHT0, GL_AMBIENT,  amb);
      glLightfv(GL_LIGHT0, GL_DIFFUSE,  dif);
      glLightfv(GL_LIGHT0, GL_SPECULAR, spc);
    }

  glPushMatrix ();
  glScalef(1.1, 1.1, 1.1);

# ifdef HAVE_MOBILE	/* Keep it the same relative size when rotated. */
  {
    GLfloat h = MI_HEIGHT(mi) / (GLfloat) MI_WIDTH(mi);
    int o = (int) current_device_rotation();
    if (o != 0 && o != 180 && o != -180)
      glScalef (1/h, 1/h, 1/h);
    glRotatef(o, 0, 0, 1);
  }
# endif

  {
    double x, y, z;
    get_position (bp->rot, &x, &y, &z, !bp->button_down_p);
    glTranslatef((x - 0.5) * 11,
                 (y - 0.5) * 5,
                 (z - 0.5) * 3);
    gltrackball_rotate (bp->trackball);

    get_rotation (bp->rot, &x, &y, &z, !bp->button_down_p);
    glRotatef (x * 360, 1.0, 0.0, 0.0);
    glRotatef (y * 360, 0.0, 1.0, 0.0);
    glRotatef (z * 360, 0.0, 0.0, 1.0);
  }

  mi->polygon_count = 0;

  glScalef (6, 6, 6);

  {
    int nmodel = bp->history [bp->history_fp];
    int omodel = bp->history [bp->history_fp > 0
                              ? bp->history_fp-1
                              : countof(bp->history)-1];
    double now = double_time();
    double ratio = 1 - ((bp->last_time + bp->frequency) - now) / bp->frequency;
    if (ratio > 1) ratio = 1;
    mi->polygon_count += draw_histogram (mi, ratio);

    if (MI_WIDTH(mi) > MI_HEIGHT(mi) * 5) {   /* wide window: scale up */
      glScalef (8, 8, 8);
    }

    mi->polygon_count += animate_bits (mi, omodel, nmodel, ratio);
    tick_bit (mi, now);
  }
  glPopMatrix ();

  if (mi->fps_p) do_fps (mi);
  glFinish();

  glXSwapBuffers(dpy, window);
}
예제 #9
0
void redraw(void)
{
  int start, end;

  if (reportSpeed) {
    start = glutGet(GLUT_ELAPSED_TIME);
  }

  /* Clear; default stencil clears to zero. */
  if ((stencilReflection && renderReflection) || (stencilShadow && renderShadow)) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  } else {
    /* Avoid clearing stencil when not using it. */
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  }

  /* Reposition the light source. */
  lightPosition[0] = 12*cos(lightAngle);
  lightPosition[1] = lightHeight;
  lightPosition[2] = 12*sin(lightAngle);
  if (directionalLight) {
    lightPosition[3] = 0.0;
  } else {
    lightPosition[3] = 1.0;
  }

  shadowMatrix(floorShadow, floorPlane, lightPosition);

  glPushMatrix();
    /* Perform scene rotations based on user mouse input. */
    glRotatef(angle2, 1.0, 0.0, 0.0);
    glRotatef(angle, 0.0, 1.0, 0.0);
     
    /* Tell GL new light source position. */
    glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);

    if (renderReflection)
    {
      if (stencilReflection) 
      {
        /* We can eliminate the visual "artifact" of seeing the "flipped"
  	   dinosaur underneath the floor by using stencil.  The idea is
	   draw the floor without color or depth update but so that 
	   a stencil value of one is where the floor will be.  Later when
	   rendering the dinosaur reflection, we will only update pixels
	   with a stencil value of 1 to make sure the reflection only
	   lives on the floor, not below the floor. */

        /* Don't update color or depth. */
        glDisable(GL_DEPTH_TEST);
        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);

        /* Draw 1 into the stencil buffer. */
        glEnable(GL_STENCIL_TEST);
        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
        glStencilFunc(GL_ALWAYS, 1, 0xffffffff);

        /* Now render floor; floor pixels just get their stencil set to 1. */
        drawFloor();

        /* Re-enable update of color and depth. */ 
        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
        glEnable(GL_DEPTH_TEST);

        /* Now, only render where stencil is set to 1. */
        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
        glStencilFunc(GL_EQUAL, 1, 0xffffffff);  /* draw if ==1 */
      }

      glPushMatrix();

        /* The critical reflection step: Reflect dinosaur through the floor
           (the Y=0 plane) to make a relection. */
        glScalef(1.0, -1.0, 1.0);

	/* Reflect the light position. */
        glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);

        /* To avoid our normals getting reversed and hence botched lighting
	   on the reflection, turn on normalize.  */
        glEnable(GL_NORMALIZE);
        glCullFace(GL_FRONT);

        /* Draw the reflected dinosaur. */
        drawDinosaur();

        /* Disable noramlize again and re-enable back face culling. */
        glDisable(GL_NORMALIZE);
        glCullFace(GL_BACK);

      glPopMatrix();

      /* Switch back to the unreflected light position. */
      glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);

      if (stencilReflection) {
        glDisable(GL_STENCIL_TEST);
      }
    }

    /* Back face culling will get used to only draw either the top or the
       bottom floor.  This let's us get a floor with two distinct
       appearances.  The top floor surface is reflective and kind of red.
       The bottom floor surface is not reflective and blue. */

    /* Draw "bottom" of floor in blue. */
    glFrontFace(GL_CW);  /* Switch face orientation. */
    glColor4f(0.1, 0.1, 0.7, 1.0);
    drawFloor();
    glFrontFace(GL_CCW);

    if (renderShadow) {
      if (stencilShadow) {
	/* Draw the floor with stencil value 3.  This helps us only 
	   draw the shadow once per floor pixel (and only on the
	   floor pixels). */
        glEnable(GL_STENCIL_TEST);
        glStencilFunc(GL_ALWAYS, 3, 0xffffffff);
        glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
      }
    }

    /* Draw "top" of floor.  Use blending to blend in reflection. */
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glColor4f(0.7, 0.0, 0.0, 0.3);
    glColor4f(1.0, 1.0, 1.0, 0.3);
    drawFloor();
    glDisable(GL_BLEND);

    if (renderDinosaur) {
      /* Draw "actual" dinosaur, not its reflection. */
      drawDinosaur();
    }

    if (renderShadow) {

      /* Render the projected shadow. */

      if (stencilShadow) {

        /* Now, only render where stencil is set above 2 (ie, 3 where
	   the top floor is).  Update stencil with 2 where the shadow
	   gets drawn so we don't redraw (and accidently reblend) the
	   shadow). */
        glStencilFunc(GL_LESS, 2, 0xffffffff);  /* draw if ==1 */
        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
      }

      /* To eliminate depth buffer artifacts, we use polygon offset
	 to raise the depth of the projected shadow slightly so
	 that it does not depth buffer alias with the floor. */
      if (offsetShadow) {
	switch (polygonOffsetVersion) {
	case EXTENSION:
#ifdef GL_EXT_polygon_offset
	  glEnable(GL_POLYGON_OFFSET_EXT);
	  break;
#endif
#ifdef GL_VERSION_1_1
	case ONE_DOT_ONE:
          glEnable(GL_POLYGON_OFFSET_FILL);
	  break;
#endif
	case MISSING:
	  /* Oh well. */
	  break;
	}
      }

      /* Render 50% black shadow color on top of whatever the
         floor appareance is. */
      glEnable(GL_BLEND);
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
      glDisable(GL_LIGHTING);  /* Force the 50% black. */
      glColor4f(0.0, 0.0, 0.0, 0.5);

      glPushMatrix();
	/* Project the shadow. */
        glMultMatrixf((GLfloat *) floorShadow);
        drawDinosaur();
      glPopMatrix();

      glDisable(GL_BLEND);
      glEnable(GL_LIGHTING);

      if (offsetShadow) {
	switch (polygonOffsetVersion) {
#ifdef GL_EXT_polygon_offset
	case EXTENSION:
	  glDisable(GL_POLYGON_OFFSET_EXT);
	  break;
#endif
#ifdef GL_VERSION_1_1
	case ONE_DOT_ONE:
          glDisable(GL_POLYGON_OFFSET_FILL);
	  break;
#endif
	case MISSING:
	  /* Oh well. */
	  break;
	}
      }
      if (stencilShadow) {
        glDisable(GL_STENCIL_TEST);
      }
    }

// draw the light arrow
    glPushMatrix();
    glDisable(GL_LIGHTING);
    glColor3f(1.0, 1.0, 0.0);
    if (directionalLight) {
//      /* Draw an arrowhead. 
      glDisable(GL_CULL_FACE);
      glTranslatef(lightPosition[0], lightPosition[1], lightPosition[2]);
      glRotatef(lightAngle * -180.0 / M_PI, 0, 1, 0);
      glRotatef(atan(lightHeight/12) * 180.0 / M_PI, 0, 0, 1);
      glBegin(GL_TRIANGLE_FAN);
	glVertex3f(0, 0, 0);
	glVertex3f(2, 1, 1);
	glVertex3f(2, -1, 1);
	glVertex3f(2, -1, -1);
	glVertex3f(2, 1, -1);
	glVertex3f(2, 1, 1);
      glEnd();
//      /* Draw a white line from light direction. 
      glColor3f(1.0, 1.0, 1.0);
      glBegin(GL_LINES);
	glVertex3f(0, 0, 0);
	glVertex3f(5, 0, 0);
      glEnd();
      glEnable(GL_CULL_FACE);
    } else {
//      Draw a yellow ball at the light source. 
      glTranslatef(lightPosition[0], lightPosition[1], lightPosition[2]);
      glutSolidSphere(1.0, 5, 5);
    }
    glEnable(GL_LIGHTING);
    glPopMatrix();
//
  glPopMatrix();

  if (reportSpeed) {
    glFinish();
    end = glutGet(GLUT_ELAPSED_TIME);
    printf("Speed %.3g frames/sec (%d ms)\n", 1000.0/(end-start), end-start);
  }

  glutSwapBuffers();
}
예제 #10
0
double Display(GLuint l,int *maxframes)
{
	int x,y;
	GLfloat col[]={.25,0,.25,1};
	int frames=0;
	struct timeval start,stop;
	double len;
	GLfloat rotate=0;

	gettimeofday(&start,NULL);


	while(1)
	{
		glClearColor(0,0,0,0);
		glClearIndex(0);

		#ifdef ZBUFFER
			glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
		#else
			glClear(GL_COLOR_BUFFER_BIT);
		#endif	

		glPushMatrix();
	
		glRotatef(30,1,0,0);
		glRotatef(rotate/10,0,0,1);
		glTranslatef(-6,-4,0);
		for (y=0;y<3;y++)
		{
			glPushMatrix();
			for (x=0;x<5;x++)
			{
				glPushMatrix();
				glRotatef(rotate,y+1,-x-1,0);

				col[0]=(GLfloat)(x+1)/4;
				col[1]=0;
				col[2]=(GLfloat)(y+1)/2;
				glMaterialfv(GL_FRONT,GL_AMBIENT,col);
				glCallList(l);
				glPopMatrix();
				glTranslatef(3,0,0);
			}
			glPopMatrix();
			glTranslatef(0,4,0);
		}
		glPopMatrix();
		glFinish();

		ggiPutBox(vis,0,0,screen_x,screen_y,ggiDBGetBuffer(vis,0)->read);
		rotate+=10;
		frames++;
		if (frames==(*maxframes)) break;

		if (ggiKbhit(vis))
		{
			*maxframes=frames;
			break;
		}
	}

	gettimeofday(&stop,NULL);
	len=(double)(stop.tv_sec-start.tv_sec)+
		(double)(stop.tv_usec-start.tv_usec)/1e6;	
	return len;
}
예제 #11
0
int map (struct DIVERSsysteme *systeme,struct typeFORthreads *online,struct PACKbouton *bouton ,struct PACKobjet *objet,
        struct PERSO *perso,struct DIVERSinventaire *inventaire,struct DIVERSdeplacement *deplacement,
		struct DIVERStemps *temps,struct DIVERSui *ui,struct DIVERSchat *chat,struct DIVERScraft *craft,
		struct PACKrecompense *recompense,struct typeFORevent *FORevent,struct TIR *TIR)
{
    int index;
    chargement(systeme);
    #if CHEAT == 1

    for (index = 0 ; index < TAILLESAC ; index++)
    {
        videemplacement(&FORevent->objet->sac1[index]);
    }
    for (index = 0 ; index < 10 ; index++)
    {
		insertionsac(objet, 0);
		insertionsac(objet, 2);
		insertionsac(objet, 7);
	}
	insertionsac(objet, 3);
	insertionsac(objet, 1);
	insertionsac(objet, 4);
	insertionsac(objet, 5);
	insertionsac(objet, 6);
	insertionsac(objet, 8);
	insertionsac(objet, 9);

    #endif

    struct DONJON dj0;
    initdonjon(&dj0, systeme);
    LoadDonjon(&dj0, "dj0");

    systeme->djisloaded = true;

    online->jeuxACTIF = 1;

    for(index = 0 ; index < MAX_JOUEURS ; index++)
    {
        online->joueurs[index].ppseudo.x = 20000;
        online->joueurs[index].ppseudo.y = 20000;
        online->joueurs[index].position.w = 0;
        online->joueurs[index].position.h = 0;
    }
    checkandrefreshstuff(perso, objet, systeme, ui);
    checkinventaire(objet, inventaire);

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluOrtho2D(0,screenw,0,screenh);
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

/*#############################################################################################################################################################
											##################### Boucle De Jeu #####################																					#
######################################################################################################################################################################*/
systeme->continuer = 1;
    while (systeme->continuer == 1)
    {

        temps->tpact = SDL_GetTicks();

        if (temps->tpact - temps->tpapr >= 15) /*15   ms*/
        {
            temps->tpapr = temps->tpact;
            temps->i++;

			/*sichronisation des données*/
			sinchronisation(craft, systeme, online, perso, &dj0);
			SyncMob(&dj0, perso);
            /*calcul direction joueur client*/
            deplacement->direction.direction = directionperso(&deplacement->direction);
            /*deplacement*/
            checkPixel(&dj0.map, perso, systeme);
            move_map(perso, &deplacement->direction, &dj0.origin);
            /*gestion des dégats*/
            hitboxplayer (&dj0, perso, systeme);
            /*recupération coordonées souris*/
            SDL_GetMouseState(&systeme->pointeur.pos.x, &systeme->pointeur.pos.y);
            systeme->pointeur.pos.y = (systeme->pointeur.pos.y - screenh + systeme->pointeur.pos.h) * -1;
            /*gestion de l'ui*/
            gestionui(systeme, ui, craft, bouton, chat, inventaire, objet, perso);
            /*detection des combats*/
           // detectioncombat(monstre, inventaire, ui, deplacement, objet, perso, systeme, recompense, false);
            /*gestion des evenement*/
            boucleevent(&online->chat.lancermessage, FORevent, TIR);
            /*gestion du chat*/
            gestionchat(chat, systeme, online);

            if (TIR->letirdemander == true)
            {
                gestiontir(TIR, systeme, perso, &dj0);
            }
            COMBATgestionprojectile (TIR, &dj0);


/*##################################################################################################################################################################################
											##################### AFFICHAGE #####################																	#
##################################################################################################################################################################################*/

            /*effacage de l'écran*/
                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) ;

            /*affichage de la carte*/
            draw_pict(&dj0.map.pict);
            for (index=0 ; index<dj0.nombremonstre ; index++)
            {
                if(dj0.mob[index].BarreDeVie->life > 0)
                {
                    turn_draw_hookpict(dj0.mob[index].angle, &dj0.mob[index].hookpict, &dj0.map.pict.pos);
                    CalculerBarreDeVie(dj0.mob[index].BarreDeVie->baselife , dj0.mob[index].BarreDeVie->life, 68);
                    setPos2rect(&dj0.mob[index].BarreDeVie->pBG, dj0.mob[index].hookpict.pict.pos.x-1 + ((dj0.mob[index].hookpict.pict.pos.w-68)/2),
                                dj0.mob[index].hookpict.pict.pos.y + dj0.mob[index].hookpict.pict.pos.h+4);
                    setPos4(&dj0.mob[index].BarreDeVie->pbarre, dj0.mob[index].hookpict.pict.pos.x + ((dj0.mob[index].hookpict.pict.pos.w-68)/2),
                                dj0.mob[index].hookpict.pict.pos.y + dj0.mob[index].hookpict.pict.pos.h+5,
                                CalculerBarreDeVie(dj0.mob[index].BarreDeVie->baselife , dj0.mob[index].BarreDeVie->life, 68), 5);

                    draw(systeme->BGnoir, &dj0.mob[index].BarreDeVie->pBG);
                    draw(systeme->BGblanc, &dj0.mob[index].BarreDeVie->pbarre);
                }
            }

            /*affichage des joueurs*/
            afficherJOUEURS(perso, deplacement, systeme, online, temps);

            BattleDraw_Projectile(TIR, &dj0);
            /*affichage du chat*/
            if (ui->chat_open == true)
            {
                afficherCHAT(chat, ui, online->chat.lenbuffer, systeme);
            }
            /*affichage de l'inventaire*/
            else if (ui->inventaire_open == true)
            {
                afficherINVENTAIRE(inventaire, ui, objet, systeme);
            }
            /*affichage de l'interface utilisateur*/
            afficherUI(online->isonline, ui, bouton, temps, perso, inventaire, systeme, recompense, objet);
            /*affichage de l'interface de crafting*/
            if (ui->craft_open == true)
            {
                afficherCRAFT(craft, ui, bouton, objet, inventaire, systeme);
            }
            /*affichage du pointeur*/
            afficherPOINTEUR(systeme, objet);

            /*rendu éran*/
            glFlush();
            glFinish();
            SDL_GL_SwapWindow(systeme->screen);
        }
        else
        {
			SDL_Delay(5);
		}

/*###########################################################################################################################
								##################### Frame Par Secondes #####################								#
###########################################################################################################################*/

        if (temps->tpact - temps->tpap >= 1000)
        {
            temps->temptotal++;

			/*if it's the first second of this player*/
            if (temps->temptotal == 5)
            {
                char texte[2548] = "\nprisonnier :  \n   salut ... \n ça tombe bien,\n j'avais besoin d'un coup de main !\n tiens ! prend ce lance pierre et vas nous chercher\nquelques rat !\n\n\n\n\n\n\n\n\n\n\n\n\n\n   APPUIE SUR ENTRÉE POUR CONTINUER";
                ui->dialogue_text.texture = fenetredialogue(screenw*0.4, screenh*0.8, &ui->dialogue_back.pos, &ui->dialogue_text.pos, texte, BLANC, systeme);
                ui->dialogueactif = 1;
                insertionsac(objet, 3);
            }

            if (temps->temptotal - temps->oldipourregen >= 3)
            {
                if (perso->life < perso->lifemax)
                {
                    perso->life += REGEN;
                    perso->life += perso->regenlife;
                    if (perso->life > perso->lifemax)
					{
						perso->life = perso->lifemax;
					}
                    temps->oldipourregen = temps->temptotal;
                }

            }
            else
			{
				if (perso->life < perso->lifemax)
                {
                    perso->life += perso->regenlife;
                    if (perso->life > perso->lifemax)
					{
						perso->life = perso->lifemax;
					}
                }
			}
            if (temps->temptotal - temps->tpspoursave >= 30)
            {
                sauvegardetout(systeme->sauvegarde, dj0.map.pict.pos, perso, temps->temptotal, 0, objet->sac1, TAILLESAC, ui);
                temps->tpspoursave = temps->temptotal;
            }

            sprintf(temps->StringI, "IPS => %d", temps->i);
            sprintf(perso->slife, "vie : %0.0f/%d", perso->life, perso->lifemax);
            sprintf(temps->stringtempstotal, "age du personnage : %dj %dh %dmin %dsec", calcultempsjours(temps->temptotal), calcultempsheures(temps->temptotal), calcultempsminutes(temps->temptotal), calcultempssecondes(temps->temptotal));

            temps->fps.texture = imprime (temps->StringI, screenw, BLANC, systeme, NULL, NULL);
            perso->tlife.texture = imprime (perso->slife, screenw, BLANC, systeme, NULL, NULL);
            temps->temps.texture = imprime (temps->stringtempstotal, screenw, BLANC, systeme, NULL, NULL);

            for(index = 0; index < 10 ; index++)
            {
                if(online->chat.schat[index][0] != '\0')
                {
                    chat->pstringchat[index].y = (screenh*0.5)+(online->chat.poschat[index]*(screenh*0.047));
                    SDL_DestroyTexture(chat->tstringchat[index]);
                  //  chat->tstringchat[index] = imprime(online->chat.schat[index], screenw, BLANC, systeme, NULL, NULL);
                }
            }

            temps->i = 0;
            temps->tpap = temps->tpact;
        }
    }

/*###########################################################################################################################
																															#
								##################### Fin de Fonction #####################									#
																														#
###########################################################################################################################*/

    sauvegardetout(systeme->sauvegarde, dj0.map.pict.pos, perso, temps->temptotal, 0, objet->sac1, TAILLESAC, ui);

    return 1;
}
예제 #12
0
/** does dirty work drawing scene, moving pieces */
ENTRYPOINT void draw_chess(ModeInfo *mi) 
{
  Chesscreen *cs = &qs[MI_SCREEN(mi)];
  Window w = MI_WINDOW(mi);
  Display *disp = MI_DISPLAY(mi);

  if(!cs->glx_context)
    return;

  glXMakeCurrent(disp, w, *(cs->glx_context));

  /** code for moving a piece */
  if(cs->moving && ++cs->steps == 100) {
    cs->moving = cs->count = cs->steps = cs->take = 0;
    cs->game.board[cs->game.moves[cs->mc][2]][cs->game.moves[cs->mc][3]] = cs->mpiece;
    ++cs->mc;
    
    if(cs->mc == cs->game.movecount) {
      cs->done = 1;
      cs->mc = 0;
    }
  }

  if(++cs->count == 100) {
    if(!cs->done) {
      cs->mpiece = cs->game.board[cs->game.moves[cs->mc][0]][cs->game.moves[cs->mc][1]];
      cs->game.board[cs->game.moves[cs->mc][0]][cs->game.moves[cs->mc][1]] = NONE;
      
      if((cs->tpiece = cs->game.board[cs->game.moves[cs->mc][2]][cs->game.moves[cs->mc][3]])) {
	cs->game.board[cs->game.moves[cs->mc][2]][cs->game.moves[cs->mc][3]] = NONE;
	cs->take = 1;
      }
      
      cs->from[0] = cs->game.moves[cs->mc][0];
      cs->from[1] = cs->game.moves[cs->mc][1];
      cs->to[0] = cs->game.moves[cs->mc][2];
      cs->to[1] = cs->game.moves[cs->mc][3];
      
      cs->dz = (cs->to[0] - cs->from[0]) / 100;
      cs->dx = (cs->to[1] - cs->from[1]) / 100;
      cs->steps = 0;
      cs->moving = 1;
    }
    else if(cs->done == 1) {
      int newgame = cs->oldgame;
      while(newgame == cs->oldgame)
	newgame = random()%GAMES;

      /* mod the mod */
      cs->mod = 0.6 + (random()%20)/10.0;

      /* same old game */
      cs->oldgame = newgame;
      cs->game = games[cs->oldgame];
      build_colors(cs);
      cs->done = 2;
      cs->count = 0;
    }
    else {
      cs->done = 0;
      cs->count = 0;
    }
  }

  /* set lighting */
  if(cs->done) {
    glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 
	     cs->done == 1 ? 1.0+0.1*cs->count : 100.0/cs->count);
    glLightf(GL_LIGHT1, GL_CONSTANT_ATTENUATION, 
	     cs->done == 1 ? 1.0+0.1*cs->count : 100.0/cs->count);
    glLightf(GL_LIGHT1, GL_LINEAR_ATTENUATION, 0.14);
    glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.14);
  }

  display(mi, cs);

  if(mi->fps_p) do_fps(mi);
  glFinish(); 
  glXSwapBuffers(disp, w);
}
예제 #13
0
ENTRYPOINT void
draw_photopile (ModeInfo *mi)
{
  photopile_state *ss = &sss[MI_SCREEN(mi)];
  int i;

  if (!ss->glx_context)
    return;

  glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(ss->glx_context));

  if (ss->mode == EARLY)
    if (loading_initial_image (mi))
      return;

  /* Only check the wall clock every 10 frames */
  if (ss->now == 0 || ss->draw_tick++ > 10)
    {
      ss->now = time((time_t *) 0);
      if (ss->last_time == 0) ss->last_time = ss->now;
      ss->draw_tick = 0;
    }

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  {
    GLfloat t;

    glPushMatrix();
    glTranslatef (MI_WIDTH(mi)/2, MI_HEIGHT(mi)/2, 0);
    glRotatef(current_device_rotation(), 0, 0, 1);
    glTranslatef (-MI_WIDTH(mi)/2, -MI_HEIGHT(mi)/2, 0);

    /* Handle state transitions. */
    switch (ss->mode)
      {
      case SHUFFLE:
        if (--ss->mode_tick <= 0)
          {
            ss->nframe = (ss->nframe+1) % (MI_COUNT(mi)+1);

            ss->mode = NORMAL;
            ss->last_time = time((time_t *) 0);
          }
        break;
      case NORMAL:
        if (ss->now - ss->last_time > duration)
          {
            ss->mode = LOADING;
            load_image(mi);
          }
        break;
      case LOADING:
        if (ss->frames[ss->nframe].loaded_p)
          {
            set_new_positions(ss);
            ss->mode = SHUFFLE;
            ss->mode_tick = fade_ticks / speed;
          }
        break;
      default:
        abort();
      }

    t = 1.0 - ss->mode_tick / (fade_ticks / speed);
    t = 0.5 * (1.0 - cos(M_PI * t));

    /* Draw the images. */
    for (i = 0; i < MI_COUNT(mi) + (ss->mode == SHUFFLE); ++i)
      {
        int j = (ss->nframe + i + 1) % (MI_COUNT(mi) + 1);

        if (ss->frames[j].loaded_p)
          {
            GLfloat s = 1.0;
            GLfloat z = (GLfloat)i / (MI_COUNT(mi) + 1);

            switch (ss->mode)
              {
              case SHUFFLE:
                if (i == MI_COUNT(mi))
                  {
                    s *= t;
                  }
                else if (i == 0)
                  {
                    s *= 1.0 - t;
                  }
                break;
              case NORMAL:
              case LOADING:
                t = 1.0;
                break;
              default:
                abort();
              }

            draw_image(mi, j, t, s, z);
          }
      }
    glPopMatrix();
  }

  if (mi->fps_p) do_fps (mi);
  glFinish();
  glXSwapBuffers (MI_DISPLAY (mi), MI_WINDOW(mi));
}
PsychError SCREENTestTextureTwo(void) 
{
#if PSYCH_SYSTEM == PSYCH_OSX

    PsychWindowRecordType 	*sourceWinRec, *destWinRec;
    unsigned int			memorySizeBytes;
    UInt32					*textureMemory;
    GLuint					myTexture;
	int						sourceWinWidth, sourceWinHeight;

    double					t1, t2;
    			
    //all subfunctions should have these two lines.  
    PsychPushHelp(useString, synopsisString, seeAlsoString);
    if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);};
	
	//check for superfluous or missing arguments
	PsychErrorExit(PsychCapNumInputArgs(2));   	
    PsychErrorExit(PsychRequireNumInputArgs(2)); 	

    
    //Get the window structure for the onscreen and offscreen windows.
	PsychAllocInWindowRecordArg(1, TRUE, &sourceWinRec);
	PsychAllocInWindowRecordArg(2, TRUE, &destWinRec);

        
	//Now allocate memory for our texture.   This is a still a hack so we assume 32 bit pixels which could be overgenerous.  
	sourceWinWidth=(int)PsychGetWidthFromRect(sourceWinRec->rect);
	sourceWinHeight=(int)PsychGetWidthFromRect(sourceWinRec->rect);
	memorySizeBytes=sizeof(GLuint) * sourceWinWidth * sourceWinHeight;
	textureMemory=(GLuint *)malloc(memorySizeBytes);
    if(!textureMemory)
		PsychErrorExitMsg(PsychError_internal, "Failed to allocate surface memory\n");
	
	//Now read the contents of the source window in to our memory with glReadPixels.
	//The pixel format in which we pack the pixels, specified using glPixelStorei() and glReadPixels()
	//arguments should agree with the format used by glTexImage2D when we turn it into a texture below.
	//glTextImage2D is constrained by the requirement that it math the video memory pixel format,
	//therefore there is really now choice here either.  
	PsychSetGLContext(sourceWinRec);
	glReadBuffer(GL_FRONT);
	glPixelStorei(GL_PACK_ALIGNMENT, (GLint)sizeof(GLuint));
	//fromInvertedY=fromWindowRect[kPsychBottom]-fromSampleRect[kPsychBottom];
	//PsychGetPrecisionTimerSeconds(&t1);
	glReadPixels(0,0, sourceWinWidth, sourceWinHeight, GL_BGRA , GL_UNSIGNED_INT_8_8_8_8_REV, textureMemory);
	//PsychGetPrecisionTimerSeconds(&t2);
	//mexPrintf("glReadPixels took %f seconds\n", t2-t1);
	PsychTestForGLErrors();
	CGLSetCurrentContext(NULL);		//clear the current context. 
      

    //Convert the bitmap which we created into into a texture held in "client storage" aka system memory.  
    PsychSetGLContext(destWinRec); 
    glEnable(GL_TEXTURE_RECTANGLE_EXT);
    glGenTextures(1, &myTexture);								//create an index "name" for our texture
    glBindTexture(GL_TEXTURE_RECTANGLE_EXT, myTexture);			//instantiate a texture of type associated with the index and set it to be the target for subsequent gl texture operators.
   //new
	//glTextureRangeAPPLE(GL_TEXTURE_RECTANGLE_EXT, 0, NULL); 
	glTextureRangeAPPLE(GL_TEXTURE_RECTANGLE_EXT, 1 * 1600 * 1200 * 4, textureMemory); 
	glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_STORAGE_HINT_APPLE , GL_STORAGE_SHARED_APPLE);
   //end new
	glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, 1);			//tell gl how to unpack from our memory when creating a surface, namely don't really unpack it but use it for texture storage.
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MIN_FILTER, GL_NEAREST);	//specify interpolation scaling rule for copying from texture.  
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MAG_FILTER, GL_NEAREST);  //specify interpolation scaling rule from copying from texture.
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	//PsychGetPrecisionTimerSeconds(&t1);
    glTexImage2D(GL_TEXTURE_RECTANGLE_EXT, 0, GL_RGBA,  sourceWinWidth, sourceWinHeight, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, textureMemory);
	//PsychGetPrecisionTimerSeconds(&t2);
	//mexPrintf("glTexImage2D took %f seconds\n", t2-t1);
	
    
    //Copy the texture to the display.  What are the s and  t indices  of the first pixel of the texture ? 0 or 1 ?
    //set the GL context to be the onscreen window
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);		//how to combine the texture with the target.  We could also alpha blend.
	PsychGetPrecisionTimerSeconds(&t1);
	    glBegin(GL_QUADS);
        glTexCoord2d(0.0, 0.0);								glVertex2d(0.0, 0.0);
        glTexCoord2d(sourceWinWidth, 0.0 );					glVertex2d(sourceWinWidth, 0.0);
        glTexCoord2d(sourceWinWidth, sourceWinHeight);		glVertex2d(sourceWinWidth, sourceWinHeight);
        glTexCoord2d(0.0, sourceWinHeight);					glVertex2d(0.0, sourceWinHeight);
    glEnd();
    glFinish();
	PsychGetPrecisionTimerSeconds(&t2);
	mexPrintf("TestTextureTwo took %f seconds\n", t2-t1);
    glDisable(GL_TEXTURE_RECTANGLE_EXT);

    //Close  up shop.  Unlike with normal textures is important to release the context before deallocating the memory which glTexImage2D() was given. 
    //First release the GL context, then the CG context, then free the memory.
#endif

    return(PsychError_none);

}
예제 #15
0
//Called to draw scene
void Display(void)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();

	//use gluLookAt to look at torus
	gluLookAt(	0.0f,10.0f,10.0f, 
				0.0f, 0.0f, 0.0f,
				0.0f, 1.0f, 0.0f);

	//rotate torus
	static float angle=0.0f;
	angle+=0.1f;
	glRotatef(angle, 0.0f, 1.0f, 0.0f);


	//Get the inverse model matrix
	MATRIX4X4 inverseModelMatrix;
	glPushMatrix();
	glLoadIdentity();
	glRotatef(-angle, 0.0f, 1.0f, 0.0f);
	glGetFloatv(GL_MODELVIEW_MATRIX, inverseModelMatrix);
	glPopMatrix();

	//Get the object space light vector
	VECTOR3D objectLightPosition=inverseModelMatrix*worldLightPosition;
	
	//Loop through vertices
	for(int i=0; i<torus.numVertices; ++i)
	{
		VECTOR3D lightVector=objectLightPosition-torus.vertices[i].position;
		
		//Calculate tangent space light vector
		torus.vertices[i].tangentSpaceLight.x=
			torus.vertices[i].sTangent.DotProduct(lightVector);
		torus.vertices[i].tangentSpaceLight.y=
			torus.vertices[i].tTangent.DotProduct(lightVector);
		torus.vertices[i].tangentSpaceLight.z=
			torus.vertices[i].normal.DotProduct(lightVector);
	}


	//Draw bump pass
	if(drawBumps)
	{
		//Bind normal map to texture unit 0
		glBindTexture(GL_TEXTURE_2D, normalMap);
		glEnable(GL_TEXTURE_2D);

		//Bind normalisation cube map to texture unit 1
		glActiveTexture(GL_TEXTURE1_ARB);
		glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, normalisationCubeMap);
		glEnable(GL_TEXTURE_CUBE_MAP_ARB);
		glActiveTextureARB(GL_TEXTURE0_ARB);

		//Set vertex arrays for torus
		glVertexPointer(3, GL_FLOAT, sizeof(TORUS_VERTEX), &torus.vertices[0].position);
		glEnableClientState(GL_VERTEX_ARRAY);

		//Send texture coords for normal map to unit 0
		glTexCoordPointer(2, GL_FLOAT, sizeof(TORUS_VERTEX), &torus.vertices[0].s);
		glEnableClientState(GL_TEXTURE_COORD_ARRAY);

		//Send tangent space light vectors for normalisation to unit 1
		glClientActiveTexture(GL_TEXTURE1_ARB);
		glTexCoordPointer(3, GL_FLOAT, sizeof(TORUS_VERTEX), &torus.vertices[0].tangentSpaceLight);
		glEnableClientState(GL_TEXTURE_COORD_ARRAY);
		glClientActiveTexture(GL_TEXTURE0_ARB);


		//Set up texture environment to do (tex0 dot tex1)*color
		glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);
		glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);
		glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_REPLACE);

		glActiveTextureARB(GL_TEXTURE1_ARB);
	
		glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);
		glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);
		glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_DOT3_RGB_ARB);
		glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);
	
		glActiveTextureARB(GL_TEXTURE0_ARB);


	
		//Draw torus
		glDrawElements(GL_TRIANGLES, torus.numIndices, GL_UNSIGNED_INT, torus.indices);


		//Disable textures
		glDisable(GL_TEXTURE_2D);

		glActiveTextureARB(GL_TEXTURE1_ARB);
		glDisable(GL_TEXTURE_CUBE_MAP_ARB);
		glActiveTextureARB(GL_TEXTURE0_ARB);

		//disable vertex arrays
		glDisableClientState(GL_VERTEX_ARRAY);
	
		glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	
		glClientActiveTexture(GL_TEXTURE1_ARB);
		glDisableClientState(GL_TEXTURE_COORD_ARRAY);
		glClientActiveTexture(GL_TEXTURE0_ARB);

		//Return to standard modulate texenv
		glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	}

	//If we are drawing both passes, enable blending to multiply them together
	if(drawBumps && drawColor)
	{
		//Enable multiplicative blending
		glBlendFunc(GL_DST_COLOR, GL_ZERO);
		glEnable(GL_BLEND);
	}

	//Perform a second pass to color the torus
	if(drawColor)
	{
		if(!drawBumps)
		{
			glLightfv(GL_LIGHT1, GL_POSITION, VECTOR4D(objectLightPosition));
			glLightfv(GL_LIGHT1, GL_DIFFUSE, white);
			glLightfv(GL_LIGHT1, GL_AMBIENT, black);
			glLightModelfv(GL_LIGHT_MODEL_AMBIENT, black);
			glEnable(GL_LIGHT1);
			glEnable(GL_LIGHTING);

			glMaterialfv(GL_FRONT, GL_DIFFUSE, white);
		}

		//Bind decal texture
		glBindTexture(GL_TEXTURE_2D, decalTexture);
		glEnable(GL_TEXTURE_2D);

		//Set vertex arrays for torus
		glVertexPointer(3, GL_FLOAT, sizeof(TORUS_VERTEX), &torus.vertices[0].position);
		glEnableClientState(GL_VERTEX_ARRAY);

		glNormalPointer(GL_FLOAT, sizeof(TORUS_VERTEX), &torus.vertices[0].normal);
		glEnableClientState(GL_NORMAL_ARRAY);

		glTexCoordPointer(2, GL_FLOAT, sizeof(TORUS_VERTEX), &torus.vertices[0].s);
		glEnableClientState(GL_TEXTURE_COORD_ARRAY);

		//Draw torus
		glDrawElements(GL_TRIANGLES, torus.numIndices, GL_UNSIGNED_INT, torus.indices);

		if(!drawBumps)
			glDisable(GL_LIGHTING);

		//Disable texture
		glDisable(GL_TEXTURE_2D);

		//disable vertex arrays
		glDisableClientState(GL_VERTEX_ARRAY);
		glDisableClientState(GL_NORMAL_ARRAY);
		glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	}

	//Disable blending if it is enabled
	if(drawBumps && drawColor)
		glDisable(GL_BLEND);

	glFinish();
	glutSwapBuffers();
	glutPostRedisplay();
}
예제 #16
0
/* Render one frame
 */
ENTRYPOINT void
draw_glblur (ModeInfo *mi)
{
  glblur_configuration *bp = &bps[MI_SCREEN(mi)];
  Display *dpy = MI_DISPLAY(mi);
  Window window = MI_WINDOW(mi);

  GLfloat color0[4] = {0.0, 0.0, 0.0, 1.0};
  GLfloat color1[4] = {0.0, 0.0, 0.0, 1.0};
  GLfloat color2[4] = {0.0, 0.0, 0.0, 1.0};
  GLfloat color3[4] = {0.0, 0.0, 0.0, 1.0};
  GLfloat spec[4]   = {1.0, 1.0, 1.0, 1.0};

  double rx, ry, rz;
  double px, py, pz;
  int extra_polys = 0;

  if (!bp->glx_context)
    return;

  glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(bp->glx_context));

  /* Decide what we're drawing
   */
  if (0 == (random() % 30))
    {
      bp->show_cube_p   = (0 == (random() % 10));
      bp->show_spikes_p = (0 == (random() % 20));
    }

  /* Select new colors for the various objects
   */
  color0[0] = bp->colors0[bp->ccolor].red   / 65536.0;
  color0[1] = bp->colors0[bp->ccolor].green / 65536.0;
  color0[2] = bp->colors0[bp->ccolor].blue  / 65536.0;

  color1[0] = bp->colors1[bp->ccolor].red   / 65536.0;
  color1[1] = bp->colors1[bp->ccolor].green / 65536.0;
  color1[2] = bp->colors1[bp->ccolor].blue  / 65536.0;

  color2[0] = bp->colors2[bp->ccolor].red   / 65536.0;
  color2[1] = bp->colors2[bp->ccolor].green / 65536.0;
  color2[2] = bp->colors2[bp->ccolor].blue  / 65536.0;

  color3[0] = bp->colors3[bp->ccolor].red   / 65536.0;
  color3[1] = bp->colors3[bp->ccolor].green / 65536.0;
  color3[2] = bp->colors3[bp->ccolor].blue  / 65536.0;

  bp->ccolor++;
  if (bp->ccolor >= bp->ncolors) bp->ccolor = 0;


  get_position (bp->rot, &px, &py, &pz, !bp->button_down_p);
  get_rotation (bp->rot, &rx, &ry, &rz, !bp->button_down_p);

  px = (px - 0.5) * 2;
  py = (py - 0.5) * 2;
  pz = (pz - 0.5) * 8;
  rx *= 360;
  ry *= 360;
  rz *= 360;

  /* Generate scene_dlist1, which contains the box (not spikes),
     rotated into position.
   */
  glNewList (bp->scene_dlist1, GL_COMPILE);
  {
    glMatrixMode (GL_MODELVIEW);
    glPushMatrix ();
    glTranslatef (px, py, pz);
    gltrackball_rotate (bp->trackball);
    glRotatef (rx, 1.0, 0.0, 0.0);
    glRotatef (ry, 0.0, 1.0, 0.0);
    glRotatef (rz, 0.0, 0.0, 1.0);

    glMaterialfv (GL_FRONT_AND_BACK, GL_SPECULAR, spec);

    glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color0);
    glCallList (bp->obj_dlist0);

    glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color1);
    glCallList (bp->obj_dlist1);

    glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color2);
    glCallList (bp->obj_dlist2);

    glMatrixMode (GL_MODELVIEW);
    glPopMatrix ();
  }
  glEndList ();


  /* Generate scene_dlist2, which contains the spikes (not box),
     rotated into position.
   */
  glNewList (bp->scene_dlist2, GL_COMPILE);
  {
    glMatrixMode (GL_MODELVIEW);
    glPushMatrix ();
    glTranslatef (px, py, pz);
    gltrackball_rotate (bp->trackball);
    glRotatef (rx, 1.0, 0.0, 0.0);
    glRotatef (ry, 0.0, 1.0, 0.0);
    glRotatef (rz, 0.0, 0.0, 1.0);

    glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color3);
    glCallList (bp->obj_dlist3);

    glMatrixMode (GL_MODELVIEW);
    glPopMatrix ();
  }
  glEndList ();


  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  render_scene_to_texture (mi);

  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  if (bp->show_cube_p || bp->button_down_p)
    {
      glCallList (bp->scene_dlist1);
      extra_polys += bp->scene_polys1;
    }
  if (bp->show_spikes_p || bp->button_down_p)
    {
      glCallList (bp->scene_dlist2);
      extra_polys += bp->scene_polys2;
    }

  overlay_blur_texture (mi);
  mi->polygon_count += extra_polys;

  glFlush ();

  if (mi->fps_p) do_fps (mi);
  glFinish();

  glXSwapBuffers(dpy, window);
}
예제 #17
0
ENTRYPOINT void
draw_pinion (ModeInfo *mi)
{
  pinion_configuration *pp = &pps[MI_SCREEN(mi)];
  Display *dpy = MI_DISPLAY(mi);
  Window window = MI_WINDOW(mi);
  Bool wire_p = MI_IS_WIREFRAME(mi);

  if (!pp->glx_context)
    return;

  glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(pp->glx_context));

  if (!pp->button_down_p)
    {
      if (!debug_one_gear_p || pp->ngears == 0)
        scroll_gears (mi);
      spin_gears (mi);
    }

  glShadeModel(GL_SMOOTH);

  glEnable(GL_DEPTH_TEST);
  glEnable(GL_NORMALIZE);
  glEnable(GL_CULL_FACE);

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glPushMatrix ();
  {
    gltrackball_rotate (pp->trackball);
    mi->polygon_count = 0;

    glScalef (16, 16, 16);   /* map vp_width/height to the screen */

    if (debug_one_gear_p)    /* zoom in */
      glScalef (3, 3, 3);
    else if (debug_p)        /* show the "visible" and "layout" areas */
      {
        GLfloat ow = pp->layout_right - pp->render_left;
        GLfloat rw = pp->render_right - pp->render_left;
        GLfloat s = (pp->vp_width / ow) * 0.85;
        glScalef (s, s, s);
        glTranslatef (-(ow - rw) / 2, 0, 0);
      }
    else
      {
        GLfloat s = 1.2;
        glScalef (s, s, s);           /* zoom in a little more */
        glRotatef (-35, 1, 0, 0);     /* tilt back */
        glRotatef (  8, 0, 1, 0);     /* tilt left */
        glTranslatef (0.02, 0.1, 0);  /* pan up */
      }

    draw_gears (mi);

    if (debug_p)
      {
        if (!wire_p) glDisable(GL_LIGHTING);
        glColor3f (0.6, 0, 0);
        glBegin(GL_LINE_LOOP);
        glVertex3f (pp->render_left,  pp->vp_top,    0);
        glVertex3f (pp->render_right, pp->vp_top,    0);
        glVertex3f (pp->render_right, pp->vp_bottom, 0);
        glVertex3f (pp->render_left,  pp->vp_bottom, 0);
        glEnd();
        glColor3f (0.4, 0, 0);
        glBegin(GL_LINES);
        glVertex3f (pp->vp_left,      pp->vp_top,    0);
        glVertex3f (pp->vp_left,      pp->vp_bottom, 0);
        glVertex3f (pp->vp_right,     pp->vp_top,    0);
        glVertex3f (pp->vp_right,     pp->vp_bottom, 0);
        glEnd();
        glColor3f (0, 0.4, 0);
        glBegin(GL_LINE_LOOP);
        glVertex3f (pp->layout_left,  pp->vp_top,    0);
        glVertex3f (pp->layout_right, pp->vp_top,    0);
        glVertex3f (pp->layout_right, pp->vp_bottom, 0);
        glVertex3f (pp->layout_left,  pp->vp_bottom, 0);
        glEnd();
        if (!wire_p) glEnable(GL_LIGHTING);
      }

    if (pp->draw_tick++ > 10)   /* only do this every N frames */
      {
        pp->draw_tick = 0;
        find_mouse_gear (mi);
        new_label (mi);
      }
  }
  glPopMatrix ();

  glCallList (pp->title_list);

  if (mi->fps_p) do_fps (mi);
  glFinish();

  glXSwapBuffers(dpy, window);
}
예제 #18
0
static void dotest0param(benchmark * bmark)
{
    float stime, etime, dtime, tottime, maxtime, mintime;
    int num, numelem, calibnum, j;

    glPushAttrib(GL_ALL_ATTRIB_BITS);
    bmark->init();

    stime = glutGet(GLUT_ELAPSED_TIME);

    dtime = 0.0;
    calibnum = 0;
    while (dtime < 2.0) {
	bmark->run(0, 1);
	glFinish();
	etime = glutGet(GLUT_ELAPSED_TIME);
	dtime = (etime - stime) / 1000.0;
	calibnum++;
    }
    glPopAttrib();

    crDebug( "Elapsed time for the calibration test (%d): %f",
	    calibnum, dtime);

    num = (int) ((BMARKS_TIME / dtime) * calibnum);
	
    num = num / 50;

    if (num < 1)
	num = 1;

    crDebug( "Selected number of benchmark iterations: %d", num);

    mintime = HUGE_VAL;
    maxtime = -HUGE_VAL;

    for (tottime = 0.0, j = 0; j < 5; j++) {
	glPushAttrib(GL_ALL_ATTRIB_BITS);
	bmark->init();

	stime = glutGet(GLUT_ELAPSED_TIME);
	numelem = bmark->run(0, num);
	glFinish();
	etime = glutGet(GLUT_ELAPSED_TIME);

	glPopAttrib();

	dtime = (etime - stime) / 1000.0;
	tottime += dtime;

	crDebug( "Elapsed time for run %d: %f", j, dtime);

	if (dtime < mintime)
	    mintime = dtime;
	if (dtime > maxtime)
	    maxtime = dtime;
    }

    tottime -= mintime + maxtime;

    crDebug( "%s%f %s/sec", bmark->name,
	    numelem / (tottime / 3.0), bmark->unit);

    if (bmark->type == 3)
	crDebug( ", MPixel Fill/sec: %f",
		(numelem * bmark->size[0] * (float) bmark->size[0]) /
		(1000000.0 * tottime / 3.0));
    else
	crDebug( " ");
}
예제 #19
0
void CGLRenderer::FinishDrawing()
{
	glFinish();
	glFlush();
}
예제 #20
0
/* static */
void
GLComputeEvaluator::Synchronize(void * /*kernel*/) {
    // XXX: this is currently just for the performance measuring purpose.
    // need to be reimplemented by fence and sync.
    glFinish();
}
void FontRenderer::drawText(char *text, TTF_Font *font, SDL_Color color,
		SDL_Rect *location) {
	SDL_Surface *initial;
	SDL_Surface *intermediary;
	SDL_Rect rect;
	int w, h;
	GLuint texture;

	/* Use SDL_TTF to render our text */
	initial = TTF_RenderText_Blended(font, text, color);

	/* Convert the rendered text to a known format */
	w = nextpoweroftwo(initial->w);
	h = nextpoweroftwo(initial->h);

	intermediary = SDL_CreateRGBSurface(0, w, h, 32,
#if SDL_BYTEORDER != SDL_LIL_ENDIAN // OpenGL RGBA masks
                               0x000000FF,
                               0x0000FF00,
                               0x00FF0000,
                               0xFF000000
#else
                               0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF
#endif
								);
	//0x00ff0000, 0x0000ff00,
	//0x000000ff, 0xff000000);

	SDL_BlitSurface(initial, 0, intermediary, 0);

	/* Tell GL about our new texture */
	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D, texture);
	glTexImage2D(GL_TEXTURE_2D, 0, 4, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE,
			intermediary->pixels);

	/* GL_NEAREST looks horrible, if scaled... */
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	/* prepare to render our texture */
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, texture);
	glColor3f(1.0f, 1.0f, 1.0f);

	/* Draw a quad at location */
	glBegin(GL_QUADS);
	/* Recall that the origin is in the lower-left corner
	 That is why the TexCoords specify different corners
	 than the Vertex coors seem to. */
	glTexCoord2f(0.0f, 1.0f);
	glVertex2f(location->x, location->y);
	glTexCoord2f(1.0f, 1.0f);
	glVertex2f(location->x + w, location->y);
	glTexCoord2f(1.0f, 0.0f);
	glVertex2f(location->x + w, location->y + h);
	glTexCoord2f(0.0f, 0.0f);
	glVertex2f(location->x, location->y + h);
	glEnd();

	/* Bad things happen if we delete the texture before it finishes */
	glFinish();

	/* return the deltas in the unused w,h part of the rect */
	location->w = initial->w;
	location->h = initial->h;

	/* Clean up */
	SDL_FreeSurface(initial);
	SDL_FreeSurface(intermediary);
	glDeleteTextures(1, &texture);
}
예제 #22
0
파일: demo.cpp 프로젝트: issakomi/mmt
void render(double et)
{
    if (!cgshaders||!run||!camera||!context) return;
ms_fbo->Activate();
glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT);

    if (v_forward != 0 || v_backward != 0)
    {
         if (v_forward == 1)
         {
         camera->set_velocity(10.0f);
         }
         else
         {
             if (v_backward == 1)
             {
             camera->set_velocity(-10.0f);
             }
         }
    }
    else
    {
    camera->set_velocity(0.0f);
    }

    if (v_right != 0 || v_left != 0)
    {
         if (v_right == 1)
         {
         camera->set_side_velocity(10.0f);
         }
         else
         {
             if (v_left == 1)
             {
             camera->set_side_velocity(-10.0f);
             }
         }
    }
    else
    {
    camera->set_side_velocity(0.0f);
    }

#ifndef QUERY_POINTER
camera->change_heading(DEMO_D2R*heading_degrees);
camera->change_pitch  (DEMO_D2R*pitch_degrees  );
#else
camera->set_heading(DEMO_D2R*90.0f*heading_degrees);
camera->set_pitch  (DEMO_D2R*90.0f*pitch_degrees  );
#endif

camera->set_viewer_matrix(et);

camera->perspective((float)win_w,
                    (float)win_h,
                    camera_fov_radians,
                    camera_znear,
                    camera_zfar);

int_params[0] = 1;
lights_positions[0]  = light0_direction[0];
lights_positions[1]  = light0_direction[1];
lights_positions[2]  = light0_direction[2];

float_params[0] = camera->m_position_aos.getX();
float_params[1] = camera->m_position_aos.getY();
float_params[2] = camera->m_position_aos.getZ();

cgshaders->set_array_param_3f(std::string("lights_positions"),0, 0, lights_positions);
cgshaders->set_array_param_3f(std::string("float_params"),    0, 0, float_params);

glViewport(0, 0, GLsizei(win_w), GLsizei(win_h));

/////////////////////////////////////////////////////////// skybox

cgshaders->set_effect_matrix_param_fc("PROJECTION", camera->m_projection);
cgshaders->set_effect_matrix_param_fc("VIEW_INVERSE", camera->m_inv_view);    
CGpass p0 = cgGetFirstPass(cgshaders->get_technique(std::string("skybox")));

cgSetPassState(p0);

glActiveTexture(GL_TEXTURE5);
glBindTexture(GL_TEXTURE_CUBE_MAP, skybox_t);

glBindBuffer(GL_ARRAY_BUFFER, sphere0_vbo[0]);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);

glDrawArrays(GL_TRIANGLES, 0, (faces_size_sphere0/12)*3);

glDisableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER, GL_NONE);

glBindTexture(GL_TEXTURE_CUBE_MAP, GL_NONE);

//cgResetPassState(p0);
//////////////////////////////////////////////////////////////

float mvp[16];
Matrix4 mvp_aos =  camera->m_projection_aos*camera->m_view_aos;
copy_matrix4_to_float(mvp_aos,mvp);

    if (plant_shader_time > 60.0)
    {
    plant_shader_time = 0.0;
    }
plant_shader_time += et;
cgshaders->set_effect_param_1f(std::string("PLANT_SHADER_TIME"), (float)plant_shader_time);

//#if 0
    for (unsigned int x = 0; x < objects.size(); x++)
    {

    DisplayInterface * di = objects.at(x);
        for (int k = 0; k < di->submeshes_size(); k++)
        {
        SubMesh * sm = di->get_submesh(k);
            if (!sm)             continue;
            if (!sm->get_data()) continue;
            //if (pass == L_SHADOW_PASS     && sm->get_data()->cast_shadows[0] == 0)
            //    continue;
            //if (pass == L_2ND_SHADOW_PASS && sm->get_data()->cast_shadows[1] == 0)
            //    continue;
            if (sm->callback != 0)
            {
            mparams[5] = sm->get_data()->shininess;
            mparams[6] = sm->get_data()->tc_scale_x;
            mparams[7] = sm->get_data()->tc_scale_y;
            mparams[8] = (float)win_w;
            mparams[9] = (float)win_h;
            sm->callback(sm->get_data(), 
                         cgshaders,
                         int_params,
                         mparams,
                         float_params,
                         lights_positions,
                         camera->m_view,
                         camera->m_inv_view,
                         0,
                         0,
                         mvp,
                         0,
                         0);
            }
        }
    }
//#endif
//

// ARK
cgshaders->set_pass_state(cgshaders->get_first_pass(std::string("tbn0")));

// ARK MAIN
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, ark_sp);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, ark_nm);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, ark_t);

    for (unsigned int x = 0; x < ark.size(); x++)
    {
    DisplayInterface * di = ark.at(x);
        for (int k = 0; k < di->submeshes_size(); k++)
        {
        SubMesh * sm = di->get_submesh(k);
            if (!sm)             continue;
            if (!sm->get_data()) continue;
            //if (pass == L_SHADOW_PASS     && sm->get_data()->cast_shadows[0] == 0)
            //    continue;
            //if (pass == L_2ND_SHADOW_PASS && sm->get_data()->cast_shadows[1] == 0)
            //    continue;
            if (sm->callback != 0)
            {
            mparams[5] = sm->get_data()->shininess;
            mparams[6] = sm->get_data()->tc_scale_x;
            mparams[7] = sm->get_data()->tc_scale_y;
            mparams[8] = (float)win_w;
            mparams[9] = (float)win_h;
            sm->callback(sm->get_data(), 
                         cgshaders,
                         int_params,
                         mparams,
                         float_params,
                         lights_positions,
                         camera->m_view,
                         camera->m_inv_view,
                         0,
                         0,
                         mvp,
                         0,
                         0);
            }
        }
    }

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, GL_NONE);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, GL_NONE);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, GL_NONE);

////////

// ARK WHEELS
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, ark_wheels_sp);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, ark_wheels_nm);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, ark_wheels_t);

    for (unsigned int x = 0; x < ark_wheels.size(); x++)
    {
    DisplayInterface * di = ark_wheels.at(x);
        for (int k = 0; k < di->submeshes_size(); k++)
        {
        SubMesh * sm = di->get_submesh(k);
            if (!sm)             continue;
            if (!sm->get_data()) continue;
            //if (pass == L_SHADOW_PASS     && sm->get_data()->cast_shadows[0] == 0)
            //    continue;
            //if (pass == L_2ND_SHADOW_PASS && sm->get_data()->cast_shadows[1] == 0)
            //    continue;
            if (sm->callback != 0)
            {
            mparams[5] = sm->get_data()->shininess;
            mparams[6] = sm->get_data()->tc_scale_x;
            mparams[7] = sm->get_data()->tc_scale_y;
            mparams[8] = (float)win_w;
            mparams[9] = (float)win_h;
            sm->callback(sm->get_data(), 
                         cgshaders,
                         int_params,
                         mparams,
                         float_params,
                         lights_positions,
                         camera->m_view,
                         camera->m_inv_view,
                         0,
                         0,
                         mvp,
                         0,
                         0);
            }
        }
    }

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, GL_NONE);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, GL_NONE);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, GL_NONE);

//

// ARK WHEELS
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, ark_tread_sp);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, ark_tread_nm);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, ark_tread_t);

    for (unsigned int x = 0; x < ark_tread.size(); x++)
    {
    DisplayInterface * di = ark_tread.at(x);
        for (int k = 0; k < di->submeshes_size(); k++)
        {
        SubMesh * sm = di->get_submesh(k);
            if (!sm)             continue;
            if (!sm->get_data()) continue;
            //if (pass == L_SHADOW_PASS     && sm->get_data()->cast_shadows[0] == 0)
            //    continue;
            //if (pass == L_2ND_SHADOW_PASS && sm->get_data()->cast_shadows[1] == 0)
            //    continue;
            if (sm->callback != 0)
            {
            mparams[5] = sm->get_data()->shininess;
            mparams[6] = sm->get_data()->tc_scale_x;
            mparams[7] = sm->get_data()->tc_scale_y;
            mparams[8] = (float)win_w;
            mparams[9] = (float)win_h;
            sm->callback(sm->get_data(), 
                         cgshaders,
                         int_params,
                         mparams,
                         float_params,
                         lights_positions,
                         camera->m_view,
                         camera->m_inv_view,
                         0,
                         0,
                         mvp,
                         0,
                         0);
            }
        }
    }

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, GL_NONE);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, GL_NONE);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, GL_NONE);

//

glFinish();
glBindFramebuffer(GL_READ_FRAMEBUFFER, ms_fbo->GetFramebuffer());
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, scene_fbo->GetFramebuffer());
glBlitFramebuffer(0, 0, win_w, win_h, 0, 0, win_w, win_h, GL_COLOR_BUFFER_BIT, GL_LINEAR);
glBindFramebuffer(GL_FRAMEBUFFER, GL_NONE);
cgshaders->set_pass_state(cgshaders->get_first_pass(std::string("fsquad")));
glViewport(0, 0, static_cast<GLsizei>(win_w), static_cast<GLsizei>(win_h) );
glDepthFunc(GL_ALWAYS);
glActiveTexture(GL_TEXTURE0);
scene_fbo->BindColor();
glBindBuffer(GL_ARRAY_BUFFER, fsquad[0]);
glVertexAttribPointer(0, 2, GL_FLOAT,GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, GL_NONE);
glBindTexture(GL_TEXTURE_RECTANGLE, GL_NONE);
glDepthFunc(GL_LEQUAL);

print_info();

context->swap_buffers();
}
예제 #23
0
파일: shContext.c 프로젝트: gdawg/androidvg
VG_API_CALL void vgFinish(void)
{
  VG_GETCONTEXT(VG_NO_RETVAL);
  glFinish();
  VG_RETURN(VG_NO_RETVAL);
}
예제 #24
0
void OpenCLKernel::initialize()
{
	string sourceString;
	const char *sourceCString;
	cl_platform_id *platform_ids, platform_id = NULL;
	cl_device_id *device_ids, device_id = NULL;
	cl_uint ret_num_devices;
	cl_uint ret_num_platforms;
	cl_uint extensions_size;
	char* extensions;
	bool deviceSelected = false;

	/* Load the source code containing the kernel*/
	sourceString = getFileContents(fileName);
	sourceCString = sourceString.c_str();

	//Wait until all opengl commands are processed
	glFinish();

	/* Get Platform and Device Info */
	status = clGetPlatformIDs( 0, NULL, &ret_num_platforms);
	if (status != CL_SUCCESS)
		return;

	platform_ids = new cl_platform_id[ret_num_platforms];
	status = clGetPlatformIDs(ret_num_platforms, platform_ids, &ret_num_platforms);
	if (status != CL_SUCCESS)
		return;

	for(cl_uint i = 0; i < ret_num_platforms && !deviceSelected; i++)
	{
		platform_id = platform_ids[i];

		/* Get GPU type devices */
		status = clGetDeviceIDs( platform_id, CL_DEVICE_TYPE_GPU, 0, NULL, &ret_num_devices);
		device_ids = new cl_device_id[ret_num_devices];
		status = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, ret_num_devices, device_ids, NULL);

		for(cl_uint j = 0; j < ret_num_devices && !deviceSelected; j++)
		{
			device_id = device_ids[j];

			/* Look for device with CL_GL_SHARING_EXT extension */
			status = clGetDeviceInfo( device_id, CL_DEVICE_EXTENSIONS, 0, NULL, &extensions_size);
			extensions = new char[extensions_size];
			status = clGetDeviceInfo( device_id, CL_DEVICE_EXTENSIONS, extensions_size, extensions, NULL);

			string ext = extensions;   
			deviceSelected = ext.find(CL_GL_SHARING_EXT) != string::npos;
			delete[] extensions;
		}

		delete[] device_ids;
	}

	delete[] platform_ids;

// Apple use share group
#ifdef __APPLE__
	// Get current CGL Context and CGL Share group
	CGLContextObj kCGLContext = CGLGetCurrentContext();
	CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
#endif

	// Create CL context properties
	cl_context_properties properties[] = 
	{
//Windows properties
#if defined(WIN32) || defined(WIN64)
		CL_GL_CONTEXT_KHR, (cl_context_properties) wglGetCurrentContext(), // WGL Context
		CL_WGL_HDC_KHR, (cl_context_properties) wglGetCurrentDC(), // WGL HDC
		CL_CONTEXT_PLATFORM, (cl_context_properties) platform_id, // OpenCL platform
//Apple properties
#elif __APPLE__
		CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
		(cl_context_properties) kCGLShareGroup,
//Other unix properties 
#elif __unix
		CL_GL_CONTEXT_KHR, (cl_context_properties) glXGetCurrentContext(), // GLX Context
		CL_GLX_DISPLAY_KHR, (cl_context_properties) glXGetCurrentDisplay(), // GLX Display
		CL_CONTEXT_PLATFORM, (cl_context_properties) platform_id, // OpenCL platform
#endif
		0
	};

#ifdef __APPLE__
	// Create a context with device in the CGL share group
	context = clCreateContext(properties, 0, 0, NULL, 0, 0);
#else
	/* Create OpenCL context */
	context = clCreateContext(properties, 1, &device_id, NULL, NULL, &status);
#endif

	/* Create Command Queue */
	command_queue = clCreateCommandQueue(context, device_id, 0, &status);

	/* Create Kernel Program from the source */
	program = clCreateProgramWithSource(context, 1, &sourceCString,
		NULL, &status);

	/* Build Kernel Program */
	status = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL);

	/* Create OpenCL Kernel */
	kernel = clCreateKernel(program, kernelName.c_str(), &status);
}
/**
 * @brief 描画イベント関数
 */
void display()
{
  // 移動方向判別
  if (!moveChange)
    position_x += realSlitSpeed;
  else
    position_x -= realSlitSpeed;

  // 不用意な領域にいかない
  switch (mode)
  {
  case SLIT_MOVE_MODE:
    if (repetition == 0)
    {
      if (position_x > 2.95)     // 右端に行き過ぎたとき
        position_x = 0.0 - realSlitWidth;
      else if (position_x + realSlitWidth < 0.0) // 左端に行き過ぎたとき
        position_x = 2.95;
    }
    else
    {
      if (position_x > 2.95)     // 右端に行き過ぎたとき
        moveChange = true;
      else if (position_x + realSlitWidth < 0.0) // 左端に行き過ぎたとき
        moveChange = false;
    }
    break;

  case IMAGE_MOVE_MODE:
    if (repetition == 0)
    {
      if (position_x > 1.5 + (realSlitWidth / 2.0))      // 右端に行き過ぎたとき
        position_x = -1.5 - (realSlitWidth / 2.0);
      else if (position_x + 3.0 < 1.5 - (realSlitWidth / 2.0)) // 左端に行き過ぎたとき
        position_x = 1.5 + (realSlitWidth / 2.0);
    }
    else
    {
      if (position_x > 1.5 + (realSlitWidth / 2.0))      // 右端に行き過ぎたとき
        moveChange = true;
      else if (position_x + 3.0 < 1.5 - (realSlitWidth / 2.0)) // 左端に行き過ぎたとき
        moveChange = false;
    }
    break;

  default:
    break;
  }

  glutPostRedisplay(); // 再描画要求


  // バッファのクリア
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  // モデルを見る準備
  glMatrixMode(GL_MODELVIEW);
  // 行列を初期化
  glLoadIdentity();

  // 現在のパラメーターを表示
  //viewParam();

  // 描画する
  switch (mode)
  {
  case SLIT_MOVE_MODE:  // スリットが動く
    draw_moveSlit(position_x, realSlitWidth, ImageMode, slitColor);
    break;

  case IMAGE_MOVE_MODE: // 画像が動く
    draw_moveImage(position_x, realSlitWidth, ImageMode, slitColor);
    break;

  default:
    break;
  }

  // 描画させる
  glFlush();
  // バッファの入れ替え
  glutSwapBuffers();

  // swap buf が終了するまでwait
  glFinish();
}
예제 #26
0
void PlatformFlushIfNeeded()
{
	glFinish();
}
예제 #27
0
int main(int argc, char* argv[])
{
	b3SetCustomPrintfFunc(myprintf);
	b3Vector3 test(1,2,3);
	test.x = 1;
	test.y = 4;

    printf("main start");

	b3CommandLineArgs args(argc,argv);
	ParticleDemo::ConstructionInfo ci;

	if (args.CheckCmdLineFlag("help"))
	{
		Usage();
		return 0;
	}


	args.GetCmdLineArgument("selected_demo",selectedDemo);


	if (args.CheckCmdLineFlag("new_batching"))
	{
		useNewBatchingKernel = true;
	}
	bool benchmark=args.CheckCmdLineFlag("benchmark");
	dump_timings=args.CheckCmdLineFlag("dump_timings");
	ci.useOpenCL = !args.CheckCmdLineFlag("disable_opencl");
	ci.m_useConcaveMesh = true;//args.CheckCmdLineFlag("use_concave_mesh");
	if (ci.m_useConcaveMesh)
	{
		enableExperimentalCpuConcaveCollision = true;
	}

	args.GetCmdLineArgument("cl_device", ci.preferredOpenCLDeviceIndex);
	args.GetCmdLineArgument("cl_platform", ci.preferredOpenCLPlatformIndex);
	args.GetCmdLineArgument("x_dim", ci.arraySizeX);
	args.GetCmdLineArgument("y_dim", ci.arraySizeY);
	args.GetCmdLineArgument("z_dim", ci.arraySizeZ);
	args.GetCmdLineArgument("x_gap", ci.gapX);
	args.GetCmdLineArgument("y_gap", ci.gapY);
	args.GetCmdLineArgument("z_gap", ci.gapZ);



	#ifndef B3_NO_PROFILE
	b3ProfileManager::Reset();
#endif //B3_NO_PROFILE


	window = new b3gDefaultOpenGLWindow();

	b3gWindowConstructionInfo wci(g_OpenGLWidth,g_OpenGLHeight);

	window->createWindow(wci);
	window->setResizeCallback(MyResizeCallback);
	window->setMouseMoveCallback(MyMouseMoveCallback);
	window->setMouseButtonCallback(MyMouseButtonCallback);
	window->setKeyboardCallback(MyKeyboardCallback);

	window->setWindowTitle("Bullet 3.x GPU Rigid Body http://bulletphysics.org");
	printf("-----------------------------------------------------\n");


#ifndef __APPLE__
	glewInit();
#endif

	gui = new GwenUserInterface();

    printf("started GwenUserInterface");


	GLPrimitiveRenderer prim(g_OpenGLWidth,g_OpenGLHeight);

	stash = initFont(&prim);


	gui->init(g_OpenGLWidth,g_OpenGLHeight,stash,window->getRetinaScale());

    printf("init fonts");


	gui->setToggleButtonCallback(MyButtonCallback);

	gui->registerToggleButton(MYPAUSE,"Pause");
	gui->registerToggleButton(MYPROFILE,"Profile");
	gui->registerToggleButton(MYRESET,"Reset");






	int numItems = sizeof(allDemos)/sizeof(ParticleDemo::CreateFunc*);
	demoNames.clear();
	for (int i=0;i<numItems;i++)
	{
		GpuDemo* demo = allDemos[i]();
		demoNames.push_back(demo->getName());
		delete demo;
	}

	gui->registerComboBox(MYCOMBOBOX1,numItems,&demoNames[0]);
	gui->setComboBoxCallback(MyComboBoxCallback);



	do
	{
		bool syncOnly = false;
		gReset = false;




	static bool once=true;




	glClearColor(1,0,0,1);
	glClear(GL_COLOR_BUFFER_BIT);

	{

		window->startRendering();
		glFinish();

		


		float color[4] = {1,1,1,1};
		prim.drawRect(0,0,200,200,color);
		float retinaScale = 1;

		  float x = 10;
            float y=220;
            float  dx=0;
            if (1)
            {
                B3_PROFILE("font sth_draw_text");

				glEnable(GL_BLEND);
				GLint err = glGetError();
				assert(err==GL_NO_ERROR);

				glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
				err = glGetError();
				assert(err==GL_NO_ERROR);

				glDisable(GL_DEPTH_TEST);
				err = glGetError();
				assert(err==GL_NO_ERROR);


				glDisable(GL_CULL_FACE);

                sth_begin_draw(stash);
                sth_flush_draw(stash);
                sth_draw_text(stash, droidRegular,20.f, x, y, "Non-retina font rendering !@#$", &dx,g_OpenGLWidth,g_OpenGLHeight,0,1);//retinaScale);
                if (retinaScale!=1.f)
                    sth_draw_text(stash, droidRegular,20.f*retinaScale, x, y+20, "Retina font rendering!@#$", &dx,g_OpenGLWidth,g_OpenGLHeight,0,retinaScale);
                sth_flush_draw(stash);

                sth_end_draw(stash);
            }

		gui->draw(g_OpenGLWidth,g_OpenGLHeight);
		window->endRendering();
		glFinish();
	}
	once=false;

//	OpenGL3CoreRenderer render;

	glClearColor(0,1,0,1);
	glClear(GL_COLOR_BUFFER_BIT);

	window->endRendering();

	glFinish();



	window->setWheelCallback(b3DefaultWheelCallback);




	{
		GpuDemo* demo = allDemos[selectedDemo]();
//		demo->myinit();
		bool useGpu = false;


		int maxObjectCapacity=128*1024;

		ci.m_instancingRenderer = new GLInstancingRenderer(maxObjectCapacity);//render.getInstancingRenderer();
		ci.m_window = window;
		ci.m_gui = gui;
		ci.m_instancingRenderer->init();
		ci.m_instancingRenderer->InitShaders();
		ci.m_primRenderer = &prim;
//		render.init();

		demo->initPhysics(ci);



		

		printf("-----------------------------------------------------\n");

		FILE* csvFile = 0;
		FILE* detailsFile = 0;

		if (benchmark)
		{
			gPause = false;
			char prefixFileName[1024];
			char csvFileName[1024];
			char detailsFileName[1024];

			b3OpenCLDeviceInfo info;
			b3OpenCLUtils::getDeviceInfo(demo->getInternalData()->m_clDevice,&info);
			
			//todo: move this time stuff into the Platform/Window class
#ifdef _WIN32
			SYSTEMTIME time;
			GetLocalTime(&time);
			char buf[1024];
			DWORD dwCompNameLen = 1024;
			if (0 != GetComputerName(buf, &dwCompNameLen))
			{
				printf("%s", buf);
			} else
			{
				printf("unknown", buf);
			}

			sprintf(prefixFileName,"%s_%s_%s_%d_%d_%d_date_%d-%d-%d_time_%d-%d-%d",info.m_deviceName,buf,demoNames[selectedDemo],ci.arraySizeX,ci.arraySizeY,ci.arraySizeZ,time.wDay,time.wMonth,time.wYear,time.wHour,time.wMinute,time.wSecond);
			
#else
			timeval now;
			gettimeofday(&now,0);
			
			struct tm* ptm;
			ptm = localtime (&now.tv_sec);
			char buf[1024];
#ifdef __APPLE__
			sprintf(buf,"MacOSX");
#else
			sprintf(buf,"Unix");
#endif
			sprintf(prefixFileName,"%s_%s_%s_%d_%d_%d_date_%d-%d-%d_time_%d-%d-%d",info.m_deviceName,buf,demoNames[selectedDemo],ci.arraySizeX,ci.arraySizeY,ci.arraySizeZ,
					ptm->tm_mday,
					ptm->tm_mon+1,
					ptm->tm_year+1900,
					ptm->tm_hour,
					ptm->tm_min,
					ptm->tm_sec);
			
#endif

			sprintf(csvFileName,"%s.csv",prefixFileName);
			sprintf(detailsFileName,"%s.txt",prefixFileName);
			printf("Open csv file %s and details file %s\n", csvFileName,detailsFileName);

			//GetSystemTime(&time2);

			csvFile=fopen(csvFileName,"w");
			detailsFile = fopen(detailsFileName,"w");
			if (detailsFile)
				defaultOutput = detailsFile;

			//if (f)
			//	fprintf(f,"%s (%dx%dx%d=%d),\n",  g_deviceName,ci.arraySizeX,ci.arraySizeY,ci.arraySizeZ,ci.arraySizeX*ci.arraySizeY*ci.arraySizeZ);
		}

		
		fprintf(defaultOutput,"Demo settings:\n");
		fprintf(defaultOutput,"  SelectedDemo=%d, demoname = %s\n", selectedDemo, demo->getName());
		fprintf(defaultOutput,"  x_dim=%d, y_dim=%d, z_dim=%d\n",ci.arraySizeX,ci.arraySizeY,ci.arraySizeZ);
		fprintf(defaultOutput,"  x_gap=%f, y_gap=%f, z_gap=%f\n",ci.gapX,ci.gapY,ci.gapZ);
		fprintf(defaultOutput,"\nOpenCL settings:\n");
		fprintf(defaultOutput,"  Preferred cl_device index %d\n", ci.preferredOpenCLDeviceIndex);
		fprintf(defaultOutput,"  Preferred cl_platform index%d\n", ci.preferredOpenCLPlatformIndex);
		fprintf(defaultOutput,"\n");

		b3OpenCLUtils::printPlatformInfo( demo->getInternalData()->m_platformId);
		fprintf(defaultOutput,"\n");
		b3OpenCLUtils::printDeviceInfo( demo->getInternalData()->m_clDevice);
		fprintf(defaultOutput,"\n");
		do
		{
			GLint err = glGetError();
			assert(err==GL_NO_ERROR);

			b3ProfileManager::Reset();
			b3ProfileManager::Increment_Frame_Counter();

//			render.reshape(g_OpenGLWidth,g_OpenGLHeight);
			ci.m_instancingRenderer->resize(g_OpenGLWidth,g_OpenGLHeight);
			prim.setScreenSize(g_OpenGLWidth,g_OpenGLHeight);

			window->startRendering();

			glClearColor(0.6,0.6,0.6,1);
			glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
			glEnable(GL_DEPTH_TEST);


			if (!gPause)
			{
				B3_PROFILE("clientMoveAndDisplay");

				demo->clientMoveAndDisplay();
			}
			else
			{

			}

			{
				B3_PROFILE("renderScene");
				demo->renderScene();
			}
			err = glGetError();
			assert(err==GL_NO_ERROR);


			/*if (demo->getDynamicsWorld() && demo->getDynamicsWorld()->getNumCollisionObjects())
			{
				B3_PROFILE("renderPhysicsWorld");
				b3AlignedObjectArray<b3CollisionObject*> arr = demo->getDynamicsWorld()->getCollisionObjectArray();
				b3CollisionObject** colObjArray = &arr[0];

				render.renderPhysicsWorld(demo->getDynamicsWorld()->getNumCollisionObjects(),colObjArray, syncOnly);
				syncOnly = true;

			}
			*/
			{
				B3_PROFILE("gui->draw");
				gui->draw(g_OpenGLWidth,g_OpenGLHeight);
			}
			err = glGetError();
			assert(err==GL_NO_ERROR);

			{
				B3_PROFILE("window->endRendering");
				window->endRendering();
			}
			err = glGetError();
			assert(err==GL_NO_ERROR);

			{
				B3_PROFILE("glFinish");
			}

			

			if (dump_timings)
			{
				b3ProfileManager::dumpAll(stdout);
			}

			if (csvFile)
			{
				static int frameCount=0;

				if (frameCount>0)
				{
					DumpSimulationTime(csvFile);
					if (detailsFile)
					{
							fprintf(detailsFile,"\n==================================\nFrame %d:\n", frameCount);
							b3ProfileManager::dumpAll(detailsFile);
					}
				}

				if (frameCount>=102)
					window->setRequestExit();
				frameCount++;
			}



		} while (!window->requestedExit() && !gReset);


		demo->exitPhysics();
		b3ProfileManager::CleanupMemory();
		delete demo;
		if (detailsFile)
		{
			fclose(detailsFile);
			detailsFile=0;
		}
		if (csvFile)
		{
			fclose(csvFile);
			csvFile=0;
		}
	}



	} while (gReset);


	gui->setComboBoxCallback(0);
	delete gui;
	gui=0;

	window->closeWindow();
	delete window;
	window = 0;

	return 0;
}
예제 #28
0
파일: window.cpp 프로젝트: bohara/Equalizer
void Window::finish() const
{
    glFinish();
}
예제 #29
0
static void
dotest1param(benchmark * bmark)
{
   float stime, etime, dtime, tottime, maxtime, mintime;
   int num, numelem, calibnum, j, k;

   fprintf(stdout, "%s\n", bmark->name);

   for (j = 0; j < bmark->numsize; j++) {
      fprintf(stderr, "Current size: %d\n", bmark->size[j]);

      glPushAttrib(GL_ALL_ATTRIB_BITS);
      bmark->init();

      stime = glutGet(GLUT_ELAPSED_TIME);

      dtime = 0.0;
      calibnum = 0;
      while (dtime < 2.0) {
	 bmark->run(bmark->size[j], 1);
	 glFinish();
	 etime = glutGet(GLUT_ELAPSED_TIME);
	 dtime = (etime - stime) / 1000.0;
	 calibnum++;
      }
      glPopAttrib();

      fprintf(stderr, "Elapsed time for the calibration test (%d): %f\n",
	      calibnum, dtime);

      num = (int) ((BMARKS_TIME / dtime) * calibnum);

      if (num < 1)
	 num = 1;

      fprintf(stderr, "Selected number of benchmark iterations: %d\n", num);

      mintime = HUGE_VAL;
      maxtime = -HUGE_VAL;

      for (numelem = 1, tottime = 0.0, k = 0; k < 5; k++) {
	 glPushAttrib(GL_ALL_ATTRIB_BITS);
	 bmark->init();

	 stime = glutGet(GLUT_ELAPSED_TIME);
	 numelem = bmark->run(bmark->size[j], num);
	 glFinish();
	 etime = glutGet(GLUT_ELAPSED_TIME);

	 glPopAttrib();

	 dtime = (etime - stime) / 1000.0;
	 tottime += dtime;

	 fprintf(stderr, "Elapsed time for run %d: %f\n", k, dtime);

	 if (dtime < mintime)
	    mintime = dtime;
	 if (dtime > maxtime)
	    maxtime = dtime;
      }

      tottime -= mintime + maxtime;

      fprintf(stdout, "SIZE=%03d => %f %s/sec", bmark->size[j],
	      numelem / (tottime / 3.0), bmark->unit);
      if (bmark->type == 2)
	 fprintf(stdout, ", MPixel Fill/sec: %f\n",
		 (numelem * bmark->size[j] * bmark->size[j] / 2) /
		 (1000000.0 * tottime / 3.0));
      else
	 fprintf(stdout, "\n");
   }

   fprintf(stdout, "\n\n");
}
예제 #30
0
void MainFrame::SaveImage()
{
    cout<<"save image"<<endl;
    static unsigned int image_index=0;
    GLint l_ViewPort[4];
    glGetIntegerv(GL_VIEWPORT, l_ViewPort);

    for (int i = 0; i != 4; ++i)
    l_ViewPort[i]-=l_ViewPort[i]%4;

    int width=  (l_ViewPort[2] - l_ViewPort[0]);
    int height=(l_ViewPort[3] - l_ViewPort[1]);
    cout<<"l_Viewport[0] is "<<l_ViewPort[0]<<endl;
    cout<<"l_Viewport[1] is "<<l_ViewPort[1]<<endl;
    cout<<"l_Viewport[2] is "<<l_ViewPort[2]<<endl;
    cout<<"l_Viewport[3] is "<<l_ViewPort[3]<<endl;

    glReadBuffer(GL_BACK);
    glFinish();
    glPixelStorei(GL_PACK_ALIGNMENT, 3);
    glPixelStorei(GL_PACK_ROW_LENGTH, 0);
    glPixelStorei(GL_PACK_SKIP_ROWS, 0);
    glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
    unsigned char *glBitmapData = new unsigned char [3 * width * height];
    unsigned char *glBitmapData_flip = new unsigned char [3 * width * height];
    //  glReadPixels((GLint)0, (GLint)0, (GLint)width, (GLint)height, GL_RGB, GL_BYTE, glBitmapData);
    glReadPixels((GLint)0, (GLint)0, (GLint)width, (GLint)height, GL_RGB, GL_UNSIGNED_BYTE, glBitmapData);
    for(int i=0;i<height;++i)
    memcpy(&glBitmapData_flip[3*i*width],&glBitmapData[3*(height-i-1)*width],3*width);
    //wxImage img (width, height, glBitmapData, true);
    wxImage img (width, height, glBitmapData_flip, true);
    cout<<"width is "<<width<<endl;
    cout<<"height is "<<height<<endl;
    wxInitAllImageHandlers();

    //glReadPixels(l_ViewPort[0], l_ViewPort[1], l_ViewPort[2], l_ViewPort[3],
    //             GL_RGB,GL_UNSIGNED_BYTE,(GLvoid*)&(pixels[0]));
    //wxImage img(width, height, &(pixels[0]),true);
    //img.Mirror(false);
    cout<<"outputed data"<<endl;
    stringstream file;
    file<<setfill('0');
    // file<<path;
    // file<<savefolder;
    file<<"./";
    file<<"Rendering";
    file<<"/";

    if(!bfs::exists(file.str().c_str()))
    {
        bfs::create_directory(file.str().c_str());
    }
    file<<"render"<<setw(4)<< m_nCurrentFrame <<".png";
    //file<<"out"<<setw(3)<<image_index++<<".bmp";
    cout<<"saving as "<<file.str()<<endl;

    wxString mystring(file.str().c_str(),wxConvUTF8);
    cout<<"made mystring"<<endl;
    img.SaveFile(mystring,wxBITMAP_TYPE_PNG);
    //img.SaveFile(mystring,wxBITMAP_TYPE_BMP);
    cout<<"Saved"<<endl;
    // // Second method:

    delete [] glBitmapData;
    delete [] glBitmapData_flip;
}