Exemple #1
0
static void warm_up(int sz, tsc_t d) {
    pthread_t th[sz];
    d += timeofday() ;
    for (int k = 0 ; k < sz ; k++) launch(&th[k], loop, &d) ;
    for (int k = 0 ; k < sz ; k++) join(&th[k]) ;
}
Exemple #2
0
int main() {
  LiftOff launch(10);
  launch.run();
} ///:~
Exemple #3
0
static unsigned long
penetrate_draw (Display *dpy, Window window, void *closure)
{
  struct state *st = (struct state *) closure;
  XWindowAttributes xgwa;

  if (st->draw_reset)
    {
      st->draw_reset = 0;
      DrawCities(st, st->draw_xlim, st->draw_ylim);
    }

  XGetWindowAttributes(st->dpy, st->window, &xgwa);
  st->draw_xlim = xgwa.width;
  st->draw_ylim = xgwa.height;

  /* see if just started */
  if (st->loop == 0) {
	 if (st->smart) {
		st->choosypersen = st->econpersen = st->carefulpersen = 100;
		st->lrate = kMinRate; st->aim = 1;
	 }
	 NewLevel(st, st->draw_xlim, st->draw_ylim);
	 DrawScore(st, st->draw_xlim, st->draw_ylim);
  }

  st->loop++;

  if (st->levMissiles == 0) {
	 /* see if anything's still on the screen, to know when to end level */
	 int i;
	 for (i=0;i<kMaxMissiles;i++)
		if (st->missile[i].alive)
		  goto END_CHECK;
	 for (i=0;i<kMaxBooms;i++)
		if (st->boom[i].alive)
		  goto END_CHECK;
	 for (i=0;i<kMaxLasers;i++)
		if (st->laser[i].alive)
		  goto END_CHECK;
	 /* okay, nothing's alive, start end of level countdown */
	 usleep(kLevelPause*1000000);
	 NewLevel(st, st->draw_xlim, st->draw_ylim);
         goto END;
  END_CHECK: ;
  }
  else if ((random() % st->levFreq) == 0) {
	 launch(st, st->draw_xlim, st->draw_ylim, -1);
	 st->levMissiles--;
  }

  if (st->loop - st->lastLaser >= st->lrate) {
	 if (fire(st, st->draw_xlim, st->draw_ylim))
		st->lastLaser = st->loop;
  }

  if ((st->loop & 7) == 0)
    st->draw_reset = 1;

  LoopMissiles(st, st->draw_xlim, st->draw_ylim);
  LoopLasers(st, st->draw_xlim, st->draw_ylim);
  LoopBooms(st, st->draw_xlim, st->draw_ylim);

 END:
  return kSleepTime;
}
Exemple #4
0
/**
   Use the specified launch filter to launch all the files in the specified list.

   \param filter the action to take
   \param files the list of files for which to perform the action
   \param fileno an internal value. Should always be set to zero.
*/
static void launch( char *filter, array_list_t *files, int fileno )
{
    char *filter_org=filter;
    int count=0;
    int launch_again=0;

    if( al_get_count( files ) <= fileno )
        return;


    launch_pos=0;

    for( ; *filter && !error; filter++)
    {
        if(*filter == '%')
        {
            filter++;
            switch( *filter )
            {
            case 'u':
            {
                launch_again = 1;
                write_url( (char *)al_get( files, fileno ) );
                break;
            }
            case 'U':
            {
                int i;
                for( i=0; i<al_get_count( files ); i++ )
                {
                    if( i != 0 )
                        writer( ' ' );
                    write_url( (char *)al_get( files, i ) );
                    if( error )
                        break;
                }

                break;
            }

            case 'f':
            case 'n':
            {
                launch_again = 1;
                write_file( (char *)al_get( files, fileno ), *filter == 'f' );
                break;
            }

            case 'F':
            case 'N':
            {
                int i;
                for( i=0; i<al_get_count( files ); i++ )
                {
                    if( i != 0 )
                        writer( ' ' );
                    write_file( (char *)al_get( files, i ), *filter == 'F' );
                    if( error )
                        break;
                }
                break;
            }


            case 'd':
            {
                char *cpy = get_fullfile( (char *)al_get( files, fileno ) );
                char *dir;

                launch_again=1;
                /*
                  We wish to modify this string, make sure it is only a copy
                */
                if( cpy == al_get( files, fileno ) )
                    cpy = my_strdup( cpy );

                if( cpy == 0 )
                {
                    break;
                }
                dir=dirname( cpy );
                write_file( dir, 1 );
                free( cpy );

                break;
            }

            case 'D':
            {
                int i;
                for( i=0; i<al_get_count( files ); i++ )
                {
                    char *cpy = get_fullfile( (char *)al_get( files, i ) );
                    char *dir;

                    /*
                      We wish to modify this string, make sure it is only a copy
                    */
                    if( cpy == al_get( files, i ) )
                        cpy = my_strdup( cpy );

                    if( cpy == 0 )
                    {
                        break;
                    }
                    dir=dirname( cpy );

                    if( i != 0 )
                        writer( ' ' );

                    write_file( dir, 1 );
                    free( cpy );

                }
                break;
            }

            default:
                fprintf( stderr, _("%s: Unsupported switch '%c' in launch string '%s'\n"), MIMEDB, *filter, filter_org );
                launch_len=0;
                break;

            }
        }
        else
        {
            writer( *filter );
            count++;
        }
    }

    if( error )
        return;

    switch( launch_len )
    {
    case -1:
    {
        launch_len = 0;
        fprintf( stderr, _( "%s: Out of memory\n"), MIMEDB );
        return;
    }
    case 0:
    {
        return;
    }
    default:
    {

        writer( ' ' );
        writer( '&' );
        writer( '\0' );

        if( system( launch_buff ) == -1 )
        {
            fprintf( stderr, _( ERROR_SYSTEM ), MIMEDB, launch_buff );
            exit(STATUS_ERROR_SYSTEM);
        }

        break;
    }
    }
    if( launch_again )
    {
        launch( filter_org, files, fileno+1 );
    }

}
void b3GpuJacobiContactSolver::solveContacts(int numBodies, cl_mem bodyBuf, cl_mem inertiaBuf, int numContacts, cl_mem contactBuf, const struct b3Config& config, int static0Index)
//
//
//void  b3GpuJacobiContactSolver::solveGroup(b3OpenCLArray<b3RigidBodyData>* bodies,b3OpenCLArray<b3InertiaData>* inertias,b3OpenCLArray<b3Contact4>* manifoldPtr,const btJacobiSolverInfo& solverInfo)
{
	b3JacobiSolverInfo solverInfo;
	solverInfo.m_fixedBodyIndex = static0Index;
	

	B3_PROFILE("b3GpuJacobiContactSolver::solveGroup");

	//int numBodies = bodies->size();
	int numManifolds = numContacts;//manifoldPtr->size();

	{
		B3_PROFILE("resize");
		m_data->m_bodyCount->resize(numBodies);
	}
	
	unsigned int val=0;
	b3Int2 val2;
	val2.x=0;
	val2.y=0;

	 {
		B3_PROFILE("m_filler");
		m_data->m_contactConstraintOffsets->resize(numManifolds);
		m_data->m_filler->execute(*m_data->m_bodyCount,val,numBodies);
		
	
		m_data->m_filler->execute(*m_data->m_contactConstraintOffsets,val2,numManifolds);
	}

	{
		B3_PROFILE("m_countBodiesKernel");
		b3LauncherCL launcher(this->m_queue,m_data->m_countBodiesKernel,"m_countBodiesKernel");
		launcher.setBuffer(contactBuf);//manifoldPtr->getBufferCL());
		launcher.setBuffer(m_data->m_bodyCount->getBufferCL());
		launcher.setBuffer(m_data->m_contactConstraintOffsets->getBufferCL());
		launcher.setConst(numManifolds);
		launcher.setConst(solverInfo.m_fixedBodyIndex);
		launcher.launch1D(numManifolds);
	}
	unsigned int totalNumSplitBodies=0;
	{
		B3_PROFILE("m_scan->execute");
		
		m_data->m_offsetSplitBodies->resize(numBodies);
		m_data->m_scan->execute(*m_data->m_bodyCount,*m_data->m_offsetSplitBodies,numBodies,&totalNumSplitBodies);
		totalNumSplitBodies+=m_data->m_bodyCount->at(numBodies-1);
	}

	{
		B3_PROFILE("m_data->m_contactConstraints->resize");
		//int numContacts = manifoldPtr->size();
		m_data->m_contactConstraints->resize(numContacts);
	}
	
	{
		B3_PROFILE("contactToConstraintSplitKernel");
		b3LauncherCL launcher( m_queue, m_data->m_contactToConstraintSplitKernel,"m_contactToConstraintSplitKernel");
		launcher.setBuffer(contactBuf);
		launcher.setBuffer(bodyBuf);
		launcher.setBuffer(inertiaBuf);
		launcher.setBuffer(m_data->m_contactConstraints->getBufferCL());
		launcher.setBuffer(m_data->m_bodyCount->getBufferCL());
        launcher.setConst(numContacts);
		launcher.setConst(solverInfo.m_deltaTime);
		launcher.setConst(solverInfo.m_positionDrift);
		launcher.setConst(solverInfo.m_positionConstraintCoeff);
		launcher.launch1D( numContacts, 64 );
		
	}

	
	{
		B3_PROFILE("m_data->m_deltaLinearVelocities->resize");
		m_data->m_deltaLinearVelocities->resize(totalNumSplitBodies);
		m_data->m_deltaAngularVelocities->resize(totalNumSplitBodies);
	}


	
	{
		B3_PROFILE("m_clearVelocitiesKernel");
		b3LauncherCL launch(m_queue,m_data->m_clearVelocitiesKernel,"m_clearVelocitiesKernel");
		launch.setBuffer(m_data->m_deltaAngularVelocities->getBufferCL());
		launch.setBuffer(m_data->m_deltaLinearVelocities->getBufferCL());
		launch.setConst(totalNumSplitBodies);
		launch.launch1D(totalNumSplitBodies);
		clFinish(m_queue);
	}
	
	
	int maxIter = solverInfo.m_numIterations;

	for (int iter = 0;iter<maxIter;iter++)
	{
		{
			B3_PROFILE("m_solveContactKernel");
			b3LauncherCL launcher( m_queue, m_data->m_solveContactKernel,"m_solveContactKernel" );
			launcher.setBuffer(m_data->m_contactConstraints->getBufferCL());
			launcher.setBuffer(bodyBuf);
			launcher.setBuffer(inertiaBuf);
			launcher.setBuffer(m_data->m_contactConstraintOffsets->getBufferCL());
			launcher.setBuffer(m_data->m_offsetSplitBodies->getBufferCL());
			launcher.setBuffer(m_data->m_deltaLinearVelocities->getBufferCL());
			launcher.setBuffer(m_data->m_deltaAngularVelocities->getBufferCL());
			launcher.setConst(solverInfo.m_deltaTime);
			launcher.setConst(solverInfo.m_positionDrift);
			launcher.setConst(solverInfo.m_positionConstraintCoeff);
			launcher.setConst(solverInfo.m_fixedBodyIndex);
			launcher.setConst(numManifolds);

			launcher.launch1D(numManifolds);
			clFinish(m_queue);
		}

		

		{
			B3_PROFILE("average velocities");
			b3LauncherCL launcher( m_queue, m_data->m_averageVelocitiesKernel,"m_averageVelocitiesKernel");
			launcher.setBuffer(bodyBuf);
			launcher.setBuffer(m_data->m_offsetSplitBodies->getBufferCL());
			launcher.setBuffer(m_data->m_bodyCount->getBufferCL());
			launcher.setBuffer(m_data->m_deltaLinearVelocities->getBufferCL());
			launcher.setBuffer(m_data->m_deltaAngularVelocities->getBufferCL());
			launcher.setConst(numBodies);
			launcher.launch1D(numBodies);
			clFinish(m_queue);
		}

		
		{
			B3_PROFILE("m_solveFrictionKernel");
			b3LauncherCL launcher( m_queue, m_data->m_solveFrictionKernel,"m_solveFrictionKernel");
			launcher.setBuffer(m_data->m_contactConstraints->getBufferCL());
			launcher.setBuffer(bodyBuf);
			launcher.setBuffer(inertiaBuf);
			launcher.setBuffer(m_data->m_contactConstraintOffsets->getBufferCL());
			launcher.setBuffer(m_data->m_offsetSplitBodies->getBufferCL());
			launcher.setBuffer(m_data->m_deltaLinearVelocities->getBufferCL());
			launcher.setBuffer(m_data->m_deltaAngularVelocities->getBufferCL());
			launcher.setConst(solverInfo.m_deltaTime);
			launcher.setConst(solverInfo.m_positionDrift);
			launcher.setConst(solverInfo.m_positionConstraintCoeff);
			launcher.setConst(solverInfo.m_fixedBodyIndex);
			launcher.setConst(numManifolds);

			launcher.launch1D(numManifolds);
			clFinish(m_queue);
		}

		
		{
			B3_PROFILE("average velocities");
			b3LauncherCL launcher( m_queue, m_data->m_averageVelocitiesKernel,"m_averageVelocitiesKernel");
			launcher.setBuffer(bodyBuf);
			launcher.setBuffer(m_data->m_offsetSplitBodies->getBufferCL());
			launcher.setBuffer(m_data->m_bodyCount->getBufferCL());
			launcher.setBuffer(m_data->m_deltaLinearVelocities->getBufferCL());
			launcher.setBuffer(m_data->m_deltaAngularVelocities->getBufferCL());
			launcher.setConst(numBodies);
			launcher.launch1D(numBodies);
			clFinish(m_queue);
		}

		

	}

	
	{
			B3_PROFILE("update body velocities");
			b3LauncherCL launcher( m_queue, m_data->m_updateBodyVelocitiesKernel,"m_updateBodyVelocitiesKernel");
			launcher.setBuffer(bodyBuf);
			launcher.setBuffer(m_data->m_offsetSplitBodies->getBufferCL());
			launcher.setBuffer(m_data->m_bodyCount->getBufferCL());
			launcher.setBuffer(m_data->m_deltaLinearVelocities->getBufferCL());
			launcher.setBuffer(m_data->m_deltaAngularVelocities->getBufferCL());
			launcher.setConst(numBodies);
			launcher.launch1D(numBodies);
			clFinish(m_queue);
		}



}
void
LauncherApplication::launchNewInstance()
{
    launch();
}
jdwpError
transport_startTransport(jboolean isServer, char *name, char *address,
                         long timeout)
{
    jvmtiStartFunction func;
    jdwpTransportEnv *trans;
    char threadName[MAXPATHLEN + 100];
    jint err;
    jdwpError serror;

    /*
     * If the transport is already loaded then use it
     * Note: We're assuming here that we don't support multiple
     * transports - when we do then we need to handle the case
     * where the transport library only supports a single environment.
     * That probably means we have a bag a transport environments
     * to correspond to the transports bag.
     */
    if (transport != NULL) {
        trans = transport;
    } else {
        serror = loadTransport(name, &trans);
        if (serror != JDWP_ERROR(NONE)) {
            return serror;
        }
    }

    if (isServer) {

        char *retAddress;
        char *launchCommand;
        TransportInfo *info;
        jvmtiError error;
        int len;
        char* prop_value;

        info = jvmtiAllocate(sizeof(*info));
        if (info == NULL) {
            return JDWP_ERROR(OUT_OF_MEMORY);
        }
        info->name = jvmtiAllocate((int)strlen(name)+1);
        (void)strcpy(info->name, name);
        info->address = NULL;
        info->timeout = timeout;
        if (info->name == NULL) {
            serror = JDWP_ERROR(OUT_OF_MEMORY);
            goto handleError;
        }
        if (address != NULL) {
            info->address = jvmtiAllocate((int)strlen(address)+1);
            (void)strcpy(info->address, address);
            if (info->address == NULL) {
                serror = JDWP_ERROR(OUT_OF_MEMORY);
                goto handleError;
            }
        }

        info->transport = trans;

        err = (*trans)->StartListening(trans, address, &retAddress);
        if (err != JDWPTRANSPORT_ERROR_NONE) {
            printLastError(trans, err);
            serror = JDWP_ERROR(TRANSPORT_INIT);
            goto handleError;
        }

        /*
         * Record listener address in a system property
         */
        len = (int)strlen(name) + (int)strlen(retAddress) + 2; /* ':' and '\0' */
        prop_value = (char*)jvmtiAllocate(len);
        strcpy(prop_value, name);
        strcat(prop_value, ":");
        strcat(prop_value, retAddress);
        setTransportProperty(getEnv(), prop_value);
        jvmtiDeallocate(prop_value);


        (void)strcpy(threadName, "JDWP Transport Listener: ");
        (void)strcat(threadName, name);

        func = &acceptThread;
        error = spawnNewThread(func, (void*)info, threadName);
        if (error != JVMTI_ERROR_NONE) {
            serror = map2jdwpError(error);
            goto handleError;
        }

        launchCommand = debugInit_launchOnInit();
        if (launchCommand != NULL) {
            serror = launch(launchCommand, name, retAddress);
            if (serror != JDWP_ERROR(NONE)) {
                goto handleError;
            }
        } else {
            if ( ! gdata->quiet ) {
                TTY_MESSAGE(("Listening for transport %s at address: %s",
                    name, retAddress));
            }
        }
        return JDWP_ERROR(NONE);

handleError:
        jvmtiDeallocate(info->name);
        jvmtiDeallocate(info->address);
        jvmtiDeallocate(info);
    } else {
        /*
         * Note that we don't attempt to do a launch here. Launching
         * is currently supported only in server mode.
         */

        /*
         * If we're connecting to another process, there shouldn't be
         * any concurrent listens, so its ok if we block here in this
         * thread, waiting for the attach to finish.
         */
         err = (*trans)->Attach(trans, address, timeout, 0);
         if (err != JDWPTRANSPORT_ERROR_NONE) {
             printLastError(trans, err);
             serror = JDWP_ERROR(TRANSPORT_INIT);
             return serror;
         }

         /*
          * Start the transport loop in a separate thread
          */
         (void)strcpy(threadName, "JDWP Transport Listener: ");
         (void)strcat(threadName, name);

         func = &attachThread;
         err = spawnNewThread(func, (void*)trans, threadName);
         serror = map2jdwpError(err);
    }
    return serror;
}
Exemple #8
0
void DialogStartup::on_listWidget_2_itemDoubleClicked()
{
    QString ItemText = listWidget_2->currentItem()->data(Qt::UserRole).toString();
    launch(ItemText);
}
Exemple #9
0
bool handleInput () {
	static int l = 0;
	static Uint32 theTime;

	theTime = SDL_GetTicks() / 1000;
	if (lastSeconds != theTime) {
		lastSeconds = theTime;
		lastFramesPerSecond = thisFramesPerSecond;
		thisFramesPerSecond = 1;
	} else {
		thisFramesPerSecond ++;
	}
//	lastFramesPerSecond = theTime.wSecond;

	if (launchMe) {
		if (l) {
			// Still paused because of spawned thingy...
		} else {
			l = 1;

			setVariable (* launchResult, SVT_INT, launch(launchMe) > 31);
			launchMe = NULL;
			launchResult = NULL;
		}
		return true;
	} else {
		 l = 0;
	}

	if (! overRegion) getOverRegion ();

	if (input.justMoved) {
		if (currentEvents -> moveMouseFunction) {
			if (! startNewFunctionNum (currentEvents -> moveMouseFunction, 0, NULL, noStack)) return false;
		}
	}
	input.justMoved = false;

	if (lastRegion != overRegion && currentEvents -> focusFunction) {
		variableStack * tempStack = new variableStack;
		if (! checkNew (tempStack)) return false;
		
		initVarNew (tempStack -> thisVar);
		if (overRegion) {
			setVariable (tempStack -> thisVar, SVT_OBJTYPE, overRegion -> thisType -> objectNum);
		} else {
			setVariable (tempStack -> thisVar, SVT_INT, 0);
		}
		tempStack -> next = NULL;
		if (! startNewFunctionNum (currentEvents -> focusFunction, 1, NULL, tempStack)) return false;
	}
	if (input.leftRelease && currentEvents -> leftMouseUpFunction)  {
		if (! startNewFunctionNum (currentEvents -> leftMouseUpFunction, 0, NULL, noStack)) return false;
	}
	if (input.rightRelease && currentEvents -> rightMouseUpFunction) {
		if (! startNewFunctionNum (currentEvents -> rightMouseUpFunction, 0, NULL, noStack)) return false;
	}
	if (input.leftClick && currentEvents -> leftMouseFunction)
		if (! startNewFunctionNum (currentEvents -> leftMouseFunction, 0, NULL, noStack)) return false;
	if (input.rightClick && currentEvents -> rightMouseFunction) {
		if (! startNewFunctionNum (currentEvents -> rightMouseFunction, 0, NULL, noStack)) return false;
	}
	if (input.keyPressed && currentEvents -> spaceFunction) {
		char * tempString = NULL;
		switch (input.keyPressed) {
			case 127:	
				tempString = copyString ("BACKSPACE");	break;
			case 9:		tempString = copyString ("TAB");		break;
			case 13:	tempString = copyString ("ENTER");		break;
			case 27:	tempString = copyString ("ESCAPE");		break;
			/*
			case 1112:	tempString = copyString ("ALT+F1");		break;
			case 1113:	tempString = copyString ("ALT+F2");		break;
			case 1114:	tempString = copyString ("ALT+F3");		break;
			case 1115:	tempString = copyString ("ALT+F4");		break;
			case 1116:	tempString = copyString ("ALT+F5");		break;
			case 1117:	tempString = copyString ("ALT+F6");		break;
			case 1118:	tempString = copyString ("ALT+F7");		break;
			case 1119:	tempString = copyString ("ALT+F8");		break;
			case 1120:	tempString = copyString ("ALT+F9");		break;
			case 1121:	tempString = copyString ("ALT+F10");	break;
			case 1122:	tempString = copyString ("ALT+F11");	break;
			case 1123:	tempString = copyString ("ALT+F12");	break;

			case 2019:	tempString = copyString ("PAUSE");		break;
			*/
			case 63276:	tempString = copyString ("PAGE UP");	break;
			case 63277:	tempString = copyString ("PAGE DOWN");	break;
			case 63275:	tempString = copyString ("END");		break;
			case 63273:	tempString = copyString ("HOME");		break;
			case 63234:	tempString = copyString ("LEFT");		break;
			case 63232:	tempString = copyString ("UP");			break;
			case 63235:	tempString = copyString ("RIGHT");		break;
			case 63233:	tempString = copyString ("DOWN");		break;
				/*
			case 2045:	tempString = copyString ("INSERT");		break;
			case 2046:	tempString = copyString ("DELETE");		break;
				*/
			case 63236:	tempString = copyString ("F1");			break;
			case 63237:	tempString = copyString ("F2");			break;
			case 63238:	tempString = copyString ("F3");			break;
			case 63239:	tempString = copyString ("F4");			break;
			case 63240:	tempString = copyString ("F5");			break;
			case 63241:	tempString = copyString ("F6");			break;
			case 63242:	tempString = copyString ("F7");			break;
			case 63243:	tempString = copyString ("F8");			break;
			case 63244:	tempString = copyString ("F9");			break;
			case 63245:	tempString = copyString ("F10");		break;
			case 63246:	tempString = copyString ("F11");		break;
			case 63247:	tempString = copyString ("F12");		break;

			default:
			if (input.keyPressed >= 256) {
				//if (captureAllKeys) {
					tempString = copyString ("ABCDEF");
					sprintf (tempString, "%i", input.keyPressed);
				//}
			} else {
				tempString = copyString (" ");
				tempString[0] = input.keyPressed;
			}
		}

		if (tempString) {
			variableStack * tempStack = new variableStack;
			if (! checkNew (tempStack)) return false;
			initVarNew (tempStack -> thisVar);
			makeTextVar (tempStack -> thisVar, tempString);
			delete tempString;
			tempString = NULL;
			tempStack -> next = NULL;
			if (! startNewFunctionNum (currentEvents -> spaceFunction, 1, NULL, tempStack)) return false;
		}
	}
	input.rightClick = false;
	input.leftClick = false;
	input.rightRelease = false;
	input.leftRelease = false;
	input.keyPressed = 0;
	lastRegion = overRegion;
	return runSludge ();
}
Exemple #10
0
void App_info::launch(QString filename) {
  launch( QStringList() << filename );
}
int launch_test(void){
	pid_t pid;
	pid_t pid_alt;
	int status;
	char exec_path[PATH_MAX];
	char exec_path_alt[PATH_MAX];
	int ret;
	int fd;
	char buffer[64];

	printf("Test launch() (BAD PATH)...");
	fflush(stdout);
	if( launch("1", 0, 0, 0, 0, update_progress, 0) < 0 ){
		if ( errno == ENOENT ){
			printf("passed\n");
		} else {
			printf("failed with %d not %d\n", errno, ENOENT);
		}
	} else {
		printf("failed (returned success on empty path)\n");
	}

	printf("Test launch() (INVALID PATH)...");
	fflush(stdout);
	if( launch("/home/NO_PROGRAM", 0, 0, 0, 0, update_progress, 0) < 0 ){
		if ( errno == ENOENT ){
			printf("passed\n");
		} else {
			printf("failed with %d not %d\n", errno, ENOENT);
		}
	} else {
		printf("failed (returned success on empty path)\n");
	}


	printf("Test launch() (no children)...");
	fflush(stdout);
	errno = 0;
	wait(&status);
	if( errno != ECHILD ){
		printf("failed (%d != %d)\n", errno, ECHILD);
	} else {
		printf("passed\n");
	}


	printf("Test launch()...");
	fflush(stdout);
	if( (pid = launch(LAUNCH_SLAVE_PATH, exec_path, 0, 0, 0, update_progress, 0)) < 0 ){
		perror("failed to launch");
		return -1;
	} else {
		do {
			errno = 0;
			ret = wait(&status);
		} while( errno == EINTR );

		if( errno != 0 ){
			perror("failed to wait");
		} else {
			printf("passed\n");
		}
	}

	printf("Test launch() (relaunch)...");
	fflush(stdout);
	if( (pid = launch(LAUNCH_SLAVE_PATH, 0, 0, 0, 0, update_progress, 0)) < 0 ){
		perror("failed to launch");
		return -1;
	} else {
		do {
			errno = 0;
			ret = wait(&status);
		} while( errno == EINTR );

		if( errno != 0 ){
			perror("failed to wait");
		} else {
			printf("passed\n");
		}

		unlink(exec_path);
	}

	printf("Test launch() (with options)...");
	fflush(stdout);
	if( (pid = launch(LAUNCH_SLAVE_PATH, exec_path, "2 3 4 5 6 7", 0, 0, update_progress, 0)) < 0 ){
		perror("failed to launch");
		return -1;
	} else {

		do {
			errno = 0;
			ret = wait(&status);
		} while( (ret < 0) && (errno = EINTR) );

		unlink(exec_path);

		if( ((status >> 8) & 0xff) != 7 ){
			printf("Failed (return value %d != %d)\n", 7, (status >> 8) & 0xff);
			return -1;
		}

		if( errno != 0 ){
			perror("failed to wait");
		} else {
			printf("passed\n");
		}
	}

	printf("Test launch() (orphan)...");
	unlink("/home/orphan.txt");
	fflush(stdout);
	if( (pid = launch(LAUNCH_SLAVE_PATH, exec_path, "orphan", LINK_APPFS_EXEC_OPTIONS_ORPHAN, 0, update_progress, 0)) < 0 ){
		perror("failed to launch");
		return -1;
	} else {

		//orphan creates a file called orphan.txt
		usleep(500*1000);

		fd = open("/home/orphan.txt", O_RDONLY);
		if( fd < 0 ){
			printf("orphan failed to create file\n");
		} else {
			printf("passed\n");
		}

		unlink(exec_path);

	}

	printf("Test launch() (flash)...");
	fflush(stdout);
	if( (pid = launch(LAUNCH_SLAVE_PATH, exec_path, 0, LINK_APPFS_EXEC_OPTIONS_FLASH, 0, update_progress, 0)) < 0 ){
		perror("failed to launch");
		return -1;
	} else {
		do {
			errno = 0;
			ret = wait(&status);
		} while( errno == EINTR );

		if( errno != 0 ){
			perror("failed to wait");
		} else {
			printf("passed\n");
		}

		unlink(exec_path);
	}

	printf("Test launch() (child wait)...");
	fflush(stdout);
	if( (pid = launch(LAUNCH_SLAVE_PATH, exec_path, "wait", 0, 0, update_progress, 0)) < 0 ){
		perror("failed to launch");
		return -1;
	} else {
		do {
			errno = 0;
			ret = wait(&status);
		} while( errno == EINTR );

		if( errno != 0 ){
			perror("failed to wait");
		} else {
			printf("passed\n");
		}

		unlink(exec_path);
	}

	printf("Test launch() (parent wait)...");
	fflush(stdout);
	if( (pid = launch(LAUNCH_SLAVE_PATH, exec_path, 0, 0, 0, update_progress, 0)) < 0 ){
		perror("failed to launch");
		return -1;
	} else {

		usleep(100*1000);

		do {
			errno = 0;
			ret = wait(&status);
		} while( errno == EINTR );

		if( errno != 0 ){
			perror("failed to wait");
		} else {
			printf("passed\n");
		}

		unlink(exec_path);
	}

	printf("Test launch() (SIGCHLD)...");
	fflush(stdout);
	sprintf(buffer, "child %d", getpid());
	if( (pid = launch(LAUNCH_SLAVE_PATH, exec_path, buffer, 0, 0, update_progress, 0)) < 0 ){
		perror("failed to launch");
		return -1;
	} else {

		do {
			errno = 0;
			ret = wait(&status);
		} while( errno == EINTR );

		if( errno != 0 ){
			perror("failed to wait");
		} else {
			printf("passed\n");
		}

		unlink(exec_path);
	}

	printf("Test launch() (SIGCHLD wait)...");
	fflush(stdout);
	sprintf(buffer, "child %d", getpid());
	if( (pid = launch(LAUNCH_SLAVE_PATH, exec_path, buffer, 0, 0, update_progress, 0)) < 0 ){
		perror("failed to launch");
		return -1;
	} else {

		usleep(50*1000);

		do {
			errno = 0;
			ret = wait(&status);
		} while( errno == EINTR );

		if( errno != 0 ){
			perror("failed to wait");
		} else {
			printf("passed\n");
		}

		unlink(exec_path);
	}

	printf("Test launch() (two copies)...");
	fflush(stdout);
	if( (pid = launch(LAUNCH_SLAVE_PATH, exec_path, "1", 0, 0, update_progress, 0)) < 0 ){
		perror("failed to launch");
		return -1;
	}

	usleep(50*1000);

	if( (pid_alt = launch(LAUNCH_SLAVE_PATH, exec_path_alt, "2", 0, 0, update_progress, 0)) < 0 ){
		wait(&status);
		unlink(exec_path);
		perror("failed to launch alt");
		return -1;
	}

	//wait for both to finish
	fd = 0;
	do {
		ret = wait(&status);
		if( ret == pid ){
			fd++;
		}
		if( ret == pid_alt ){
			fd++;
		}
	} while( ret > 0 );

	if( errno != ECHILD ){
		printf("failed -- errno %d != %d\n", ECHILD, errno);
	}

	unlink(exec_path);
	unlink(exec_path_alt);

	if( fd == 2 ){
		printf("passed\n");
	} else {
		printf("failed (didn't wait for 2 processes)\n");
	}

	printf("Test launch() (EXCESS RAM)...");
	fflush(stdout);
	if( (pid = launch(LAUNCH_SLAVE_PATH, exec_path, 0, 0, 128*1024, update_progress, 0)) < 0 ){
		if( errno == ENOSPC ){
			printf("passed\n");
		} else {
			printf("failed -- errno %d != %d\n", errno, ENOSPC);
		}
	} else {
		printf("failed -- not enough RAM");
	}



	return 0;
}
void
ProcessController::MessageReceived(BMessage *message)
{
	team_id team;
	thread_id thread;
	BAlert *alert;
	char	question[1000];
	switch (message->what) {
		case 'Puls':
			Update ();
			DoDraw (false);
			break;

		case 'QtTm':
			if (message->FindInt32("team", &team) == B_OK) {
				resume_thread(spawn_thread(thread_quit_application,
					B_TRANSLATE("Quit application"), B_NORMAL_PRIORITY,
					(void*)(addr_t)team));
			}
			break;

		case 'KlTm':
			if (message->FindInt32("team", &team) == B_OK) {
				info_pack infos;
				if (get_team_info(team, &infos.team_info) == B_OK) {
					get_team_name_and_icon(infos);
					snprintf(question, sizeof(question),
					B_TRANSLATE("What do you want to do with the team \"%s\"?"),
					infos.team_name);
					alert = new BAlert(B_TRANSLATE("Please confirm"), question,
					B_TRANSLATE("Cancel"), B_TRANSLATE("Debug this team!"),
					B_TRANSLATE("Kill this team!"), B_WIDTH_AS_USUAL,
					B_STOP_ALERT);
					alert->SetShortcut(0, B_ESCAPE);
					int result = alert->Go();
					switch (result) {
						case 1:
							_HandleDebugRequest(team, -1);
							break;
						case 2:
							kill_team(team);
							break;
						default:
							break;
					}
				} else {
					alert = new BAlert(B_TRANSLATE("Info"),
						B_TRANSLATE("This team is already gone" B_UTF8_ELLIPSIS),
						B_TRANSLATE("Ok!"), NULL, NULL, B_WIDTH_AS_USUAL,
						B_STOP_ALERT);
					alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
					alert->Go();
				}
			}
			break;

		case 'KlTh':
			if (message->FindInt32("thread", &thread) == B_OK) {
				thread_info	thinfo;
				if (get_thread_info(thread, &thinfo) == B_OK) {
					#if DEBUG_THREADS
					snprintf(question, sizeof(question),
						B_TRANSLATE("What do you want to do "
						"with the thread \"%s\"?"), thinfo.name);
					alert = new BAlert(B_TRANSLATE("Please confirm"), question,
						B_TRANSLATE("Cancel"), B_TRANSLATE("Debug this thread!"),
						B_TRANSLATE("Kill this thread!"), B_WIDTH_AS_USUAL,
						B_STOP_ALERT);
					alert->SetShortcut(0, B_ESCAPE);

					#define KILL 2
					#else
					snprintf(question, sizeof(question),
						B_TRANSLATE("Are you sure you want "
						"to kill the thread \"%s\"?"), thinfo.name);
					alert = new BAlert(B_TRANSLATE("Please confirm"), question,
						B_TRANSLATE("Cancel"), B_TRANSLATE("Kill this thread!"),
						NULL, B_WIDTH_AS_USUAL,	B_STOP_ALERT);
					alert->SetShortcut(0, B_ESCAPE);

					#define KILL 1
					#endif
					alert->SetShortcut(0, B_ESCAPE);
					int r = alert->Go();
					if (r == KILL)
						kill_thread(thread);
					#if DEBUG_THREADS
					else if (r == 1)
						_HandleDebugRequest(thinfo.team, thinfo.thread);
					#endif
				} else {
					alert = new BAlert(B_TRANSLATE("Info"),
						B_TRANSLATE("This thread is already gone" B_UTF8_ELLIPSIS),
						B_TRANSLATE("Ok!"),	NULL, NULL,
						B_WIDTH_AS_USUAL, B_STOP_ALERT);
					alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
					alert->Go();
				}
			}
			break;

		case 'PrTh':
			if (message->FindInt32("thread", &thread) == B_OK) {
				int32 new_priority;
				if (message->FindInt32("priority", &new_priority) == B_OK)
					set_thread_priority(thread, new_priority);
			}
			break;

		case 'Trac':
		{
			BPath trackerPath;
			if (find_directory(B_SYSTEM_DIRECTORY, &trackerPath) == B_OK
				&& trackerPath.Append("Tracker") == B_OK) {
				launch(kTrackerSig, trackerPath.Path());
			}
			break;
		}

		case 'Dbar':
		{
			BPath deskbarPath;
			if (find_directory(B_SYSTEM_DIRECTORY, &deskbarPath) == B_OK
				&& deskbarPath.Append("Deskbar") == B_OK) {
				launch(kDeskbarSig, deskbarPath.Path());
			}
			break;
		}

		case 'Term':
		{
			BPath terminalPath;
			if (find_directory(B_SYSTEM_APPS_DIRECTORY, &terminalPath) == B_OK
				&& terminalPath.Append("Terminal") == B_OK) {
				launch(kTerminalSig, terminalPath.Path());
			}
			break;
		}

		case 'AlDb':
		{
			if (!be_roster->IsRunning(kDeskbarSig)) {
				BPath deskbarPath;
				if (find_directory(B_SYSTEM_DIRECTORY, &deskbarPath) == B_OK
					&& deskbarPath.Append("Deskbar") == B_OK) {
					launch(kDeskbarSig, deskbarPath.Path());
				}
			}
			BDeskbar deskbar;
			if (gInDeskbar || deskbar.HasItem (kDeskbarItemName))
				deskbar.RemoveItem (kDeskbarItemName);
			else
				move_to_deskbar(deskbar);
			break;
		}

		case 'CPU ':
		{
			uint32 cpu;
			if (message->FindInt32("cpu", (int32*)&cpu) == B_OK) {
				bool last = true;
				for (unsigned int p = 0; p < gCPUcount; p++) {
					if (p != cpu && _kern_cpu_enabled(p)) {
						last = false;
						break;
					}
				}
				if (last) {
					alert = new BAlert(B_TRANSLATE("Info"),
						B_TRANSLATE("This is the last active processor...\n"
						"You can't turn it off!"),
						B_TRANSLATE("That's no Fun!"), NULL, NULL,
						B_WIDTH_AS_USUAL, B_WARNING_ALERT);
					alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
					alert->Go();
				} else
					_kern_set_cpu_enabled(cpu, !_kern_cpu_enabled(cpu));
			}
			break;
		}

		case 'Schd':
		{
			int32 mode;
			if (message->FindInt32 ("mode", &mode) == B_OK)
				set_scheduler_mode(mode);
			break;
		}

		case B_ABOUT_REQUESTED:
			AboutRequested();
			break;

		default:
			BView::MessageReceived(message);
	}
}
Exemple #13
0
int main (void)
{
    L4_Word_t total;

    printf("\n\nHasenpfeffer operating system\n");
    printf("Copyright (C) 2005,2006. Senko Rasic <*****@*****.**>\n\n");


    printf("Initializing root task...\n");
    L4_KernelInterfacePage_t *kip = (L4_KernelInterfacePage_t *) L4_GetKernelInterface();
    void *bi = (void *) L4_BootInfo(kip);
    
    // we need to preload these I/O pages
    // ATA
    L4_Sigma0_GetPage(L4_nilthread, L4_Fpage(0x0000, 4096));

    // KIP
    L4_Sigma0_GetPage(L4_nilthread, L4_Fpage(L4_BootInfo(kip), 4096));
    L4_BootRec_t *br = NULL;

    if (L4_BootInfo_Valid((void *) bi)) {
        int n = L4_BootInfo_Entries(bi);
        br = L4_BootInfo_FirstEntry(bi);
        while (--n) {
            /* touch roottask data from here, because sigma0 only gives pages to initial *thread* */
            if (L4_BootRec_Type(br) == L4_BootInfo_SimpleExec) {
                L4_Word_t mi;
                for (mi = 0; mi < L4_Module_Size(br); mi += 4096) {
                    L4_Sigma0_GetPage(L4_nilthread, L4_Fpage(L4_Module_Start(br) + mi, 4096));
                }
            }
            br = L4_BootRec_Next(br);
        }
    } else {
        printf("panic: invalid bootinfo data\n");
        return 0;
    }

    memory_init();
    total = memory_get_free();

    printf("Creating root memory manager...\n");
    mman_tid = create_local_thread("root memory manager", kip, 1, memman, 4096);
    thread_init(mman_tid);

    printf("Initializing root task manager...\n");
    HpfCapability full, newthread, newtask;
    task_manager_init(&full, &newtask, &newthread);

    dir_paths[0] = "/process/TaskManager";
    dir_caps[0] = full;
    n_paths = 1;

    printf("Loading initial programs...\n");
    int n = L4_BootInfo_Entries(bi);
    br = L4_BootInfo_FirstEntry(bi);
    int first_program = 1;
    while (--n) {
        if (L4_BootRec_Type(br) == L4_BootInfo_Module) {
            L4_ThreadId_t tid = launch(br);
            if (first_program) {
                first_program = 0;

                // this is the root directory server
                if (hermes_capability(tid, &(dir_caps[1]))) {
                    // dir_paths[1] = "/process/DirectoryService";
                    dir_paths[1] = ""; // <- catch-all
                    n_paths = 2;
                }
            }
        }
        br = L4_BootRec_Next(br);
    }

    printf("Init done, running...\n\n");
    task_manager_main();

    return 0;
}
void q_task_create(char* name, uint32_t priority, uint32_t stack_size, void * entry, void * arg)
{
    qprintf("*** task_create('%s', %d, %x, %x, %x)\n", name, priority, stack_size, entry, arg);
    launch(entry);
}
Exemple #15
0
/**
   Main function. Parses options and calls helper function for any heavy lifting.
*/
int main (int argc, char *argv[])
{	
	int input_type=FILEDATA;
	int output_type=MIMETYPE;
	
	const char *mimetype;
	char *output=0;
	
	int i;

    typedef std::map<std::string, string_list_t> launch_hash_t;
    launch_hash_t launch_hash;

	locale_init();
	
	/*
	  Parse options
	*/
	while( 1 )
	{
		static struct option
			long_options[] =
			{
				{
					"input-file-data", no_argument, 0, 't' 
				}
				,
				{
					"input-filename", no_argument, 0, 'f' 
				}
				,
				{
					"input-mime", no_argument, 0, 'i' 
				}
				,
				{
					"output-mime", no_argument, 0, 'm' 
				}
				,
				{
					"output-description", no_argument, 0, 'd' 
				}
				,
				{
					"output-action", no_argument, 0, 'a' 
				}
				,
				{
					"help", no_argument, 0, 'h' 
				}
				,
				{
					"version", no_argument, 0, 'v' 
				}
				,
				{
					"launch", no_argument, 0, 'l'
				}
				,
				{ 
					0, 0, 0, 0 
				}
			}
		;
		
		int opt_index = 0;
		
		int opt = getopt_long( argc,
							   argv, 
							   GETOPT_STRING,
							   long_options, 
							   &opt_index );
		
		if( opt == -1 )
			break;
		
		switch( opt )
		{
			case 0:
				break;				

			case 't':		
				input_type=FILEDATA;
				break;

			case 'f':		
				input_type=FILENAME;
				break;

			case 'i':		
				input_type=MIMETYPE;
				break;

			case 'm':		
				output_type=MIMETYPE;
				break;

			case 'd':		
				output_type=DESCRIPTION;
				break;

			case 'a':		
				output_type=ACTION;
				break;

			case 'l':		
				output_type=LAUNCH;
				break;

			case 'h':
				print_help( argv[0], 1 );
				exit(0);				
								
			case 'v':
				printf( _("%s, version %s\n"), MIMEDB, PACKAGE_VERSION );
				exit( 0 );				
				
			case '?':
				return 1;
				
		}		
	}

	if( ( output_type == LAUNCH )&&(input_type==MIMETYPE))
	{
		fprintf( stderr, _("%s: Can not launch a mimetype\n"), MIMEDB );
		print_help( argv[0], 2 );
		exit(1);
	}	
	
	/* 
	   Loop over all non option arguments and do the specified lookup
	*/
	
	//fprintf( stderr, "Input %d, output %d\n", input_type, output_type );	

	for (i = optind; (i < argc)&&(!error); i++)
    {
		/* Convert from filename to mimetype, if needed */
		if( input_type == FILENAME )
		{
			mimetype = xdg_mime_get_mime_type_from_file_name(argv[i]);
		}
		else if( input_type == FILEDATA )
		{
			mimetype = xdg_mime_get_mime_type_for_file(argv[i]);
		}
		else
			mimetype = xdg_mime_is_valid_mime_type(argv[i])?argv[i]:0;

		mimetype = xdg_mime_unalias_mime_type (mimetype);
		if( !mimetype )
		{
			fprintf( stderr, _( "%s: Could not parse mimetype from argument '%s'\n"), MIMEDB, argv[i] );
			error=1;
			return 1;
		}
		
		/*
		  Convert from mimetype to whatever, if needed
		*/
		switch( output_type )
		{
			case MIMETYPE:
			{
				output = (char *)mimetype;
				break;
				
			}
			case DESCRIPTION:
			{
				output = get_description( mimetype );				
				if( !output )
					output = strdup( _("Unknown") );
				
				break;
			}
			case ACTION:
			{
				output = get_action( mimetype );
				break;
			}			
			case LAUNCH:
			{
				/*
				  There may be more files using the same launcher, we
				  add them all up in little array_list_ts and launched
				  them together after all the arguments have been
				  parsed.
				*/
				output = 0;
                string_list_t &l = launch_hash[mimetype];
                l.push_back(argv[i]);
			}
		}
		
		/*
		  Print the glorious result
		*/
		if( output )
		{
			printf( "%s\n", output );
			if( output != mimetype )
				free( output );
		}
		output = 0;
    }

	/*
	  Perform the actual launching
	*/
	if( output_type == LAUNCH && !error )
	{
		for( launch_hash_t::iterator iter = launch_hash.begin(); iter != launch_hash.end(); ++iter)
		{
			const char *mimetype = iter->first.c_str();
			string_list_t &files = iter->second;
			
			char *launcher = get_action( mimetype );

			if( launcher )
			{
				launch( launcher, files, 0 );
				free( launcher );
			}
		}
	}
	
	if( launch_buff )
		free( launch_buff );

	if( start_re )
	{
		regfree( start_re );
		regfree( stop_re );
		free( start_re );
		free( stop_re );
	}	

	xdg_mime_shutdown();
	
	return error;	
}
Exemple #16
0
QLayout *ZDLInterface::getButtonPane(){
	QHBoxLayout *box = new QHBoxLayout();

	QPushButton *btnExit = new QPushButton("Exit", this);
	btnZDL = new QPushButton("ZDL", this);
	QPushButton *btnMSet = new QPushButton("Multi Settings", this);
	btnEpr = new QPushButton(this);
	QPushButton *btnLaunch = new QPushButton("Launch", this);

	QMenu *context = new QMenu(btnZDL);
	QMenu *actions = new QMenu("Actions",context);

	QAction *showCommandline = actions->addAction("Show Command Line");
	QAction *clearAllPWadsAction = actions->addAction("Clear PWAD list");
	QAction *clearAllFieldsAction = actions->addAction("Clear all fields");
	clearAllFieldsAction->setShortcut(QKeySequence::New);
	QAction *clearEverythingAction = actions->addAction("Clear everything");
	actions->addSeparator();
#if !defined(NO_IMPORT)
	QAction *actImportCurrentConfig = actions->addAction("Import current config");
#endif
	QAction *clearCurrentGlobalConfig = actions->addAction("Clear current global config");
	clearCurrentGlobalConfig->setEnabled(false);	

	//QAction *newDMFlagger = actions->addAction("New DMFlag picker");

	context->addMenu(actions);
	context->addSeparator();
	QAction *loadZdlFileAction = context->addAction("Load .zdl");
	loadZdlFileAction->setShortcut(QKeySequence::Open);
	QAction *saveZdlFileAction = context->addAction("Save .zdl");
	saveZdlFileAction->setShortcut(QKeySequence::Save);
	context->addSeparator();
	QAction *loadAction = context->addAction("Load .ini");
	QAction *saveAction = context->addAction("Save .ini");
	context->addSeparator();
	QAction *aboutAction = context->addAction("About");
	aboutAction->setShortcut(QKeySequence::HelpContents);

	connect(loadAction, SIGNAL(triggered()), this, SLOT(loadConfigFile()));
	connect(saveAction, SIGNAL(triggered()), this, SLOT(saveConfigFile()));
	connect(loadZdlFileAction, SIGNAL(triggered()), this, SLOT(loadZdlFile()));
	connect(saveZdlFileAction, SIGNAL(triggered()), this, SLOT(saveZdlFile()));
	connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClick()));
