Example #1
0
// this is called during hardware initialization.
// allocate memory.
void app_init(void) {

  print_dbg("\r\n preset_init...");  
  presets_init();

  // this must come after preset init!
  // uses preset data when adding system ops...
  print_dbg("\r\n net_init... ");
  net_init();

  print_dbg("\r\n scene_init...");
  scene_init();

  print_dbg("\r\n files_init...");
  files_init();

  /// WARNING: initialization order is important.

  print_dbg("\r\n render_init...");
  render_init();

  // initialize flash-management buffers
  print_dbg("\r\n flash_bees_init...");
  flash_bees_init();
}
Example #2
0
File: SMS.c Project: wally4000/code
int MenuPlusAction(int action, void* param)			{
	switch (action)			{
		case MA_LOADROM:
			if (systemInit)
			{
				machine_poweroff();
			}

			strcpy(menuConfig.file.filename, (char*)param);

			if(load_rom(menuConfig.file.filename) == 0) 
			{
				return 0;
			}

			if(systemInit)
			{
				if (gblMachineType == EM_SMS)			{
					sms_init();
					render_init();
					system_poweron();
				}
			}

			gblNewGame = 1;
			menuPlusTerminated = 1;
			menuConfig.video.pause = 0;
			break;
	}
	return 1;
}
Example #3
0
// this is called during hardware initialization.
// allocate memory.
void app_init(void) {
  print_dbg("\r\n net_init... ");
  net_init();

  print_dbg("\r\n preset_init...");  
  presets_init();

  print_dbg("\r\n scene_init...");
  scene_init();

  print_dbg("\r\n files_init...");
  files_init();

  /// WARNING: initialization order is important.

  print_dbg("\r\n render_init...");
  render_init();

  /// move these after scene load,
  // so that initial graphics reflect scene data
  /* print_dbg("\r\n pages_init..."); */
  /* pages_init(); */

  /* print_dbg("\r\n play_init..."); */
  /* play_init(); */

  // initialize flash-management buffers
  print_dbg("\r\n flash_bees_init...");
  flash_bees_init();
}
Example #4
0
File: render.c Project: ccxvii/mio
void render_reshape(int w, int h)
{
	render_init();

	if (fbo_w == w && fbo_h == h)
		return;

	fbo_w = w;
	fbo_h = h;

	glBindTexture(GL_TEXTURE_2D, tex_depth);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, w, h, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);

	glBindTexture(GL_TEXTURE_2D, tex_normal);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, w, h, 0, GL_RGB, GL_FLOAT, NULL);

	glBindTexture(GL_TEXTURE_2D, tex_albedo);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB_ALPHA, w, h, 0, GL_RGB, GL_FLOAT, NULL);

	glBindTexture(GL_TEXTURE_2D, tex_forward);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB, w, h, 0, GL_RGB, GL_FLOAT, NULL);

	glBindFramebuffer(GL_FRAMEBUFFER, fbo_geometry);
	gl_assert_framebuffer(GL_FRAMEBUFFER, "geometry");

	glBindFramebuffer(GL_FRAMEBUFFER, fbo_forward);
	gl_assert_framebuffer(GL_FRAMEBUFFER, "deferred");

	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
Example #5
0
/*
** For render.c, the bitmap pixel numbering starts at the bottom
** left and goes to the top right.  The coordinate of the bottom
** left point on the bottom left pixel is (0,0) and the coordinate
** of the top right point of the top right pixel is (1,1).
** The pixels go in integers from (0,0) [bottom left]
**                             to (bmap->width-1,bmap->height-1) [top right]
**
*/
void render_triangle(WILLUSBITMAP *bmap,TRIANGLE2D *tri,RENDER_COLOR *rcolor,
                     RENDER_COLOR *bgcolor,int render_type)

    {
    TRIANGLE2D    newtri;
    static POINT2D clippath[16];
    int         i,nc;

/*
printf(";render_triangle\n");
printf("; rcolor=%g, %g, %g\n",rcolor->rgb[0],rcolor->rgb[1],rcolor->rgb[2]);
printf("; bgcolor=%g, %g, %g\n",bgcolor->rgb[0],bgcolor->rgb[1],bgcolor->rgb[2]);
printf("; type=%d\n",render_type);
for (i=0;i<4;i++)
printf("%6.4f %6.4f\n",tri->p[i%3].x,tri->p[i%3].y);
printf("//nc\n");
*/
    if (clipbox==NULL)
        render_init();
    render_clipped_triangle(clippath,&nc,clipbox,tri);
    for (i=1;i<nc-1;i++)
        {
        newtri = tri2d_triangle(clippath[0],clippath[i],clippath[i+1]);
        render_triangle_1(bmap,&newtri,rcolor,bgcolor,render_type);
        }
    }
Example #6
0
int main(int argc,char **argv)
{
	printf("Keys:\n"
	       "ESC/q: quit\n"
	       "    w: pitch forward\n"
	       "    s: pitch back\n"
	       "    a: rotate left\n"
	       "    d: rotate right\n"
	       "    R: reset all rotations\n"
	       "    h: Toggle reference led display\n"
	       "    x: Toggle reference axis display\n"
	       "    p: Toggle glove position information\n"
	       "    r: Toggle glove rotation information\n");
	glutInit(&argc,argv);

	glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
	glutInitWindowSize(600,600);
	glutCreateWindow(argv[0]);

	render_init();

	glove=p5glove_open(0);
	if (glove==NULL) {
		perror(argv[0]);
		exit(1);
	}

	glutDisplayFunc(render_display);
	glutIdleFunc(render_next);
	glutKeyboardFunc(render_keyboard);
	glutReshapeFunc(render_reshape);
	glutMainLoop();

    return 0;
}
Example #7
0
int init(void)
{
// ARA begin insert new code
#ifdef __ANDROID__
	runNEONTests();
#endif
// ARA end

	perf_init();
	ctrl_init();
	render_init();
	physics_init();

	landscapeMeshId = render_init_mesh(
		LargeMeshVtx,sizeof(float)*6,
		LargeMeshVtx+3,sizeof(float)*6,
		LargeMeshIdx,sizeof(unsigned short)*3,
		LargeMeshVtxCount,LargeMeshIdxCount/3);

	convexMeshId = render_init_mesh(
		BarrelVtx,sizeof(float)*6,
		BarrelVtx+3,sizeof(float)*6,
		BarrelIdx,sizeof(unsigned short)*3,
		BarrelVtxCount,BarrelIdxCount/3);

	return 0;
}
Example #8
0
bool Indigo::run(const char* name, void (*fn)(void*), void* param)
{
	// Create render comms pipe
	PIPE_RACK::instance().m_render_pipe =  OOBase::allocate_shared<Indigo::Pipe,OOBase::ThreadLocalAllocator>("render");
	if (!PIPE_RACK::instance().m_render_pipe)
		LOG_ERROR_RETURN(("Failed to allocate render pipe: %s",OOBase::system_error_text()),false);

	render_init(PIPE_RACK::instance().m_render_pipe.get());

	// Not sure if we need to set this first...
	glfwSetErrorCallback(&on_glfw_error);

	if (!glfwInit())
		LOG_ERROR_RETURN(("glfwInit failed"),false);

	// Set defaults
	glfwDefaultWindowHints();

	bool ret = false;
	OOBase::SharedPtr<OOBase::Thread> thread;
	PIPE_RACK::instance().m_logic_pipe = Indigo::start_thread(name,thread);
	if (PIPE_RACK::instance().m_logic_pipe)
	{
		ret = PIPE_RACK::instance().m_logic_pipe->call(OOBase::make_delegate<OOBase::ThreadLocalAllocator>(fn),param);
		if (ret)
			thread->join();
	}

	glfwTerminate();

	return ret;
}
Example #9
0
/**
 * Initializes game modules.
 * 
 * Mostly what this function does is link up the various game modules.
 */
