Ejemplo n.º 1
0
void KX_BlenderMaterial::OnConstruction(int layer)
{
	if (mConstructed)
		// when material are reused between objects
		return;
	
	if (mMaterial->glslmat)
		SetBlenderGLSLShader(layer);

	// for each unique material...
	int i;
	for (i=0; i<mMaterial->num_enabled; i++) {
		if ( mMaterial->mapping[i].mapping & USEENV ) {
			if (!GLEW_ARB_texture_cube_map) {
				spit("CubeMap textures not supported");
				continue;
			}
			if (!mTextures[i].InitCubeMap(i, mMaterial->cubemap[i] ) )
				spit("unable to initialize image("<<i<<") in "<< 
						 mMaterial->matname<< ", image will not be available");
		} 
	
		else {
			if ( mMaterial->img[i] ) {
				if ( ! mTextures[i].InitFromImage(i, mMaterial->img[i], (mMaterial->flag[i] &MIPMAP)!=0 ))
					spit("unable to initialize image("<<i<<") in "<< 
						mMaterial->matname<< ", image will not be available");
			}
		}
	}

	mBlendFunc[0] =0;
	mBlendFunc[1] =0;
	mConstructed = true;
}
Ejemplo n.º 2
0
void Scoremiddlegoal()
{  waitForButton();
  starttask(CollectD);
  {
    drive_Enc(63,7,4);
  }
  stopdrivemotors();
  StopTask(CollectD);
  StartTask(medgoal);
  {

    stopTime(1.75);//wait for arm
    drive_Enc(63,8,5);//drive foward
  }
  StopTask(medgoal);
  spit(0.75);
  drive_Enc(-63,4,2);
  spit(0.75);
  StartTask(armDown);
  {
    drive_Enc(-63,15,5);
  }
  StopTask(armDown);
  waitForButton();
  StartTask(CollectD);
  {
    drive_Enc(70,15,5);
  }
  StopTask(CollectD);

}
Ejemplo n.º 3
0
void KX_BlenderMaterial::InitTextures()
{
	// for each unique material...
	int i;
	for (i=0; i<BL_Texture::GetMaxUnits(); i++) {
		if ( mMaterial->mapping[i].mapping & USEENV ) {
			if (!GLEW_ARB_texture_cube_map) {
				spit("CubeMap textures not supported");
				continue;
			}
			if (!mTextures[i].InitCubeMap(i, mMaterial->cubemap[i] ) )
				spit("unable to initialize image("<<i<<") in "<<
				     mMaterial->matname<< ", image will not be available");
		}
		/* If we're using glsl materials, the textures are handled by bf_gpu, so don't load them twice!
		 * However, if we're using a custom shader, then we still need to load the textures ourselves. */
		else if (!mMaterial->glslmat || mShader) {
			if ( mMaterial->img[i] ) {
				if ( ! mTextures[i].InitFromImage(i, mMaterial->img[i], (mMaterial->flag[i] &MIPMAP)!=0 ))
					spit("unable to initialize image("<<i<<") in "<< 
						mMaterial->matname<< ", image will not be available");
			}
		}
	}
}
Ejemplo n.º 4
0
void beginpage()
{
    int i;
    for (i = 0; i < o_m1; i++) spit('\n');
    writetitle(ohead);
    for (i = 0; i < o_m2; i++) spit('\n');
    line_no = 0;
}
Ejemplo n.º 5
0
void endpage()
{
    int i;
    for (i = line_no; i < TXTLEN; i++) {
        spit('\n');
        line_no++;
    }
    for (i = 0; i < o_m3; i++) spit('\n');
    writetitle(ofoot);
    for (i = 0; i < o_m4; i++) spit('\n');
    page_no++;
}
Ejemplo n.º 6
0
void spits(char *s)
{
    while (*s) {
        spit(*s);
        s++;
    }
}
Ejemplo n.º 7
0
static ava_value main_impl(void* arg) {
  unsigned argc = ((const main_data*)arg)->argc;
  const char*const* argv = ((const main_data*)arg)->argv;

  ava_string package_name, package_prefix, file_prefix, infile, outfile;
  const char* slash;
  size_t len;
  const ava_pcode_global_list* pcode;

  if (2 != argc)
    errx(EX_USAGE, "Usage: %s <filename>", argv[0]);

  slash = strchr(argv[1], '/');
  if (!slash || slash == argv[1])
    errx(EX_USAGE, "Bad input filename: %s", argv[1]);

  package_name = ava_string_of_bytes(argv[1], slash - argv[1]);
  package_prefix = ava_strcat(package_name, AVA_ASCII9_STRING(":"));
  file_prefix = ava_strcat(package_name, AVA_ASCII9_STRING("/"));
  infile = ava_string_of_cstring(slash + 1);

  len = ava_strlen(infile);
  if (len < 5 || !ava_string_equal(AVA_ASCII9_STRING(".ava"),
                                   ava_string_slice(infile, len - 4, len)))
    errx(EX_USAGE, "Bad input filename: %s", argv[1]);

  outfile = ava_strcat(
    ava_string_slice(infile, 0, len - 4), AVA_ASCII9_STRING(".avam"));

  pcode = compile(package_prefix, file_prefix, infile);
  spit(ava_strcat(file_prefix, outfile), pcode);

  return ava_value_of_string(AVA_EMPTY_STRING);
}
Ejemplo n.º 8
0
void RAS_ListSlot::SetModified(bool mod)
{
	if (mod && !(m_flag & LIST_MODIFY)) {
		spit("Modifying list (" << m_list << ")");
		m_flag = m_flag &~ LIST_END;
		m_flag |= LIST_STREAM;
	}
}
Ejemplo n.º 9
0
void RAS_ListSlot::RemoveList()
{
	if (m_list != 0) {
		spit("Releasing display list (" << m_list << ")");
		glDeleteLists((GLuint)m_list, 1);
		m_list =0;
	}
}
Ejemplo n.º 10
0
void BlockMiddleGoal()
{
  StartTask(medgoal);
  {
    drivetime(80,1.2)
  }
  StopTask(medgoal);
  spit(20);
}
Ejemplo n.º 11
0
void nodeDisplay (node *gotN) {
  printf("%s\n", spit(gotN));

  if (gotN->type != NODE_END) {
    for (int i = 0; i < gotN->optNum; i++) {
      printf("%i: %s\n", i + 1, gotN->options[i]);
    }
  }
}
Ejemplo n.º 12
0
void drive_Highgoal()
{
  spit(0.5);/// let the spinners roll out.
  drivetime(80,1.2);
  stopDrivemotors(); ;//zero-out the motors
  //stopTime(1.75);//wait for arm
  // drivetime(50,2);//drive foward more...
  stopTime(20);//sit at the wall for three seconds.
  // drive_Enc(-85,2.75,3.4);//back up and spit.
  // spit(4);// spit
  // drive_Enc(-100, 7,2);//back up
}
Ejemplo n.º 13
0
/*
* Initialize the GUI interface for the plugin
*/
void QgsSpitPlugin::initGui()
{
  // Create the action for tool
  spitAction = new QAction( QIcon( spitIcon ), tr( "&Import Shapefiles to PostgreSQL" ), this );
  spitAction->setWhatsThis( tr( "Import shapefiles into a PostGIS-enabled PostgreSQL database. "
                                "The schema and field names can be customized on import" ) );
  // Connect the action to the spit slot
  connect( spitAction, SIGNAL( triggered() ), this, SLOT( spit() ) );
  // Add the icon to the toolbar and to the plugin menu
  qI->addToolBarIcon( spitAction );
  qI->addPluginToMenu( tr( "&Spit" ), spitAction );

}
Ejemplo n.º 14
0
static char *
remote_event_locked(const char *command)
{
    if (strcmp(command, "burp") == 0) {
	burp();
    } else if (strcmp(command, "spit") == 0) {
	spit();
    } else {
	return strdup("Invalid command");
    }

    return strdup(SERVER_OK);
}
Ejemplo n.º 15
0
static void
take_action()
{
    pthread_mutex_lock(&event_lock);

    if (randomly_with_prob(BURP_PROB)) {
	if (! n_consecutive_spits) {
	    printf("Too many burps, do a spit instead.\n");
	    spit();
	} else {
	    burp();
	}
    } else {
	if (n_consecutive_spits >= MAX_CONSECUTIVE_SPITS) {
	    printf("Too many spits, do a burp instead.\n");
	    burp();
	} else {
	    spit();
	}
    }

    pthread_mutex_unlock(&event_lock);
}
Ejemplo n.º 16
0
void writeline(int adflag, int flushflag)
{
    int j;
    int q;
    for (j = assylen - 1; j; j--) {
        if (assyline[j] == ' ')
            assylen--;
        else
            break;
    }
    q = TXTLEN;
    if (line_no >= q) newpage();
    for (j = 0; j < assylen; j++) spit(assyline[j]);
    spit('\n');
    assylen = 0;
    assyline[0] = 0;
    line_no++;
    if (flushflag==0) {
        strcpy(assyline, holdword);
        assylen = strlen(holdword);
        *holdword = 0;
        holdp = holdword;
    }
}
Ejemplo n.º 17
0
int BL_Shader::GetUniformLocation(const char *name)
{
	if ( GLEW_ARB_fragment_shader &&
		GLEW_ARB_vertex_shader &&
		GLEW_ARB_shader_objects
		)
	{
		MT_assert(mShader!=0);
		int location = glGetUniformLocationARB(mShader, name);
		if (location == -1)
			spit("Invalid uniform value: " << name << ".");
		return location;
	}

	return -1;
}
Ejemplo n.º 18
0
/*
* Initialize the GUI interface for the plugin
*/
void QgsSpitPlugin::initGui()
{
  delete spitAction;

  // Create the action for tool
  spitAction = new QAction( QIcon(), tr( "&Import Shapefiles to PostgreSQL" ), this );
  spitAction->setObjectName( "spitAction" );
  setCurrentTheme( "" );
  spitAction->setWhatsThis( tr( "Import shapefiles into a PostGIS-enabled PostgreSQL database. "
                                "The schema and field names can be customized on import" ) );
  // Connect the action to the spit slot
  connect( spitAction, SIGNAL( triggered() ), this, SLOT( spit() ) );
  // Add the icon to the toolbar and to the plugin menu
  qI->addDatabaseToolBarIcon( spitAction );
  qI->addPluginToDatabaseMenu( tr( "&Spit" ), spitAction );

  // this is called when the icon theme is changed
  connect( qI, SIGNAL( currentThemeChanged( QString ) ), this, SLOT( setCurrentTheme( QString ) ) );
}
Ejemplo n.º 19
0
void RAS_ListSlot::DrawList()
{
	if (m_flag &LIST_STREAM || m_flag& LIST_NOCREATE) {
		RemoveList();
		return;
	}
	if (m_flag &LIST_MODIFY) {
		if (m_flag &LIST_CREATE) {
			if (m_list == 0) {
				m_list = (unsigned int)glGenLists(1);
				m_flag =  m_flag &~ LIST_CREATE;
				spit("Created display list (" << m_list << ")");
			}
		}
		if (m_list != 0)
			glNewList((GLuint)m_list, GL_COMPILE);
	
		m_flag |= LIST_BEGIN;
		return;
	}
	glCallList(m_list);
}
Ejemplo n.º 20
0
void blankline()
{
    if (line_no >= TXTLEN) newpage();
    spit('\n');
    line_no++;
}
Ejemplo n.º 21
0
bool BL_Texture::InitCubeMap(int unit,  EnvMap *cubemap)
{
    if (!GLEW_ARB_texture_cube_map)
    {
        spit("cubemaps not supported");
        mOk = false;
        return mOk;
    }
    else if (!cubemap || cubemap->ima->ok==0)
    {
        mOk = false;
        return mOk;
    }

    ImBuf *ibuf= BKE_image_get_ibuf(cubemap->ima, NULL);
    if (ibuf==0)
    {
        cubemap->ima->ok = 0;
        mOk = false;
        return mOk;
    }

    mNeedsDeleted =	1;
    mType = GL_TEXTURE_CUBE_MAP_ARB;
    mTexture = 0;
    mUnit = unit;

    ActivateUnit(mUnit);

    BL_TextureMap::iterator mapLook = g_textureManager.find(cubemap->ima->id.name);
    if (mapLook != g_textureManager.end())
    {
        if (mapLook->second.gl_texture != 0 && mapLook->second.ref_buffer == cubemap->ima)
        {
            mTexture = mapLook->second.gl_texture;
            glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, mTexture);
            mOk = IsValid();
            return mOk;
        }
    }


    glGenTextures(1, (GLuint*)&mTexture);
    glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, mTexture);


    // track created units
    BL_TextureObject obj;
    obj.gl_texture = mTexture;
    obj.ref_buffer = cubemap->ima;
    g_textureManager.insert(std::pair<char*, BL_TextureObject>((char*)cubemap->ima->id.name, obj));


    bool needs_split = false;
    if (!cubemap->cube[0])
    {
        needs_split = true;
        spit ("Re-Generating texture buffer");
    }

    if (needs_split)
        my_envmap_split_ima(cubemap, ibuf);


    if (!is_pow2(cubemap->cube[0]->x) || !is_pow2(cubemap->cube[0]->y))
    {
        spit("invalid envmap size please render with CubeRes @ power of two");

        my_free_envmapdata(cubemap);
        mOk = false;
        return mOk;
    }