#if !defined(NO_IMPORT)
	connect(actImportCurrentConfig, SIGNAL(triggered()), this, SLOT(importCurrentConfig()));
#endif

	connect(clearAllPWadsAction, SIGNAL(triggered()), this, SLOT(clearAllPWads()));
	connect(clearAllFieldsAction, SIGNAL(triggered()), this, SLOT(clearAllFields()));
	connect(clearEverythingAction, SIGNAL(triggered()), this, SLOT(clearEverything()));

	connect(showCommandline, SIGNAL(triggered()),this,SLOT(showCommandline()));
	//connect(newDMFlagger, SIGNAL(triggered()),this,SLOT(showNewDMFlagger()));
	connect(btnExit, SIGNAL(clicked()), this, SLOT(exitzdl()));

	btnZDL->setMenu(context);

	int minBtnWidth = 50;

	btnExit->setMinimumWidth(minBtnWidth-15);
	btnZDL->setMinimumWidth(minBtnWidth-15);
	btnMSet->setMinimumWidth(minBtnWidth+30);
	btnEpr->setMinimumWidth(20);
	btnLaunch->setMinimumWidth(minBtnWidth);

	connect(btnLaunch, SIGNAL( clicked() ), this, SLOT(launch()));

	setContentsMargins(0,0,0,0);
	layout()->setContentsMargins(0,0,0,0);
	box->setSpacing(2);
	box->addWidget(btnExit);
	box->addWidget(btnZDL);
	box->addWidget(btnMSet);
	box->addWidget(btnEpr);
	box->addWidget(btnLaunch);
	box->setSpacing(1);
	connect(btnEpr, SIGNAL(clicked()), this, SLOT(mclick()));

	connect(btnMSet, SIGNAL(clicked()), this, SLOT(ampclick()));
	return box;
}
Exemple #17
0
void ThreadManager::launchApp(quint32 appid)
{
	emit launch(appid);
}
void MapleManager::reLaunchMaple()
{
    m_launch_status = LaunchStatus::RELAUNCHIGN;
    launch();
}
Exemple #19
0
static unsigned long
pyro_draw (Display *dpy, Window window, void *closure)
{
    struct state *st = (struct state *) closure;
    XWindowAttributes xgwa;
    int g = 100;
    int resort = 0;
    int i;

    for (i = 0; i < st->how_many; i++)
    {
        struct projectile *p = st->sorted_projectiles [i];
        int old_x, old_y, old_size;
        int size, x, y;
        if (p->dead) continue;
        old_x = p->x >> 10;
        old_y = p->y >> 10;
        old_size = p->size >> 10;
        size = (p->size += p->decay) >> 10;
        x = (p->x += p->dx) >> 10;
        y = (p->y += p->dy) >> 10;
        p->dy += (p->size >> 6);
        if (p->primary) p->fuse--;

        /* erase old one */
        if (old_size > 0)
        {
            if (old_size == 1)
                XDrawPoint (st->dpy, st->window, st->erase_gc, old_x, old_y);
            else
                XFillRectangle (st->dpy, st->window, st->erase_gc, old_x, old_y,
                                old_size, old_size);
        }

        if ((p->primary ? (p->fuse > 0) : (p->size > 0)) &&
                x < st->real_draw_xlim &&
                y < st->real_draw_ylim &&
                x > 0 &&
                y > 0)
        {
            if (size > 0)
            {
                unsigned long pixel;

                if (mono_p || p->primary)
                    pixel = st->default_fg_pixel;
                else
                    pixel = p->color.pixel;

                if (pixel != st->last_pixel)
                {
                    st->last_pixel = pixel;
                    XSetForeground (st->dpy, st->draw_gc, pixel);
                }

                if (size == 1)
                    XDrawPoint (st->dpy, st->window, st->draw_gc, x, y);
                else if (size < 4)
                    XFillRectangle (st->dpy, st->window, st->draw_gc, x, y, size, size);
                else
                    XFillArc (st->dpy, st->window, st->draw_gc, x, y, size, size, 0, 360*64);
            }
        }
        else
        {
            free_projectile (st, p);
            if (! mono_p)
                if (p->color.pixel != WhitePixel (st->dpy, DefaultScreen (st->dpy)))
                    XFreeColors (st->dpy, st->cmap, &p->color.pixel, 1, 0);
        }

        if (p->primary && p->fuse <= 0)
        {
            int j = (random () % st->scatter) + (st->scatter/2);
            while (j--)
                shrapnel (st, p);
            resort = 1;
        }
    }

    if ((random () % st->frequency) == 0)
    {
        XGetWindowAttributes (st->dpy, st->window, &xgwa);
        st->real_draw_xlim = xgwa.width;
        st->real_draw_ylim = xgwa.height;
        st->draw_xlim = st->real_draw_xlim * 1000;
        st->draw_ylim = st->real_draw_ylim * 1000;
        launch (st, st->draw_xlim, st->draw_ylim, g);
        resort = 1;
    }

    /* being sorted lets us avoid changing the GC's foreground color as often. */
    if (resort)
        sort_by_pixel (st, st->how_many);

    return st->delay;
}
void fiber_group::launch(const boost::function<void (void)> &spawn_function) {
  launch(spawn_function, affinity);
}
void  b3GpuGridBroadphase::calculateOverlappingPairs(int maxPairs)
{
	B3_PROFILE("b3GpuGridBroadphase::calculateOverlappingPairs");
	

	if (0)
	{
		calculateOverlappingPairsHost(maxPairs);
	/*
		b3AlignedObjectArray<b3Int4> cpuPairs;
		m_gpuPairs.copyToHost(cpuPairs);
		printf("host m_gpuPairs.size()=%d\n",m_gpuPairs.size());
		for (int i=0;i<m_gpuPairs.size();i++)
		{
			printf("host pair %d = %d,%d\n",i,cpuPairs[i].x,cpuPairs[i].y);
		}
		*/
		return;
	}
	
	


	
	int numSmallAabbs = m_smallAabbsMappingGPU.size();

	b3OpenCLArray<int> pairCount(m_context,m_queue);
	pairCount.push_back(0);
	m_gpuPairs.resize(maxPairs);//numSmallAabbs*maxPairsPerBody);

	{
		int numLargeAabbs = m_largeAabbsMappingGPU.size();
		if (numLargeAabbs && numSmallAabbs)
		{
			B3_PROFILE("sap2Kernel");
			b3BufferInfoCL bInfo[] = { 
				b3BufferInfoCL( m_allAabbsGPU1.getBufferCL() ),
				b3BufferInfoCL( m_largeAabbsMappingGPU.getBufferCL() ),
				b3BufferInfoCL( m_smallAabbsMappingGPU.getBufferCL() ), 
				b3BufferInfoCL( m_gpuPairs.getBufferCL() ), 
				b3BufferInfoCL(pairCount.getBufferCL())};
			b3LauncherCL launcher(m_queue, m_sap2Kernel,"m_sap2Kernel");
			launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(b3BufferInfoCL) );
			launcher.setConst(   numLargeAabbs  );
			launcher.setConst( numSmallAabbs);
			launcher.setConst( 0  );//axis is not used
			launcher.setConst( maxPairs  );
	//@todo: use actual maximum work item sizes of the device instead of hardcoded values
			launcher.launch2D( numLargeAabbs, numSmallAabbs,4,64);
                
			int numPairs = pairCount.at(0);
			
			if (numPairs >maxPairs)
			{
				b3Error("Error running out of pairs: numPairs = %d, maxPairs = %d.\n", numPairs, maxPairs);
				numPairs =maxPairs;
			}
		}
	}




	if (numSmallAabbs)
	{
		B3_PROFILE("gridKernel");
		m_hashGpu.resize(numSmallAabbs);
		{
			B3_PROFILE("kCalcHashAABB");
			b3LauncherCL launch(m_queue,kCalcHashAABB,"kCalcHashAABB");
			launch.setConst(numSmallAabbs);
			launch.setBuffer(m_allAabbsGPU1.getBufferCL());
			launch.setBuffer(m_smallAabbsMappingGPU.getBufferCL());
			launch.setBuffer(m_hashGpu.getBufferCL());
			launch.setBuffer(this->m_paramsGPU.getBufferCL());
			launch.launch1D(numSmallAabbs);
		}

		m_sorter->execute(m_hashGpu);
		
		int numCells = this->m_paramsCPU.m_gridSize[0]*this->m_paramsCPU.m_gridSize[1]*this->m_paramsCPU.m_gridSize[2];
		m_cellStartGpu.resize(numCells);
		//b3AlignedObjectArray<int >			cellStartCpu;
				
		
		{
			B3_PROFILE("kClearCellStart");
			b3LauncherCL launch(m_queue,kClearCellStart,"kClearCellStart");
			launch.setConst(numCells);
			launch.setBuffer(m_cellStartGpu.getBufferCL());
			launch.launch1D(numCells);
			//m_cellStartGpu.copyToHost(cellStartCpu);
			//printf("??\n");

		}


		{
			B3_PROFILE("kFindCellStart");
			b3LauncherCL launch(m_queue,kFindCellStart,"kFindCellStart");
			launch.setConst(numSmallAabbs);
			launch.setBuffer(m_hashGpu.getBufferCL());
			launch.setBuffer(m_cellStartGpu.getBufferCL());
			launch.launch1D(numSmallAabbs);
			//m_cellStartGpu.copyToHost(cellStartCpu);
			//printf("??\n");

		}
		
		{
			B3_PROFILE("kFindOverlappingPairs");
			
			
			b3LauncherCL launch(m_queue,kFindOverlappingPairs,"kFindOverlappingPairs");
			launch.setConst(numSmallAabbs);
			launch.setBuffer(m_allAabbsGPU1.getBufferCL());
			launch.setBuffer(m_smallAabbsMappingGPU.getBufferCL());
			launch.setBuffer(m_hashGpu.getBufferCL());
			launch.setBuffer(m_cellStartGpu.getBufferCL());
			
			launch.setBuffer(m_paramsGPU.getBufferCL());
			//launch.setBuffer(0);
			launch.setBuffer(pairCount.getBufferCL());
			launch.setBuffer(m_gpuPairs.getBufferCL());
			
			launch.setConst(maxPairs);
			launch.launch1D(numSmallAabbs);
			

			int numPairs = pairCount.at(0);
			if (numPairs >maxPairs)
			{
				b3Error("Error running out of pairs: numPairs = %d, maxPairs = %d.\n", numPairs, maxPairs);
				numPairs =maxPairs;
			}
			
			m_gpuPairs.resize(numPairs);
	
			if (0)
			{
				b3AlignedObjectArray<b3Int4> pairsCpu;
				m_gpuPairs.copyToHost(pairsCpu);
			
				printf("m_gpuPairs.size()=%d\n",m_gpuPairs.size());
				for (int i=0;i<m_gpuPairs.size();i++)
				{
					printf("pair %d = %d,%d\n",i,pairsCpu[i].x,pairsCpu[i].y);
				}

				printf("?!?\n");
			}
			
		}
	

	}

	



	//calculateOverlappingPairsHost(maxPairs);
}
Exemple #22
0
void Launcher::was_triggered() {
    if ( trigger.triggered() ) {
        trigger.untrigger();
        launch();
    }
}
Exemple #23
0
/**
   Main function. Parses options and calls helper function for any heavy lifting.
*/
int main (int argc, char *argv[])
{
    int input_type=FILEDATA;
    int output_type=MIMETYPE;

    const char *mimetype;
    char *output=0;

    int i;

    hash_table_t launch_hash;

    locale_init();

    /*
      Parse options
    */
    while( 1 )
    {
        static struct option
            long_options[] =
        {
            {
                "input-file-data", no_argument, 0, 't'
            }
            ,
            {
                "input-filename", no_argument, 0, 'f'
            }
            ,
            {
                "input-mime", no_argument, 0, 'i'
            }
            ,
            {
                "output-mime", no_argument, 0, 'm'
            }
            ,
            {
                "output-description", no_argument, 0, 'd'
            }
            ,
            {
                "output-action", no_argument, 0, 'a'
            }
            ,
            {
                "help", no_argument, 0, 'h'
            }
            ,
            {
                "version", no_argument, 0, 'v'
            }
            ,
            {
                "launch", no_argument, 0, 'l'
            }
            ,
            {
                0, 0, 0, 0
            }
        }
        ;

        int opt_index = 0;

        int opt = getopt_long( argc,
                               argv,
                               GETOPT_STRING,
                               long_options,
                               &opt_index );

        if( opt == -1 )
            break;

        switch( opt )
        {
        case 0:
            break;

        case 't':
            input_type=FILEDATA;
            break;

        case 'f':
            input_type=FILENAME;
            break;

        case 'i':
            input_type=MIMETYPE;
            break;

        case 'm':
            output_type=MIMETYPE;
            break;

        case 'd':
            output_type=DESCRIPTION;
            break;

        case 'a':
            output_type=ACTION;
            break;

        case 'l':
            output_type=LAUNCH;
            break;

        case 'h':
            print_help( argv[0], 1 );
            exit(0);

        case 'v':
            printf( _("%s, version %s\n"), MIMEDB, PACKAGE_VERSION );
            exit( 0 );

        case '?':
            return 1;

        }
    }

    if( ( output_type == LAUNCH )&&(input_type==MIMETYPE))
    {
        fprintf( stderr, _("%s: Can not launch a mimetype\n"), MIMEDB );
        print_help( argv[0], 2 );
        exit(1);
    }

    if( output_type == LAUNCH )
        hash_init( &launch_hash, &hash_str_func, &hash_str_cmp );


    /*
       Loop over all non option arguments and do the specified lookup
    */

    //fprintf( stderr, "Input %d, output %d\n", input_type, output_type );

    for (i = optind; (i < argc)&&(!error); i++)
    {
        /* Convert from filename to mimetype, if needed */
        if( input_type == FILENAME )
        {
            mimetype = xdg_mime_get_mime_type_from_file_name(argv[i]);
        }
        else if( input_type == FILEDATA )
        {
            mimetype = xdg_mime_get_mime_type_for_file(argv[i]);
        }
        else
            mimetype = xdg_mime_is_valid_mime_type(argv[i])?argv[i]:0;

        mimetype = xdg_mime_unalias_mime_type (mimetype);
        if( !mimetype )
        {
            fprintf( stderr, _( "%s: Could not parse mimetype from argument '%s'\n"), MIMEDB, argv[i] );
            error=1;
            return 1;
        }

        /*
          Convert from mimetype to whatever, if needed
        */
        switch( output_type )
        {
        case MIMETYPE:
        {
            output = (char *)mimetype;
            break;

        }
        case DESCRIPTION:
        {
            output = get_description( mimetype );
            if( !output )
                output = strdup( _("Unknown") );

            break;
        }
        case ACTION:
        {
            output = get_action( mimetype );
            break;
        }
        case LAUNCH:
        {
            /*
              There may be more files using the same launcher, we
              add them all up in little array_list_ts and launched
              them together after all the arguments have been
              parsed.
            */
            array_list_t *l= (array_list_t *)hash_get( &launch_hash, mimetype );
            output = 0;

            if( !l )
            {
                l = my_malloc( sizeof( array_list_t ) );
                if( l == 0 )
                {
                    break;
                }
                al_init( l );
                hash_put( &launch_hash, mimetype, l );
            }
            al_push( l, argv[i] );
        }
        }

        /*
          Print the glorious result
        */
        if( output )
        {
            printf( "%s\n", output );
            if( output != mimetype )
                free( output );
        }
        output = 0;
    }

    /*
      Perform the actual launching
    */
    if( output_type == LAUNCH && !error )
    {
        int i;
        array_list_t mimes;
        al_init( &mimes );
        hash_get_keys( &launch_hash, &mimes );
        for( i=0; i<al_get_count( &mimes ); i++ )
        {
            char *mimetype = (char *)al_get( &mimes, i );
            array_list_t *files = (array_list_t *)hash_get( &launch_hash, mimetype );
            if( !files )
            {
                fprintf( stderr, _( "%s: Unknown error\n"), MIMEDB );
                error=1;
                break;
            }

            char *launcher = get_action( mimetype );

            if( launcher )
            {
                launch( launcher, files, 0 );
                free( launcher );
            }
        }
        hash_foreach( &launch_hash, &clear_entry );
        hash_destroy( &launch_hash );
        al_destroy( &mimes );
    }

    if( launch_buff )
        free( launch_buff );

    if( start_re )
    {
        regfree( start_re );
        regfree( stop_re );
        free( start_re );
        free( stop_re );
    }

    xdg_mime_shutdown();

    return error;
}
Exemple #24
0
cypher()
{
    register int n;
    int junk;
    int lflag = -1;
    char buffer[10];

    while (wordtype[wordnumber] == ADJS)
        wordnumber++;
    while (wordnumber <= wordcount) {
        switch(wordvalue[wordnumber]) {

        case UP:
            if (location[position].access || wiz || tempwiz) {
                if (!location[position].access)
                    puts("Zap!  A gust of wind lifts you up.");
                if (!move(location[position].up, AHEAD))
                    return(-1);
            } else {
                puts("There is no way up");
                return(-1);
            }
            lflag = 0;
            break;

        case DOWN:
            if (!move(location[position].down, AHEAD))
                return(-1);
            lflag = 0;
            break;

        case LEFT:
            if (!move(left, LEFT))
                return(-1);
            lflag = 0;
            break;

        case RIGHT:
            if (!move(right, RIGHT))
                return(-1);
            lflag = 0;
            break;

        case AHEAD:
            if (!move(ahead, AHEAD))
                return(-1);
            lflag = 0;
            break;

        case BACK:
            if (!move(back, BACK))
                return(-1);
            lflag = 0;
            break;

        case SHOOT:
            if (wordnumber < wordcount && wordvalue[wordnumber+1] == EVERYTHING) {
                for (n=0; n < NUMOFOBJECTS; n++)
                    if (testbit(location[position].objects,n) && *objsht[n]) {
                        wordvalue[wordnumber+1] = n;
                        wordnumber = shoot();
                    }
                wordnumber++;
                wordnumber++;
            }
            else
                shoot();
            break;

        case TAKE:
            if (wordnumber < wordcount && wordvalue[wordnumber+1] == EVERYTHING) {
                for (n=0; n < NUMOFOBJECTS; n++)
                    if (testbit(location[position].objects,n) && *objsht[n]) {
                        wordvalue[wordnumber+1] = n;
                        wordnumber = take(location[position].objects);
                    }
                wordnumber++;
                wordnumber++;
            }
            else
                take(location[position].objects);
            break;

        case DROP:

            if (wordnumber < wordcount && wordvalue[wordnumber+1] == EVERYTHING) {
                for (n=0; n < NUMOFOBJECTS; n++)
                    if (testbit(inven,n)) {
                        wordvalue[wordnumber+1] = n;
                        wordnumber = drop("Dropped");
                    }
                wordnumber++;
                wordnumber++;
            }
            else
                drop("Dropped");
            break;


        case KICK:
        case THROW:
            if (wordnumber < wordcount && wordvalue[wordnumber+1] == EVERYTHING) {
                for (n=0; n < NUMOFOBJECTS; n++)
                    if (testbit(inven,n) ||
                            testbit(location[position].objects, n) && *objsht[n]) {
                        wordvalue[wordnumber+1] = n;
                        wordnumber = throw(wordvalue[wordnumber] == KICK ? "Kicked" : "Thrown");
                    }
                wordnumber += 2;
            } else
                throw(wordvalue[wordnumber] == KICK ? "Kicked" : "Thrown");
            break;

        case TAKEOFF:
            if (wordnumber < wordcount && wordvalue[wordnumber+1] == EVERYTHING) {
                for (n=0; n < NUMOFOBJECTS; n++)
                    if (testbit(wear,n)) {
                        wordvalue[wordnumber+1] = n;
                        wordnumber = takeoff();
                    }
                wordnumber += 2;
            }
            else
                takeoff();
            break;


        case DRAW:

            if (wordnumber < wordcount && wordvalue[wordnumber+1] == EVERYTHING) {
                for (n=0; n < NUMOFOBJECTS; n++)
                    if (testbit(wear,n)) {
                        wordvalue[wordnumber+1] = n;
                        wordnumber = draw();
                    }
                wordnumber += 2;
            }
            else
                draw();
            break;


        case PUTON:

            if (wordnumber < wordcount && wordvalue[wordnumber+1] == EVERYTHING) {
                for (n=0; n < NUMOFOBJECTS; n++)
                    if (testbit(location[position].objects,n) && *objsht[n]) {
                        wordvalue[wordnumber+1] = n;
                        wordnumber = puton();
                    }
                wordnumber += 2;
            }
            else
                puton();
            break;

        case WEARIT:

            if (wordnumber < wordcount && wordvalue[wordnumber+1] == EVERYTHING) {
                for (n=0; n < NUMOFOBJECTS; n++)
                    if (testbit(inven,n)) {
                        wordvalue[wordnumber+1] = n;
                        wordnumber = wearit();
                    }
                wordnumber += 2;
            }
            else
                wearit();
            break;


        case EAT:

            if (wordnumber < wordcount && wordvalue[wordnumber+1] == EVERYTHING) {
                for (n=0; n < NUMOFOBJECTS; n++)
                    if (testbit(inven,n)) {
                        wordvalue[wordnumber+1] = n;
                        wordnumber = eat();
                    }
                wordnumber += 2;
            }
            else
                eat();
            break;


        case PUT:
            put();
            break;


        case INVEN:
            if (ucard(inven)) {
                puts("You are holding:\n");
                for (n=0; n < NUMOFOBJECTS; n++)
                    if (testbit(inven,n))
                        printf("\t%s\n", objsht[n]);
                printf("\n= %d kilogram%s (%d%%)\n", carrying, (carrying == 1 ? "." : "s."),(WEIGHT ? carrying*100/WEIGHT : -1));
                printf("Your arms are %d%% full.\n",encumber*100/CUMBER);
            }
            else
                puts("You aren't carrying anything.");

            if (ucard(wear)) {
                puts("\nYou are wearing:\n");
                for (n=0; n < NUMOFOBJECTS; n++)
                    if (testbit(wear,n))
                        printf("\t%s\n", objsht[n]);
            }
            else
                puts("\nYou are stark naked.");
            if (card(injuries,NUMOFINJURIES)) {
                puts("\nYou have suffered:\n");
                for (n=0; n < NUMOFINJURIES; n++)
                    if (injuries[n])
                        printf("\t%s\n",ouch[n]);
                printf("\nYou can still carry up to %d kilogram%s\n",WEIGHT,(WEIGHT == 1 ? "." : "s."));
            }
            else
                puts("\nYou are in perfect health.");
            break;

        case USE:
            lflag = use();
            break;

        case LOOK:
            if (!notes[CANTSEE] || testbit(inven,LAMPON) || testbit(location[position].objects,LAMPON) || matchlight) {
                beenthere[position] = 2;
                writedes();
                printobjs();
                if (matchlight) {
                    puts("\nYour match splutters out.");
                    matchlight = 0;
                }
            } else
                puts("I can't see anything.");
            return(-1);
            break;

        case SU:
            if (wiz || tempwiz) {
                printf("\nRoom (was %d) = ", position);
                fgets(buffer,10,stdin);
                if (*buffer != '\n')
                    sscanf(buffer,"%d", &position);
                printf("Time (was %d) = ",time);
                fgets(buffer,10,stdin);
                if (*buffer != '\n')
                    sscanf(buffer,"%d", &time);
                printf("Fuel (was %d) = ",fuel);
                fgets(buffer,10,stdin);
                if (*buffer != '\n')
                    sscanf(buffer,"%d", &fuel);
                printf("Torps (was %d) = ",torps);
                fgets(buffer,10,stdin);
                if (*buffer != '\n')
                    sscanf(buffer,"%d", &torps);
                printf("CUMBER (was %d) = ",CUMBER);
                fgets(buffer,10,stdin);
                if (*buffer != '\n')
                    sscanf(buffer,"%d", &CUMBER);
                printf("WEIGHT (was %d) = ",WEIGHT);
                fgets(buffer,10,stdin);
                if (*buffer != '\n')
                    sscanf(buffer,"%d",&WEIGHT);
                printf("Clock (was %d) = ",clock);
                fgets(buffer,10,stdin);
                if (*buffer != '\n')
                    sscanf(buffer,"%d",&clock);
                printf("Wizard (was %d, %d) = ",wiz, tempwiz);
                fgets(buffer,10,stdin);
                if (*buffer != '\n') {
                    sscanf(buffer,"%d",&junk);
                    if (!junk)
                        tempwiz = wiz = 0;
                }
                printf("\nDONE.\n");
                return(0);
            }
            else
                puts("You aren't a wizard.");
            break;

        case SCORE:
            printf("\tPLEASURE\tPOWER\t\tEGO\n");
            printf("\t%3d\t\t%3d\t\t%3d\n\n",pleasure,power,ego);
            printf("This gives you the rating of %s in %d turns.\n",rate(),time);
            printf("You have visited %d out of %d rooms this run (%d%%).\n",card(beenthere,NUMOFROOMS),NUMOFROOMS,card(beenthere,NUMOFROOMS)*100/NUMOFROOMS);
            break;

        case KNIFE:
        case KILL:
            murder();
            break;

        case UNDRESS:
        case RAVAGE:
            ravage();
            break;

        case SAVE:
            save();
            break;

        case FOLLOW:
            lflag = follow();
            break;

        case GIVE:
            give();
            break;

        case KISS:
            kiss();
            break;

        case LOVE:
            love();
            break;

        case RIDE:
            lflag = ride();
            break;

        case DRIVE:
            lflag = drive();
            break;

        case LIGHT:
            light();
            break;

        case LAUNCH:
            if (!launch())
                return(-1);
            else
                lflag = 0;
            break;

        case LANDIT:
            if (!land())
                return(-1);
            else
                lflag = 0;
            break;

        case TIME:
            chime();
            break;

        case SLEEP:
            zzz();
            break;

        case DIG:
            dig();
            break;

        case JUMP:
            lflag = jump();
            break;

        case BURY:
            bury();
            break;

        case SWIM:
            puts("Surf's up!");
            break;

        case DRINK:
            drink();
            break;

        case QUIT:
            die();

        default:
            puts("How's that?");
            return(-1);
            break;


        }
        if (wordnumber < wordcount && *words[wordnumber++] == ',')
            continue;
        else return(lflag);
    }
    return(lflag);
}
void  b3GpuJacobiContactSolver::solveGroupMixed(b3OpenCLArray<b3RigidBodyData>* bodiesGPU,b3OpenCLArray<b3InertiaData>* inertiasGPU,b3OpenCLArray<b3Contact4>* manifoldPtrGPU,const btJacobiSolverInfo& solverInfo)
{

	b3AlignedObjectArray<b3RigidBodyData> bodiesCPU;
	bodiesGPU->copyToHost(bodiesCPU);
	b3AlignedObjectArray<b3InertiaData> inertiasCPU;
	inertiasGPU->copyToHost(inertiasCPU);
	b3AlignedObjectArray<b3Contact4> manifoldPtrCPU;
	manifoldPtrGPU->copyToHost(manifoldPtrCPU);
	
	int numBodiesCPU = bodiesGPU->size();
	int numManifoldsCPU = manifoldPtrGPU->size();
	B3_PROFILE("b3GpuJacobiContactSolver::solveGroupMixed");

	b3AlignedObjectArray<unsigned int> bodyCount;
	bodyCount.resize(numBodiesCPU);
	for (int i=0;i<numBodiesCPU;i++)
		bodyCount[i] = 0;

	b3AlignedObjectArray<b3Int2> contactConstraintOffsets;
	contactConstraintOffsets.resize(numManifoldsCPU);


	for (int i=0;i<numManifoldsCPU;i++)
	{
		int pa = manifoldPtrCPU[i].m_bodyAPtrAndSignBit;
		int pb = manifoldPtrCPU[i].m_bodyBPtrAndSignBit;

		bool isFixedA = (pa <0) || (pa == solverInfo.m_fixedBodyIndex);
		bool isFixedB = (pb <0) || (pb == solverInfo.m_fixedBodyIndex);

		int bodyIndexA = manifoldPtrCPU[i].getBodyA();
		int bodyIndexB = manifoldPtrCPU[i].getBodyB();

		if (!isFixedA)
		{
			contactConstraintOffsets[i].x = bodyCount[bodyIndexA];
			bodyCount[bodyIndexA]++;
		}
		if (!isFixedB)
		{
			contactConstraintOffsets[i].y = bodyCount[bodyIndexB];
			bodyCount[bodyIndexB]++;
		} 
	}

	b3AlignedObjectArray<unsigned int> offsetSplitBodies;
	offsetSplitBodies.resize(numBodiesCPU);
	unsigned int totalNumSplitBodiesCPU;
	m_data->m_scan->executeHost(bodyCount,offsetSplitBodies,numBodiesCPU,&totalNumSplitBodiesCPU);
	int numlastBody = bodyCount[numBodiesCPU-1];
	totalNumSplitBodiesCPU += numlastBody;

		int numBodies = bodiesGPU->size();
	int numManifolds = manifoldPtrGPU->size();

	m_data->m_bodyCount->resize(numBodies);
	
	unsigned int val=0;
	b3Int2 val2;
	val2.x=0;
	val2.y=0;

	 {
		B3_PROFILE("m_filler");
		m_data->m_contactConstraintOffsets->resize(numManifolds);
		m_data->m_filler->execute(*m_data->m_bodyCount,val,numBodies);
		
	
		m_data->m_filler->execute(*m_data->m_contactConstraintOffsets,val2,numManifolds);
	}

	{
		B3_PROFILE("m_countBodiesKernel");
		b3LauncherCL launcher(this->m_queue,m_data->m_countBodiesKernel);
		launcher.setBuffer(manifoldPtrGPU->getBufferCL());
		launcher.setBuffer(m_data->m_bodyCount->getBufferCL());
		launcher.setBuffer(m_data->m_contactConstraintOffsets->getBufferCL());
		launcher.setConst(numManifolds);
		launcher.setConst(solverInfo.m_fixedBodyIndex);
		launcher.launch1D(numManifolds);
	}

	unsigned int totalNumSplitBodies=0;
	m_data->m_offsetSplitBodies->resize(numBodies);
	m_data->m_scan->execute(*m_data->m_bodyCount,*m_data->m_offsetSplitBodies,numBodies,&totalNumSplitBodies);
	totalNumSplitBodies+=m_data->m_bodyCount->at(numBodies-1);

	if (totalNumSplitBodies != totalNumSplitBodiesCPU)
	{
		printf("error in totalNumSplitBodies!\n");
	}

	int numContacts = manifoldPtrGPU->size();
	m_data->m_contactConstraints->resize(numContacts);

	
	{
		B3_PROFILE("contactToConstraintSplitKernel");
		b3LauncherCL launcher( m_queue, m_data->m_contactToConstraintSplitKernel);
		launcher.setBuffer(manifoldPtrGPU->getBufferCL());
		launcher.setBuffer(bodiesGPU->getBufferCL());
		launcher.setBuffer(inertiasGPU->getBufferCL());
		launcher.setBuffer(m_data->m_contactConstraints->getBufferCL());
		launcher.setBuffer(m_data->m_bodyCount->getBufferCL());
        launcher.setConst(numContacts);
		launcher.setConst(solverInfo.m_deltaTime);
		launcher.setConst(solverInfo.m_positionDrift);
		launcher.setConst(solverInfo.m_positionConstraintCoeff);
		launcher.launch1D( numContacts, 64 );
		clFinish(m_queue);
	}



	b3AlignedObjectArray<b3GpuConstraint4> contactConstraints;
	contactConstraints.resize(numManifoldsCPU);

	for (int i=0;i<numManifoldsCPU;i++)
	{
		ContactToConstraintKernel(&manifoldPtrCPU[0],&bodiesCPU[0],&inertiasCPU[0],&contactConstraints[0],numManifoldsCPU,
			solverInfo.m_deltaTime,
			solverInfo.m_positionDrift,
			solverInfo.m_positionConstraintCoeff,
			i, bodyCount);
	}
	int maxIter = solverInfo.m_numIterations;


	b3AlignedObjectArray<b3Vector3> deltaLinearVelocities;
	b3AlignedObjectArray<b3Vector3> deltaAngularVelocities;
	deltaLinearVelocities.resize(totalNumSplitBodiesCPU);
	deltaAngularVelocities.resize(totalNumSplitBodiesCPU);
	for (int i=0;i<totalNumSplitBodiesCPU;i++)
	{
		deltaLinearVelocities[i].setZero();
		deltaAngularVelocities[i].setZero();
	}

	m_data->m_deltaLinearVelocities->resize(totalNumSplitBodies);
	m_data->m_deltaAngularVelocities->resize(totalNumSplitBodies);


	
	{
		B3_PROFILE("m_clearVelocitiesKernel");
		b3LauncherCL launch(m_queue,m_data->m_clearVelocitiesKernel);
		launch.setBuffer(m_data->m_deltaAngularVelocities->getBufferCL());
		launch.setBuffer(m_data->m_deltaLinearVelocities->getBufferCL());
		launch.setConst(totalNumSplitBodies);
		launch.launch1D(totalNumSplitBodies);
	}
	

		///!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


	m_data->m_contactConstraints->copyToHost(contactConstraints);
	m_data->m_offsetSplitBodies->copyToHost(offsetSplitBodies);
	m_data->m_contactConstraintOffsets->copyToHost(contactConstraintOffsets);
	m_data->m_deltaLinearVelocities->copyToHost(deltaLinearVelocities);
	m_data->m_deltaAngularVelocities->copyToHost(deltaAngularVelocities);

	for (int iter = 0;iter<maxIter;iter++)
	{

				{
			B3_PROFILE("m_solveContactKernel");
			b3LauncherCL launcher( m_queue, m_data->m_solveContactKernel );
			launcher.setBuffer(m_data->m_contactConstraints->getBufferCL());
			launcher.setBuffer(bodiesGPU->getBufferCL());
			launcher.setBuffer(inertiasGPU->getBufferCL());
			launcher.setBuffer(m_data->m_contactConstraintOffsets->getBufferCL());
			launcher.setBuffer(m_data->m_offsetSplitBodies->getBufferCL());
			launcher.setBuffer(m_data->m_deltaLinearVelocities->getBufferCL());
			launcher.setBuffer(m_data->m_deltaAngularVelocities->getBufferCL());
			launcher.setConst(solverInfo.m_deltaTime);
			launcher.setConst(solverInfo.m_positionDrift);
			launcher.setConst(solverInfo.m_positionConstraintCoeff);
			launcher.setConst(solverInfo.m_fixedBodyIndex);
			launcher.setConst(numManifolds);

			launcher.launch1D(numManifolds);
			clFinish(m_queue);
		}


		int i=0;
		for( i=0; i<numManifoldsCPU; i++)
		{

			float frictionCoeff = contactConstraints[i].getFrictionCoeff();
			int aIdx = (int)contactConstraints[i].m_bodyA;
			int bIdx = (int)contactConstraints[i].m_bodyB;
			b3RigidBodyData& bodyA = bodiesCPU[aIdx];
			b3RigidBodyData& bodyB = bodiesCPU[bIdx];

			b3Vector3 zero(0,0,0);
			
			b3Vector3* dlvAPtr=&zero;
			b3Vector3* davAPtr=&zero;
			b3Vector3* dlvBPtr=&zero;
			b3Vector3* davBPtr=&zero;
			
			if (bodyA.m_invMass)
			{
				int bodyOffsetA = offsetSplitBodies[aIdx];
				int constraintOffsetA = contactConstraintOffsets[i].x;
				int splitIndexA = bodyOffsetA+constraintOffsetA;
				dlvAPtr = &deltaLinearVelocities[splitIndexA];
				davAPtr = &deltaAngularVelocities[splitIndexA];
			}

			if (bodyB.m_invMass)
			{
				int bodyOffsetB = offsetSplitBodies[bIdx];
				int constraintOffsetB = contactConstraintOffsets[i].y;
				int splitIndexB= bodyOffsetB+constraintOffsetB;
				dlvBPtr =&deltaLinearVelocities[splitIndexB];
				davBPtr = &deltaAngularVelocities[splitIndexB];
			}



			{
				float maxRambdaDt[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX};
				float minRambdaDt[4] = {0.f,0.f,0.f,0.f};

				solveContact( contactConstraints[i], (b3Vector3&)bodyA.m_pos, (b3Vector3&)bodyA.m_linVel, (b3Vector3&)bodyA.m_angVel, bodyA.m_invMass, inertiasCPU[aIdx].m_invInertiaWorld, 
					(b3Vector3&)bodyB.m_pos, (b3Vector3&)bodyB.m_linVel, (b3Vector3&)bodyB.m_angVel, bodyB.m_invMass, inertiasCPU[bIdx].m_invInertiaWorld,
					maxRambdaDt, minRambdaDt , *dlvAPtr,*davAPtr,*dlvBPtr,*davBPtr		);


			}
		}

		
		{
			B3_PROFILE("average velocities");
			b3LauncherCL launcher( m_queue, m_data->m_averageVelocitiesKernel);
			launcher.setBuffer(bodiesGPU->getBufferCL());
			launcher.setBuffer(m_data->m_offsetSplitBodies->getBufferCL());
			launcher.setBuffer(m_data->m_bodyCount->getBufferCL());
			launcher.setBuffer(m_data->m_deltaLinearVelocities->getBufferCL());
			launcher.setBuffer(m_data->m_deltaAngularVelocities->getBufferCL());
			launcher.setConst(numBodies);
			launcher.launch1D(numBodies);
			clFinish(m_queue);
		}

		//easy
		for (int i=0;i<numBodiesCPU;i++)
		{
			if (bodiesCPU[i].m_invMass)
			{
				int bodyOffset = offsetSplitBodies[i];
				int count = bodyCount[i];
				float factor = 1.f/float(count);
				b3Vector3 averageLinVel;
				averageLinVel.setZero();
				b3Vector3 averageAngVel;
				averageAngVel.setZero();
				for (int j=0;j<count;j++)
				{
					averageLinVel += deltaLinearVelocities[bodyOffset+j]*factor;
					averageAngVel += deltaAngularVelocities[bodyOffset+j]*factor;
				}
				for (int j=0;j<count;j++)
				{
					deltaLinearVelocities[bodyOffset+j] = averageLinVel;
					deltaAngularVelocities[bodyOffset+j] = averageAngVel;
				}
			}
		}
//	m_data->m_deltaAngularVelocities->copyFromHost(deltaAngularVelocities);
	//m_data->m_deltaLinearVelocities->copyFromHost(deltaLinearVelocities);
	m_data->m_deltaAngularVelocities->copyToHost(deltaAngularVelocities);
	m_data->m_deltaLinearVelocities->copyToHost(deltaLinearVelocities);

#if 0

		{
			B3_PROFILE("m_solveFrictionKernel");
			b3LauncherCL launcher( m_queue, m_data->m_solveFrictionKernel);
			launcher.setBuffer(m_data->m_contactConstraints->getBufferCL());
			launcher.setBuffer(bodiesGPU->getBufferCL());
			launcher.setBuffer(inertiasGPU->getBufferCL());
			launcher.setBuffer(m_data->m_contactConstraintOffsets->getBufferCL());
			launcher.setBuffer(m_data->m_offsetSplitBodies->getBufferCL());
			launcher.setBuffer(m_data->m_deltaLinearVelocities->getBufferCL());
			launcher.setBuffer(m_data->m_deltaAngularVelocities->getBufferCL());
			launcher.setConst(solverInfo.m_deltaTime);
			launcher.setConst(solverInfo.m_positionDrift);
			launcher.setConst(solverInfo.m_positionConstraintCoeff);
			launcher.setConst(solverInfo.m_fixedBodyIndex);
			launcher.setConst(numManifolds);

			launcher.launch1D(numManifolds);
			clFinish(m_queue);
		}

		//solve friction

		for(int i=0; i<numManifoldsCPU; i++)
		{
			float maxRambdaDt[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX};
			float minRambdaDt[4] = {0.f,0.f,0.f,0.f};

			float sum = 0;
			for(int j=0; j<4; j++)
			{
				sum +=contactConstraints[i].m_appliedRambdaDt[j];
			}
			float frictionCoeff = contactConstraints[i].getFrictionCoeff();
			int aIdx = (int)contactConstraints[i].m_bodyA;
			int bIdx = (int)contactConstraints[i].m_bodyB;
			b3RigidBodyData& bodyA = bodiesCPU[aIdx];
			b3RigidBodyData& bodyB = bodiesCPU[bIdx];

			b3Vector3 zero(0,0,0);
			
			b3Vector3* dlvAPtr=&zero;
			b3Vector3* davAPtr=&zero;
			b3Vector3* dlvBPtr=&zero;
			b3Vector3* davBPtr=&zero;
			
			if (bodyA.m_invMass)
			{
				int bodyOffsetA = offsetSplitBodies[aIdx];
				int constraintOffsetA = contactConstraintOffsets[i].x;
				int splitIndexA = bodyOffsetA+constraintOffsetA;
				dlvAPtr = &deltaLinearVelocities[splitIndexA];
				davAPtr = &deltaAngularVelocities[splitIndexA];
			}

			if (bodyB.m_invMass)
			{
				int bodyOffsetB = offsetSplitBodies[bIdx];
				int constraintOffsetB = contactConstraintOffsets[i].y;
				int splitIndexB= bodyOffsetB+constraintOffsetB;
				dlvBPtr =&deltaLinearVelocities[splitIndexB];
				davBPtr = &deltaAngularVelocities[splitIndexB];
			}

			for(int j=0; j<4; j++)
			{
				maxRambdaDt[j] = frictionCoeff*sum;
				minRambdaDt[j] = -maxRambdaDt[j];
			}

			solveFriction( contactConstraints[i], (b3Vector3&)bodyA.m_pos, (b3Vector3&)bodyA.m_linVel, (b3Vector3&)bodyA.m_angVel, bodyA.m_invMass,inertiasCPU[aIdx].m_invInertiaWorld, 
				(b3Vector3&)bodyB.m_pos, (b3Vector3&)bodyB.m_linVel, (b3Vector3&)bodyB.m_angVel, bodyB.m_invMass, inertiasCPU[bIdx].m_invInertiaWorld,
				maxRambdaDt, minRambdaDt , *dlvAPtr,*davAPtr,*dlvBPtr,*davBPtr);

		}

		{
			B3_PROFILE("average velocities");
			b3LauncherCL launcher( m_queue, m_data->m_averageVelocitiesKernel);
			launcher.setBuffer(bodiesGPU->getBufferCL());
			launcher.setBuffer(m_data->m_offsetSplitBodies->getBufferCL());
			launcher.setBuffer(m_data->m_bodyCount->getBufferCL());
			launcher.setBuffer(m_data->m_deltaLinearVelocities->getBufferCL());
			launcher.setBuffer(m_data->m_deltaAngularVelocities->getBufferCL());
			launcher.setConst(numBodies);
			launcher.launch1D(numBodies);
			clFinish(m_queue);
		}

		//easy
		for (int i=0;i<numBodiesCPU;i++)
		{
			if (bodiesCPU[i].m_invMass)
			{
				int bodyOffset = offsetSplitBodies[i];
				int count = bodyCount[i];
				float factor = 1.f/float(count);
				b3Vector3 averageLinVel;
				averageLinVel.setZero();
				b3Vector3 averageAngVel;
				averageAngVel.setZero();
				for (int j=0;j<count;j++)
				{
					averageLinVel += deltaLinearVelocities[bodyOffset+j]*factor;
					averageAngVel += deltaAngularVelocities[bodyOffset+j]*factor;
				}
				for (int j=0;j<count;j++)
				{
					deltaLinearVelocities[bodyOffset+j] = averageLinVel;
					deltaAngularVelocities[bodyOffset+j] = averageAngVel;
				}
			}
		}

#endif

	}

	{
		B3_PROFILE("update body velocities");
		b3LauncherCL launcher( m_queue, m_data->m_updateBodyVelocitiesKernel);
		launcher.setBuffer(bodiesGPU->getBufferCL());
		launcher.setBuffer(m_data->m_offsetSplitBodies->getBufferCL());
		launcher.setBuffer(m_data->m_bodyCount->getBufferCL());
		launcher.setBuffer(m_data->m_deltaLinearVelocities->getBufferCL());
		launcher.setBuffer(m_data->m_deltaAngularVelocities->getBufferCL());
		launcher.setConst(numBodies);
		launcher.launch1D(numBodies);
		clFinish(m_queue);
	}


	//easy
	for (int i=0;i<numBodiesCPU;i++)
	{
		if (bodiesCPU[i].m_invMass)
		{
			int bodyOffset = offsetSplitBodies[i];
			int count = bodyCount[i];
			if (count)
			{
				bodiesCPU[i].m_linVel += deltaLinearVelocities[bodyOffset];
				bodiesCPU[i].m_angVel += deltaAngularVelocities[bodyOffset];
			}
		}
	}


//	bodiesGPU->copyFromHost(bodiesCPU);


}
Exemple #26
0
/**
 * Read /task/control and execute the commands.
 * The file contains one command per line. If a line starts with '!', it will
 * be run unprivileged.
 */