void initialize_game()
{
    int window_id;
    
    // Seed the random number generator
    srand( time(NULL) );
    
	/* Initialize windowing and rendering */
    window_id = Window_new(PROJECT_TITLE);

    // Create a new game
    new_game();
    // TODO: show main menu instead of immediately starting the game
    /* Initialize the game mechanics module */
    //mechanics_init( GET_CURRENT_TIME() );
    
    Window_registerReshapeEventHandler( window_id, window_resized );
    
    /* Initialize input */
    input_init(window_id);
    
	render_init();

    /* Register the game loop */
    glutIdleFunc(game_loop);
}
Example #10
0
void Sunrise::render(double time) {
  render_init();
  glDisable(GL_DEPTH_TEST);
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glShadeModel(GL_SMOOTH);
  glDrawArrays(GL_TRIANGLE_FAN, 0, mesh.vertexCount());
  logErrors();
}
Example #11
0
static void LoadCommon(MDFNFILE *fp)
{
 try
 {
  /* Assign default settings (US NTSC machine) */
  sms.display     = DISPLAY_NTSC;

  sms.territory   = MDFN_GetSettingI("sms.territory");
  sms.use_fm      = FALSE;

  Cart_Init(fp);
  Cart_LoadNV();

  if(IS_SMS && sms.territory == TERRITORY_DOMESTIC)
   sms.use_fm = MDFN_GetSettingB("sms.fm");

  MDFNMP_Init(1024, 65536 / 1024);

  system_assign_device(PORT_A, DEVICE_PAD2B);
  system_assign_device(PORT_B, DEVICE_PAD2B);

  MDFNMP_AddRAM(8192, 0xC000, sms.wram);

  sms_init();
  pio_init();
  vdp_init(IS_SMS && sms.territory == TERRITORY_DOMESTIC);
  render_init();

  MDFNGameInfo->GameSetMD5Valid = FALSE;

  uint32 sndclk;

  if(sms.display == DISPLAY_PAL)
  {
   sndclk = 3546893;
   MDFNGameInfo->fps = (uint32)((uint64)65536 * 256 * sndclk / 313 / 228); //6144000 * 65536 * 256 / 515 / 198); // 3072000 * 2 * 10000 / 515 / 198
  }
  else
  {
   sndclk = 3579545;
   MDFNGameInfo->fps = (uint32)((uint64)65536 * 256 * sndclk / 262 / 228); //6144000 * 65536 * 256 / 515 / 198); // 3072000 * 2 * 10000 / 515 / 198
  }

  MDFNGameInfo->MasterClock = MDFN_MASTERCLOCK_FIXED(sndclk);

  SMS_SoundInit(sndclk, sms.use_fm);

  sms.save = 0;

  system_reset();
 }
 catch(...)
 {
  Cleanup();
  throw;
 }
}
Example #12
0
void system_init(void)
{
    sms_init();
    pio_init();
    vdp_init();
    render_init();
    sound_init();

    sms.save = 0;
}
Example #13
0
void
shader_init() {
	if (RS) return;

	struct render_state * rs = (struct render_state *) malloc(sizeof(*rs));
	memset(rs, 0 , sizeof(*rs));

	struct render_init_args RA;
	// todo: config these args
	RA.max_buffer = 128;
	RA.max_layout = 4;
	RA.max_target = 128;
	RA.max_texture = 256;
	RA.max_shader = MAX_PROGRAM;

	int rsz = render_size(&RA);
	rs->R = (struct render *)malloc(rsz);
	rs->R = render_init(&RA, rs->R, rsz);
	texture_initrender(rs->R);
	screen_initrender(rs->R);
	label_initrender(rs->R);
	lsprite_initrender(rs->R);
	renderbuffer_initrender(rs->R);

	rs->current_program = -1;
	rs->blendchange = 0;
	render_setblend(rs->R, BLEND_ONE, BLEND_ONE_MINUS_SRC_ALPHA);

	uint16_t idxs[6 * MAX_COMMBINE];
	int i;
	for (i=0;i<MAX_COMMBINE;i++) {
		idxs[i*6] = i*4;
		idxs[i*6+1] = i*4+1;
		idxs[i*6+2] = i*4+2;
		idxs[i*6+3] = i*4;
		idxs[i*6+4] = i*4+2;
		idxs[i*6+5] = i*4+3;
	}
	
	rs->index_buffer = render_buffer_create(rs->R, INDEXBUFFER, idxs, 6 * MAX_COMMBINE, sizeof(uint16_t));
	rs->vertex_buffer = render_buffer_create(rs->R, VERTEXBUFFER, NULL,  4 * MAX_COMMBINE, sizeof(struct vertex));

	struct vertex_attrib va[4] = {
		{ "position", 0, 2, sizeof(float), BUFFER_OFFSET(vp.vx) },
		{ "texcoord", 0, 2, sizeof(uint16_t), BUFFER_OFFSET(vp.tx) },
		{ "color", 0, 4, sizeof(uint8_t), BUFFER_OFFSET(rgba) },
		{ "additive", 0, 4, sizeof(uint8_t), BUFFER_OFFSET(add) },
	};
	rs->layout = render_register_vertexlayout(rs->R, sizeof(va)/sizeof(va[0]), va);
	render_set(rs->R, VERTEXLAYOUT, rs->layout, 0);
	render_set(rs->R, INDEXBUFFER, rs->index_buffer, 0);
	render_set(rs->R, VERTEXBUFFER, rs->vertex_buffer, 0);

	RS = rs;
}
Example #14
0
void GLWindow::initializeGL()
{
	// инициализируем рендер из libvrender
	if(!render_init()) {
		qDebug() << "ERROR: failed to init render";
		exit(-1);
	}
	
	// инициализация ввода
	input_init();
}
Example #15
0
int main(int argc, char *argv[]) {
	uint8_t buf[1024];
	size_t n;
#ifdef FRSKY
	frsky_state_t fs;
#endif
	telemetry_data_t td;
	telemetry_init(&td);

	render_init();

	long long prev_time = current_timestamp();
	while(1) {
		FD_ZERO(&set);
		FD_SET(STDIN_FILENO, &set);
		timeout.tv_sec = 0;
		//read 100ms
		timeout.tv_usec = 100*1000;
		n = select(STDIN_FILENO + 1, &set, NULL, NULL, &timeout);
		//printf("%d\n",n);
		if(n > 0) {
			n = read(STDIN_FILENO, buf, sizeof(buf));

			if(n == 0) {
			//	break; //EOF
			}

			if(n<0) {
				perror("read");
				exit(-1);
			}
#ifdef FRSKY
			frsky_parse_buffer(&fs, &td, buf, n);
#elif defined(LTM)
			ltm_read(&td, buf, n);
#elif defined(MAVLINK)
			mavlink_read(&td, buf, n);
#endif
		}

	#ifdef DEBUG
		prev_time = current_timestamp();
		render(&td);
		long long took = current_timestamp() - prev_time;
		printf("Render took %lldms to execute.\n", took);
	#else
		render(&td);
	#endif

	}

	return 0;
}
Example #16
0
int	main(int ac, char **av)
{
	t_data	*d;

	if (init_start(&d, ac, av) < 0 || render_init(d) < 0)
	{
		exit_free();
		return (error("main:: Initialization error"));
	}
	run_the_game(d);
	return (0);
}
Example #17
0
void load_holomesh(int craft_index) {
    g_current_craft = craft_index;
#ifdef OVERDRAW_TEST
    int resource_id = RESOURCE_ID_HOLO_TIEFTR;
#else
    int resource_id = c_craft_info[craft_index].resource_id;
#endif
    ResHandle handle = resource_get_handle(resource_id);
    
#ifdef PROFILE
    max_time = 0;
    min_time = 10000;
    total_time = 0;
    samples = 0;
#endif
    
    // Allocate space for the resource
    // TODO: estimate this better
    if (g_holomesh == NULL) {
        g_holomesh = (holomesh_t*) malloc(MAX_MEMORY_SIZE);
        ASSERT(g_holomesh != NULL);
    }

    // Load it
    size_t size = resource_size(handle);
    size_t copied = resource_load(handle, (uint8_t*) g_holomesh, size);
    ASSERT(copied == g_holomesh->file_size);
    ASSERT(size >= g_holomesh->file_size);
    
    // Deserialize it
    holomesh_result hr = holomesh_deserialize(g_holomesh, size);
    ASSERT(hr == hmresult_ok);
    
    // Allocate renderer resources
    size_t scratch_size = g_holomesh->scratch_size;
    scratch_set(((uint8_t*)g_holomesh) + size, scratch_size);
    
    // Init the renderer
    render_init();
    
    // Load the logo
    load_background_image(g_holomesh->info.affiliation);
    
    APP_LOG(APP_LOG_LEVEL_DEBUG, "HOLOMESH: %u bytes [0x%x-0x%x], %u mesh, %u scratch, %u hulls", 
            (unsigned) MAX_MEMORY_SIZE,
            (unsigned) g_holomesh,
            (unsigned) g_holomesh + (unsigned) MAX_MEMORY_SIZE,
            (unsigned) size,
            (unsigned) scratch_size,
            (unsigned) g_holomesh->hulls.size);

    ASSERT(g_holomesh->hulls.size <= MAX_HULLS);
}
Example #18
0
static xsltStylesheetPtr
render_load_stylesheet (const gchar *xsltName)
{
	xsltStylesheetPtr	i18n_filter;
	xsltStylesheetPtr	xslt;
	xmlDocPtr		xsltDoc, resDoc;
	gchar			*filename;

	if (!stylesheets)
		render_init ();

	/* try to serve the stylesheet from the cache */
	xslt = (xsltStylesheetPtr)g_hash_table_lookup (stylesheets, xsltName);
	if (xslt)
		return xslt;

	/* or load and translate it... */

	/* 1. load localization stylesheet */
	i18n_filter = xsltParseStylesheetFile (PACKAGE_DATA_DIR G_DIR_SEPARATOR_S PACKAGE G_DIR_SEPARATOR_S "xslt" G_DIR_SEPARATOR_S "i18n-filter.xslt");
	if (!i18n_filter) {
		g_warning ("fatal: could not load localization stylesheet!");
		return NULL;
	}

	/* 2. load and localize the rendering stylesheet */
	filename = g_strjoin (NULL, PACKAGE_DATA_DIR G_DIR_SEPARATOR_S PACKAGE G_DIR_SEPARATOR_S "xslt" G_DIR_SEPARATOR_S, xsltName, ".xml", NULL);
	xsltDoc = xmlParseFile (filename);
	if (!xsltDoc)
		g_warning ("fatal: could not load rendering stylesheet (%s)!", xsltName);

	g_free (filename);

	resDoc = xsltApplyStylesheet (i18n_filter, xsltDoc, (const gchar **)langParams->params);
	if (!resDoc)
		g_warning ("fatal: applying localization stylesheet failed (%s)!", xsltName);

	/* Use the following to debug XSLT transformation problems */
	/* xsltSaveResultToFile (stdout, resDoc, i18n_filter); */

	/* 3. create localized rendering stylesheet */
	xslt = xsltParseStylesheetDoc(resDoc);
	if (!xslt)
		g_warning("fatal: could not load rendering stylesheet (%s)!", xsltName);

	xmlFreeDoc (xsltDoc);
	xsltFreeStylesheet (i18n_filter);

	g_hash_table_insert (stylesheets, g_strdup (xsltName), xslt);
	
	return xslt;
}
Example #19
0
int init(void)
{
	perf_init();
	ctrl_init();
	render_init();
	physics_init();

	float angX,angY,r;
	render_get_view_angle(angX,angY,r);
	r *= 0.5f;
	render_set_view_angle(angX,angY,r);

	return 0;
}
Example #20
0
void PhongModel::render(double /*time*/) {
  render_init();
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LESS);
  glEnable(GL_CULL_FACE);
  uniform("ambient", ambient);
  uniform("diffuse", diffuse);
  uniform("specular", specular);
  uniform("shininess", shininess);
  uniform("colour", colour);

  glDrawArrays(mesh.meshType(), 0, mesh.vertexCount());

  logErrors();
}
Example #21
0
int xlib_init() {
	scr = DefaultScreen(dpy);
	root = DefaultRootWindow(dpy);
#ifdef module_randr
	randr_init();
#else
	set(presX, 0); set(presY, 0);
	set(presW, DisplayWidth(dpy,scr));
	set(presH, DisplayHeight(dpy,scr));
#endif /* moudle_randr */
	XSetWindowAttributes wa;
	wa.background_pixel = 0x000000;
	wa.backing_store = Always;
	wa.event_mask = ButtonPressMask | KeyPressMask | PointerMotionMask;
	topWin = XCreateWindow(dpy, root, get_d(presX), get_d(presY), get_d(presW),
			get_d(presH), 0, DefaultDepth(dpy,scr), InputOutput,
			DefaultVisual(dpy,scr), CWBackPixel | CWBackingStore | CWEventMask, &wa);
	presWin = XCreateWindow(dpy, topWin, 0, 0, get_d(presW), get_d(presH), 0,
			DefaultDepth(dpy,scr), InputOutput, DefaultVisual(dpy,scr),
			CWBackingStore | CWEventMask, &wa);
	XClassHint hint;
	hint.res_name = "Presentation";
	hint.res_class = "Slider";
	XSetClassHint(dpy, topWin, &hint);
	XStoreName(dpy, topWin, "Slider");
	XMapWindow(dpy, topWin); // TODO where is it?
	XMapWindow(dpy, presWin);
	/* override placement of annoying WMs */
	XMoveWindow(dpy, topWin, get_d(presX), get_d(presY));
	/* other init functions */
	if (command_init()) return xlib_free(1);
	if (render_init(get_s(presFile))) return xlib_free(2);
//	render_init(get_s(noteFile));
#ifdef module_cursor
	if (cursor_init(presWin)) return xlib_free(3);
#endif
#ifdef module_sorter
	if (sorter_init(topWin)) return xlib_free(4);
#endif
	render_set_fader(presWin, 1);
	command(cmdFullscreen, NULL);
	return 0;
}
Example #22
0
void system_init(int rate)
{
    /* Initialize the VDP emulation */
    vdp_init();

    /* Initialize the SMS emulation */
    sms_init();

    /* Initialize the look-up tables and related data */
    render_init();

    /* Enable sound emulation if the sample rate was specified */
    audio_init(rate);

    /* Don't save SRAM by default */
    sms.save = 0;

    /* Clear emulated button state */
    memset(&input, 0, sizeof(t_input));
}
Example #23
0
void Edges::render(double /*time*/) {
  logErrors();
  glShadeModel(GL_SMOOTH);
  glDisable(GL_DEPTH_TEST);
  glDisable(GL_CULL_FACE);
  render_init();

  uniform_i("colour", 0);
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, colour_texture);

  uniform_i("depth", 1);
  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_2D, depth_texture);

  glDrawArrays(mesh.meshType(), 0, mesh.vertexCount());

  logErrors();
  glActiveTexture(GL_TEXTURE0);
  logErrors();
}
Example #24
0
int init(void)
{
	perf_init();
	ctrl_init();
	render_init();
	physics_init();

	landscapeMeshId = render_init_mesh(
		LargeMeshVtx,sizeof(float)*6,
		LargeMeshVtx+3,sizeof(float)*6,
		LargeMeshIdx,sizeof(unsigned short)*3,
		LargeMeshVtxCount,LargeMeshIdxCount/3);

	convexMeshId = render_init_mesh(
		BarrelVtx,sizeof(float)*6,
		BarrelVtx+3,sizeof(float)*6,
		BarrelIdx,sizeof(unsigned short)*3,
		BarrelVtxCount,BarrelIdxCount/3);

	return 0;
}
Example #25
0
int main(int argc, char **argv)
{
    setlocale(LC_ALL, "");

    if (argc != 2) {
        printf("Say the magic word?\n");
        return 1;
    }

    GameState game;
    InputState input;

    srand(hash(argv[1]));

    game_init(&game, argv[1]);
    render_init();

    do {
        render(&game);
        game_process(&game, &input);
    } while (!input.quit);

    render_teardown();
}
Example #26
0
int main(int argc, char ** argv)
{
	set_exe_str(argv[0]);
	data_block *blocks = NULL;
	data_block *seek_block = NULL;
	uint32_t seek_offset;
	uint32_t block_offset;

	uint32_t fps = 60;
	config = load_config(argv[0]);
	render_init(320, 240, "vgm play", 60, 0);

	uint32_t opts = 0;
	if (argc >= 3 && !strcmp(argv[2], "-y")) {
		opts |= YM_OPT_WAVE_LOG;
	}

	ym2612_context y_context;
	ym_init(&y_context, render_sample_rate(), MCLKS_NTSC, MCLKS_PER_YM, render_audio_buffer(), opts);

	psg_context p_context;
	psg_init(&p_context, render_sample_rate(), MCLKS_NTSC, MCLKS_PER_PSG, render_audio_buffer());

	FILE * f = fopen(argv[1], "rb");
	vgm_header header;
	fread(&header, sizeof(header), 1, f);
	if (header.version < 0x150 || !header.data_offset) {
		header.data_offset = 0xC;
	}
	fseek(f, header.data_offset + 0x34, SEEK_SET);
	uint32_t data_size = header.eof_offset + 4 - (header.data_offset + 0x34);
	uint8_t * data = malloc(data_size);
	fread(data, 1, data_size, f);
	fclose(f);

	uint32_t mclks_sample = MCLKS_NTSC / 44100;
	uint32_t loop_count = 2;

	uint8_t * end = data + data_size;
	uint8_t * cur = data;
	uint32_t current_cycle = 0;
	while (cur < end) {
		uint8_t cmd = *(cur++);
		switch(cmd)
		{
		case CMD_PSG_STEREO:
			//ignore for now
			cur++;
			break;
		case CMD_PSG:
			psg_write(&p_context, *(cur++));
			break;
		case CMD_YM2612_0:
			ym_address_write_part1(&y_context, *(cur++));
			ym_data_write(&y_context, *(cur++));
			break;
		case CMD_YM2612_1:
			ym_address_write_part2(&y_context, *(cur++));
			ym_data_write(&y_context, *(cur++));
			break;
		case CMD_WAIT: {
			uint32_t wait_time = *(cur++);
			wait_time |= *(cur++) << 8;
			wait_time *= mclks_sample;
			vgm_wait(&y_context, &p_context, &current_cycle, wait_time);
			break;
		}
		case CMD_WAIT_60:
			vgm_wait(&y_context, &p_context, &current_cycle, 735 * mclks_sample);
			break;
		case CMD_WAIT_50:
			vgm_wait(&y_context, &p_context, &current_cycle, 882 * mclks_sample);
			break;
		case CMD_END:
			if (header.loop_offset && --loop_count) {
				cur = data + header.loop_offset + 0x1C - (header.data_offset + 0x34);
			} else {
				//TODO: fade out
				return 0;
			}
			break;
		case CMD_DATA: {
			cur++; //skip compat command
			uint8_t data_type = *(cur++);
			uint32_t data_size = *(cur++);
			data_size |= *(cur++) << 8;
			data_size |= *(cur++) << 16;
			data_size |= *(cur++) << 24;
			if (data_type == DATA_YM2612_PCM) {
				data_block ** curblock = &blocks;
				while(*curblock)
				{
					curblock = &((*curblock)->next);
				}
				*curblock = malloc(sizeof(data_block));
				(*curblock)->size = data_size;
				(*curblock)->type = data_type;
				(*curblock)->data = cur;
				(*curblock)->next = NULL;
			} else {
				fprintf(stderr, "Skipping data block with unrecognized type %X\n", data_type);
			}
			cur += data_size;
			break;
		}
		case CMD_DATA_SEEK: {
			uint32_t new_offset = *(cur++);
			new_offset |= *(cur++) << 8;
			new_offset |= *(cur++) << 16;
			new_offset |= *(cur++) << 24;
			if (!seek_block || new_offset < seek_offset) {
				seek_block = blocks;
				seek_offset = 0;
				block_offset = 0;
			}
			while (seek_block && (seek_offset - block_offset + seek_block->size) < new_offset)
			{
				seek_offset += seek_block->size - block_offset;
				seek_block = seek_block->next;
				block_offset = 0;
			}
			block_offset += new_offset-seek_offset;
			seek_offset = new_offset;
			break;
		}

		default:
			if (cmd >= CMD_WAIT_SHORT && cmd < (CMD_WAIT_SHORT + 0x10)) {
				uint32_t wait_time = (cmd & 0xF) + 1;
				wait_time *= mclks_sample;
				vgm_wait(&y_context, &p_context, &current_cycle, wait_time);
			} else if (cmd >= CMD_YM2612_DAC && cmd < CMD_DAC_STREAM_SETUP) {
				if (seek_block) {
					ym_address_write_part1(&y_context, 0x2A);
					ym_data_write(&y_context, seek_block->data[block_offset++]);
					seek_offset++;
					if (block_offset > seek_block->size) {
						seek_block = seek_block->next;
						block_offset = 0;
					}
				} else {
					fputs("Encountered DAC write command but data seek pointer is invalid!\n", stderr);
				}
				uint32_t wait_time = (cmd & 0xF);
				if (wait_time)
				{
					wait_time *= mclks_sample;
					vgm_wait(&y_context, &p_context, &current_cycle, wait_time);
				}
			} else {
				fatal_error("unimplemented command: %X at offset %X\n", cmd, (unsigned int)(cur - data - 1));
			}
		}
	}
	return 0;
}
Example #27
0
BOOL CALLBACK
WndProc (HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam)
{
    static HBRUSH hBrush = NULL;

    switch (umsg)
    {
    case WM_CREATE:
	if (!render_init (hwnd, g_gui_prefs.default_skin)) {
	    MessageBox(hwnd, "Failed to find the skin bitmap", "Error", 0);
	    break;
	}
	stop_button_disable();
	if (OPT_FLAG_ISSET(g_rmo.flags, OPT_MAKE_RELAY)) {
	    render_relay_button_enable ();
	} else {
	    render_relay_button_disable ();
	}

	SetTimer (hwnd, 1, 500, (TIMERPROC)UpdateDisplay);
	dock_init (hwnd);

	return 0;

    case WM_PAINT:
	{
	    PAINTSTRUCT pt;
	    HDC hdc = BeginPaint(hwnd, &pt);
	    render_do_paint(hdc);
	    EndPaint(hwnd, &pt);
	}
	return 0;
		
    case WM_MOUSEMOVE:
	render_do_mousemove (hwnd, wParam, lParam);
	dock_do_mousemove (hwnd, wParam, lParam);
	break;

    case WM_COMMAND:
	switch(wParam)
	{
	case ID_MENU_STARTRIPPING:
	    start_button_pressed();
	    break;
	case ID_MENU_STOPRIPPING:
	    stop_button_pressed();
	    break;
	case ID_MENU_OPTIONS:
	    options_button_pressed();
	    break;
	case ID_MENU_OPEN:
	    PostMessage(hwnd, WM_MY_TRAY_NOTIFICATION, (WPARAM)NULL, WM_LBUTTONDBLCLK);
	    break;
	case ID_MENU_RESET_URL:
	    strcpy(g_rmo.url, "");
	    set_ripping_url (0);
	    break;
	case ID_MENU_LOAD_URL:
	    debug_printf ("Load URL dialog box\n");
	    open_load_url_dialog ();
	    break;
	case ID_MENU_EXIT:
	    debug_printf ("User requested exit\n");
	    quit ();
	    PostQuitMessage( 0 );
	    break;
	default:
	    if (wParam >= ID_MENU_HISTORY_LIST && wParam < ID_MENU_HISTORY_LIST + RIPLIST_LEN) {
		int i = wParam - ID_MENU_HISTORY_LIST;
		char* url = g_gui_prefs.riplist[i];
		debug_printf ("Setting URL through history list\n");
		strcpy(g_rmo.url, url);
		set_ripping_url (url);
	    }
	    break;
	}
	break;

    case WM_MY_TRAY_NOTIFICATION:
	switch(lParam)
	{
	case WM_LBUTTONDBLCLK:
	    dock_show_window(m_hwnd, SW_NORMAL);
	    SetForegroundWindow(hwnd);
	    g_gui_prefs.m_start_minimized = FALSE;
	    break;

	case WM_RBUTTONDOWN:
	    {
		int item;
		POINT pt;
		GetCursorPos(&pt);
		SetForegroundWindow(hwnd);
		item = TrackPopupMenu(m_hmenu_systray_sub, 
				      0,
				      pt.x,
				      pt.y,
				      (int)NULL,
				      hwnd,
				      NULL);
	    }
	    break;
	}
	break;

    case WM_LBUTTONDOWN:
	dock_do_lbuttondown(hwnd, wParam, lParam);
	render_do_lbuttondown(hwnd, wParam, lParam);
	break;

    case WM_LBUTTONUP:
	dock_do_lbuttonup(hwnd, wParam, lParam);
	render_do_lbuttonup(hwnd, wParam, lParam);
	{
	    BOOL rc;
	    RECT rt;
	    rc = GetWindowRect(hwnd, &rt);
	    if (rc) {
		g_gui_prefs.oldpos_x = rt.left;
		g_gui_prefs.oldpos_y = rt.top;
	    }
	}
	break;
	
    case WM_RBUTTONDOWN:
	{
	    int item;
	    POINT pt;
	    if (!m_bRipping) {
		GetCursorPos (&pt);
		SetForegroundWindow (hwnd);
		item = TrackPopupMenu (m_hmenu_context_sub, 
					0,
					pt.x,
					pt.y,
					(int)NULL,
					hwnd,
					NULL);
	    }
	}
	break;
	
    case WM_APP+0:
	handle_wm_app (hwnd, wParam, lParam);
	break;
    case WM_APP+1:
	/* Exit request from thread */
	quit ();
	PostQuitMessage( 0 );
	break;
    case WM_DESTROY:
	debug_printf ("Got WM_DESTROY\n");
	PostQuitMessage( 0 );
	break;
    case WM_QUIT:
	debug_printf ("Got WM_QUIT\n");
	break;
    }
    return DefWindowProc (hwnd, umsg, wParam, lParam);
}
Example #28
0
int main(int argc, char **argv)
{
    int fd, i, j, k;

    int c;
    int foreground=0;
    int active_slave=0;
    int log_options;
    char config_file_name[PATH_MAX] = RENDERD_CONFIG;

    while (1) {
        int option_index = 0;
        static struct option long_options[] = {
            {"config", 1, 0, 'c'},
            {"foreground", 1, 0, 'f'},
            {"slave", 1, 0, 's'},
            {"help", 0, 0, 'h'},
            {0, 0, 0, 0}
        };

        c = getopt_long(argc, argv, "hfc:", long_options, &option_index);
        if (c == -1)
            break;

        switch (c) {
            case 'f':
                foreground=1;
                break;
            case 'c':
                strncpy(config_file_name, optarg, PATH_MAX-1);
                config_file_name[PATH_MAX-1] = 0;
                break;
            case 's':
                if (sscanf(optarg, "%i", &active_slave) != 1) {
                    fprintf(stderr, "--slave needs to be nummeric (%s)\n", optarg);
                    active_slave = 0;
                }
                break;
            case 'h':
                fprintf(stderr, "Usage: renderd [OPTION] ...\n");
                fprintf(stderr, "Mapnik rendering daemon\n");
                fprintf(stderr, "  -f, --foreground     run in foreground\n");
                fprintf(stderr, "  -h, --help           display this help and exit\n");
                fprintf(stderr, "  -c, --config=CONFIG  set location of config file (default /etc/renderd.conf)\n");
                fprintf(stderr, "  -s, --slave=CONFIG_NR set which render slave this is (default 0)\n");
                exit(0);
            default:
                fprintf(stderr, "unknown config option '%c'\n", c);
                exit(1);
        }
    }

    log_options = LOG_PID;
#ifdef LOG_PERROR
    if (foreground)
        log_options |= LOG_PERROR;
#endif
    openlog("renderd", log_options, LOG_DAEMON);

    syslog(LOG_INFO, "Rendering daemon started");

    pthread_mutex_init(&qLock, NULL);
    pthread_cond_init(&qCond, NULL);
    reqHead.next = reqHead.prev = &reqHead;
    reqPrioHead.next = reqPrioHead.prev = &reqPrioHead;
    reqBulkHead.next = reqBulkHead.prev = &reqBulkHead;
    dirtyHead.next = dirtyHead.prev = &dirtyHead;
    renderHead.next = renderHead.prev = &renderHead;
    hashidxSize = HASHIDX_SIZE;
    item_hashidx = (struct item_idx *) malloc(sizeof(struct item_idx) * hashidxSize);
    bzero(item_hashidx, sizeof(struct item_idx) * hashidxSize);

    stats.noDirtyRender = 0;
    stats.noReqDroped = 0;
    stats.noReqRender = 0;
    stats.noReqPrioRender = 0;
    stats.noReqBulkRender = 0;

    xmlconfigitem maps[XMLCONFIGS_MAX];
    bzero(maps, sizeof(xmlconfigitem) * XMLCONFIGS_MAX);

    renderd_config config_slaves[MAX_SLAVES];
    bzero(config_slaves, sizeof(renderd_config) * MAX_SLAVES);
    bzero(&config, sizeof(renderd_config));

    dictionary *ini = iniparser_load(config_file_name);
    if (! ini) {
        exit(1);
    }

    noSlaveRenders = 0;

    int iconf = -1;
    char buffer[PATH_MAX];
    for (int section=0; section < iniparser_getnsec(ini); section++) {
        char *name = iniparser_getsecname(ini, section);
        syslog(LOG_INFO, "Parsing section %s\n", name);
        if (strncmp(name, "renderd", 7) && strcmp(name, "mapnik")) {
            if (config.tile_dir == NULL) {
                fprintf(stderr, "No valid (active) renderd config section available\n");
                exit(7);
            }
            /* this is a map section */
            iconf++;
            if (iconf >= XMLCONFIGS_MAX) {
                fprintf(stderr, "Config: more than %d configurations found\n", XMLCONFIGS_MAX);
                exit(7);
            }

            if (strlen(name) >= (XMLCONFIG_MAX - 1)) {
                fprintf(stderr, "XML name too long: %s\n", name);
                exit(7);
            }

            strcpy(maps[iconf].xmlname, name);
            
            sprintf(buffer, "%s:uri", name);
            char *ini_uri = iniparser_getstring(ini, buffer, (char *)"");
            if (strlen(ini_uri) >= (PATH_MAX - 1)) {
                fprintf(stderr, "URI too long: %s\n", ini_uri);
                exit(7);
            }
            strcpy(maps[iconf].xmluri, ini_uri);

            sprintf(buffer, "%s:xml", name);
            char *ini_xmlpath = iniparser_getstring(ini, buffer, (char *)"");
            if (strlen(ini_xmlpath) >= (PATH_MAX - 1)){
                fprintf(stderr, "XML path too long: %s\n", ini_xmlpath);
                exit(7);
            }
            strcpy(maps[iconf].xmlfile, ini_xmlpath);

            sprintf(buffer, "%s:host", name);
            char *ini_hostname = iniparser_getstring(ini, buffer, (char *) "");
            if (strlen(ini_hostname) >= (PATH_MAX - 1)) {
                fprintf(stderr, "Host name too long: %s\n", ini_hostname);
                exit(7);
            }
            strcpy(maps[iconf].host, ini_hostname);

            sprintf(buffer, "%s:htcphost", name);
            char *ini_htcpip = iniparser_getstring(ini, buffer, (char *) "");
            if (strlen(ini_htcpip) >= (PATH_MAX - 1)) {
                fprintf(stderr, "HTCP host name too long: %s\n", ini_htcpip);
                exit(7);
            }
            strcpy(maps[iconf].htcpip, ini_htcpip);

            sprintf(buffer, "%s:tilesize", name);
            char *ini_tilesize = iniparser_getstring(ini, buffer, (char *) "256");
            maps[iconf].tile_px_size = atoi(ini_tilesize);
            if (maps[iconf].tile_px_size < 1) {
                fprintf(stderr, "Tile size is invalid: %s\n", ini_tilesize);
                exit(7);
            }

            sprintf(buffer, "%s:tiledir", name);
            char *ini_tiledir = iniparser_getstring(ini, buffer, (char *) config.tile_dir);
            if (strlen(ini_tiledir) >= (PATH_MAX - 1)) {
                fprintf(stderr, "Tiledir too long: %s\n", ini_tiledir);
                exit(7);
            }
            strcpy(maps[iconf].tile_dir, ini_tiledir);
        } else if (strncmp(name, "renderd", 7) == 0) {
            int render_sec = 0;
            if (sscanf(name, "renderd%i", &render_sec) != 1) {
                render_sec = 0;
            }
            syslog(LOG_INFO, "Parsing render section %i\n", render_sec);
            if (render_sec >= MAX_SLAVES) {
                syslog(LOG_ERR, "Can't handle more than %i render sections\n",
                        MAX_SLAVES);
                exit(7);
            }
            sprintf(buffer, "%s:socketname", name);
            config_slaves[render_sec].socketname = iniparser_getstring(ini,
                    buffer, (char *) RENDER_SOCKET);
            sprintf(buffer, "%s:iphostname", name);
            config_slaves[render_sec].iphostname = iniparser_getstring(ini,
                    buffer, "");
            sprintf(buffer, "%s:ipport", name);
            config_slaves[render_sec].ipport = iniparser_getint(ini, buffer, 0);
            sprintf(buffer, "%s:num_threads", name);
            config_slaves[render_sec].num_threads = iniparser_getint(ini,
                    buffer, NUM_THREADS);
            sprintf(buffer, "%s:tile_dir", name);
            config_slaves[render_sec].tile_dir = iniparser_getstring(ini,
                    buffer, (char *) HASH_PATH);
            sprintf(buffer, "%s:stats_file", name);
            config_slaves[render_sec].stats_filename = iniparser_getstring(ini,
                    buffer, NULL);

            if (render_sec == active_slave) {
                config.socketname = config_slaves[render_sec].socketname;
                config.iphostname = config_slaves[render_sec].iphostname;
                config.ipport = config_slaves[render_sec].ipport;
                config.num_threads = config_slaves[render_sec].num_threads;
                config.tile_dir = config_slaves[render_sec].tile_dir;
                config.stats_filename
                        = config_slaves[render_sec].stats_filename;
                config.mapnik_plugins_dir = iniparser_getstring(ini,
                        "mapnik:plugins_dir", (char *) MAPNIK_PLUGINS);
                config.mapnik_font_dir = iniparser_getstring(ini,
                        "mapnik:font_dir", (char *) FONT_DIR);
                config.mapnik_font_dir_recurse = iniparser_getboolean(ini,
                        "mapnik:font_dir_recurse", FONT_RECURSE);
            } else {
                noSlaveRenders += config_slaves[render_sec].num_threads;
            }
        }
    }

    if (config.ipport > 0) {
        syslog(LOG_INFO, "config renderd: ip socket=%s:%i\n", config.iphostname, config.ipport);
    } else {
        syslog(LOG_INFO, "config renderd: unix socketname=%s\n", config.socketname);
    }
    syslog(LOG_INFO, "config renderd: num_threads=%d\n", config.num_threads);
    if (active_slave == 0) {
        syslog(LOG_INFO, "config renderd: num_slaves=%d\n", noSlaveRenders);
    }
    syslog(LOG_INFO, "config renderd: tile_dir=%s\n", config.tile_dir);
    syslog(LOG_INFO, "config renderd: stats_file=%s\n", config.stats_filename);
    syslog(LOG_INFO, "config mapnik:  plugins_dir=%s\n", config.mapnik_plugins_dir);
    syslog(LOG_INFO, "config mapnik:  font_dir=%s\n", config.mapnik_font_dir);
    syslog(LOG_INFO, "config mapnik:  font_dir_recurse=%d\n", config.mapnik_font_dir_recurse);
    for (i = 0; i < MAX_SLAVES; i++) {
        if (config_slaves[i].num_threads == 0) {
            continue;
        }
        if (i == active_slave) {
            syslog(LOG_INFO, "config renderd(%i): Active\n", i);
        }
        if (config_slaves[i].ipport > 0) {
                syslog(LOG_INFO, "config renderd(%i): ip socket=%s:%i\n", i,
                        config_slaves[i].iphostname, config_slaves[i].ipport);
            } else {
                syslog(LOG_INFO, "config renderd(%i): unix socketname=%s\n", i,
                        config_slaves[i].socketname);
            }
        syslog(LOG_INFO, "config renderd(%i): num_threads=%d\n", i,
                config_slaves[i].num_threads);
        syslog(LOG_INFO, "config renderd(%i): tile_dir=%s\n", i,
                config_slaves[i].tile_dir);
        syslog(LOG_INFO, "config renderd(%i): stats_file=%s\n", i,
                config_slaves[i].stats_filename);
    }

    for(iconf = 0; iconf < XMLCONFIGS_MAX; ++iconf) {
        if (maps[iconf].xmlname[0] != 0) {
         syslog(LOG_INFO, "config map %d:   name(%s) file(%s) uri(%s) htcp(%s) host(%s)",
                 iconf, maps[iconf].xmlname, maps[iconf].xmlfile, maps[iconf].xmluri,
                 maps[iconf].htcpip, maps[iconf].host);
        }
    }

    fd = server_socket_init(&config);
#if 0
    if (fcntl(fd, F_SETFD, O_RDWR | O_NONBLOCK) < 0) {
        fprintf(stderr, "setting socket non-block failed\n");
        close(fd);
        exit(5);
    }
#endif

    //sigPipeAction.sa_handler = pipe_handler;
    sigPipeAction.sa_handler = SIG_IGN;
    if (sigaction(SIGPIPE, &sigPipeAction, NULL) < 0) {
        fprintf(stderr, "failed to register signal handler\n");
        close(fd);
        exit(6);
    }

    render_init(config.mapnik_plugins_dir, config.mapnik_font_dir, config.mapnik_font_dir_recurse);

    /* unless the command line said to run in foreground mode, fork and detach from terminal */
    if (foreground) {
        fprintf(stderr, "Running in foreground mode...\n");
    } else {
        if (daemon(0, 0) != 0) {
            fprintf(stderr, "can't daemonize: %s\n", strerror(errno));
        }
        /* write pid file */
        FILE *pidfile = fopen(PIDFILE, "w");
        if (pidfile) {
            (void) fprintf(pidfile, "%d\n", getpid());
            (void) fclose(pidfile);
        }
    }

    if (config.stats_filename != NULL) {
        if (pthread_create(&stats_thread, NULL, stats_writeout_thread, NULL)) {
            syslog(LOG_WARNING, "Could not create stats writeout thread");
        }
    } else {
        syslog(LOG_INFO, "No stats file specified in config. Stats reporting disabled");
    }

    render_threads = (pthread_t *) malloc(sizeof(pthread_t) * config.num_threads);

    for(i=0; i<config.num_threads; i++) {
        if (pthread_create(&render_threads[i], NULL, render_thread, (void *)maps)) {
            fprintf(stderr, "error spawning render thread\n");
            close(fd);
            exit(7);
        }
    }

    if (active_slave == 0) {
        //Only the master renderd opens connections to its slaves
        k = 0;
        slave_threads
                = (pthread_t *) malloc(sizeof(pthread_t) * noSlaveRenders);
        for (i = 1; i < MAX_SLAVES; i++) {
            for (j = 0; j < config_slaves[i].num_threads; j++) {
                if (pthread_create(&slave_threads[k++], NULL, slave_thread,
                        (void *) &config_slaves[i])) {
                    fprintf(stderr, "error spawning render thread\n");
                    close(fd);
                    exit(7);
                }
            }
        }
    }

    process_loop(fd);

    unlink(config.socketname);
    close(fd);
    return 0;
}
Example #29
0
int
main(int argc, char *argv[], char *env[])
{
	char           *display_name = NULL;
	char	       *device_name = NULL;
	char	       *output_name = NULL;
	XSetWindowAttributes xswa;
	int             i = 0;
	double          a, a1, a2, b, b1, b2, xerr, yerr;
	int		xi_opcode, event, error;
	XExtensionVersion *version;
	XDeviceInfo	*info;
	XDevice		*device;
	long		 calib_data[4];
	unsigned long	 mask;
	unsigned char	 swap;
	int 		 keep_cursor = 0, ch;

	/* Crosshair placement */
	int		cpx[] = { 0, 0, 1, 1, 1 };
	int		cpy[] = { 0, 1, 0, 0, 1 };

	while ((ch = getopt(argc, argv, "cD:d:o:v")) != -1) {
		switch (ch) {
		case 'c':
			keep_cursor++;
			break;
		case 'D':
			display_name = optarg;
			break;
		case 'd':
			device_name = optarg;
			break;
		case 'o':
			output_name = optarg;
			break;
		case 'v':
			verbose = True;
			break;
		default:
			usage();
			/* NOTREACHED */
		}
	}
	argc -= optind;
	argv += optind;

	if (argc != 0)
		usage();

	/* connect to X server */
	if ((display = XOpenDisplay(display_name)) == NULL) {
		fprintf(stderr, "%s: cannot connect to X server %s\n",
		    __progname, XDisplayName(display_name));
		exit(1);
	}
	screen = DefaultScreen(display);
	root = RootWindow(display, screen);

	/* get screen size from display structure macro */
	xpos = 0;
	ypos = 0;
	width = DisplayWidth(display, screen);
	height = DisplayHeight(display, screen);

	if (XRRQueryExtension(display, &event, &error)) {
		int major, minor;

		if (XRRQueryVersion(display, &major, &minor) != True) {
			fprintf(stderr, "Error querying XRandR version");
		} else {
			printf("XRandR extension version %d.%d present\n",
			    major, minor);
			has_xrandr = True;
			if (major > 1 || (major == 1 && minor >=2))
				has_xrandr_1_2 = True;
			if (major > 1 || (major == 1 && minor >=3))
				has_xrandr_1_3 = True;
		}
	}

	if (output_name != NULL) {
		if (has_xrandr_1_2) {
			get_xrandr_config(display, root, output_name,
			    &xpos, &ypos, &width, &height);
		} else {
			fprintf(stderr, "%s: can not specify an output "
			    "whithout XRandr 1.2 or later", __progname);
			exit(2);
		}
	}
	if (!XQueryExtension(display, INAME, &xi_opcode,
		&event, &error)) {
		fprintf(stderr, "%s: X Input extension not available.\n",
		    __progname);
		exit(1);
	}

	version = XGetExtensionVersion(display, INAME);
	if (version == NULL ||
	    version == (XExtensionVersion *)NoSuchExtension) {
		fprintf(stderr, "Cannot query X Input version.\n");
		exit(1);
	}
	XFree(version);
	prop_calibration = XInternAtom(display, WS_PROP_CALIBRATION, True);
	if (prop_calibration == None) {
		fprintf(stderr, "Unable to find the \"%s\" device property.\n"
		    "There are probably no calibrable devices "
		    "on this system.\n", WS_PROP_CALIBRATION);
		exit(1);
	}
	prop_swap = XInternAtom(display, WS_PROP_SWAP_AXES, True);
	if (prop_swap == None) {
		fprintf(stderr, "Unable to find the \"%s\" device property\n",
		    WS_PROP_SWAP_AXES);
		exit(1);
	}
	info = find_device_info(device_name);
	if (info == NULL) {
		fprintf(stderr, "Unable to find the %s device\n",
			device_name ? device_name : "default");
		exit(1);
	}


	/* setup window attributes */
	xswa.override_redirect = True;
	xswa.background_pixel = BlackPixel(display, screen);
	xswa.event_mask = ExposureMask | KeyPressMask;
	mask = CWOverrideRedirect | CWBackPixel | CWEventMask;
	if (!keep_cursor) {
		xswa.cursor = create_empty_cursor();
		mask |= CWCursor;
	}
	win = XCreateWindow(display, RootWindow(display, screen),
			    xpos, ypos, width, height, 0,
			    CopyFromParent, InputOutput, CopyFromParent,
			    mask, &xswa);
	render_init();
	XMapWindow(display, win);
	XGrabKeyboard(display, win, False, GrabModeAsync, GrabModeAsync,
		      CurrentTime);
	XGrabServer(display);

	XClearWindow(display, win);

	if (verbose)
		printf("Calibrating %s\n", info->name);
	device = XOpenDevice(display, info->id);
	if (!device) {
		fprintf(stderr, "Unable to open the X input device \"%s\"\n",
		    info->name);
		return 0;
	}

	if (!register_events(info, device, 0))
		exit(1);

	uncalibrate(device);
calib:
	XftDrawRect(draw, &bg, 0, 0, width, height);

	for (i = 0; i < 5; i++) {
		draw_graphics(cpx[i], cpy[i], i);
		XFlush(display);
		if (!get_events(i))
			break;
		XftDrawRect(draw, &bg, 0, 0, width, height);
	}
	if (interrupted)
		cleanup_exit(device);

	/* Check if  X and Y should be swapped */
	if (fabs(x[0] - x[1]) > fabs(y[0] - y[1])) {

		calib.swapxy = 1;

		for (i = 0; i < 5; i++) {
			int t = x[i];
			x[i] = y[i];
			y[i] = t;
		}
	}

	/* get touch pad resolution to screen resolution ratio */
	a1 = (double) (x[4] - x[0]) / (double) (cx[4] - cx[0]);
	a2 = (double) (x[3] - x[1]) / (double) (cx[3] - cx[1]);
	/* get the minimum pad position on the X-axis */
	b1 = x[0] - a1 * cx[0];
	b2 = x[1] - a2 * cx[1];
	/* use the average ratio and average minimum position */
	a = (a1 + a2) / 2.0;
	b = (b1 + b2) / 2.0;
	xerr = a * width / 2 + b - x[2];
	if (fabs(xerr) > fabs(a * width * .01)) {
		fprintf(stderr, "Calibration problem: X axis error (%.2f) too high, try again\n",
			fabs(xerr));
		goto err;
	}
	calib.minx = (int) (b + 0.5);
	calib.maxx = (int) (a * width + b + 0.5);

	/* get touch pad resolution to screen resolution ratio */
	a1 = (double) (y[4] - y[0]) / (double) (cy[4] - cy[0]);
	a2 = (double) (y[3] - y[1]) / (double) (cy[3] - cy[1]);
	/* get the minimum pad position on the Y-axis */
	b1 = y[0] - a1 * cy[0];
	b2 = y[1] - a2 * cy[1];
	/* use the average ratio and average minimum position */
	a = (a1 + a2) / 2.0;
	b = (b1 + b2) / 2.0;
	yerr = a * height / 2 + b - y[2];
	if (fabs(yerr) > fabs(a * height * 0.01)) {
		fprintf(stderr, "Calibration problem: Y axis error (%.2f) too high, try again\n",
			fabs(yerr));
		goto err;
	}
	calib.miny = (int) (b + 0.5);
	calib.maxy = (int) (a * height + b + 0.5);

	XFlush(display);

	calib.resx = width;
	calib.resy = height;

	/* Send new values to the X server */
	calib_data[0] = calib.minx;
	calib_data[1] = calib.maxx;
	calib_data[2] = calib.miny;
	calib_data[3] = calib.maxy;
	XChangeDeviceProperty(display, device, prop_calibration,
	    XA_INTEGER, 32, PropModeReplace, (unsigned char *)calib_data, 4);

	swap = calib.swapxy;
	XChangeDeviceProperty(display, device, prop_swap,
	    XA_INTEGER, 8, PropModeReplace, (unsigned char *)&swap, 1);

	XCloseDevice(display, device);

	XCloseDisplay(display);

	/* And print them for storage in wsconsctl.conf */
	printf("mouse.scale=%d,%d,%d,%d,%d,%d,%d\n",
	    calib.minx, calib.maxx,
	    calib.miny, calib.maxy,
	    calib.swapxy,
	    calib.resx, calib.resy);

	return 0;
err:
	draw_text(error_message, &errorColor);
	XFlush(display);
	sleep(2);
	goto calib;
}
Example #30
0
void running_machine::start()
{
	/* initialize basic can't-fail systems here */
	fileio_init(this);
	config_init(this);
	input_init(this);
	output_init(this);
	state_init(this);
	state_save_allow_registration(this, true);
	palette_init(this);
	render_init(this);
	ui_init(this);
	generic_machine_init(this);
	generic_video_init(this);
	generic_sound_init(this);

	/* initialize the timers and allocate a soft_reset timer
	   this must be done before cpu_init so that CPU's can allocate timers */
	timer_init(this);
	m_soft_reset_timer = timer_alloc(this, static_soft_reset, NULL);

	/* init the osd layer */
	osd_init(this);

	/* initialize the base time (needed for doing record/playback) */
	time(&m_base_time);

	/* initialize the input system and input ports for the game
	   this must be done before memory_init in order to allow specifying
	   callbacks based on input port tags */
	time_t newbase = input_port_init(this, m_game.ipt);
	if (newbase != 0)
		m_base_time = newbase;

	/* intialize UI input */
	ui_input_init(this);

	/* initialize the streams engine before the sound devices start */
	streams_init(this);

	/* first load ROMs, then populate memory, and finally initialize CPUs
	   these operations must proceed in this order */
	rom_init(this);
	memory_init(this);
	watchdog_init(this);

	/* allocate the gfx elements prior to device initialization */
	gfx_init(this);

	/* initialize natural keyboard support */
	inputx_init(this);

	/* initialize image devices */
	image_init(this);

	/* start up the devices */
	m_devicelist.start_all();

	/* call the game driver's init function
	   this is where decryption is done and memory maps are altered
	   so this location in the init order is important */
	ui_set_startup_text(this, "Initializing...", true);
	if (m_game.driver_init != NULL)
		(*m_game.driver_init)(this);

	/* finish image devices init process */
	image_postdevice_init(this);

	/* start the video and audio hardware */
	video_init(this);
	tilemap_init(this);
	crosshair_init(this);

	sound_init(this);

	/* initialize the debugger */
	if ((debug_flags & DEBUG_FLAG_ENABLED) != 0)
		debugger_init(this);

	/* call the driver's _START callbacks */
	if (m_config.m_machine_start != NULL)
		(*m_config.m_machine_start)(this);
	if (m_config.m_sound_start != NULL)
		(*m_config.m_sound_start)(this);
	if (m_config.m_video_start != NULL)
		(*m_config.m_video_start)(this);

	/* set up the cheat engine */    
	cheat_init(this);
	/* set up the hiscore engine */    
    hiscore_init(this);

	/* disallow save state registrations starting here */
	state_save_allow_registration(this, false);
}