#define SetCubeMapFace(face, num)   \
	glTexImage2D(face, 0,GL_RGBA,	\
	cubemap->cube[num]->x,          \
	cubemap->cube[num]->y,          \
	0, GL_RGBA, GL_UNSIGNED_BYTE,   \
	cubemap->cube[num]->rect)

    SetCubeMapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB, 5);
    SetCubeMapFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB, 3);
    SetCubeMapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB, 0);
    SetCubeMapFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB, 1);
    SetCubeMapFace(GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB, 2);
    SetCubeMapFace(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB, 4);

    glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_S,	 GL_CLAMP_TO_EDGE );
    glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_T,	 GL_CLAMP_TO_EDGE );
    if(GLEW_VERSION_1_2)
        glTexParameteri( GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_R,	 GL_CLAMP_TO_EDGE );

    if (needs_split)
        my_free_envmapdata(cubemap);



    glDisable(GL_TEXTURE_CUBE_MAP_ARB);
    ActivateUnit(0);

    mOk = IsValid();
    return mOk;
}
Ejemplo n.º 22
0
bool BL_Shader::LinkProgram()
{
	int vertlen = 0, fraglen=0, proglen=0;
	int vertstatus=0, fragstatus=0, progstatus=0;
	unsigned int tmpVert=0, tmpFrag=0, tmpProg=0;
	int char_len=0;
	char *logInf =0;

	if (mError)
		goto programError;

	if (!vertProg || !fragProg) {
		spit("Invalid GLSL sources");
		return false;
	}
	if ( !GLEW_ARB_fragment_shader) {
		spit("Fragment shaders not supported");
		return false;
	}
	if ( !GLEW_ARB_vertex_shader) {
		spit("Vertex shaders not supported");
		return false;
	}
	
	// -- vertex shader ------------------
	tmpVert = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
	glShaderSourceARB(tmpVert, 1, (const char**)&vertProg, 0);
	glCompileShaderARB(tmpVert);
	glGetObjectParameterivARB(tmpVert, GL_OBJECT_INFO_LOG_LENGTH_ARB,(GLint*) &vertlen);
	
	// print info if any
	if ( vertlen > 0 && vertlen < MAX_LOG_LEN) {
		logInf = (char*)MEM_mallocN(vertlen, "vert-log");
		glGetInfoLogARB(tmpVert, vertlen, (GLsizei*)&char_len, logInf);
		if (char_len >0) {
			spit("---- Vertex Shader Error ----");
			spit(logInf);
		}
		MEM_freeN(logInf);
		logInf=0;
	}
	// check for compile errors
	glGetObjectParameterivARB(tmpVert, GL_OBJECT_COMPILE_STATUS_ARB,(GLint*)&vertstatus);
	if (!vertstatus) {
		spit("---- Vertex shader failed to compile ----");
		goto programError;
	}

	// -- fragment shader ----------------
	tmpFrag = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
	glShaderSourceARB(tmpFrag, 1,(const char**)&fragProg, 0);
	glCompileShaderARB(tmpFrag);
	glGetObjectParameterivARB(tmpFrag, GL_OBJECT_INFO_LOG_LENGTH_ARB, (GLint*) &fraglen);
	if (fraglen >0 && fraglen < MAX_LOG_LEN) {
		logInf = (char*)MEM_mallocN(fraglen, "frag-log");
		glGetInfoLogARB(tmpFrag, fraglen,(GLsizei*) &char_len, logInf);
		if (char_len >0) {
			spit("---- Fragment Shader Error ----");
			spit(logInf);
		}
		MEM_freeN(logInf);
		logInf=0;
	}

	glGetObjectParameterivARB(tmpFrag, GL_OBJECT_COMPILE_STATUS_ARB, (GLint*) &fragstatus);
	if (!fragstatus) {
		spit("---- Fragment shader failed to compile ----");
		goto programError;
	}

	
	// -- program ------------------------
	//  set compiled vert/frag shader & link
	tmpProg = glCreateProgramObjectARB();
	glAttachObjectARB(tmpProg, tmpVert);
	glAttachObjectARB(tmpProg, tmpFrag);
	glLinkProgramARB(tmpProg);
	glGetObjectParameterivARB(tmpProg, GL_OBJECT_INFO_LOG_LENGTH_ARB, (GLint*) &proglen);
	glGetObjectParameterivARB(tmpProg, GL_OBJECT_LINK_STATUS_ARB, (GLint*) &progstatus);
	

	if (proglen > 0 && proglen < MAX_LOG_LEN) {
		logInf = (char*)MEM_mallocN(proglen, "prog-log");
		glGetInfoLogARB(tmpProg, proglen, (GLsizei*)&char_len, logInf);
		if (char_len >0) {
			spit("---- GLSL Program ----");
			spit(logInf);
		}
		MEM_freeN(logInf);
		logInf=0;
	}

	if (!progstatus) {
		spit("---- GLSL program failed to link ----");
		goto programError;
	}

	// set
	mShader = tmpProg;
	glDeleteObjectARB(tmpVert);
	glDeleteObjectARB(tmpFrag);
	mOk		= 1;
	mError = 0;
	return true;

programError:
	if (tmpVert) {
		glDeleteObjectARB(tmpVert);
		tmpVert=0;
	}
	if (tmpFrag) {
		glDeleteObjectARB(tmpFrag);
		tmpFrag=0;
	}

	if (tmpProg) {
		glDeleteObjectARB(tmpProg);
		tmpProg=0;
	}

	mOk		= 0;
	mUse	= 0;
	mError	= 1;
	return false;
}
Ejemplo n.º 23
0
int main(int argc, const char*argv[]) {
	sm_set_program_name(argv[0]);
	
	struct sm_params params;
	struct sm_result result;
	
	struct option* ops = options_allocate(100);
	options_string(ops, "in", &p.file_in, "stdin", "Input file ");
	options_string(ops, "out", &p.file_out, "stdout", "Output file ");
	options_string(ops, "out_stats", &p.file_out_stats, "", "Output file (stats) ");
	options_string(ops, "file_jj", &p.file_jj, "",
		"File for journaling -- if left empty, journal not open.");
	options_int(ops, "algo", &p.algo, 0, "Which algorithm to use (0:(pl)ICP 1:gpm-stripped 2:HSM) ");
	
	options_int(ops, "debug", &p.debug, 0, "Shows debug information");
	options_int(ops, "recover_from_error", &p.recover_from_error, 0, "If true, tries to recover from an ICP matching error");
	
	
	p.format = 0;
/*	options_int(ops, "format", &p.format, 0,
		"Output format (0: log in JSON format, 1: log in Carmen format (not implemented))");*/
	
	sm_options(&params, ops);
	if(!options_parse_args(ops, argc, argv)) {
		fprintf(stderr, "\n\nUsage:\n");
		options_print_help(ops, stderr);
		return -1;
	}

	sm_debug_write(p.debug);

	/* Open input and output files */
	
	FILE * file_in = open_file_for_reading(p.file_in);
	if(!file_in) return -1;
	FILE * file_out = open_file_for_writing(p.file_out);
	if(!file_out) return -1;
	
	if(strcmp(p.file_jj, "")) {
		FILE * jj = open_file_for_writing(p.file_jj);
		if(!jj) return -1;
		jj_set_stream(jj);
	}
	
	FILE * file_out_stats = 0;
	if(strcmp(p.file_out_stats, "")) {
		file_out_stats = open_file_for_writing(p.file_out_stats);
		if(!file_out_stats) return -1;
	}
	
	/* Read first scan */
	LDP laser_ref;
	if(!(laser_ref = ld_read_smart(file_in))) {
		sm_error("Could not read first scan.\n");
		return -1;
	}
	if(!ld_valid_fields(laser_ref))  {
		sm_error("Invalid laser data in first scan.\n");
		return -2;
	}
	
	
	/* For the first scan, set estimate = odometry */
	copy_d(laser_ref->odometry, 3, laser_ref->estimate);
	
	spit(laser_ref, file_out);
	int count=-1;
	LDP laser_sens;
	while( (laser_sens = ld_read_smart(file_in)) ) {
		
		count++;
		if(!ld_valid_fields(laser_sens))  {
			sm_error("Invalid laser data in (#%d in file).\n", count);
			return -(count+2);
		}
		
		params.laser_ref  = laser_ref;
		params.laser_sens = laser_sens;

		/* Set first guess as the difference in odometry */
		
		if(	any_nan(params.laser_ref->odometry,3) ||  
			any_nan(params.laser_sens->odometry,3) ) {
				sm_error("The 'odometry' field is set to NaN so I don't know how to get an initial guess. I usually use the difference in the odometry fields to obtain the initial guess.\n");
				sm_error("  laser_ref->odometry = %s \n",  friendly_pose(params.laser_ref->odometry) );
				sm_error("  laser_sens->odometry = %s \n", friendly_pose(params.laser_sens->odometry) );
				sm_error(" I will quit it here. \n");
				return -3;
		}
		
		double odometry[3];
		pose_diff_d(laser_sens->odometry, laser_ref->odometry, odometry);
		double ominus_laser[3], temp[3];
		ominus_d(params.laser, ominus_laser);
		oplus_d(ominus_laser, odometry, temp);
		oplus_d(temp, params.laser, params.first_guess);
		
		/* Do the actual work */
		switch(p.algo) {
			case(0):
				sm_icp(&params, &result); break;
			case(1):
				sm_gpm(&params, &result); break;
			case(2):
				sm_hsm(&params, &result); break;
			default:
				sm_error("Unknown algorithm to run: %d.\n",p.algo);
				return -1;
		}
		
		if(!result.valid){
			if(p.recover_from_error) {
				sm_info("One ICP matching failed. Because you passed  -recover_from_error, I will try to recover."
				" Note, however, that this might not be good in some cases. \n");
				sm_info("The recover is that the displacement is set to 0. No result stats is output. \n");
				
				/* For the first scan, set estimate = odometry */
				copy_d(laser_ref->estimate, 3, laser_sens->estimate);
				
				ld_free(laser_ref); laser_ref = laser_sens;
				
			} else {
				sm_error("One ICP matching failed. Because I process recursively, I will stop here.\n");
				sm_error("Use the option -recover_from_error if you want to try to recover.\n");
				ld_free(laser_ref);
				return 2;
			}
		} else {
		
			/* Add the result to the previous estimate */
			oplus_d(laser_ref->estimate, result.x, laser_sens->estimate);

			/* Write the corrected log */
			spit(laser_sens, file_out);

			/* Write the statistics (if required) */
			if(file_out_stats) {
				JO jo = result_to_json(&params, &result);
				fputs(jo_to_string(jo), file_out_stats);
				fputs("\n", file_out_stats);
				jo_free(jo);
			}

			ld_free(laser_ref); laser_ref = laser_sens;
		}
	}
	ld_free(laser_ref);
	
	return 0;
}
Ejemplo n.º 24
0
int main(gint argc, gchar **argv) {
  const gchar *self = *argv++;

  if (argc < 2) {
    g_message("%s command [arguments...]", self);
    return 1;
  }

  if (g_getenv("NIX_CHROOTENV"))
    g_warning("chrootenv doesn't stack!");
  else
    g_setenv("NIX_CHROOTENV", "", TRUE);

  g_autofree gchar *prefix =
      g_build_filename(g_get_tmp_dir(), "chrootenvXXXXXX", NULL);

  fail_if(!g_mkdtemp_full(prefix, 0755));

  pid_t cpid = fork();

  if (cpid < 0)
    fail("fork", errno);

  else if (cpid == 0) {
    uid_t uid = getuid();
    gid_t gid = getgid();

    if (unshare(CLONE_NEWNS | CLONE_NEWUSER) < 0) {
      int unshare_errno = errno;

      g_message("Requires Linux version >= 3.19 built with CONFIG_USER_NS");
      if (g_file_test("/proc/sys/kernel/unprivileged_userns_clone",
                      G_FILE_TEST_EXISTS))
        g_message("Run: sudo sysctl -w kernel.unprivileged_userns_clone=1");

      fail("unshare", unshare_errno);
    }

    spit("/proc/self/setgroups", "deny");
    spit("/proc/self/uid_map", "%d %d 1", uid, uid);
    spit("/proc/self/gid_map", "%d %d 1", gid, gid);

    bind("/", prefix);

    fail_if(chroot(prefix));
    fail_if(chdir("/"));
    fail_if(execvp(*argv, argv));
  }

  else {
    int status;

    fail_if(waitpid(cpid, &status, 0) != cpid);
    fail_if(nftw(prefix, nftw_remove, getdtablesize(),
                 FTW_DEPTH | FTW_MOUNT | FTW_PHYS));

    if (WIFEXITED(status))
      return WEXITSTATUS(status);

    else if (WIFSIGNALED(status))
      kill(getpid(), WTERMSIG(status));

    return 1;
  }
}
Ejemplo n.º 25
0
void Utils::serializeProfit(float profit, const string filename) {
	spit(to_string(profit), filename);
}
Ejemplo n.º 26
0
int main(gint argc, gchar **argv) {
  const gchar *self = *argv++;

  if (argc < 2) {
    g_message("%s command [arguments...]", self);
    return 1;
  }

  g_autofree const gchar *prefix = create_tmpdir();

  pid_t cpid = fork();

  if (cpid < 0)
    fail("fork", errno);

  else if (cpid == 0) {
    uid_t uid = getuid();
    gid_t gid = getgid();

    if (unshare(CLONE_NEWNS | CLONE_NEWUSER) < 0) {
      int unshare_errno = errno;

      g_message("Requires Linux version >= 3.19 built with CONFIG_USER_NS");
      if (g_file_test("/proc/sys/kernel/unprivileged_userns_clone",
                      G_FILE_TEST_EXISTS))
        g_message("Run: sudo sysctl -w kernel.unprivileged_userns_clone=1");

      fail("unshare", unshare_errno);
    }

    spit("/proc/self/setgroups", "deny");
    spit("/proc/self/uid_map", "%d %d 1", uid, uid);
    spit("/proc/self/gid_map", "%d %d 1", gid, gid);

    // If there is a /host directory, assume this is nested chrootenv and use it as host instead.
    gboolean nested_host = g_file_test("/host", G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR);
    g_autofree const gchar *host = nested_host ? "/host" : "/";

    bind(host, prefix);

    // Replace /host by an actual (inner) /host.
    if (nested_host) {
      fail_if(g_mkdir("/real-host", 0755));
      fail_if(mount("/host/host", "/real-host", NULL, MS_BIND | MS_REC, NULL));
      // For some reason umount("/host") returns EBUSY even immediately after
      // pivot_root. We detach it at least to keep `/proc/mounts` from blowing
      // up in nested cases.
      fail_if(umount2("/host", MNT_DETACH));
      fail_if(mount("/real-host", "/host", NULL, MS_MOVE, NULL));
      fail_if(rmdir("/real-host"));
    }

    fail_if(chdir("/"));
    fail_if(execvp(*argv, argv));
  }

  else {
    int status;

    fail_if(waitpid(cpid, &status, 0) != cpid);
    fail_if(rmdir(prefix));

    if (WIFEXITED(status))
      return WEXITSTATUS(status);

    else if (WIFSIGNALED(status))
      kill(getpid(), WTERMSIG(status));

    return 1;
  }
}
Ejemplo n.º 27
0
void writetitle(char *t)
{
    char d;
    char *pst;
    int j;
    int l;
    int m;
    int n;
    int pstlen;

    d = *t;
    if (d=='\0') {
        spit('\n');
        return;
    }
    pst = pgform();
    pstlen= strlen(pst);
    t++;
    l = titlen(t, d, pstlen);
    while (1) {
        if (*t == 0) break;
        if (*t == d) break;
        if (*t == '%')
            spits(pst);
        else
            spit(*t);
        t++;
    }
    if (*t == '\0') {
        spit('\n');
        return;
    }
    t++;
    m = titlen(t, d, pstlen);
    for (j = l; j < (o_ll - m) / 2; j++) spit(' ');
    while (1) {
        if (*t == 0) break;
        if (*t == d) break;
        if (*t == '%')
            spits(pst);
        else
            spit(*t);
        t++;
    }
    if (*t == '\0') {
        spit('\n');
        return;
    }
    if ((o_ll - m) / 2 > l)
        m = m + (o_ll - m) / 2;
    else
        m = m + l;
    t++;
    n = titlen(t, d, pstlen);
    for (j = m; j < o_ll - n; j++) spit(' ');
    while (1) {
        if (*t == 0) break;
        if (*t == d) break;
        if (*t == '%')
            spits(pst);
        else
            spit(*t);
        t++;
    }
    spit('\n');
}
Ejemplo n.º 28
0
int main (int argc, char **argv) {
    int i=0,j=0;
    uint32_t num_tests, num_sets_per_test, num_ops_per_test, the_max_num_labels, seed;
    uint8_t x=0;
    uint32_t y=0,zz=0;
    Dpdf *pdf=NULL;
    int num_args = 6;

    if (argc-1 == num_args) {
        num_tests = atoi(argv[1]);
        num_sets_per_test = atoi(argv[2]);
        num_ops_per_test = atoi(argv[3]);
        the_max_num_labels = atoi(argv[4]);
        seed = atoi(argv[5]);
        bv_debug = atoi(argv[6]);
    }
    else {
        printf ("I needed %d args; you provided %d -- using defaults.\n", num_args, argc-1);
        printf ("usage: bvlt num_tests num_sets_per_test num_ops_per_test max_labels seed bv_debug\n");
        num_tests = 10;
        num_sets_per_test = 10;
        num_ops_per_test = 1000;
        the_max_num_labels = 32;
        seed = 1234567;
        bv_debug =  TRUE;
    }

    printf ("%d tests\n", num_tests);
    printf ("%d sets per test\n", num_sets_per_test);
    printf ("%d ops per test\n", num_ops_per_test);
    printf ("%d max unique labels\n", the_max_num_labels);
    printf ("%d random seed\n", seed);

    pdf = prob_create("bvc",NUM_OPS);
    prob_set(pdf,ERASE,0.05);
    prob_set(pdf,IS_EMPTY,0.05);
    prob_set(pdf,ADD,0.5);
    prob_set(pdf,COPY,0.05);
    prob_set(pdf,UNION,0.05);
    prob_normalize(pdf);
    printf ("dist of ops {ERASE,IS_EMPTY,ADD,COPY,UNION}\n ");
    prob_spit(pdf);

    srand(seed);
    labelset_set_max_num_labels(the_max_num_labels);
    for (i=0; i<num_tests; i++) {
        if (bv_debug) printf ("test %d\n", i);
        LabelSet **ls = (LabelSet **) my_malloc(sizeof(LabelSet *) * num_sets_per_test, poolid_label_set);
        for (j=0; j<num_sets_per_test; j++) {
            ls[j] = labelset_new();
        }
        for (j=0; j<num_ops_per_test; j++) {
            if (bv_debug) printf ("op %d: ", j);
            uint32_t l = random() % num_sets_per_test;
            int d = prob_draw(pdf);
            LabelSet *tls = ls[l];
            switch (d) {
                case ERASE:
                    labelset_erase(tls);
                    assert ((labelset_card(tls)) == 0);
                    if (bv_debug) {
                        printf ("erase set %d. ",l);
                        spit (l,ls);
                    }
                    break;
                case IS_EMPTY:
                    x = labelset_is_empty(tls);
                    if (x)
                        assert ((labelset_card(tls)) == 0);
                    else
                        assert ((labelset_card(tls)) != 0);
                    if (bv_debug) {
                        printf ("is_empty set=%d: %d. ", l, x);
                        spit (l,ls);
                    }
                    break;
                case ADD:
                    {
                        uint32_t n1 = labelset_card(tls);
                        uint32_t y = (random()) % the_max_num_labels;
                        uint8_t already_there = labelset_member(tls,y);
                        labelset_add(tls,y);
                        assert (labelset_member(tls,y));
                        uint32_t n2 = labelset_card(tls);
                        if (already_there)
                            assert (n1 == n2);
                        else
                            assert (n1 + 1 == n2);
                        if (bv_debug) {
                            printf ("add to set=%d, el=%d. ",l,y);
                            spit(l,ls);
                        }
                        break;
                    }
                case COPY:
                    {
                        uint32_t o=0;
                        do {
                            o = random() % num_sets_per_test;
                        } while (o == l);
                        labelset_copy(tls,ls[o]);
                        if (bv_debug) {
                            printf ("copy set=%d to set=%d. ",o,l);
                            spit(l,ls);
                        }
                        break;
                    }
                case UNION:
                    {
                        uint32_t o=0;
                        do {
                            o = random() % num_sets_per_test;
                        } while (o == l);
                        labelset_union(tls,ls[o]);
                        if (bv_debug) {
                            printf ("union set=%d <- set=%d. ", l,o);
                            spit(l,ls);
                        }
                        break;
                    }
                default:
                    printf ("wtf d=%d\n", d);
                    abort();
                    break;
            }
            zz += x; // make sure x actually gets computed.
        } // iterate over ops
        // release memory
        for (j=0; j<num_sets_per_test; j++) {
            labelset_free(ls[j]);
        }
        my_free(ls, sizeof(LabelSet), poolid_label_set);
    } // iterate over tests
    printf ("zz=%d\n", zz); // say no to optimizers
    prob_destroy(pdf);
} // main