static void run_control() {
    char line[CONTROL_MAXLEN+1];
    int n, i, id;
    struct shminfo shminfo;
    struct shmid_ds shm;
    struct seminfo seminfo;
    struct semid_ds sem;
    union semun {
        int              val;
        struct semid_ds *buf;
        unsigned short  *array;
        struct seminfo  *__buf;
    } semun;
    struct msginfo msginfo;
    struct msqid_ds msq;

    fcontrol = fopen("/task/control", "r");
    if(fcontrol == NULL)
        die("open /task/control", NULL);
    while(fgets(line, CONTROL_MAXLEN+1, fcontrol) != NULL) {
        // Launch command
        if(line[0] == '!')
            launch(line + 1, UID_WORKER);
        else
            launch(line, UID_MASTER);

        // Cleanup
        // Kill processes
        kill(-1, SIGKILL);

        // Release shared memory
        n = shmctl(0, IPC_INFO, (struct shmid_ds *) &shminfo);
        if(n < 0)
            die("shmctl", NULL);
        for(i = 0; i <= n; i++) {
            id = shmctl(i, SHM_STAT, &shm);
            if(id >= 0)
                shmctl(id, IPC_RMID, NULL);
        }

        // Release semaphores
        semun.__buf = &seminfo;
        n = semctl(0, 0, IPC_INFO, semun);
        if(n < 0)
            die("semctl", NULL);
        semun.buf = &sem;
        for(i = 0; i <= n; i++) {
            id = semctl(i, 0, SEM_STAT, semun);
            if(id >= 0)
                semctl(id, 0, IPC_RMID, semun);
        }

        // Release message queues
        n = msgctl(0, IPC_INFO, (struct msqid_ds *) &msginfo);
        if(n < 0)
            die("msgctl", NULL);
        for(i = 0; i <= n; i++) {
            id = msgctl(i, MSG_STAT, &msq);
            if(id >= 0)
                msgctl(id, IPC_RMID, NULL);
        }
    }
}
Exemple #27
0
static void LoopMissiles(struct state *st, int xlim, int ylim)
{
  int i, j, max = 0;
  for (i = 0; i < kMaxMissiles; i++) {
	 int old_x, old_y;
	 Missile *m = &st->missile[i];
	 if (!m->alive)
		continue;
	 old_x = m->x;
	 old_y = m->y;
	 m->pos += kMissileSpeed;
	 m->x = m->startx + ((float) (m->endx - m->startx)) * m->pos;
	 m->y = m->starty + ((float) (m->endy - m->starty)) * m->pos;

      /* erase old one */

	 XSetLineAttributes(st->dpy, st->draw_gc, 4, 0,0,0);
    XSetForeground (st->dpy, st->draw_gc, m->color.pixel);
	 XDrawLine(st->dpy, st->window, st->draw_gc,
				  old_x, old_y, m->x, m->y);

	 /* maybe split off a new missile? */
	 if (m->splits && (m->y > m->splits)) {
		m->splits = 0;
		launch(st, xlim, ylim, i);
	 }
	 
	 if (m->y >= ylim) {
		m->alive = 0;
		if (st->city[m->dcity].alive) {
		  st->city[m->dcity].alive = 0;
		  Explode(st, m->x, m->y, kBoomRad * 2, m->color, 0);
		}
	 }

	 /* check hitting explosions */
	 for (j=0;j<kMaxBooms;j++) {
		Boom *b = &st->boom[j];
		if (!b->alive)
		  continue;
		else {
		  int dx = abs(m->x - b->x);
		  int dy = abs(m->y - b->y);
		  int r = b->rad + 2;
		  if ((dx < r) && (dy < r))
			 if (dx * dx + dy * dy < r * r) {
				m->alive = 0;
				max = b->max + st->bgrowth - kBoomRad;
				AddScore(st, xlim, ylim, SCORE_MISSILE);
		  }
		}
	 }

	 if (m->alive == 0) {
		float my_pos;
		/* we just died */
		Explode(st, m->x, m->y, kBoomRad + max, m->color, 0);
		XSetLineAttributes(st->dpy, st->erase_gc, 4, 0,0,0);
		/* In a perfect world, we could simply erase a line from
		   (m->startx, m->starty) to (m->x, m->y). This is not a
		   perfect world. */
		old_x = m->startx;
		old_y = m->starty;
		my_pos = kMissileSpeed;
		while (my_pos <= m->pos) {
			m->x = m->startx + ((float) (m->endx - m->startx)) * my_pos;
			m->y = m->starty + ((float) (m->endy - m->starty)) * my_pos;
			XDrawLine(st->dpy, st->window, st->erase_gc, old_x, old_y, m->x, m->y);
			old_x = m->x;
			old_y = m->y;
			my_pos += kMissileSpeed;
		}
	 }
  }
}
Exemple #28
0
 void launch(basic_process_context& context)
   {
   boost::system::error_code ec;
   launch(context, ec);
   boost::asio::detail::throw_error(ec);
   }
// This test checks that a failed over scheduler gets the retried status update
// when the original instance dies without acknowledging the update.
TEST_F(HttpFaultToleranceTest, SchedulerFailoverStatusUpdate)
{
  master::Flags flags = CreateMasterFlags();
  flags.authenticate_frameworks = false;

  Try<Owned<cluster::Master>> master = StartMaster(flags);
  ASSERT_SOME(master);

  auto scheduler = std::make_shared<v1::MockHTTPScheduler>();
  auto executor = std::make_shared<v1::MockHTTPExecutor>();

  ExecutorID executorId = DEFAULT_EXECUTOR_ID;
  TestContainerizer containerizer(executorId, executor);

  Owned<MasterDetector> detector = master.get()->createDetector();

  Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), &containerizer);
  ASSERT_SOME(slave);

  Future<Nothing> connected;
  EXPECT_CALL(*scheduler, connected(_))
    .WillOnce(FutureSatisfy(&connected))
    .WillRepeatedly(Return()); // Ignore future invocations.

  ContentType contentType = ContentType::PROTOBUF;

  v1::scheduler::TestMesos schedulerLibrary(
      master.get()->pid,
      contentType,
      scheduler);

  AWAIT_READY(connected);

  Future<Event::Subscribed> subscribed;
  EXPECT_CALL(*scheduler, subscribed(_, _))
    .WillOnce(FutureArg<1>(&subscribed));

  EXPECT_CALL(*scheduler, heartbeat(_))
    .WillRepeatedly(Return()); // Ignore heartbeats.

  Future<Event::Offers> offers;
  EXPECT_CALL(*scheduler, offers(_, _))
    .WillOnce(FutureArg<1>(&offers));

  {
    Call call;
    call.set_type(Call::SUBSCRIBE);

    Call::Subscribe* subscribe = call.mutable_subscribe();
    subscribe->mutable_framework_info()->CopyFrom(v1::DEFAULT_FRAMEWORK_INFO);

    schedulerLibrary.send(call);
  }

  AWAIT_READY(subscribed);

  v1::FrameworkID frameworkId(subscribed->framework_id());

  AWAIT_READY(offers);
  EXPECT_NE(0, offers->offers().size());

  EXPECT_CALL(*executor, connected(_))
    .WillOnce(v1::executor::SendSubscribe(frameworkId, evolve(executorId)));

  EXPECT_CALL(*executor, subscribed(_, _));

  EXPECT_CALL(*executor, launch(_, _))
    .WillOnce(v1::executor::SendUpdateFromTask(
        frameworkId, evolve(executorId), v1::TASK_RUNNING));

  Future<Nothing> acknowledged;
  EXPECT_CALL(*executor, acknowledged(_, _))
    .WillOnce(FutureSatisfy(&acknowledged));

  Future<Event::Update> update;
  EXPECT_CALL(*scheduler, update(_, _))
    .WillOnce(FutureArg<1>(&update));

  const v1::Offer& offer = offers->offers(0);

  v1::TaskInfo taskInfo =
    evolve(createTask(devolve(offer), "", executorId));

  {
    Call call;
    call.mutable_framework_id()->CopyFrom(frameworkId);
    call.set_type(Call::ACCEPT);

    Call::Accept* accept = call.mutable_accept();
    accept->add_offer_ids()->CopyFrom(offer.id());

    v1::Offer::Operation* operation = accept->add_operations();
    operation->set_type(v1::Offer::Operation::LAUNCH);
    operation->mutable_launch()->add_task_infos()->CopyFrom(taskInfo);

    schedulerLibrary.send(call);
  }

  AWAIT_READY(acknowledged);
  AWAIT_READY(update);

  EXPECT_EQ(v1::TASK_RUNNING, update->status().state());
  EXPECT_EQ(executorId, devolve(update->status().executor_id()));

  EXPECT_TRUE(update->status().has_executor_id());
  EXPECT_TRUE(update->status().has_uuid());

  // Failover the scheduler without acknowledging the status update.

  auto scheduler2 = std::make_shared<v1::MockHTTPScheduler>();

  Future<Nothing> connected2;
  EXPECT_CALL(*scheduler2, connected(_))
    .WillOnce(FutureSatisfy(&connected2));

  // Failover to another scheduler instance.
  v1::scheduler::TestMesos schedulerLibrary2(
      master.get()->pid,
      contentType,
      scheduler2);

  AWAIT_READY(connected2);

  // The previously connected scheduler instance should receive an
  // error/disconnected event.
  Future<Nothing> error;
  EXPECT_CALL(*scheduler, error(_, _))
    .WillOnce(FutureSatisfy(&error));

  Future<Nothing> disconnected;
  EXPECT_CALL(*scheduler, disconnected(_))
    .WillOnce(FutureSatisfy(&disconnected));

  EXPECT_CALL(*scheduler2, subscribed(_, _))
    .WillOnce(FutureArg<1>(&subscribed));

  EXPECT_CALL(*scheduler2, heartbeat(_))
    .WillRepeatedly(Return()); // Ignore heartbeats.

  // Scheduler2 should receive the retried status update.
  Future<Nothing> update2;
  EXPECT_CALL(*scheduler2, update(_, _))
    .WillOnce(FutureSatisfy(&update2))
    .WillRepeatedly(Return()); // Ignore subsequent updates.

  {
    Call call;
    call.mutable_framework_id()->CopyFrom(frameworkId);
    call.set_type(Call::SUBSCRIBE);

    Call::Subscribe* subscribe = call.mutable_subscribe();
    subscribe->mutable_framework_info()->CopyFrom(v1::DEFAULT_FRAMEWORK_INFO);
    subscribe->mutable_framework_info()->mutable_id()->CopyFrom(frameworkId);

    schedulerLibrary2.send(call);
  }

  AWAIT_READY(error);
  AWAIT_READY(disconnected);
  AWAIT_READY(subscribed);

  EXPECT_EQ(frameworkId, subscribed->framework_id());

  Clock::pause();

  // Now advance time enough for the reliable timeout to kick in and
  // another status update to be sent.
  Clock::advance(slave::STATUS_UPDATE_RETRY_INTERVAL_MIN);

  AWAIT_READY(update2);

  EXPECT_CALL(*executor, shutdown(_))
    .Times(AtMost(1));

  EXPECT_CALL(*executor, disconnected(_))
    .Times(AtMost(1));
}
Exemple #30
0
bool UnitFiring::fire() {
	return launch(getProjectileLaunchPos(), calcFireDirection(mAimHeading, mAimPitch));
}