示例#1
0
int main(int argc, char * argv[])
{
    FMOD::System        *system;
    FMOD::Sound         *sound1, *sound2, *sound3;
    FMOD::SoundGroup    *soundgroup;
    FMOD::Channel       *channel[3];
    FMOD_RESULT          result;
    int                  key=0;
    int                  mode=1;
    unsigned int         version;

    printf("======================================================================\n");
    printf("soundgroups Example.  Copyright (c) Firelight Technologies 2004-2014.\n");
    printf("======================================================================\n");
    printf("This example plays 3 sounds in a sound group, demonstrating the effect\n");
    printf("of the three different sound group behavior modes\n");
    printf("======================================================================\n\n");

    /*
        Create a System object and initialize.
    */
    result = FMOD::System_Create(&system);
    ERRCHECK(result);    

    result = system->getVersion(&version);
    ERRCHECK(result);

    if (version < FMOD_VERSION)
    {
        printf("Error!  You are using an old version of FMOD %08x.  This program requires %08x\n", version, FMOD_VERSION);
        return 0;
    }

    result = system->init(100, FMOD_INIT_NORMAL, 0);
    ERRCHECK(result);
    	
	/*
	    Load some sound files from the hard disk.
	*/
	result = system->createSound("../media/drumloop.wav", FMOD_HARDWARE |  FMOD_LOOP_NORMAL, 0, &sound1);
	ERRCHECK(result);

	result = system->createSound("../media/jaguar.wav", FMOD_HARDWARE | FMOD_LOOP_NORMAL, 0, &sound2);
	ERRCHECK(result);

	result = system->createSound("../media/swish.wav", FMOD_HARDWARE | FMOD_LOOP_NORMAL, 0, &sound3);
	ERRCHECK(result);
    
    /* 
        Create the sound group with the following attributes:
          Name       = MyGroup
          MaxAudible = 1
          Behavior   = Mute 
    */
	result = system->createSoundGroup("MyGroup",&soundgroup);
	ERRCHECK(result);

    result = soundgroup->setMaxAudible(1);
    ERRCHECK(result);

    result = soundgroup->setMaxAudibleBehavior(FMOD_SOUNDGROUP_BEHAVIOR_MUTE);
    ERRCHECK(result);

    result = soundgroup->setMuteFadeSpeed(2);
    ERRCHECK(result);

    /*
        Put the sounds in the sound group
    */
	result = sound1->setSoundGroup(soundgroup);
	ERRCHECK(result);

	result = sound2->setSoundGroup(soundgroup);
	ERRCHECK(result);

	result = sound3->setSoundGroup(soundgroup);
	ERRCHECK(result);
	
    
	/*
        Play the sounds (two will be muted because of the behavior mode)
    */
	result = system->playSound(FMOD_CHANNEL_FREE, sound1,false,&channel[0]);
	ERRCHECK(result);	

	result = system->playSound(FMOD_CHANNEL_FREE, sound2,false,&channel[1]);
	ERRCHECK(result);

	result = system->playSound(FMOD_CHANNEL_FREE, sound3,false,&channel[2]);
	ERRCHECK(result);
    
    /*
        Display help
    */
    printf("=========================================================================\n");
    printf("Press 1        BEAVIOR_FAIL \n");
    printf("      2        BEAVIOR_MUTE \n");
    printf("      3        BEAVIOR_STEALLOWEST\n");
    printf("      Q        Play/stop drumloop sound\n");
    printf("      W        Play/stop Jaguar sound\n");
    printf("      E        Play/stop shwish sound\n");
    printf("      ESC      Quit\n");
    printf("=========================================================================\n");
    
	do
	{
        float audibility;
        int index;

		if( _kbhit())
		{
			key = _getch();

			if( key=='1' )
			{
                result = soundgroup->setMaxAudibleBehavior(FMOD_SOUNDGROUP_BEHAVIOR_FAIL);
                ERRCHECK(result);
			}

            if( key=='2' )
			{
                result = soundgroup->setMaxAudibleBehavior(FMOD_SOUNDGROUP_BEHAVIOR_MUTE);
                ERRCHECK(result);
			}

            if( key=='3' )
			{
                result = soundgroup->setMaxAudibleBehavior(FMOD_SOUNDGROUP_BEHAVIOR_STEALLOWEST);
                ERRCHECK(result);
			}

            if( key=='q' )
			{
                channel[0]->getIndex(&index);
                if (!index)
                {
                    result = system->playSound(FMOD_CHANNEL_FREE, sound1,false,&channel[0]);
	                if (result!=FMOD_ERR_MAXAUDIBLE)
                    {
                        ERRCHECK(result);
                    }
                }
                else
                {
                    result = channel[0]->stop();
                    ERRCHECK(result);
                }
			}

            if( key=='w' )
			{
                channel[1]->getIndex(&index);
                if (!index)
                {
                    result = system->playSound(FMOD_CHANNEL_FREE, sound2,false,&channel[1]);
                    if (result!=FMOD_ERR_MAXAUDIBLE)
                    {
	                    ERRCHECK(result);
                    }
                }
                else
                {
                    result = channel[1]->stop();
                    ERRCHECK(result);
                }
			}

            if( key=='e' )
			{
                channel[2]->getIndex(&index);
                if (!index)
                {
                    result = system->playSound(FMOD_CHANNEL_FREE, sound3,false,&channel[2]);
                    if (result!=FMOD_ERR_MAXAUDIBLE)
                    {
	                    ERRCHECK(result);
                    }
                }
                else
                {
                    result = channel[2]->stop();
                    ERRCHECK(result);
                }
			}
        }

        // print out a small visual display
        {
            char s[80];
            char s1[6];
            char s2[3][6];  
            int i;
            FMOD_SOUNDGROUP_BEHAVIOR behavior;
            soundgroup->getMaxAudibleBehavior(&behavior);
            
            switch (behavior)
            {
                case FMOD_SOUNDGROUP_BEHAVIOR_FAIL : 
                {
                    sprintf(s1,"FAIL");
                    break;
                }

                case FMOD_SOUNDGROUP_BEHAVIOR_MUTE : 
                {
                    sprintf(s1,"MUTE");
                    break;
                }

                case FMOD_SOUNDGROUP_BEHAVIOR_STEALLOWEST : 
                {
                    sprintf(s1,"STEAL");
                    break;
                }
            };
            
            for (i=0; i<3; i++)
            {
                channel[i]->getAudibility(&audibility);

                if (!audibility)
                {
                    channel[i]->getIndex(&index);
                    if (!index)
                    {
                        sprintf(s2[i], "STOP");
                    }
                    else
                    {
                        sprintf(s2[i], "MUTE");
                    }
                }
                else
                {
                    sprintf(s2[i], "PLAY");
                }
            }   
            
            sprintf(s, "MODE:%6s      | SOUND1: %s | SOUND2: %s | SOUND3: %s |", s1, s2[0], s2[1], s2[2]);
            printf("%s\r", s);
        }

		result = system->update();
		ERRCHECK(result);
        Sleep(10);
	}while (key!=27);

	return 0;
}
示例#2
0
/*
*******************************************************************************
** TestWithFaultRepaired -
** Function to run test with fault repaired
*******************************************************************************
*/
STATUS TestWithFaultRepaired(void)
{
	/* Prompt user to fix fault and perform first two drive cycles */
	LogPrint("\n\n**** Test 8.1 (Fault repaired) ****\n");
	LogUserPrompt("Turn key off for at least thirty (30) seconds and\n"
	              "reconnect sensor", ENTER_PROMPT);
	LogUserPrompt("Start engine and let idle for whatever time it takes to run the monitor\n"
	              "and detect that there is no malfunction", ENTER_PROMPT);
	LogUserPrompt("Turn key off for at least thirty (30) seconds\n"
	              "(this completes one driving cycle)", ENTER_PROMPT);
	LogUserPrompt("Start engine and let idle for whatever time it takes to run the monitor\n"
	              "and detect that there is no malfunction", ENTER_PROMPT);

	gOBDEngineRunning = TRUE;

	LogPrint("**** Test 8.1 PASSED ****\n");

	LogPrint("\n\n**** Test 8.2 ****\n");
	/* Determine the OBD protocol to use */
	if ( DetermineProtocol() != PASS )
	{
		LogPrint( "**** Test 8.2 FAILED ****\n" );
		LogPrint( "Protocol determination failed.\n" );
		return(FAIL);
	}
	else
	{
		LogPrint("**** Test 8.2 PASSED ****\n");
	}

	/* Check for a pending DTC */
	LogPrint("\n\n**** Test 8.3 ****\n");

	/* flush the STDIN stream of any user input before loop */
	clear_keyboard_buffer ();

	LogPrint("INFORMATION: Waiting for pending DTC to clear...(press any key to stop test)\n");
	while (!_kbhit())
	{
		if (IsDTCPending() == FALSE)
		{
			break;
		}
		Sleep(500);
	}

	/* Beep */
	printf("\007\n");

	/* Flush the STDIN stream of any user input above */
	clear_keyboard_buffer ();

	/* Set flag to indicate a pending DTC should NOT be present */
	gOBDDTCPending = FALSE;

	/* Verify pending DTC data */
	if (VerifyDTCPendingData() != PASS)
	{
		LogPrint("**** Test 8.3 FAILED ****\n");
		if ( TestContinue( "DTC pending data failed. Continue?" ) == 'N' )
		{
			return(FAIL);
		}
	}
	else
	{
		LogPrint("**** Test 8.3 PASSED ****\n");
	}

	/* Verify stored DTC data */
	LogPrint("\n\n**** Test 8.4 ****\n");
	if (VerifyDTCStoredData() != PASS)
	{
		LogPrint("**** Test 8.4 FAILED ****\n");
		if ( TestContinue( "DTC stored data failed. Continue?" ) == 'N' )
		{
			return(FAIL);
		}
	}

	/* Verify MIL and DTC status is cleared */
	if (LogUserPrompt("Is MIL light ON?", YES_NO_PROMPT) != 'Y')
	{
		LogPrint("**** Test 8.4 FAILED ****\n");
		if ( TestContinue( "MIL light check failed. Continue?" ) == 'N' )
		{
			return(FAIL);
		}
	}

	if (VerifyMILData() != PASS)
	{
		LogPrint("**** Test 8.4 FAILED ****\n");
		if ( TestContinue( "MIL / DTC status failed. Continue?" ) == 'N' )
		{
			return(FAIL);
		}
	}
	else
	{
		LogPrint("**** Test 8.4 PASSED ****\n");
	}

	/* Verify freeze frame support and data */
	LogPrint("\n\n**** Test 8.5 ****\n");
	if (VerifyFreezeFrameSupportAndData() != PASS)
	{
		LogPrint("**** Test 8.5 FAILED ****\n");
		if ( TestContinue( "Freeze frame support/data failed. Continue?" ) == 'N' )
		{
			return(FAIL);
		}
	}
	else
	{
		LogPrint("**** Test 8.5 PASSED ****\n");
	}


	/* Link active test to verify communication remained active for ALL protocols
	 */
	if ( VerifyLinkActive() != PASS )
	{
		return( FAIL );
	}


	gOBDDTCPermanent = TRUE;
	

	/* Verify permanent codes */
	LogPrint( "\n\n**** Test 8.6 ****\n" );
	if ( VerifyPermanentCodeSupport() != PASS )
	{
		LogPrint( "**** Test 8.6 FAILED ****\n" );
		if ( TestContinue( "Permanent code support failed. Continue?" ) == 'N' )
		{
			return(FAIL);
		}
	}
	else
	{
		LogPrint( "**** Test 8.6 PASSED ****\n" );
	}

	return(PASS);
}
示例#3
0
文件: AeDemo2.c 项目: Brainiarc7/TS
/******************************************************************************
 * Synopsis:
 *
 *     AeDemo2 [-o owner] [-s] [-g] [{-ph|-ps} proxy-host [-pp proxy-port]
 *             [-pu proxy-user] [-pw proxy-password]] [-o owner] url
 *
 * url:
 *        Use the following syntax:
 *            http://<server-name>:<port>/eMessage (non-secure communications) or
 *            https://<server-name>:<port>/eMessage  (secure communications)
 *          where <server-name> is replaced with the Enterprise server name.
 *            and <port> is replaced with the port number.  (Use 443 for SSL).
 *        For example, http://drm.axeda.com/eMessage.
 *
 * Options:
 *
 *     -o owner
 *         Use specified owner (database name).
 *     -s
 *         Use secure communication (SSL).
 *     -g
 *         Enable debug messages.
 *     -ph proxy-host
 *         Use HTTP proxy at proxy-host. Default port is 80.
 *     -ps proxy-host
 *         Use SOCKS proxy at proxy-host. Default port is 1080.
 *     -pp proxy-port
 *         Override default port for proxy.
 *     -pu proxy-user
 *         Use proxy-user as user name for proxy authentication.
 *     -pw proxy-password
 *         Use proxy-password as password for proxy authentication.
 *
 * Description:
 *
 *     The program defines a device, configures the primary Enterprise server
 *     (using url argument) and installs command callbacks. After that it loops
 *     and waits for callback invocation.
 ******************************************************************************/
int main(int argc, char *argv[])
{
    AeDemoConfig config;
    AeInt32 iDeviceId, iServerId;
    AeTimeValue pingRate, timeLimit;
    AeError rc;

    /* process options */
    if (!AeDemoProcessOptions(&config, &argc, argv, 1))
    {
        AeDemoUsage(argv[0], "url");
        return 1;
    }

    /* initialize Axeda Agent Embedded */
    AeInitialize();

    /* apply options */
    AeDemoApplyConfig(&config);

    /* configure master device */
    rc = AeDRMAddDevice(AeDRMDeviceMaster, MODEL_NUMBER, SERIAL_NUMBER, &iDeviceId);
    if (rc != AeEOK)
    {
        fprintf(stderr, "Failed to add device (%s)\n", AeGetErrorString(rc));
        return 1;
    }

    /* configure primary DRM server */
    pingRate.iSec = PING_RATE;
    pingRate.iMicroSec = 0;
    rc = AeDRMAddServer(AeDRMServerConfigPrimary, argv[argc], config.pOwner,
        &pingRate, &iServerId);
    if (rc != AeEOK)
    {
        fprintf(stderr, "Failed to add server (%s)\n", AeGetErrorString(rc));
        return 1;
    }

    AeWebSetPersistent(iServerId, AeTrue);

    /* install command callbacks */
    AeDRMSetOnCommandSetTag(AeDemoOnSetTag);
    AeDRMSetOnCommandSetTime(AeDemoOnSetTime);
    AeDRMSetOnCommandRestart(AeDemoOnRestart);

    timeLimit.iSec = 1;
    timeLimit.iMicroSec = 0;

    /* execute demo until keystroke */
#ifdef WIN32
    while (!_kbhit())
#else
    while (1)
#endif
    {
        /* do DRM processing */
        AeDRMExecute(&timeLimit);
    }

    /* shutdown Axeda Agent Embedded */
    AeShutdown();
#if defined(WIN32) && defined(_DEBUG)&& (_MSC_VER < 1300)
    _CrtDumpMemoryLeaks();
#endif

    return 0;
}
示例#4
0
int MAIN(int argc, char **argv)
{
    int off=0;
    SSL *con=NULL,*con2=NULL;
    X509_STORE *store = NULL;
    int s,k,width,state=0;
    char *cbuf=NULL,*sbuf=NULL,*mbuf=NULL;
    int cbuf_len,cbuf_off;
    int sbuf_len,sbuf_off;
    fd_set readfds,writefds;
    short port=PORT;
    int full_log=1;
    char *host=SSL_HOST_NAME;
    char *cert_file=NULL,*key_file=NULL;
    int cert_format = FORMAT_PEM, key_format = FORMAT_PEM;
    char *passarg = NULL, *pass = NULL;
    X509 *cert = NULL;
    EVP_PKEY *key = NULL;
    char *CApath=NULL,*CAfile=NULL,*cipher=NULL;
    int reconnect=0,badop=0,verify=SSL_VERIFY_NONE,bugs=0;
    int crlf=0;
    int write_tty,read_tty,write_ssl,read_ssl,tty_on,ssl_pending;
    SSL_CTX *ctx=NULL;
    int ret=1,in_init=1,i,nbio_test=0;
    int starttls_proto = 0;
    int prexit = 0, vflags = 0;
    SSL_METHOD *meth=NULL;
#ifdef sock_type
#undef sock_type
#endif
    int sock_type=SOCK_STREAM;
    BIO *sbio;
    char *inrand=NULL;
#ifndef OPENSSL_NO_ENGINE
    char *engine_id=NULL;
    ENGINE *e=NULL;
#endif
#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
    struct timeval tv;
#endif

    struct sockaddr peer;
    int peerlen = sizeof(peer);
    int enable_timeouts = 0 ;
    long mtu = 0;

#if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3)
    meth=SSLv23_client_method();
#elif !defined(OPENSSL_NO_SSL3)
    meth=SSLv3_client_method();
#elif !defined(OPENSSL_NO_SSL2)
    meth=SSLv2_client_method();
#endif

    apps_startup();
    c_Pause=0;
    c_quiet=0;
    c_ign_eof=0;
    c_debug=0;
    c_msg=0;
    c_showcerts=0;

    if (bio_err == NULL)
        bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);

    if (!load_config(bio_err, NULL))
        goto end;

    if (	((cbuf=OPENSSL_malloc(BUFSIZZ)) == NULL) ||
            ((sbuf=OPENSSL_malloc(BUFSIZZ)) == NULL) ||
            ((mbuf=OPENSSL_malloc(BUFSIZZ)) == NULL))
    {
        BIO_printf(bio_err,"out of memory\n");
        goto end;
    }

    verify_depth=0;
    verify_error=X509_V_OK;
#ifdef FIONBIO
    c_nbio=0;
#endif

    argc--;
    argv++;
    while (argc >= 1)
    {
        if	(strcmp(*argv,"-host") == 0)
        {
            if (--argc < 1) goto bad;
            host= *(++argv);
        }
        else if	(strcmp(*argv,"-port") == 0)
        {
            if (--argc < 1) goto bad;
            port=atoi(*(++argv));
            if (port == 0) goto bad;
        }
        else if (strcmp(*argv,"-connect") == 0)
        {
            if (--argc < 1) goto bad;
            if (!extract_host_port(*(++argv),&host,NULL,&port))
                goto bad;
        }
        else if	(strcmp(*argv,"-verify") == 0)
        {
            verify=SSL_VERIFY_PEER;
            if (--argc < 1) goto bad;
            verify_depth=atoi(*(++argv));
            BIO_printf(bio_err,"verify depth is %d\n",verify_depth);
        }
        else if	(strcmp(*argv,"-cert") == 0)
        {
            if (--argc < 1) goto bad;
            cert_file= *(++argv);
        }
        else if	(strcmp(*argv,"-certform") == 0)
        {
            if (--argc < 1) goto bad;
            cert_format = str2fmt(*(++argv));
        }
        else if	(strcmp(*argv,"-crl_check") == 0)
            vflags |= X509_V_FLAG_CRL_CHECK;
        else if	(strcmp(*argv,"-crl_check_all") == 0)
            vflags |= X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
        else if	(strcmp(*argv,"-prexit") == 0)
            prexit=1;
        else if	(strcmp(*argv,"-crlf") == 0)
            crlf=1;
        else if	(strcmp(*argv,"-quiet") == 0)
        {
            c_quiet=1;
            c_ign_eof=1;
        }
        else if	(strcmp(*argv,"-ign_eof") == 0)
            c_ign_eof=1;
        else if	(strcmp(*argv,"-pause") == 0)
            c_Pause=1;
        else if	(strcmp(*argv,"-debug") == 0)
            c_debug=1;
#ifdef WATT32
        else if (strcmp(*argv,"-wdebug") == 0)
            dbug_init();
#endif
        else if	(strcmp(*argv,"-msg") == 0)
            c_msg=1;
        else if	(strcmp(*argv,"-showcerts") == 0)
            c_showcerts=1;
        else if	(strcmp(*argv,"-nbio_test") == 0)
            nbio_test=1;
        else if	(strcmp(*argv,"-state") == 0)
            state=1;
#ifndef OPENSSL_NO_SSL2
        else if	(strcmp(*argv,"-ssl2") == 0)
            meth=SSLv2_client_method();
#endif
#ifndef OPENSSL_NO_SSL3
        else if	(strcmp(*argv,"-ssl3") == 0)
            meth=SSLv3_client_method();
#endif
#ifndef OPENSSL_NO_TLS1
        else if	(strcmp(*argv,"-tls1") == 0)
            meth=TLSv1_client_method();
#endif
#ifndef OPENSSL_NO_DTLS1
        else if	(strcmp(*argv,"-dtls1") == 0)
        {
            meth=DTLSv1_client_method();
            sock_type=SOCK_DGRAM;
        }
        else if (strcmp(*argv,"-timeout") == 0)
            enable_timeouts=1;
        else if (strcmp(*argv,"-mtu") == 0)
        {
            if (--argc < 1) goto bad;
            mtu = atol(*(++argv));
        }
#endif
        else if (strcmp(*argv,"-bugs") == 0)
            bugs=1;
        else if	(strcmp(*argv,"-keyform") == 0)
        {
            if (--argc < 1) goto bad;
            key_format = str2fmt(*(++argv));
        }
        else if	(strcmp(*argv,"-pass") == 0)
        {
            if (--argc < 1) goto bad;
            passarg = *(++argv);
        }
        else if	(strcmp(*argv,"-key") == 0)
        {
            if (--argc < 1) goto bad;
            key_file= *(++argv);
        }
        else if	(strcmp(*argv,"-reconnect") == 0)
        {
            reconnect=5;
        }
        else if	(strcmp(*argv,"-CApath") == 0)
        {
            if (--argc < 1) goto bad;
            CApath= *(++argv);
        }
        else if	(strcmp(*argv,"-CAfile") == 0)
        {
            if (--argc < 1) goto bad;
            CAfile= *(++argv);
        }
        else if (strcmp(*argv,"-no_tls1") == 0)
            off|=SSL_OP_NO_TLSv1;
        else if (strcmp(*argv,"-no_ssl3") == 0)
            off|=SSL_OP_NO_SSLv3;
        else if (strcmp(*argv,"-no_ssl2") == 0)
            off|=SSL_OP_NO_SSLv2;
        else if (strcmp(*argv,"-serverpref") == 0)
            off|=SSL_OP_CIPHER_SERVER_PREFERENCE;
        else if	(strcmp(*argv,"-cipher") == 0)
        {
            if (--argc < 1) goto bad;
            cipher= *(++argv);
        }
#ifdef FIONBIO
        else if (strcmp(*argv,"-nbio") == 0)
        {
            c_nbio=1;
        }
#endif
        else if	(strcmp(*argv,"-starttls") == 0)
        {
            if (--argc < 1) goto bad;
            ++argv;
            if (strcmp(*argv,"smtp") == 0)
                starttls_proto = 1;
            else if (strcmp(*argv,"pop3") == 0)
                starttls_proto = 2;
            else
                goto bad;
        }
#ifndef OPENSSL_NO_ENGINE
        else if	(strcmp(*argv,"-engine") == 0)
        {
            if (--argc < 1) goto bad;
            engine_id = *(++argv);
        }
#endif
        else if (strcmp(*argv,"-rand") == 0)
        {
            if (--argc < 1) goto bad;
            inrand= *(++argv);
        }
        else
        {
            BIO_printf(bio_err,"unknown option %s\n",*argv);
            badop=1;
            break;
        }
        argc--;
        argv++;
    }
    if (badop)
    {
bad:
        sc_usage();
        goto end;
    }

    OpenSSL_add_ssl_algorithms();
    SSL_load_error_strings();

#ifndef OPENSSL_NO_ENGINE
    e = setup_engine(bio_err, engine_id, 1);
#endif
    if (!app_passwd(bio_err, passarg, NULL, &pass, NULL))
    {
        BIO_printf(bio_err, "Error getting password\n");
        goto end;
    }

    if (key_file == NULL)
        key_file = cert_file;


    if (key_file)

    {

        key = load_key(bio_err, key_file, key_format, 0, pass, e,
                       "client certificate private key file");
        if (!key)
        {
            ERR_print_errors(bio_err);
            goto end;
        }

    }

    if (cert_file)

    {
        cert = load_cert(bio_err,cert_file,cert_format,
                         NULL, e, "client certificate file");

        if (!cert)
        {
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL
            && !RAND_status())
    {
        BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n");
    }
    if (inrand != NULL)
        BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
                   app_RAND_load_files(inrand));

    if (bio_c_out == NULL)
    {
        if (c_quiet && !c_debug && !c_msg)
        {
            bio_c_out=BIO_new(BIO_s_null());
        }
        else
        {
            if (bio_c_out == NULL)
                bio_c_out=BIO_new_fp(stdout,BIO_NOCLOSE);
        }
    }

    ctx=SSL_CTX_new(meth);
    if (ctx == NULL)
    {
        ERR_print_errors(bio_err);
        goto end;
    }

    if (bugs)
        SSL_CTX_set_options(ctx,SSL_OP_ALL|off);
    else
        SSL_CTX_set_options(ctx,off);
    /* DTLS: partial reads end up discarding unread UDP bytes :-(
     * Setting read ahead solves this problem.
     */
    if (sock_type == SOCK_DGRAM) SSL_CTX_set_read_ahead(ctx, 1);

    if (state) SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback);
    if (cipher != NULL)
        if(!SSL_CTX_set_cipher_list(ctx,cipher)) {
            BIO_printf(bio_err,"error setting cipher list\n");
            ERR_print_errors(bio_err);
            goto end;
        }
#if 0
        else
            SSL_CTX_set_cipher_list(ctx,getenv("SSL_CIPHER"));
#endif

    SSL_CTX_set_verify(ctx,verify,verify_callback);
    if (!set_cert_key_stuff(ctx,cert,key))
        goto end;

    if ((!SSL_CTX_load_verify_locations(ctx,CAfile,CApath)) ||
            (!SSL_CTX_set_default_verify_paths(ctx)))
    {
        /* BIO_printf(bio_err,"error setting default verify locations\n"); */
        ERR_print_errors(bio_err);
        /* goto end; */
    }

    store = SSL_CTX_get_cert_store(ctx);
    X509_STORE_set_flags(store, vflags);

    con=SSL_new(ctx);
#ifndef OPENSSL_NO_KRB5
    if (con  &&  (con->kssl_ctx = kssl_ctx_new()) != NULL)
    {
        kssl_ctx_setstring(con->kssl_ctx, KSSL_SERVER, host);
    }
#endif	/* OPENSSL_NO_KRB5  */
    /*	SSL_set_cipher_list(con,"RC4-MD5"); */

re_start:

    if (init_client(&s,host,port,sock_type) == 0)
    {
        BIO_printf(bio_err,"connect:errno=%d\n",get_last_socket_error());
        SHUTDOWN(s);
        goto end;
    }
    BIO_printf(bio_c_out,"CONNECTED(%08X)\n",s);

#ifdef FIONBIO
    if (c_nbio)
    {
        unsigned long l=1;
        BIO_printf(bio_c_out,"turning on non blocking io\n");
        if (BIO_socket_ioctl(s,FIONBIO,&l) < 0)
        {
            ERR_print_errors(bio_err);
            goto end;
        }
    }
#endif
    if (c_Pause & 0x01) con->debug=1;

    if ( SSL_version(con) == DTLS1_VERSION)
    {
        struct timeval timeout;

        sbio=BIO_new_dgram(s,BIO_NOCLOSE);
        if (getsockname(s, &peer, (void *)&peerlen) < 0)
        {
            BIO_printf(bio_err, "getsockname:errno=%d\n",
                       get_last_socket_error());
            SHUTDOWN(s);
            goto end;
        }

        BIO_ctrl_set_connected(sbio, 1, &peer);

        if ( enable_timeouts)
        {
            timeout.tv_sec = 0;
            timeout.tv_usec = DGRAM_RCV_TIMEOUT;
            BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);

            timeout.tv_sec = 0;
            timeout.tv_usec = DGRAM_SND_TIMEOUT;
            BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout);
        }

        if ( mtu > 0)
        {
            SSL_set_options(con, SSL_OP_NO_QUERY_MTU);
            SSL_set_mtu(con, mtu);
        }
        else
            /* want to do MTU discovery */
            BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
    }
    else
        sbio=BIO_new_socket(s,BIO_NOCLOSE);



    if (nbio_test)
    {
        BIO *test;

        test=BIO_new(BIO_f_nbio_test());
        sbio=BIO_push(test,sbio);
    }

    if (c_debug)
    {
        con->debug=1;
        BIO_set_callback(sbio,bio_dump_callback);
        BIO_set_callback_arg(sbio,bio_c_out);
    }
    if (c_msg)
    {
        SSL_set_msg_callback(con, msg_cb);
        SSL_set_msg_callback_arg(con, bio_c_out);
    }

    SSL_set_bio(con,sbio,sbio);
    SSL_set_connect_state(con);

    /* ok, lets connect */
    width=SSL_get_fd(con)+1;

    read_tty=1;
    write_tty=0;
    tty_on=0;
    read_ssl=1;
    write_ssl=1;

    cbuf_len=0;
    cbuf_off=0;
    sbuf_len=0;
    sbuf_off=0;

    /* This is an ugly hack that does a lot of assumptions */
    if (starttls_proto == 1)
    {
        BIO_read(sbio,mbuf,BUFSIZZ);
        BIO_printf(sbio,"STARTTLS\r\n");
        BIO_read(sbio,sbuf,BUFSIZZ);
    }
    if (starttls_proto == 2)
    {
        BIO_read(sbio,mbuf,BUFSIZZ);
        BIO_printf(sbio,"STLS\r\n");
        BIO_read(sbio,sbuf,BUFSIZZ);
    }

    for (;;)
    {
        FD_ZERO(&readfds);
        FD_ZERO(&writefds);

        if (SSL_in_init(con) && !SSL_total_renegotiations(con))
        {
            in_init=1;
            tty_on=0;
        }
        else
        {
            tty_on=1;
            if (in_init)
            {
                in_init=0;
                print_stuff(bio_c_out,con,full_log);
                if (full_log > 0) full_log--;

                if (starttls_proto)
                {
                    BIO_printf(bio_err,"%s",mbuf);
                    /* We don't need to know any more */
                    starttls_proto = 0;
                }

                if (reconnect)
                {
                    reconnect--;
                    BIO_printf(bio_c_out,"drop connection and then reconnect\n");
                    SSL_shutdown(con);
                    SSL_set_connect_state(con);
                    SHUTDOWN(SSL_get_fd(con));
                    goto re_start;
                }
            }
        }

        ssl_pending = read_ssl && SSL_pending(con);

        if (!ssl_pending)
        {
#if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE)
            if (tty_on)
            {
                if (read_tty)  FD_SET(fileno(stdin),&readfds);
                if (write_tty) FD_SET(fileno(stdout),&writefds);
            }
            if (read_ssl)
                FD_SET(SSL_get_fd(con),&readfds);
            if (write_ssl)
                FD_SET(SSL_get_fd(con),&writefds);
#else
            if(!tty_on || !write_tty) {
                if (read_ssl)
                    FD_SET(SSL_get_fd(con),&readfds);
                if (write_ssl)
                    FD_SET(SSL_get_fd(con),&writefds);
            }
#endif
            /*			printf("mode tty(%d %d%d) ssl(%d%d)\n",
            				tty_on,read_tty,write_tty,read_ssl,write_ssl);*/

            /* Note: under VMS with SOCKETSHR the second parameter
             * is currently of type (int *) whereas under other
             * systems it is (void *) if you don't have a cast it
             * will choke the compiler: if you do have a cast then
             * you can either go for (int *) or (void *).
             */
#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
            /* Under Windows/DOS we make the assumption that we can
            * always write to the tty: therefore if we need to
            		 * write to the tty we just fall through. Otherwise
            		 * we timeout the select every second and see if there
            		 * are any keypresses. Note: this is a hack, in a proper
            		 * Windows application we wouldn't do this.
            		 */
            i=0;
            if(!write_tty) {
                if(read_tty) {
                    tv.tv_sec = 1;
                    tv.tv_usec = 0;
                    i=select(width,(void *)&readfds,(void *)&writefds,
                             NULL,&tv);
#if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS)
                    if(!i && (!_kbhit() || !read_tty) ) continue;
#else
                    if(!i && (!((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0))) || !read_tty) ) continue;
#endif
                } else 	i=select(width,(void *)&readfds,(void *)&writefds,
                                     NULL,NULL);
            }
#elif defined(OPENSSL_SYS_NETWARE)
            if(!write_tty) {
                if(read_tty) {
                    tv.tv_sec = 1;
                    tv.tv_usec = 0;
                    i=select(width,(void *)&readfds,(void *)&writefds,
                             NULL,&tv);
                } else 	i=select(width,(void *)&readfds,(void *)&writefds,
                                     NULL,NULL);
            }
#else
            i=select(width,(void *)&readfds,(void *)&writefds,
                     NULL,NULL);
#endif
            if ( i < 0)
            {
                BIO_printf(bio_err,"bad select %d\n",
                           get_last_socket_error());
                goto shut;
                /* goto end; */
            }
        }

        if (!ssl_pending && FD_ISSET(SSL_get_fd(con),&writefds))
        {
            k=SSL_write(con,&(cbuf[cbuf_off]),
                        (unsigned int)cbuf_len);
            switch (SSL_get_error(con,k))
            {
            case SSL_ERROR_NONE:
                cbuf_off+=k;
                cbuf_len-=k;
                if (k <= 0) goto end;
                /* we have done a  write(con,NULL,0); */
                if (cbuf_len <= 0)
                {
                    read_tty=1;
                    write_ssl=0;
                }
                else /* if (cbuf_len > 0) */
                {
                    read_tty=0;
                    write_ssl=1;
                }
                break;
            case SSL_ERROR_WANT_WRITE:
                BIO_printf(bio_c_out,"write W BLOCK\n");
                write_ssl=1;
                read_tty=0;
                break;
            case SSL_ERROR_WANT_READ:
                BIO_printf(bio_c_out,"write R BLOCK\n");
                write_tty=0;
                read_ssl=1;
                write_ssl=0;
                break;
            case SSL_ERROR_WANT_X509_LOOKUP:
                BIO_printf(bio_c_out,"write X BLOCK\n");
                break;
            case SSL_ERROR_ZERO_RETURN:
                if (cbuf_len != 0)
                {
                    BIO_printf(bio_c_out,"shutdown\n");
                    goto shut;
                }
                else
                {
                    read_tty=1;
                    write_ssl=0;
                    break;
                }

            case SSL_ERROR_SYSCALL:
                if ((k != 0) || (cbuf_len != 0))
                {
                    BIO_printf(bio_err,"write:errno=%d\n",
                               get_last_socket_error());
                    goto shut;
                }
                else
                {
                    read_tty=1;
                    write_ssl=0;
                }
                break;
            case SSL_ERROR_SSL:
                ERR_print_errors(bio_err);
                goto shut;
            }
        }
#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE)
        /* Assume Windows/DOS can always write */
        else if (!ssl_pending && write_tty)
#else
        else if (!ssl_pending && FD_ISSET(fileno(stdout),&writefds))
#endif
        {
#ifdef CHARSET_EBCDIC
            ascii2ebcdic(&(sbuf[sbuf_off]),&(sbuf[sbuf_off]),sbuf_len);
#endif
            i=write(fileno(stdout),&(sbuf[sbuf_off]),sbuf_len);

            if (i <= 0)
            {
                BIO_printf(bio_c_out,"DONE\n");
                goto shut;
                /* goto end; */
            }

            sbuf_len-=i;;
            sbuf_off+=i;
            if (sbuf_len <= 0)
            {
                read_ssl=1;
                write_tty=0;
            }
        }
        else if (ssl_pending || FD_ISSET(SSL_get_fd(con),&readfds))
        {
#ifdef RENEG
        { static int iiii; if (++iiii == 52) {
                    SSL_renegotiate(con);
                    iiii=0;
                }
            }
#endif
#if 1
            k=SSL_read(con,sbuf,1024 /* BUFSIZZ */ );
#else
            /* Demo for pending and peek :-) */
            k=SSL_read(con,sbuf,16);
            {   char zbuf[10240];
                printf("read=%d pending=%d peek=%d\n",k,SSL_pending(con),SSL_peek(con,zbuf,10240));
            }
#endif

            switch (SSL_get_error(con,k))
            {
            case SSL_ERROR_NONE:
                if (k <= 0)
                    goto end;
                sbuf_off=0;
                sbuf_len=k;

                read_ssl=0;
                write_tty=1;
                break;
            case SSL_ERROR_WANT_WRITE:
                BIO_printf(bio_c_out,"read W BLOCK\n");
                write_ssl=1;
                read_tty=0;
                break;
            case SSL_ERROR_WANT_READ:
                BIO_printf(bio_c_out,"read R BLOCK\n");
                write_tty=0;
                read_ssl=1;
                if ((read_tty == 0) && (write_ssl == 0))
                    write_ssl=1;
                break;
            case SSL_ERROR_WANT_X509_LOOKUP:
                BIO_printf(bio_c_out,"read X BLOCK\n");
                break;
            case SSL_ERROR_SYSCALL:
                BIO_printf(bio_err,"read:errno=%d\n",get_last_socket_error());
                goto shut;
            case SSL_ERROR_ZERO_RETURN:
                BIO_printf(bio_c_out,"closed\n");
                goto shut;
            case SSL_ERROR_SSL:
                ERR_print_errors(bio_err);
                goto shut;
                /* break; */
            }
        }

#if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
#if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS)
        else if (_kbhit())
#else
        else if ((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0)))
#endif
#elif defined (OPENSSL_SYS_NETWARE)
        else if (_kbhit())
#else
        else if (FD_ISSET(fileno(stdin),&readfds))
#endif
        {
            if (crlf)
            {
                int j, lf_num;

                i=read(fileno(stdin),cbuf,BUFSIZZ/2);
                lf_num = 0;
                /* both loops are skipped when i <= 0 */
                for (j = 0; j < i; j++)
                    if (cbuf[j] == '\n')
                        lf_num++;
                for (j = i-1; j >= 0; j--)
                {
                    cbuf[j+lf_num] = cbuf[j];
                    if (cbuf[j] == '\n')
                    {
                        lf_num--;
                        i++;
                        cbuf[j+lf_num] = '\r';
                    }
                }
                assert(lf_num == 0);
            }
            else
                i=read(fileno(stdin),cbuf,BUFSIZZ);

            if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q')))
            {
                BIO_printf(bio_err,"DONE\n");
                goto shut;
            }

            if ((!c_ign_eof) && (cbuf[0] == 'R'))
            {
                BIO_printf(bio_err,"RENEGOTIATING\n");
                SSL_renegotiate(con);
                cbuf_len=0;
            }
            else
            {
                cbuf_len=i;
                cbuf_off=0;
#ifdef CHARSET_EBCDIC
                ebcdic2ascii(cbuf, cbuf, i);
#endif
            }

            write_ssl=1;
            read_tty=0;
        }
    }
shut:
    SSL_shutdown(con);
    SHUTDOWN(SSL_get_fd(con));
    ret=0;
end:
    if(prexit) print_stuff(bio_c_out,con,1);
    if (con != NULL) SSL_free(con);
    if (con2 != NULL) SSL_free(con2);
    if (ctx != NULL) SSL_CTX_free(ctx);
    if (cert)
        X509_free(cert);
    if (key)
        EVP_PKEY_free(key);
    if (pass)
        OPENSSL_free(pass);
    if (cbuf != NULL) {
        OPENSSL_cleanse(cbuf,BUFSIZZ);
        OPENSSL_free(cbuf);
    }
    if (sbuf != NULL) {
        OPENSSL_cleanse(sbuf,BUFSIZZ);
        OPENSSL_free(sbuf);
    }
    if (mbuf != NULL) {
        OPENSSL_cleanse(mbuf,BUFSIZZ);
        OPENSSL_free(mbuf);
    }
    if (bio_c_out != NULL)
    {
        BIO_free(bio_c_out);
        bio_c_out=NULL;
    }
    apps_shutdown();
    OPENSSL_EXIT(ret);
}
示例#5
0
/* This is somewhat different to other ports: we have a main loop here:
 * a dedicated task that waits for packets to arrive. This would normally be
 * done from interrupt context with embedded hardware, but we don't get an
 * interrupt in windows for that :-) */
static void
main_loop(void)
{
#if !NO_SYS
  err_t err;
  sys_sem_t init_sem;
#endif /* NO_SYS */
#if USE_PPP
#if !USE_ETHERNET
  int count;
  u8_t rxbuf[1024];
#endif
  volatile int callClosePpp = 0;
#endif /* USE_PPP */

  /* initialize lwIP stack, network interfaces and applications */
#if NO_SYS
  lwip_init();
  test_init(NULL);
#else /* NO_SYS */
  err = sys_sem_new(&init_sem, 0);
  LWIP_ASSERT("failed to create init_sem", err == ERR_OK);
  tcpip_init(test_init, &init_sem);
  /* we have to wait for initialization to finish before
   * calling update_adapter()! */
  sys_sem_wait(&init_sem);
  sys_sem_free(&init_sem);
#endif /* NO_SYS */

#if (LWIP_SOCKET || LWIP_NETCONN) && LWIP_NETCONN_SEM_PER_THREAD
  netconn_thread_init();
#endif

  /* MAIN LOOP for driver update (and timers if NO_SYS) */
  while (!_kbhit()) {
#if NO_SYS
    /* handle timers (already done in tcpip.c when NO_SYS=0) */
    sys_check_timeouts();
#endif /* NO_SYS */

#if USE_ETHERNET
#if !PCAPIF_RX_USE_THREAD
    /* check for packets and link status*/
    pcapif_poll(&netif);
    /* When pcapif_poll comes back, there are not packets, so sleep to
       prevent 100% CPU load. Don't do this in an embedded system since it
       increases latency! */
    sys_msleep(1);
#else /* !PCAPIF_RX_USE_THREAD */
    sys_msleep(50);
#endif /* !PCAPIF_RX_USE_THREAD */
#else /* USE_ETHERNET */
    /* try to read characters from serial line and pass them to PPPoS */
    count = sio_read(ppp_sio, (u8_t*)rxbuf, 1024);
    if(count > 0) {
      pppos_input(ppp, rxbuf, count);
    } else {
      /* nothing received, give other tasks a chance to run */
      sys_msleep(1);
    }

#endif /* USE_ETHERNET */
#if USE_SLIPIF
    slipif_poll(&slipif1);
#if USE_SLIPIF > 1
    slipif_poll(&slipif2);
#endif /* USE_SLIPIF > 1 */
#endif /* USE_SLIPIF */
#if ENABLE_LOOPBACK && !LWIP_NETIF_LOOPBACK_MULTITHREADING
    /* check for loopback packets on all netifs */
    netif_poll_all();
#endif /* ENABLE_LOOPBACK && !LWIP_NETIF_LOOPBACK_MULTITHREADING */
#if USE_PPP
    {
    int do_hup = 0;
    if(do_hup) {
      ppp_close(ppp, 1);
      do_hup = 0;
    }
    }
    if(callClosePpp && ppp) {
      /* make sure to disconnect PPP before stopping the program... */
      callClosePpp = 0;
#if NO_SYS
      ppp_close(ppp, 0);
#else
      pppapi_close(ppp, 0);
#endif
      ppp = NULL;
    }
#endif /* USE_PPP */
  }

#if USE_PPP
    if(ppp) {
      u32_t started;
      printf("Closing PPP connection...\n");
      /* make sure to disconnect PPP before stopping the program... */
#if NO_SYS
      ppp_close(ppp, 0);
#else
      pppapi_close(ppp, 0);
#endif
      ppp = NULL;
      /* Wait for some time to let PPP finish... */
      started = sys_now();
      do
      {
#if USE_ETHERNET && !PCAPIF_RX_USE_THREAD
        pcapif_poll(&netif);
#else /* USE_ETHERNET && !PCAPIF_RX_USE_THREAD */
        sys_msleep(50);
#endif /* USE_ETHERNET && !PCAPIF_RX_USE_THREAD */
        /* @todo: need a better check here: only wait until PPP is down */
      } while(sys_now() - started < 5000);
    }
#endif /* USE_PPP */
#if (LWIP_SOCKET || LWIP_NETCONN) && LWIP_NETCONN_SEM_PER_THREAD
  netconn_thread_cleanup();
#endif
#if USE_ETHERNET
  /* release the pcap library... */
  pcapif_shutdown(&netif);
#endif /* USE_ETHERNET */
}
示例#6
0
int main(int argc, char *argv[])
{
    FMOD::System     *system  = 0;
    FMOD::Sound      *sound   = 0;
    FMOD::Channel    *channel = 0;
    FMOD_RESULT       result;
    int               count;
    bool              playing = false;
    int               key, numoutputplugins;
    unsigned int      version;
    unsigned int      handle;

    /*
        Create a System object and initialize.
    */
    result = FMOD::System_Create(&system);
    ERRCHECK(result);

    result = system->getVersion(&version);
    ERRCHECK(result);

    if (version < FMOD_VERSION)
    {
        printf("Error!  You are using an old version of FMOD %08x.  This program requires %08x\n", version, FMOD_VERSION);
        return 0;
    }

    /*
        Set the source directory for all of the FMOD plugins.
    */
#ifdef _WIN64
    result = system->setPluginPath("../../api/plugins/64bit");
#else    
    result = system->setPluginPath("../../api/plugins");
#endif    
    ERRCHECK(result);

    /*
        Load up an extra plugin that is not normally used by FMOD.
    */
#ifdef _WIN64
    result = system->loadPlugin("output_mp364.dll", 0, 0);
#else
    result = system->loadPlugin("output_mp3.dll", 0, 0);
#endif    
    if (result == FMOD_ERR_FILE_NOTFOUND)
    {
        /*
            If it isn't in the same directory, try for the plugin directory.
        */
#ifdef _WIN64
        result = system->loadPlugin("../plugin_dev/output_mp3/output_mp364.dll", 0, 0);
#else
        result = system->loadPlugin("../plugin_dev/output_mp3/output_mp3.dll", 0, 0);
#endif        
        ERRCHECK(result);
    }


    /*
        Display plugins
    */
    {
        int num;
        char name[256];

        printf("Codec plugins\n");
        printf("--------------\n");
        result = system->getNumPlugins(FMOD_PLUGINTYPE_CODEC, &num);
        ERRCHECK(result);
        for (count = 0; count < num; count++)
        {
            result = system->getPluginHandle(FMOD_PLUGINTYPE_CODEC, count, &handle);
            ERRCHECK(result);

            result = system->getPluginInfo(handle, 0, name, 256, 0);
            ERRCHECK(result);

            printf("%2d - %-30s", count + 1, name);

            if (count % 2)
            {
                printf("\n");
            }
        }
        printf("\n");
        if (count % 2)
        {
            printf("\n");
        }

        printf("DSP plugins\n");
        printf("--------------\n");
        result = system->getNumPlugins(FMOD_PLUGINTYPE_DSP, &num);
        ERRCHECK(result);
        for (count = 0; count < num; count++)
        {
            result = system->getPluginHandle(FMOD_PLUGINTYPE_DSP, count, &handle);
            ERRCHECK(result);

            result = system->getPluginInfo(handle, 0, name, 256, 0);
            ERRCHECK(result);

            printf("%2d - %-30s", count + 1, name);

            if (count % 2)
            {
                printf("\n");
            }
        }
        printf("\n");
        if (count % 2)
        {
            printf("\n");
        }

        printf("Output plugins\n");
        printf("--------------\n");
        result = system->getNumPlugins(FMOD_PLUGINTYPE_OUTPUT, &numoutputplugins);
        ERRCHECK(result);
        for (count = 0; count < numoutputplugins; count++)
        {
            result = system->getPluginHandle(FMOD_PLUGINTYPE_OUTPUT, count, &handle);
            ERRCHECK(result);

            result = system->getPluginInfo(handle, 0, name, 256, 0);
            ERRCHECK(result);

            printf("%2d - %-30s", count + 1, name);

            if (count % 2)
            {
                printf("\n");
            }
        }
        if (count % 2)
        {
            printf("\n");
        }
    }

    /*
        System initialization
    */
    printf("-----------------------------------------------------------------------\n");    // print driver names
    printf("Press a corresponding number for an OUTPUT PLUGIN to use or ESC to quit\n");

    do
    {
        key = _getch();
    } while (key != 27 && key < '1' && key > '0' + numoutputplugins);
    if (key == 27)
    {
        return 0;
    }
    
    result = system->getPluginHandle(FMOD_PLUGINTYPE_OUTPUT, key - '1', &handle);
    ERRCHECK(result);

    result = system->setOutputByPlugin(handle);
    ERRCHECK(result);

    int drivers;
    result = system->getNumDrivers(&drivers);
    ERRCHECK(result);

    result = system->init(32, FMOD_INIT_NORMAL, 0);
    ERRCHECK(result);

    result = system->createSound("../media/wave.mp3", FMOD_SOFTWARE | FMOD_CREATESTREAM, 0, &sound);
    ERRCHECK(result);

    printf("Press a key to play sound to output device.\n");

    result = system->playSound(FMOD_CHANNEL_FREE, sound, 0, &channel);
    ERRCHECK(result);

    /*
        Main loop.
    */
    do
    {
        unsigned int ms = 0;
        unsigned int lenms = 0;
        bool         paused = false;
        int          channelsplaying = 0;
        FMOD::Sound *currentsound = 0;

        system->update();

        playing = false;

        result = channel->isPlaying(&playing);
        if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
        {
            ERRCHECK(result);
        }

        result = channel->getPaused(&paused);
        if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
        {
            ERRCHECK(result);
        }

        result = channel->getPosition(&ms, FMOD_TIMEUNIT_MS);
        if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
        {
            ERRCHECK(result);
        }
       
        channel->getCurrentSound(&currentsound);
        if (currentsound)
        {
            result = currentsound->getLength(&lenms, FMOD_TIMEUNIT_MS);
            if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
            {
                ERRCHECK(result);
            }
        }

        system->getChannelsPlaying(&channelsplaying);

        printf("Time %02d:%02d:%02d/%02d:%02d:%02d : %s : Channels Playing %2d\r", ms / 1000 / 60, ms / 1000 % 60, ms / 10 % 100, lenms / 1000 / 60, lenms / 1000 % 60, lenms / 10 % 100, paused ? "Paused " : playing ? "Playing" : "Stopped", channelsplaying);

        Sleep(5);

        if (_kbhit())
        {
            key = _getch();
            if (key == 27)
            {
                break;
            }
        }

    } while (playing);

    printf("\n");

    /*
        Shut down
    */
    result = sound->release();
    ERRCHECK(result);
    result = system->close();
    ERRCHECK(result);
    result = system->release();
    ERRCHECK(result);

    return 0;
}
示例#7
0
int main(int argc, char *argv[])
{
    FMOD::Channel    *channel[2] = { 0,0 };
    FMOD_RESULT       result;
    int               key, outputrate, slot = 0, count, numdrivers;
    unsigned int      version;
    
    printf("=============================================================================\n");
    printf("Granular Synthesis SetDelay example.\n");
    printf("Copyright (c) Firelight Technologies 2004-2011.\n");
    printf("=============================================================================\n");
    printf("\n");
    printf("TOGGLE #define USE_STREAMS ON/OFF TO SWITCH BETWEEN STREAMS/STATIC SAMPLES.\n");
    printf("Press space to pause, Esc to quit\n");
    printf("\n");
    
    /*
        ===============================================================================================================
        RECOMMENDED STARTUP SEQUENCE BEGIN
        ===============================================================================================================
    */

    result = FMOD::System_Create(&gSystem);
    ERRCHECK(result);
    
    result = gSystem->getVersion(&version);
    ERRCHECK(result);

    if (version < FMOD_VERSION)
    {
        printf("Error!  You are using an old version of FMOD %08x.  This program requires %08x\n", version, FMOD_VERSION);
        return 0;
    }
    
    result = gSystem->getNumDrivers(&numdrivers);
    ERRCHECK(result);

    if (numdrivers == 0)
    {
        result = gSystem->setOutput(FMOD_OUTPUTTYPE_NOSOUND);
        ERRCHECK(result);
    }
    else
    {
        FMOD_CAPS caps;
        FMOD_SPEAKERMODE speakermode;
        char name[256];
        
        result = gSystem->getDriverCaps(0, &caps, 0, &speakermode);
        ERRCHECK(result);

        result = gSystem->setSpeakerMode(speakermode);       /* Set the user selected speaker mode. */
        ERRCHECK(result);

        if (caps & FMOD_CAPS_HARDWARE_EMULATED)             /* The user has the 'Acceleration' slider set to off!  This is really bad for latency!. */
        {                                                   /* You might want to warn the user about this. */
            result = gSystem->setDSPBufferSize(1024, 10);
            ERRCHECK(result);
        }

        result = gSystem->getDriverInfo(0, name, 256, 0);
        ERRCHECK(result);

        if (strstr(name, "SigmaTel"))   /* Sigmatel sound devices crackle for some reason if the format is PCM 16bit.  PCM floating point output seems to solve it. */
        {
            result = gSystem->setSoftwareFormat(48000, FMOD_SOUND_FORMAT_PCMFLOAT, 0,0, FMOD_DSP_RESAMPLER_LINEAR);
            ERRCHECK(result);
        }
    }

    result = gSystem->init(100, FMOD_INIT_NORMAL, 0);
    if (result == FMOD_ERR_OUTPUT_CREATEBUFFER)         /* Ok, the speaker mode selected isn't supported by this soundcard.  Switch it back to stereo... */
    {
        result = gSystem->setSpeakerMode(FMOD_SPEAKERMODE_STEREO);
        ERRCHECK(result);
            
        result = gSystem->init(100, FMOD_INIT_NORMAL, 0);/* ... and re-init. */
        ERRCHECK(result);
    }
    
    /*
        ===============================================================================================================
        RECOMMENDED STARTUP SEQUENCE END
        ===============================================================================================================
    */
        
    result = gSystem->getSoftwareFormat(&outputrate, 0,0,0,0,0);
    ERRCHECK(result);   
   
#if !defined(USE_STREAMS)
    for (count = 0; count < NUMSOUNDS; count++)
    {
        result = gSystem->createSound(soundname[count], FMOD_IGNORETAGS, 0, &sound[count]);
        ERRCHECK(result);
    }
#endif

    /*
        Kick off the first 2 sounds.  First one is immediate, second one will be triggered to start after the first one.
    */
    channel[slot] = queue_next_sound(outputrate, channel[1-slot], rand()%NUMSOUNDS, slot);
    slot = 1-slot;  /* flip */
    channel[slot] = queue_next_sound(outputrate, channel[1-slot], rand()%NUMSOUNDS, slot);
    slot = 1-slot;  /* flip */

    /*
        Main loop.
    */
    do
    {
        bool isplaying;
        static bool paused = false;

        if (_kbhit())
        {
            key = _getch();

            switch (key)
            {
                case ' ' :
                {
                    set_paused(channel, paused);
                    paused = !paused;
                    break;
                }
            }
        }

        gSystem->update();

        /*
            Replace the sound that just finished with a new sound, to create endless seamless stitching!
        */
        result = channel[slot]->isPlaying(&isplaying);
        if (!isplaying && !paused)
        {
            printf("sound %d finished, start a new one\n", slot);
            #ifdef USE_STREAMS
            /* 
                Release the sound that isn't playing any more. 
            */
            result = sound[slot]->release();       
            ERRCHECK(result);
            sound[slot] = 0;
            #endif
   
            /*
                Replace sound that just ended with a new sound, queued up to trigger exactly after the other sound ends.
            */
            channel[slot] = queue_next_sound(outputrate, channel[1-slot], rand()%NUMSOUNDS, slot);
            slot = 1-slot;  /* flip */
        }
        
        Sleep(10);  /* If you wait too long, ie longer than the length of the shortest sound, you will get gaps. */

    } while (key != 27);

    printf("\n");

    for (count = 0; count < sizeof(sound) / sizeof(sound[0]); count++)
    {
        if (sound[count])
        {
            sound[count]->release();
        }
    }
    
    /*
        Shut down
    */
    result = gSystem->release();
    ERRCHECK(result);

    return 0;
}
示例#8
0
文件: mc.c 项目: cheeryguo/BnR_MC
tEplKernel PUBLIC AppCbSync(void)
{
    tEplKernel          EplRet;

    EplRet = EplApiProcessImageExchange(&AppProcessImageCopyJob_g);
    if (EplRet != kEplSuccessful)
    {
        return EplRet;
    }

    uiCnt_g++;

#if 0
	static UINT uiDigitalModData = 1;
	int ch1;
	int ch2 = 0;
	static UINT uiCount = 0;
	static const UINT uiWait = 10;




	uiDigitalModData++;
	
	switch (AutoHome)
	{

		case 0:	//wait connection
		{	
			AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 0;

			if	(AppProcessImageOut_g.CN2_M00_OutChannel_REC_StatusWord != 0)
			{
				if ( ++uiCount > uiWait )
				{
					uiCount = 0;
					AutoHome = 1;
					printf("Connection complete\n");
				}
			}
		}
		break;

		case 1:	//auto error acknowledge
		{
			if	(AppProcessImageOut_g.CN2_M00_OutChannel_REC_ErrorCode != 0)	//check if error
			{
				if ( ++uiCount > uiWait )
				{
					uiCount = 0;

					AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 128;
					AutoHome = 0;
					printf("clear errors not complete\n");
				}
			}
			else	//no error
			{
				if ( ++uiCount > uiWait )
				{
					uiCount = 0;

					AutoHome = 2;
					printf("No errors complete\n");
				}
			}
		}
		break;

		case 2:	//shutdown
		{
			AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 6;

			if(AppProcessImageOut_g.CN2_M00_OutChannel_REC_StatusWord & 0x0001) // 0000000000000001 check ready to switch on
			{
				if ( ++uiCount > uiWait )
				{
					uiCount = 0;

					AutoHome = 3;
					printf("Shutdown complete\n");
				}
			}
		}
		break;

		case 3:	//switch on
		{
			AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 7;

			if(AppProcessImageOut_g.CN2_M00_OutChannel_REC_StatusWord & 0x0002) // 0000000000000010 check bit switched on
			{
				if ( ++uiCount > uiWait )
				{
					uiCount = 0;

					AutoHome = 4;
					printf("Switch on complete\n");
				}
			}
		}
		break;

		case 4:	//enable homing
		{
			AppProcessImageIn_g.CN2_M80_InputChannel_REC_ModesOfOperation = 6;
			AppProcessImageIn_g.CN2_M80_InputChannel_REC_HomingMethod = -128;
			AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 15;

			if(AppProcessImageOut_g.CN2_M00_OutChannel_REC_StatusWord & 0x0004) // 0000000000000100 check mode bit enabled
			{
				if ( ++uiCount > uiWait )
				{
					uiCount = 0;

					AutoHome = 5;
					printf("Enable homing complete\n");
				}
			}
		}
		break;

		case 5:	//start homing
		{
			AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 31;

			if(AppProcessImageOut_g.CN2_M00_OutChannel_REC_StatusWord & 0x3000) // 0011000000000000 check homing done
			{
				if ( ++uiCount > uiWait )
				{
					uiCount = 0;

					AutoHome = 6;
					printf("Start homing complete\n");
				}
			}
		}
		break;

		case 6:	//disable operation
		{
			AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 7;

			if(AppProcessImageOut_g.CN2_M00_OutChannel_REC_StatusWord & 0x0002) // 0000000000000010 check switched on
			{
				if ( ++uiCount > uiWait )
				{
					uiCount = 0;

					AutoHome = 10;
					printf("Auto homing complete\n");
				}
			}
		}
		break;

		case 10: //auto homing done
		{
			if (_kbhit())
			{
				ch1 = getchar();
				printf("%c", ch1);

				switch (ch1)
				{
					case '1':	//shutdown
					{
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 6;
						break;
					}
					case '2':	//switch on
					{
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 7;
						break;
					}
					case '3':	//enable homing operation
					{
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ModesOfOperation = 6;
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_HomingMethod = -128;
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 15;
						break;
					}
					case '4':	//home
					{
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 31;
						break;
					}
					case '5':	//disable operation
					{
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 7;
						break;
					}
					case '6':	//enable position move operation
					{
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ModesOfOperation = 1;
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 15;
						break;
					}
					case '7':	//new set point
					{
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 31;
						  AppProcessImageIn_g.CN2_M40_InputChannel_REC_TargetPosition = AppProcessImageIn_g.CN2_M40_InputChannel_REC_TargetPosition + 1000;
						  AppProcessImageIn_g.CN2_M80_InputChannel_REC_ProfileAcceleration = 5000;
						  AppProcessImageIn_g.CN2_M80_InputChannel_REC_ProfileDeceleration = 5000;
						  AppProcessImageIn_g.CN2_M80_InputChannel_REC_ProfileVelocity		= 1000;
						break;
					}
					case '8':	//new set point
					{
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 31;
						  AppProcessImageIn_g.CN2_M40_InputChannel_REC_TargetPosition = AppProcessImageIn_g.CN2_M40_InputChannel_REC_TargetPosition - 1000;
						  AppProcessImageIn_g.CN2_M80_InputChannel_REC_ProfileAcceleration = 5000;
						  AppProcessImageIn_g.CN2_M80_InputChannel_REC_ProfileDeceleration = 5000;
						  AppProcessImageIn_g.CN2_M80_InputChannel_REC_ProfileVelocity		= 1000;
						break;
					}

					case '9':	//enable profile velocity move operation
					{
						AppProcessImageIn_g.CN2_MC0_InputChannel_REC_Polarity = 0;
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ProfileAcceleration = 5000;
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ProfileDeceleration = 5000;
						AppProcessImageIn_g.CN2_M40_InputChannel_REC_TargetVelocity	= 5000;
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ModesOfOperation = 3;
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 15;
						break;
					}

					case '0':	//enable profile velocity move operation
					{
						AppProcessImageIn_g.CN2_MC0_InputChannel_REC_Polarity = 64;
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ProfileAcceleration = 5000;
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ProfileDeceleration = 5000;
						AppProcessImageIn_g.CN2_M40_InputChannel_REC_TargetVelocity	= 5000;
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ModesOfOperation = 3;
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 15;
						break;
					}

					case 'a':	//error reset
					{
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 128;
						break;
					}
					case 'b':	//error reset
					{
						AppProcessImageIn_g.CN2_M80_InputChannel_REC_ControlWord = 0;
						
						break;
					}
				}
			}
		}
		break;
	}

#endif

    return EplRet;
}
示例#9
0
void main(){
	int a,b,c,i,j,k;
	int y=8,g=0,g1,l=8,p=-1,n=1,n1=2,n2=3,z1=0,z=11;
	int f[112],s[112],d[112]={0},e[112]={0};
	for(i=0;++i<113;)f[i-1]=i%8<2|i>103?1:0;//マップデータの代入
while(1){
//キー入力
	if(g==0&&_kbhit()){
		k=(int)_getch();
		if(k==75)z-=f[z+l-1]|f[z-1]?0:1;//左
		if(k==77)z+=f[z+l+1]|f[z+1]?0:1;//右
		if(k==72)f[z]=n%4+2,f[z+l]=n/4+2,z1=0,g=1;//落下
		if(k==80){
			z+=y;
			if(f[z]|f[z+l])f[z-y]=n%4+2,f[z-y+l]=n/4+2,g=1,n=0;//フィールドにぷよ
		}//下
		if(k==122)z1=0,i=-p,p=l,l=i;//左回転
		if(k==120)z1=0,i=p,p=-l,l=i;//右回転
	}
//連鎖
	for(;g==1;){
		for(g=2,i=8;i<103;i++)
			if(f[i]==0&&f[i-8])f[i]=f[i-8],f[i-8]=0,g=1;//処理落下
	}
	
	if(g==2){
		g=3;
		for(i=103;i--;)d[i]=0;//調査リセット
		//全ぷよ調査
		for(i=103;i--;){
			for(a=103;a--;)e[a]=0;b=c=0,e[0]=i;//座標、カウンタリセット
			//周りを調べる
			for(;f[i]>1&&b>=c/4;){
				j=p,p=-l,l=j;//周りの座標
				j+=e[c/4];//調べる座標
				if(j<103)if(d[j]==0)if(f[i]==f[j]){
					e[++b]=j;//座標
					d[j]=1;//調査フラグ
				}
				c++;//カウント
			}
				if(c>16)for(g=4,g1=1;b;b--)f[e[b]]=0;//ぷよを消す
		}
	}
	if(g==3)l=8,p=-1,z=11,n=n1,n1=n2,n2=rand()%16,g=0;//連鎖が終了したらぷよ

//画面表示
	if(z-z1|g==4){
		for(i=0;i<112;i++)s[i]=f[i];//ステージにマップ
		if(g==0)s[z]=n%4+2,s[z+l]=n/4+2;//ステージにぷよ
		system("cls");
		for(i=0;i<112;i++){
			a=s[i];
			printf(a?a>1?a>2?a>3?a>4?"△":"×":"○":"□":"■":" ");
			
			if(i==7){
				a=n1%4+2;printf(a>2?a>3?a>4?"△":"×":"○":"□");
				a=n2%4+2;printf(a>2?a>3?a>4?"△":"×":"○":"□");
			}
			if(i==15){
				a=n1/4+2;printf(a>2?a>3?a>4?"△":"×":"○":"□");
				a=n2/4+2;printf(a>2?a>3?a>4?"△":"×":"○":"□");	
			}
			(i+1)%8||printf("\n");
		}if(g==4)_getch(),g=g1;
	}z1=z;

}}
示例#10
0
int main(int argc, char** argv) {

	EmoEngineEventHandle eEvent			= IEE_EmoEngineEventCreate();
	EmoStateHandle eState				= IEE_EmoStateCreate();
	unsigned int userID					= 0;
	const unsigned short composerPort	= 1726;
	int option = 0;
	int state  = 0;
	std::string input;

	try {

		if (argc != 2) {
            throw std::runtime_error("Please supply the log file name.\n"
                                     "Usage: EmoStateLogger [log_file_name].");
		}

        std::cout << "==================================================================="
                  << std::endl;
        std::cout << "Example to show how to log the EmoState from EmoEngine/EmoComposer."
                  << std::endl;
        std::cout << "==================================================================="
                  << std::endl;
        std::cout << "Press '1' to start and connect to the EmoEngine                    "
                  << std::endl;
        std::cout << "Press '2' to connect to the EmoComposer                            "
                  << std::endl;
		std::cout << ">> ";

		std::getline(std::cin, input, '\n');
		option = atoi(input.c_str());

		switch (option) {
        case 1:
        {
            if (IEE_EngineConnect() != EDK_OK) {
                throw std::runtime_error("Emotiv Driver start up failed.");
            }
            break;
        }
        case 2:
        {
            std::cout << "Target IP of EmoComposer? [127.0.0.1] ";
            std::getline(std::cin, input, '\n');

            if (input.empty()) {
                input = std::string("127.0.0.1");
            }

            if (IEE_EngineRemoteConnect(input.c_str(), composerPort) != EDK_OK) {
                std::string errMsg = "Cannot connect to EmoComposer on [" +
                                            input + "]";
                throw std::runtime_error(errMsg.c_str());
            }
            break;
        }
        default:
            throw std::runtime_error("Invalid option...");
            break;
		}
		
		
        std::cout << "Start receiving EmoState! Press any key to stop logging...\n"
                  << std::endl;

		std::ofstream ofs(argv[1]);
		bool writeHeader = true;
		
		while (!_kbhit()) {

			state = IEE_EngineGetNextEvent(eEvent);

			// New event needs to be handled
			if (state == EDK_OK) {

				IEE_Event_t eventType = IEE_EmoEngineEventGetType(eEvent);
				IEE_EmoEngineEventGetUserId(eEvent, &userID);

				// Log the EmoState if it has been updated
				if (eventType == IEE_EmoStateUpdated) {

					IEE_EmoEngineEventGetEmoState(eEvent, eState);
					const float timestamp = IS_GetTimeFromStart(eState);

                    printf("%10.3fs : New EmoState from user %d ...\r",
                           timestamp, userID);
					
					logEmoState(ofs, userID, eState, writeHeader);
					writeHeader = false;
				}
			}
			else if (state != EDK_NO_EVENT) {
				std::cout << "Internal error in Emotiv Engine!" << std::endl;
				break;
			}

#ifdef _WIN32
            Sleep(1);
#endif
#ifdef __linux__
            sleep(1);
#endif
		}

		ofs.close();
	}
    catch (const std::runtime_error& e) {
		std::cerr << e.what() << std::endl;
		std::cout << "Press any key to exit..." << std::endl;
		getchar();
	}

	IEE_EngineDisconnect();
	IEE_EmoStateFree(eState);
	IEE_EmoEngineEventFree(eEvent);

	return 0;
}
示例#11
0
int main(int argc, char *argv[])
{
    FMOD::EventSystem    *eventsystem = 0;
    FMOD::System         *system      = 0;

    void                 *project_mem = 0;
    unsigned int          project_len = 0;

    FMOD::Event          *sampleevent    = 0;
    FMOD::Sound          *samplebank     = 0;
    void                 *samplebank_mem = 0;
    unsigned int          samplebank_len = 0;

    FMOD::Event          *streamevent = 0;
    FMOD::Sound          *streambank  = 0;

    FMOD_RESULT           result = FMOD_OK;
    int                   key = 0;

    printf("======================================================================\n");
    printf("Load Event Data Example.  Copyright (c) Firelight Technologies 2004-2015.\n");
    printf("==============================-------=================================\n");
    printf("This Demonstrates loading all resources from memory allocated and filled\n");
    printf("by the user.\n");
    printf("======================================================================\n\n");
    
    /* Load FEV file into memory */
    loadFileIntoMemory("..\\media\\examples.fev", &project_mem, &project_len);

    ERRCHECK(result = FMOD::EventSystem_Create(&eventsystem));
    ERRCHECK(result = eventsystem->getSystemObject(&system));
    ERRCHECK(result = eventsystem->init(64, FMOD_INIT_NORMAL, 0, FMOD_EVENT_INIT_NORMAL));
    ERRCHECK(result = eventsystem->setMediaPath("..\\media\\"));

    /* we require a loadinfo struct to tell FMOD how big the in memory FEV file is */
    FMOD_EVENT_LOADINFO load_info;
    memset(&load_info, 0, sizeof(FMOD_EVENT_LOADINFO));
    load_info.size = sizeof(FMOD_EVENT_LOADINFO);
    load_info.loadfrommemory_length = project_len;

    /* load the project from memory */
    ERRCHECK(result = eventsystem->load((char*)project_mem, &load_info, NULL));

    printf("======================================================================\n");
    printf("Press 'e'        to load sample data\n");
    printf("Press 'E'        to unload sample data\n");
    printf("Press 'd'        to start sample event\n");
    printf("Press 'w'        to open stream\n");
    printf("Press 'W'        to close stream\n");
    printf("Press 's'        to start stream event\n");
    printf("Press ESC        to quit\n");
    printf("======================================================================\n");

    key = 0;
    do
    {
        if (_kbhit())
        {
            key = _getch();

            if (key == 'e')
            {
                /* Attempt to get the event without disk access */
                result = eventsystem->getEvent("examples/FeatureDemonstration/Basics/SimpleEvent", FMOD_EVENT_ERROR_ON_DISKACCESS, &sampleevent);
                if (result != FMOD_ERR_FILE_UNWANTED)
                {
                    ERRCHECK(result);
                }
                else
                {
                    /* file unwanted error tells us we haven't got the soundbank preloaded, so preload it now... */
                    printf("Loading event data\n");

                    loadFileIntoMemory("..\\media\\tutorial_bank.fsb", &samplebank_mem, &samplebank_len);

                    /* We need to create a FMOD::Sound object to use with preloadFSB */
                    FMOD_CREATESOUNDEXINFO info = {0};
                    info.cbsize = sizeof(FMOD_CREATESOUNDEXINFO);
                    info.length = samplebank_len;
                    ERRCHECK(result = system->createSound((char*)samplebank_mem, FMOD_OPENMEMORY_POINT | FMOD_CREATECOMPRESSEDSAMPLE, &info, &samplebank));

                    /* Tell FMOD that we have loaded this FSB */
                    ERRCHECK(result = eventsystem->preloadFSB("tutorial_bank.fsb", 0, samplebank));
                    
                    /* Now we can get the event without diskaccess */
                    ERRCHECK(result = eventsystem->getEvent("examples/FeatureDemonstration/Basics/SimpleEvent", FMOD_EVENT_ERROR_ON_DISKACCESS, &sampleevent));
                }                
                printf("Sample event ready\n");
            }
            else if (key == 'E')
            {
                if (!samplebank)
                {
                    printf("Nothing to unload\n");
                }
                else
                {
                    ERRCHECK(result = sampleevent->stop());
                    sampleevent = 0;
                    /* Note: we *MUST* call unload before freeing data */
                    ERRCHECK(result = eventsystem->unloadFSB("tutorial_bank.fsb", 0));
                    ERRCHECK(result = samplebank->release());
                    samplebank = 0;
                    if (samplebank_mem)
                    {
                        free(samplebank_mem);
                        samplebank_mem = 0;
                    }
                    printf("Event data unloaded\n");
                }
            }
            else if (key == 'd')
            {
                if (!sampleevent)
                {
                    printf("no event loaded!\n");
                }
                else
                {
                    ERRCHECK(result = sampleevent->start());
                }
            }
            else if (key == 'w')
            {   
                /* Attempt to get the event without opening a new stream */
                result = eventsystem->getEvent("examples/AdvancedTechniques/MultiChannelMusic", FMOD_EVENT_ERROR_ON_DISKACCESS, &streamevent);
                if (result != FMOD_ERR_FILE_UNWANTED)
                {
                    ERRCHECK(result);
                }
                else
                {
                    /*  file unwanted error tells us we haven't got the stream instance preloaded so preload it now */
                    printf("Opening stream\n");

                    /* If the 'Max Streams' property of the sound bank is greater than 1 then mutiple streams can be opened. This means we need
                       to preload it multiple times if we want to prevent FMOD from creating streams internally. Each stream is uniquely identified
                       using the 'streaminstance' parameter to preloadFSB which counts upwards from 0.
                    */
                    ERRCHECK(result = system->createSound("..\\media\\streaming_bank.fsb", FMOD_CREATESTREAM, 0, &streambank));
                    ERRCHECK(result = eventsystem->preloadFSB("streaming_bank.fsb", 0, streambank));
                    
                    /* Now we can get the event without opening a new stream */
                    ERRCHECK(result = eventsystem->getEvent("examples/AdvancedTechniques/MultiChannelMusic", FMOD_EVENT_ERROR_ON_DISKACCESS, &streamevent));
                }
                
                printf("Stream event ready\n");
            }
            else if (key == 'W')
            {
                if (!streambank)
                {
                    printf("Nothing to unload\n");
                }
                else
                {
                    ERRCHECK(result = streamevent->stop());
                    streamevent = 0;
                    /* Note: we *MUST* call unload before releasing stream */
                    ERRCHECK(result = eventsystem->unloadFSB("streaming_bank.fsb", 0));
                    ERRCHECK(result = streambank->release());
                    streambank = 0;
                    printf("Stream closed\n");
                }
            }
            else if (key == 's')
            {
                if (!streamevent)
                {
                    printf("no event loaded!\n");
                }
                else
                {
                    ERRCHECK(result = streamevent->start());
                }
            }
        }

        ERRCHECK(result = eventsystem->update());
        Sleep(15);

    } while (key != 27);
    
    if (samplebank)
    {
        /* Note: we *MUST* call unload before freeing data */
        ERRCHECK(result = eventsystem->unloadFSB("tutorial_bank.fsb", 0));
        ERRCHECK(result = samplebank->release());

        if (samplebank_mem)
        {
            free(samplebank_mem);
        }
    }
    
    if (streambank)
    {
        /* Note: we *MUST* call unload before releasing stream */
        ERRCHECK(result = eventsystem->unloadFSB("streaming_bank.fsb", 0));
        ERRCHECK(result = streambank->release());
    }

    ERRCHECK(result = eventsystem->release());

    /* Free the memory we have allocated */
    free(project_mem);

    return 0;
}
示例#12
0
// To read the console input in a non-blocking way
void GetUserInput(Game& game)
{
	if (_kbhit())
		game.c = _getch();
}
示例#13
0
文件: CELL_MY.CPP 项目: pyal/eos_cpp
void main( int argc, char *argv[] )
  {
argc--;
cout<<" Coreleft "<<Coreleft()<<"\n";
//   char tmp[50];
   if ((argc<2) || (GetCmd("/h",argc,argv)!=NULL))
     { cout<<"usage:\n"<<argv[0]<<"  in_lmethod  output_file\n"<<
           "      /h - display help\n"; exit(1);  }
   my_file=new fstream(argv[2],ios::out);


   int FstIter=0;
   double TimeStp,EndTime,CurTime=0,TimeWrite,PresDerivCoef;
   RegionIO *Reg=GetRegion(argv[1],*my_file,FstIter,
			               CurTime,TimeStp,TimeWrite,PresDerivCoef,EndTime); 

   if (argc>2) CoefUp=max(1,atoi(argv[3]));else CoefUp=1;
   ClcMass(*Reg);
   int x=1;

   double CurStp,OldTimeWrite,NewTimeWrite,PresDeriv=1,OldStp=1e5;
   int BreakSignal=0;
//#ifdef WCPP
   double elapsed_time;
   clock_t start, finish;start=clock();
//#endif

   while ((!(CurTime>=EndTime)) && (!BreakSignal))
     {
  	  OldTimeWrite=CurTime;
	  NewTimeWrite=min(OldTimeWrite+TimeWrite/(1+PresDeriv*PresDerivCoef),EndTime);
//cout<<" Before While NewTime "<<NewTimeWrite<<"\n";
        while ((!(CurTime>=NewTimeWrite)) && (!BreakSignal))
        {
 	     NewTimeWrite=min(OldTimeWrite+
		              TimeWrite/(1+PresDeriv*PresDerivCoef),EndTime);
		 if (x<100) {x++;CurStp=0.5*log10(x)*TimeStp;}
		 else CurStp=TimeStp;
		 if (CurStp+CurTime>NewTimeWrite) CurStp=NewTimeWrite-CurTime;
		 if (CurStp<MathZer) break;
         if (CurStp>OldStp) CurStp=OldStp*(CoefUp*log(CurStp/OldStp)+1);
         OldStp=CurStp;
//cout<<" CurStp "<<CurStp<<" CurTime "<<CurTime<<"\n";
//ChRead();
         if ((x==2) && (FstIter)) CalcPos(*Reg,-0.5*CurStp,TimeStp); // Exracted? 
//cout<<" StepRegion \n";
         CurTime+=CurStp;StepRegion(*Reg,CurStp,TimeStp,PresDeriv);
//         if (i++==10) {i=0;Reconstruct(*Reg);}
//      Reg.SaveIni(output);

		}
	OutHead(*my_file,*Reg,CurTime,TimeStp,TimeWrite,PresDerivCoef,EndTime);
cout<<" Write !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1\n";
cout<<" CurStp "<<CurStp<<" CurTime "<<CurTime<<"\n";cout.flush();
#ifdef WCPP
		 if (_kbhit()) { BreakSignal=_getch();if (BreakSignal==ESC) break;}
#else
         while ((BreakSignal=bioskey(1))!=0) if (BreakSignal==ESC) break;else {cout<<" "<<BreakSignal;bioskey(0);}
#endif
     }
//#ifdef WCPP
  finish=clock();elapsed_time=(finish-start);//CLK_TCK;
cout<<" RunTime "<<elapsed_time<<"\n";
//#endif
//cout<<" Reg.InterfaceIODelete();  \n";
cout<<" Coreleft "<<Coreleft()<<"\n";
    Reg->InterfaceIODelete();
	my_file->close();
cout<<" Coreleft "<<Coreleft()<<"\n";
  };
 bool keyboard_hit(){
     return _kbhit() != 0;
 }
示例#15
0
/*void UpdateCmd()
{
	::Sleep(100);
		if ((_getch() == 'c' || _getch() == 'C') && !isInput)
	  {
		  isInput = true;
		  char n[512];
		  scanf("%s",&n);
		  isInput = false;
		  r3dOutToLog("cmd :%s\n",n);
	  }
}*/
int main(int argc, char* argv[])
{
  extern int _r3d_bLogToConsole;
  _r3d_bLogToConsole = 1;
  
  extern int _r3d_bSilent_r3dError;
  _r3d_bSilent_r3dError = 1;
  
  extern int _r3d_Network_DoLog;
  _r3d_Network_DoLog = 0;

  r3d_CurrentProcess = GetCurrentProcess();
  SetConsoleCtrlHandler(ConsoleHandlerRoutine, TRUE);
  
  win::hInstance = GetModuleHandle(NULL);

  // change log file now and install handler, so we'll record r3dErrors
  {  
    _mkdir("logms");
    time_t t1;
    time(&t1);
    char fname[MAX_PATH];
    sprintf(fname, "logms\\MS_%x.txt", (DWORD)t1);
    extern void r3dChangeLogFile(const char* fname);
    r3dChangeLogFile(fname);

    sprintf(fname, "logms\\MS_%x.dmp", (DWORD)t1);
    SrvSetCrashHandler(fname);
  }
  
  try
  {
    serverCreateTempD3DWindow();
    ClipCursor(NULL);
    
    moveWindowToCorner();

    gServerConfig = new CMasterServerConfig();

    // from SF config.cpp, bah.
    //extern void RegisterAllVars();
    //RegisterAllVars();
    //r3dOutToLog("API: %s\n", g_api_ip->GetString());
    
//	AllocConsole();
	//isInput = false;
	//CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) UpdateCmd, NULL, 0, NULL);
    gMasterGameServer.Start(gServerConfig->masterPort_, gServerConfig->serverId_);
    gMasterUserServer.Start(gServerConfig->clientPort_, gServerConfig->masterCCU_);
    gUdpMonitor.Start(SBNET_MASTER_WATCH_PORT);

    r3dStartFrame();
    while(1) 
    {
      r3dEndFrame();
      r3dStartFrame();
      
      Sleep(1);

      gMasterGameServer.Tick();
      gMasterUserServer.Tick();
      gUdpMonitor.Tick();


      if(_kbhit()) {
        int k1 = _getch();
        
         

        // weird way to check for F4 (two symbols - 0, 62)
        if(k1 == 0 && _kbhit()) {
          if(_getch() == 62) {
            gMasterGameServer.RequestShutdown();
          }
        }
        
        if(k1 == 'r' || k1 == 'R') {
          r3dOutToLog("-- reloading games configuration\n");
          gServerConfig->LoadConfig();
        }

        if(k1 == 'd' || k1 == 'D') {
          gMasterUserServer.Temp_Debug1();
		}

      }

      // gracefully shutdown if requested
      if(gMasterGameServer.shuttingDown_ && gMasterGameServer.shutdownLeft_ < 0) {
	  extern void killProcessByName(const char *filename);
        r3dOutToLog("Shutting down...\n");
        break;
      }
	 
	}
  } 
  catch(const char* what)
  {
    r3dOutToLog("!!! Exception: %s\n", what);
    what = what;
    HRESULT res = TerminateProcess(r3d_CurrentProcess, 0);
  }
  
  gMasterUserServer.Stop();
  gMasterGameServer.Stop();
  gUdpMonitor.Stop();
  
  DestroyWindow(win::hWnd);
  HRESULT res = TerminateProcess(r3d_CurrentProcess, 0);

  return 0;
}
示例#16
0
文件: Source.cpp 项目: chari8/Tetris
int main() {

	//set window 
	BOOL bRtn;
	HANDLE hand;
	CONSOLE_SCREEN_BUFFER_INFO info;
	COORD dwCoord = { 100, 40 };
	SMALL_RECT rctWindowRect = { 0, 0, 30, 35 };

	hand = GetStdHandle(STD_OUTPUT_HANDLE);
	bRtn = SetConsoleScreenBufferSize(hand, dwCoord);
	bRtn = SetConsoleWindowInfo(hand, TRUE, &rctWindowRect);

	//initialization
	t = time(NULL);
	buff = false;
	memset(field, 0, sizeof(field)); // initialize field
	
	//use ASCII art to count down
	system("cls");
	int i = 3;
	while (i > 0) {
		if (t != time(NULL)) {
			system("cls");
			for (int j = 0; j < ASCII_HEIGHT; j++) {
				for (int k = 0; k < ASCII_WIDTH; k++)
					printf(ASCII[i - 1][j][k] ? "■" : " ");
				printf("\n");
			}
			i--;
			t = time(NULL);
		}
	}


	//prepare frame
	for (int i = 0; i < FIELD_HEIGHT; i++)
		field[i][0] = field[i][FIELD_WIDTH - 1] = 1;

	for (int i = 0; i < FIELD_HEIGHT; i++)
		field[FIELD_HEIGHT - 1][i] = 1;
	resetMino();


	while (1) {
		if (_kbhit()) {
			switch (_getch()) {
			case 0x1b: //hit esc to exit
				return 0;
			case 0x20: //hit space to restart
				main();
				return 0; //end old game
			case 'j':
				if (!isHit(
					minoX,
					minoY + 1,
					minoType,
					minoAngle))
					minoY++;
				break;
			case 'h':
				if (!isHit(
					minoX - 1,
					minoY,
					minoType,
					minoAngle))
					minoX--;
				break;
			case 'l':
				if (!isHit(
					minoX + 1,
					minoY,
					minoType,
					minoAngle))
					minoX++;
				break;
			case 'k':
				if (!isHit(
					minoX,
					minoY,
					minoType,
					(minoAngle + 1) % MINO_ANGLE_MAX))
					minoAngle = (minoAngle + 1) % MINO_ANGLE_MAX;
				break;
			case 'r':
				if (!isHit(
					minoX,
					minoY,
					minoType,
					minoAngle))
					store();
				break;
			}
			display();
		}
		if (t != time(NULL)) {
			t = time(NULL);
			if (isHit(minoX, minoY + 1, minoType, minoAngle))
			{
				for (int i = 0; i < MINO_HEIGHT; i++)
					for (int j = 0; j < MINO_WIDTH; j++)
						//if mino hit the block beneath it, fix it as a field
						field[minoY + i][minoX + j] |= minoShapes[minoType][minoAngle][i][j];
				for (int i = 0; i < FIELD_HEIGHT - 1; i++) {
					bool lineFill = true;
					for (int j = 0; j < FIELD_WIDTH - 1; j++) {
						if (!field[i][j])
							lineFill = false;
					}

					if (lineFill) {

						for (int j = i; 0 < j; j--)
							memcpy(field[j], field[j - 1], FIELD_WIDTH);
					}
				}
				resetMino();
			}
			else
				minoY++;
			display();
		}
	}

	return 0;
}
示例#17
0
void update_menu(data_t *data)
{
    int redraw = 0;

    if(data->menu_current < 0) {
        /* Print the menu and select the first entry on startup */
        data->menu_current = 0;
        redraw = 1;
    }

    if(_kbhit())
    {
        /* Handling of keyboard-events */
        redraw = 1;
        switch(_getch())
        {
        case 0x0D:
            action(data, ACTION_INVOKE);
            break;
        case 0xE0:
            switch(_getch())
            {
            case 0x48: // Up Arrow
                data->menu_current =
                        (MENU_SIZE + data->menu_current - 1) % MENU_SIZE;
                break;
            case 0x50: // Down Arrow
                data->menu_current = (data->menu_current + 1) % MENU_SIZE;
                break;
            case 0x4b: // Left Arrow
                action(data, ACTION_DECREASE);
                break;
            case 0x4d: // Right Arrow
                action(data, ACTION_INCREASE);
                break;
            }
            break;
        }
        while(_kbhit())
            _getch();
    }

    if(redraw)
    {
        /* Print the current state of the menu */
        gotoxy(0, 14);
        printf("%c Calibration:     %s\n",
               data->menu_current == MENU_AUTO_CALIB ? '>' : ' ',
               data->auto_calib ? "Automatic" : "Manual   ");
        printf("%c Calibrate Now\n",
               data->menu_current == MENU_CALIBRATE ? '>' : ' ');
        printf("%c Touch Detection: %s\n",
               data->menu_current == MENU_TOUCH_DETECT ? '>' : ' ',
               data->touch_detect ? "Enabled " : "Disabled");
        printf("%c Air Wheel:       %s\n",
               data->menu_current == MENU_AIR_WHEEL ? '>' : ' ',
               data->air_wheel ? "Enabled " : "Disabled");
        printf("%c Quit\n",
               data->menu_current == MENU_QUIT ? '>' : ' ');
    }
}
示例#18
0
文件: main.c 项目: chandonnet/FTB2015
int main(int argc, char *argv[])
{
    FMOD_RESULT        result;
    FMOD_EVENTSYSTEM  *eventsystem;
    FMOD_EVENTGROUP   *eventgroup;
    FMOD_EVENT        *event;
    int                key;

    enum
    {
        StealOldest,
        StealNewest,
        StealQuietest,
        JustFail,
        JustFailIfQuietest
    } event_behaviour = StealOldest;

    ERRCHECK(result = FMOD_EventSystem_Create(&eventsystem));
    ERRCHECK(result = FMOD_EventSystem_Init(eventsystem, 64, FMOD_INIT_NORMAL, 0, FMOD_EVENT_INIT_NORMAL));
    ERRCHECK(result = FMOD_EventSystem_SetMediaPath(eventsystem, (char *)MEDIA_PATH));
    ERRCHECK(result = FMOD_EventSystem_Load(eventsystem, "examples.fev", 0, 0));
    ERRCHECK(result = FMOD_EventSystem_GetGroup(eventsystem, "examples/FeatureDemonstration/MaxPlayback", FMOD_EVENT_DEFAULT, &eventgroup));
    ERRCHECK(result);

    printf("======================================================================\n");
    printf("Max Playbacks Example.  Copyright (c) Firelight Technologies 2004-2014.\n");
    printf("----------------------------------------------------------------------\n");
    printf("Press '1'   to select 'Steal oldest' behaviour\n");
    printf("Press '2'   to select 'Steal newest' behaviour\n");
    printf("Press '3'   to select 'Steal quietest' behaviour\n");
    printf("Press '4'   to select 'Just fail' behaviour\n");
    printf("Press '5'   to select 'Just fail if quietest' behaviour\n");
    printf("Press Space to start an event\n");
    printf("Press 's'   to stop all events\n");
    printf("Press '>'   to increase event distance\n");
    printf("Press '<'   to decrease event distance\n");
    printf("Press ESC to quit\n");
    printf("======================================================================\n");

    key = 0;
    do
    {
        if (_kbhit())
        {
            char *name;
            key = _getch();

            switch(key)
            {
                case '1' : // 'Steal oldest'
                    event_behaviour = StealOldest;
                    stopAllEvents(eventgroup);
                    break;

                case '2' : // 'Steal newest'
                    event_behaviour = StealNewest;
                    stopAllEvents(eventgroup);
                    break;

                case '3' : // 'Steal quietest'
                    event_behaviour = StealQuietest;
                    stopAllEvents(eventgroup);
                    break;

                case '4' : // 'Just fail'
                    event_behaviour = JustFail;
                    stopAllEvents(eventgroup);
                    break;

                case '5' : // 'Just fail if quietest'
                    event_behaviour = JustFailIfQuietest;
                    stopAllEvents(eventgroup);
                    break;

                case ' ' : // Play an event

                    switch(event_behaviour)
                    {
                        case StealOldest :
                            name = "MaxPlay-StealOldest";
                            break;

                        case StealNewest :
                            name = "MaxPlay-StealNewest";
                            break;

                        case StealQuietest :
                            name = "MaxPlay-StealQuietest";
                            break;

                        case JustFail :
                            name = "MaxPlay-JustFail";
                            break;

                        case JustFailIfQuietest :
                            name = "MaxPlay-JustFailIfQuietest";
                            break;
                    }

                    // Clear the line
                    printf("%79s\r", " ");

                    if (event_behaviour == JustFailIfQuietest)
                    {
                        /* The 'Just fail if quietest' behaviour calculates the expected
                           volume of the event based on the properties of the info-only
                           event, so we have to get the info-only event first and set it
                           up appropriately.
                         */

                        // get the info-only event to set up for volume calculation
                        ERRCHECK(result = FMOD_EventGroup_GetEvent(eventgroup, name, FMOD_EVENT_INFOONLY, &event));

                        /* set the desired properties on the info-only event
                           Notes:
                           - distances below the event's 3D Min Distance all give the
                             same volume; in this case, getEvent will just fail
                           - we could set other volume-affecting properties here as
                             well (e.g. orientation if the event has a falloff cone)
                         */
                        setupEvent(event);

                        // attempt to get a real event instance
                        result = FMOD_EventGroup_GetEvent(eventgroup, name, FMOD_EVENT_DEFAULT, &event);
                        if (result == FMOD_OK)
                        {
                            FMOD_EVENTPARAMETER *param;

                            printf("getEvent(\"%s\") succeeded\n", name);

                            /* we don't need to set the position of the instance,
                               as it is copied from the info-only event, but we
                               do need to set the parameter value.
                             */
                            ERRCHECK(result = FMOD_Event_GetParameter(event, "sound", &param));
                            ERRCHECK(result = FMOD_EventParameter_SetValue(param, g_sound));
                            ERRCHECK(result = FMOD_Event_Start(event));
                        }
                        else
                        {
                            printf("getEvent(\"%s\") failed\n", name);
                        }
                    }
                    else
                    {
                        result = FMOD_EventGroup_GetEvent(eventgroup, name, FMOD_EVENT_DEFAULT, &event);
                        if (result == FMOD_OK)
                        {
                            printf("getEvent(\"%s\") succeeded\n", name);
                            setupEvent(event);
                            ERRCHECK(result = FMOD_Event_Start(event));
                        }
                        else
                        {
                            printf("getEvent(\"%s\") failed\n", name);
                        }
                    }

                    ++g_sound;
                    if(g_sound > 3)
                    {
                        g_sound = 0;
                    }

                    break;

                case 's' :
                    stopAllEvents(eventgroup);
                    break;

                case '>' : case '.' :
                    g_distance += 0.1f;
                    break;

                case '<' : case ',' :
                    g_distance -= 0.1f;
                    g_distance = (g_distance < 0.0f) ? 0.0f : g_distance;
                    break;
            }


            switch(event_behaviour)
            {
                case StealOldest:
                    name = "Steal oldest";
                    break;

                case StealNewest:
                    name = "Steal newest";
                    break;

                case StealQuietest:
                    name = "Steal quietest";
                    break;

                case JustFail:
                    name = "Just fail";
                    break;

                case JustFailIfQuietest:
                    name = "Just fail if quietest";
                    break;
            }

            printf("Sound = %1.0f, Distance = %4.1f, Behaviour = %-25s\r", g_sound, g_distance, name);
        }

        ERRCHECK(result = FMOD_EventSystem_Update(eventsystem));
        Sleep(10);

    } while (key != 27);

    ERRCHECK(result = FMOD_EventSystem_Unload(eventsystem));
    ERRCHECK(result = FMOD_EventSystem_Release(eventsystem));
    return 0;
}
示例#19
0
文件: main.cpp 项目: 89grad/Fish-Game
int main(int argc, char ** argv)
{
  AllocateAllGlobals();
  init_eventsocket("EVENT_SERVER_IP",8000);

  
  // Initialize the point tracker
  XnStatus rc = g_pSessionManager->Initialize(&g_Context, "Wave", "RaiseHand");
  if (rc != XN_STATUS_OK)
    {
      printf("Couldn't initialize the Session Manager: %s\n", xnGetStatusString(rc));
      CleanupExit();
    }
  g_pSessionManager->RegisterSession(NULL, &SessionStart, &SessionEnd);

  // init & register wave control
  XnVWaveDetector wc;
  wc.RegisterWave(NULL, OnWaveCB);
  g_pSessionManager->AddListener(&wc);
  
  // Add TrackPad to the point tracker
  g_TrackPadHandle = g_pSessionManager->AddListener(g_pTrackPad);
  
  // Register for the Hover event of the TrackPad
  g_nItemHoverHandle = g_pTrackPad->RegisterItemHover(NULL, &TrackPad_ItemHover);
  // Register for the Value Change event of the TrackPad
  g_nValueChangeHandle = g_pTrackPad->RegisterValueChange(NULL, &TrackPad_ValueChange);
  // Register for the Select event of the TrackPad
  g_nItemSelectHandle = g_pTrackPad->RegisterItemSelect(NULL, &TrackPad_ItemSelect);
  
  // Register for Input Start event of the TrackPad
  g_nPrimaryCreateHandle = g_pTrackPad->RegisterPrimaryPointCreate(NULL, &TrackPad_PrimaryCreate);
  // Register for Input Stop event of the TrackPad
  g_nPrimaryDestroyHandle = g_pTrackPad->RegisterPrimaryPointDestroy(NULL, &TrackPad_PrimaryDestroy);

  // Start catching signals for quit indications
  CatchSignals(&g_bQuit);

  
  
#ifdef USE_GLUT
  
  glInit(&argc, argv);
  glutMainLoop();
  
#else
  
  
  if (!opengles_init(GL_WIN_SIZE_X, GL_WIN_SIZE_Y, &display, &surface, &context))
    {
      printf("Error initing opengles\n");
      CleanupExit();
    }
  
  glDisable(GL_DEPTH_TEST);
  //	glEnable(GL_TEXTURE_2D);
  glEnableClientState(GL_VERTEX_ARRAY);
  glDisableClientState(GL_COLOR_ARRAY);
  
  while ((!_kbhit()) && (!g_bQuit))
    {
      glutDisplay();
      eglSwapBuffers(display, surface);
    }
  
  opengles_shutdown(display, surface, context);
  
  CleanupExit();
  
  
#endif
}
示例#20
0
int CLobbyApp::Run()
{
  const DWORD c_dwUpdateInterval = 200; // milliseconds
  DWORD dwSleep = c_dwUpdateInterval;
  DWORD dwWait = WAIT_TIMEOUT;
  InitializeCriticalSectionAndSpinCount(&HttpCriticalSection, 0x00000400);
  InitializeCriticalSectionAndSpinCount(GetLogonCS(), 0x00000400);
  m_plas->LogEvent(EVENTLOG_INFORMATION_TYPE, LE_Running);
  puts("---------Press Q to exit---------");
   printf("Ready for clients/servers.\n");
  CTempTimer timerIterations("between iterations", .25f);
  timerIterations.Start();
  CTempTimer timerReceiveClientsMessages("in clients ReceiveMessages()", .05f);
  CTempTimer timerReceiveServersMessages("in servers ReceiveMessages()", .05f);
  Time timeLastQueueCheck = Time::Now();
  Time timeLastGameInfo = Time::Now();

  while (true)
  {
    timerIterations.Stop();
    timerIterations.Start();

    if (ProcessMsgPump() || (_kbhit() && toupper(_getch()) == 'Q')) {
		//Imago #111 7/10
		if(g_pAutoUpdate)
		{ 
			char szFileName[MAX_PATH+16];
			strcpy(szFileName, _Module.GetModulePath());
			Strcat(szFileName, "FileList.txt");
			g_pAutoUpdate->LoadCRC(szFileName);
			FedMessaging * pfm = &g_pLobbyApp->GetFMClients();
			int count = pfm->GetConnectionCount();
			ListConnections::Iterator iterCnxn(*pfm->GetConnections());
			while (!iterCnxn.End()) {
				BEGIN_PFM_CREATE(*pfm, pfmAutoUpdate, L, AUTO_UPDATE_INFO)
				  FM_VAR_PARM(g_pAutoUpdate->GetFTPServer(), CB_ZTS)
				  FM_VAR_PARM(g_pAutoUpdate->GetFTPInitialDir(), CB_ZTS)
				  FM_VAR_PARM(g_pAutoUpdate->GetFTPAccount(), CB_ZTS)
				  FM_VAR_PARM(g_pAutoUpdate->GetFTPPassword(), CB_ZTS)
				END_PFM_CREATE
				pfmAutoUpdate->crcFileList = g_pAutoUpdate->GetFileListCRC();
				pfmAutoUpdate->nFileListSize = g_pAutoUpdate->GetFileListSize();
				pfm->SendMessages(iterCnxn.Value(), FM_GUARANTEED, FM_FLUSH);
				iterCnxn.Next();
			}
		}
      return 0;
	}

    SetNow();

    m_pCounters->timeInnerLoop = timerIterations.LastInterval();

    // receive any messages in the queue
    timerReceiveClientsMessages.Start();
    m_fmClients.ReceiveMessages();
    timerReceiveClientsMessages.Stop();

    timerReceiveServersMessages.Start();
    m_fmServers.ReceiveMessages();
    timerReceiveServersMessages.Stop();

    if (GetNow() - timeLastQueueCheck >= 1.0f)
    {
      // count the fairly expensive stuff no more than once a second
      UpdatePerfCounters();
      timeLastQueueCheck = GetNow();
      if (GetNow() - timeLastGameInfo >= (float) m_sGameInfoInterval)
      {
        SendGameInfo();
        timeLastGameInfo = GetNow();
      }

      // Do a periodic roll call. If we haven't heard from anyone for two roll calls in a row, waste 'em
      static Time timeRollCall = Time::Now();
      if (GetNow() - timeRollCall >= 5.0f)
      {
        RollCall();
        timeRollCall = GetNow();
      }
    }
    Sleep(1);
  }
  DeleteCriticalSection(GetLogonCS());
  DeleteCriticalSection(&HttpCriticalSection);
  return 0;
}
示例#21
0
int main(int argc, char** argv) {

	EmoEngineEventHandle eEvent			= IEE_EmoEngineEventCreate();
	EmoStateHandle eState				= IEE_EmoStateCreate();
	unsigned int userID					= 0;	
	float secs							= 1;
	unsigned int datarate				= 0;
	bool readytocollect					= false;
	int state							= 0;

	try {

		if (argc != 2) {
            throw std::runtime_error("Please supply the log file name.\n"
                                     "Usage: MotionDataLogger [log_file_name].");
		}

        std::cout << "==================================================================="
                  << std::endl;
        std::cout << "Example to show how to log Motion Data from EmoDriver."
                  << std::endl;
        std::cout << "==================================================================="
                  << std::endl;

        
		if (IEE_EngineConnect() != EDK_OK) 
			throw std::runtime_error("Emotiv Driver start up failed.");
		
        std::cout << "Start receiving IEEG Data! "
                  << "Press any key to stop logging...\n"
                  << std::endl;

    	std::ofstream ofs(argv[1],std::ios::trunc);
		ofs << header << std::endl;
		
		DataHandle hMotionData = IEE_MotionDataCreate();
		IEE_MotionDataSetBufferSizeInSec(secs);

		std::cout << "Buffer size in secs:" << secs << std::endl;
		
		while (!_kbhit()) {

			state = IEE_EngineGetNextEvent(eEvent);
			if (state == EDK_OK) {

				IEE_Event_t eventType = IEE_EmoEngineEventGetType(eEvent);
				IEE_EmoEngineEventGetUserId(eEvent, &userID);

				// Log the EmoState if it has been updated
				if (eventType == IEE_UserAdded) {
					std::cout << "User added";
					readytocollect = true;
				}
			}

			if (readytocollect) {
						
                IEE_MotionDataUpdateHandle(0, hMotionData);

                unsigned int nSamplesTaken=0;
                IEE_MotionDataGetNumberOfSample(hMotionData, &nSamplesTaken);

                std::cout << "Updated " << nSamplesTaken << std::endl;

                if (nSamplesTaken != 0) {

                    double* data = new double[nSamplesTaken];
                    for (int sampleIdx=0 ; sampleIdx<(int)nSamplesTaken ; ++ sampleIdx) {
                        for (int i = 0 ;
                             i<sizeof(targetChannelList)/sizeof(IEE_MotionDataChannel_t) ;
                             i++) {

                            IEE_MotionDataGet(hMotionData, targetChannelList[i],
                                        data, nSamplesTaken);
                            ofs << data[sampleIdx] << ",";
                        }
                        ofs << std::endl;
                    }
                    delete[] data;
                }

			}

#ifdef _WIN32
            Sleep(1);
#endif
#ifdef __linux__
            usleep(10000);
#endif
		}

		ofs.close();
		IEE_MotionDataFree(hMotionData);
		

	}
    catch (const std::runtime_error& e) {
		std::cerr << e.what() << std::endl;
		std::cout << "Press any key to exit..." << std::endl;
		getchar();
	}

	IEE_EngineDisconnect();
	IEE_EmoStateFree(eState);
	IEE_EmoEngineEventFree(eEvent);

	return 0;
}
示例#22
0
static long
msvcrt_kbhit_impl(PyModuleDef *module)
/*[clinic end generated code: output=2b7293fcbe5cb24e input=e70d678a5c2f6acc]*/
{
    return _kbhit();
}
示例#23
0
文件: main.cpp 项目: poppeman/Pictus
int wmain(int argc, wchar_t* argv[])
{
	if (argc < 3)
	{
		OutputString("Error: Bad params.\nStresser.exe CACHER|FOLDER|FULL PATH");
		return EXIT_FAILURE;
	}

	g_runner.reset(new ThreadRunner);

	auto test = boost::locale::to_upper(WStringToUTF8(argv[1]));

	wchar_t wfullPath[MAX_PATH];

	GetFullPathName(
		argv[2],
		MAX_PATH,
		wfullPath,
		0);

	auto fullPath = WStringToUTF8(wfullPath);

	auto path = IO::GetPath(fullPath + "\\");

	OutputString("Setting up ...");

	// FIXME: Cacher test didn't like it when these lines were missing
	copyFiles(path + "a\\", path + "d\\");
	copyFiles(path + "b\\", path + "e\\");

	auto numThreads = std::max<unsigned int>(2, std::thread::hardware_concurrency());

	OutputString("Processor count : " + ToAString(numThreads));

	if (test == "CACHER")
	{
		OutputString("Cacher-only test");
		prepareCacherTest(path);
	}
	else if (test == "FOLDER")
	{
		OutputString("Folder-only test");
		prepareFolderTest(path);
	}
	else if (test == "FULL")
	{
		OutputString("Full test");
		prepareCacherTest(path);
		prepareFolderTest(path);
	}

	OutputString("Starting threads, press Enter to quit ...");
	g_runner->Run();

	for (;;) {
		if(_kbhit()) {
			int c = _getch();
			if(c == '\n' || c=='\r')
				break;
		}
		if(!g_run)
			break;
		Sleep(100);
	}
	g_runner->Terminate();
	g_runner.reset();
	if(!g_run) {
		std::cout << "Some sort of error occurred. Press enter to terminate.\n";
		std::cin.get();
	}

	return EXIT_SUCCESS;
}
int getch_noblock() {
    if (_kbhit())
        return _getch();
    else
        return -1;
}
示例#25
0
int main(int argc, char *argv[])
{
    FMOD::EventSystem    *eventsystem;
    FMOD::EventGroup     *eventgroup;
    FMOD::Event          *event = 0;
    FMOD_RESULT           result;
    int                   key;

    printf("======================================================================\n");
    printf("Load Event Data Example.  Copyright (c) Firelight Technologies 2004-2014.\n");
    printf("==============================-------=================================\n");
    printf("This demonstrates loading and unloading of event data per event and\n");
    printf("per group.\n");
    printf("======================================================================\n\n");

    ERRCHECK(result = FMOD::EventSystem_Create(&eventsystem));
    ERRCHECK(result = eventsystem->init(64, FMOD_INIT_NORMAL, 0, FMOD_EVENT_INIT_NORMAL));
    ERRCHECK(result = eventsystem->setMediaPath("..\\media\\"));
    ERRCHECK(result = eventsystem->load("examples.fev", 0, 0));
    ERRCHECK(result = eventsystem->getGroup("examples/FeatureDemonstration/Basics", false, &eventgroup));

    printf("======================================================================\n");
    printf("Press 'e'        to load event data\n");
    printf("Press 'E'        to unload event data\n");
    printf("Press 'g'        to load group data\n");
    printf("Press 'G'        to unload group data\n");
    printf("Press ESC        to quit\n");
    printf("======================================================================\n");

    bool memory_changed = true;

    key = 0;
    do
    {
        if (_kbhit())
        {

            key = _getch();

            if (key == 'e')
            {
                ERRCHECK(result = eventgroup->getEvent("SimpleEvent", FMOD_EVENT_DEFAULT, &event));
                printf("Event data loaded\n");
                memory_changed = true;
            }
            else if (key == 'E')
            {
                if (event)
                {
                    result = eventgroup->freeEventData(event);
                    if (result != FMOD_ERR_INVALID_HANDLE)
                    {
                        ERRCHECK(result);
                        printf("Event data unloaded\n");
                        memory_changed = true;
                    }
                    event = 0;
                }
            }
            else if (key == 'g')
            {
                ERRCHECK(result = eventgroup->loadEventData());
                printf("Event group data loaded\n");
                memory_changed = true;
            }
            else if (key == 'G')
            {
                ERRCHECK(result = eventgroup->freeEventData());
                printf("Event group data unloaded\n");
                memory_changed = true;
            }

        }

        if (memory_changed)
        {
            int memory_current, memory_max;
            ERRCHECK(result = FMOD::Memory_GetStats(&memory_current, &memory_max));

            printf("Memory usage: current = %10d, max = %10d\n", memory_current, memory_max);
            memory_changed = false;
        }

        ERRCHECK(result = eventsystem->update());
        Sleep(15);

    } while (key != 27);

    ERRCHECK(result = eventgroup->freeEventData());
    ERRCHECK(result = eventsystem->release());
    return 0;
}
示例#26
0
void main(int argc, char **argv)
{
	BUFSTUFF b,b2;
	BASS_3DVECTOR p={0,0,0};

	printf("BASS 2 stereo channels on 4 speakers example : MOD/MPx/OGG/WAV\n"
			"--------------------------------------------------------------\n"
			"       Set your soundcard's output to 4 or 5.1 speakers\n");

	/* check that BASS 1.6 was loaded */
	if (BASS_GetVersion()!=MAKELONG(1,6)) {
		printf("BASS version 1.6 was not loaded\n");
		return;
	}

	if (argc!=3) {
		printf("\tusage: 4speaker <file1> <file2>\n");
		return;
	}

	/* setup output - default device, 44100hz, stereo, 16 bits */
	if (!BASS_Init(-1,44100,BASS_DEVICE_3D,0))
		Error("Can't initialize device");

	/* try initializing the 1st (front) file */
	if (!(b.dstr=BASS_StreamCreateFile(FALSE,argv[1],0,0,BASS_STREAM_DECODE)))
		if (!(b.dstr=BASS_MusicLoad(FALSE,argv[1],0,0,BASS_MUSIC_DECODE|BASS_MUSIC_RAMPS)))
			Error("Can't play the 1st file");
	if (BASS_ChannelGetFlags(b.dstr)&BASS_SAMPLE_MONO)
		Error("The 1st stream is mono!");

	/* try initializing the 2nd (rear) file */
	if (!(b2.dstr=BASS_StreamCreateFile(FALSE,argv[2],0,0,BASS_STREAM_DECODE)))
		if (!(b2.dstr=BASS_MusicLoad(FALSE,argv[2],0,0,BASS_MUSIC_DECODE|BASS_MUSIC_RAMPS)))
			Error("Can't play the 2nd file");
	if (BASS_ChannelGetFlags(b2.dstr)&BASS_SAMPLE_MONO)
		Error("The 2nd stream is mono!");

	printf("front : %s\n",argv[1]);
	printf("rear  : %s\n",argv[2]);

	/* Get sample rates and allocate buffers */
	BASS_ChannelGetAttributes(b.dstr,&b.freq,0,0);
	b.buf=malloc(b.freq*4); // 1 sec buffer
	BASS_ChannelGetAttributes(b2.dstr,&b2.freq,0,0);
	b2.buf=malloc(b2.freq*4); // 1 sec buffer

	/* Create streams to play the 1st decoded data, and link them */
	b.lstr=BASS_StreamCreate(b.freq,BASS_SAMPLE_MONO|BASS_SAMPLE_3D,(STREAMPROC*)&stream_left,(DWORD)&b);
	b.rstr=BASS_StreamCreate(b.freq,BASS_SAMPLE_MONO|BASS_SAMPLE_3D,(STREAMPROC*)&stream_right,(DWORD)&b);
	BASS_ChannelSetLink(b.lstr,b.rstr);

	/* Create streams to play the 2nd decoded data, and link them */
	b2.lstr=BASS_StreamCreate(b2.freq,BASS_SAMPLE_MONO|BASS_SAMPLE_3D,(STREAMPROC*)&stream_left,(DWORD)&b2);
	b2.rstr=BASS_StreamCreate(b2.freq,BASS_SAMPLE_MONO|BASS_SAMPLE_3D,(STREAMPROC*)&stream_right,(DWORD)&b2);
	BASS_ChannelSetLink(b2.lstr,b2.rstr);

	/* position the streams */
	p.z=3; // front
	p.x=-1.5; // left
	BASS_ChannelSet3DPosition(b.lstr,&p,0,0);
	p.x=1.5; // right
	BASS_ChannelSet3DPosition(b.rstr,&p,0,0);
	p.z=-3; // rear
	p.x=-1.5; // left
	BASS_ChannelSet3DPosition(b2.lstr,&p,0,0);
	p.x=1.5; // right
	BASS_ChannelSet3DPosition(b2.rstr,&p,0,0);
	BASS_Apply3D();

	BASS_Start();
	/* start it! */
	b.writepos=b.readposl=b.readposr=0;
	BASS_StreamPlay(b.lstr,FALSE,0); // start front
	b2.writepos=b2.readposl=b2.readposr=0;
	BASS_StreamPlay(b2.lstr,FALSE,0); // start rear

	while (!_kbhit() && (BASS_ChannelIsActive(b.lstr) || BASS_ChannelIsActive(b2.lstr))) {
		/* display some stuff and wait a bit */
		printf("pos %09I64d %09I64d - cpu %.1f%%  \r",
			BASS_ChannelGetPosition(b.lstr)*2,BASS_ChannelGetPosition(b2.lstr)*2,BASS_GetCPU());
		Sleep(50);
	}

	BASS_Free();
	free(b.buf);
}
示例#27
0
文件: main.cpp 项目: 1170390/OpenNI2
int wasKeyboardHit()
{
        return (int)_kbhit();
}
示例#28
0
void  main() {
	std::string userName = "******";
	std::string password = "******";
	std::string profileName = "EmotivProfile";
	int version	= -1; // Lastest version

	int option	= 0;
	std::string input;
	bool ready  = false;

	EmoEngineEventHandle eEvent	= IEE_EmoEngineEventCreate();
	EmoStateHandle eState		= IEE_EmoStateCreate();
	unsigned int engineUserID	= -1;
	int userCloudID		= -1;
	int state			= 0;
		
	if (IEE_EngineConnect() != EDK_OK) {
                throw std::runtime_error(
                            "Emotiv Driver start up failed.");
	}

	std::cout << "==================================================================="
                << std::endl;
    std::cout << "Example to saving and loading profile from Emotiv Cloud "
                << std::endl;
    std::cout << "==================================================================="
                << std::endl;
    std::cout << "Press '1' to saving profile to Emotiv Cloud "
                << std::endl;
    std::cout << "Press '2' to loading profile from Emotiv Cloud "
                << std::endl;
	std::cout << ">> ";

	std::getline(std::cin, input, '\n');
	option = atoi(input.c_str());

	if(!EC_Connect())
	{
		std::cout << "Cannot connect to Emotiv Cloud";
		return;
	}

	if(!EC_Login(userName.c_str(), password.c_str()))
	{
			
		std::cout << "Your login attempt has failed. The username or password may be incorrect";
		_getch();
		return;
	}

	if (!EC_GetUserDetail(&userCloudID))
		return;

	while (!_kbhit())
	{
		state = IEE_EngineGetNextEvent(eEvent);

		if (state == EDK_OK) {

		IEE_Event_t eventType = IEE_EmoEngineEventGetType(eEvent);
		IEE_EmoEngineEventGetUserId(eEvent, &engineUserID);

		if (eventType == IEE_UserAdded) {
		std::cout << "User added" << std::endl;
		ready = true;
		}
		}

		if (ready)
		{
			int getNumberProfile = EC_GetAllProfileName(userCloudID);

			switch (option) {
				case 1:{    
					int profileID = EC_GetProfileId(userCloudID, profileName.c_str());

					if (profileID >= 0) {
						std::cout << "Profile with " << profileName << " is existed" << std::endl;
						if (EC_UpdateUserProfile(userCloudID, engineUserID, profileID, profileName.c_str())) {
						std::cout << "Updating finished";      
						}
						else std::cout << "Updating failed";
						}
					else if (EC_SaveUserProfile(userCloudID, (int)engineUserID, profileName.c_str(),
						profileFileType::TRAINING))
					{
						std::cout << "Saving finished";
					}
					else std::cout << "Saving failed";

					_getch();
					return;
				}
				case 2:{
					if (getNumberProfile > 0)
						if (EC_LoadUserProfile(userCloudID, (int)engineUserID, EC_ProfileIDAtIndex(userCloudID, 0)))
						std::cout << "Loading finished";
						else std::cout << "Loading failed";

					_getch();
					return;
				}
				default:
					throw std::runtime_error("Invalid option...");
					break;
			}
		}

#ifdef _WIN32
	Sleep(1);
#endif
#ifdef linux
	sleep(1);
#endif
	}

	IEE_EngineDisconnect();
	IEE_EmoStateFree(eState);
	IEE_EmoEngineEventFree(eEvent);
}
int main(int argc, char ** argv)
{
	// Configure
	XnStatus rc = g_Context.InitFromXmlFile(SAMPLE_XML_FILE);
	if (rc != XN_STATUS_OK)
	{
		printf("Couldn't initialize from file: %s\n", xnGetStatusString(rc));
		return 1;
	}

	// Create and initialize point tracker
	g_pSessionManager = new XnVSessionManager();
	rc = g_pSessionManager->Initialize(&g_Context, "Wave", "RaiseHand");
	if (rc != XN_STATUS_OK)
	{
		printf("Couldn't initialize the Session Manager: %s\n", xnGetStatusString(rc));
		CleanupExit();
	}

	g_pSessionManager->RegisterSession(NULL, &SessionStart, &SessionEnd);

	// Start catching signals for quit indications
	CatchSignals(&g_bQuit);

	// init and register circle control
	g_pCircle = new XnVCircleDetector;
	g_pCircle->RegisterCircle(NULL, &CircleCB);
	g_pCircle->RegisterNoCircle(NULL, &NoCircleCB);
	g_pCircle->RegisterPrimaryPointCreate(NULL, &Circle_PrimaryCreate);
	g_pCircle->RegisterPrimaryPointDestroy(NULL, &Circle_PrimaryDestroy);
	g_pSessionManager->AddListener(g_pCircle);

	SetCircle(true, 0);
	SetCircleColor(1,1,1);
	SetCircleLineColor(0.7,0.7,0.7);

	g_Context.StartGeneratingAll();

	#ifdef USE_GLUT

	glInit(&argc, argv);
	glutMainLoop();

	#else

	if (!opengles_init(GL_WIN_SIZE_X, GL_WIN_SIZE_Y, &display, &surface, &context))
	{
		printf("Error initing opengles\n");
		CleanupExit();
	}

	glDisable(GL_DEPTH_TEST);
	//glEnable(GL_TEXTURE_2D);
	
	glEnableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_COLOR_ARRAY);

	while ((!_kbhit()) && (!g_bQuit))
	{
		glutDisplay();
	}

	opengles_shutdown(display, surface, context);
	
	CleanupExit();

	#endif
}
示例#30
0
int main(int argc, char *argv[])
{
    FMOD_SYSTEM        *system;
    FMOD_SOUND         *sound;
    FMOD_CHANNEL       *channel;
    FMOD_DSP           *dsplowpass, *dspchorus, *dsphead, *dspchannelmixer;
	FMOD_DSPCONNECTION *dsplowpassconnection, *dspchorusconnection;
    FMOD_RESULT         result;
    int                 key;
    unsigned int        version;
    float               pan = 0;

    /*
        Create a System object and initialize.
    */
    result = FMOD_System_Create(&system);
    ERRCHECK(result);

    result = FMOD_System_GetVersion(system, &version);
    ERRCHECK(result);

    if (version < FMOD_VERSION)
    {
        printf("Error!  You are using an old version of FMOD %08x.  This program requires %08x\n", version, FMOD_VERSION);
        return 0;
    }

    result = FMOD_System_Init(system, 32, FMOD_INIT_NORMAL, 0);
    ERRCHECK(result);

    result = FMOD_System_CreateSound(system, "../media/drumloop.wav", FMOD_SOFTWARE | FMOD_LOOP_NORMAL, 0, &sound);
    ERRCHECK(result);

    printf("===============================================================================\n");
    printf("DSP Effect per speaker example. Copyright (c) Firelight Technologies 2004-2015.\n");
    printf("===============================================================================\n");
    printf("Press 'L' to toggle reverb on/off on left speaker only\n");
    printf("Press 'R' to toggle chorus on/off on right speaker only\n");
    printf("Press '[' to pan sound left\n");
    printf("Press ']' to pan sound right\n");
    printf("Press 'Esc' to quit\n");
    printf("\n");

    result = FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sound, FALSE, &channel);
    ERRCHECK(result);

    /*
        Create the DSP effects.
    */  
    result = FMOD_System_CreateDSPByType(system, FMOD_DSP_TYPE_LOWPASS, &dsplowpass);
    ERRCHECK(result);

    result = FMOD_System_CreateDSPByType(system, FMOD_DSP_TYPE_CHORUS, &dspchorus);
    ERRCHECK(result);

    /*
        Connect up the DSP network
    */

    /*
        When a sound is played, a subnetwork is set up in the DSP network which looks like this.
        Wavetable is the drumloop sound, and it feeds its data from right to left.

        [DSPHEAD]<------------[DSPCHANNELMIXER]
    */  
    result = FMOD_System_GetDSPHead(system, &dsphead);
    ERRCHECK(result);

    result = FMOD_DSP_GetInput(dsphead, 0, &dspchannelmixer, 0);
    ERRCHECK(result);

    /*
        Now disconnect channeldsp head from wavetable to look like this.

        [DSPHEAD]             [DSPCHANNELMIXER]
    */
    result = FMOD_DSP_DisconnectFrom(dsphead, dspchannelmixer);
    ERRCHECK(result);

    /*
        Now connect the 2 effects to channeldsp head.
		Store the 2 connections this makes so we can set their speakerlevels later.

                  [DSPLOWPASS]
                 /x           
        [DSPHEAD]             [DSPCHANNELMIXER]
                 \y           
                  [DSPCHORUS]
    */
    result = FMOD_DSP_AddInput(dsphead, dsplowpass, &dsplowpassconnection); /* x = dsplowpassconnection */
    ERRCHECK(result);
    result = FMOD_DSP_AddInput(dsphead, dspchorus, &dspchorusconnection);   /* y = dspchorusconnection */
    ERRCHECK(result);
    
    /*
        Now connect the wavetable to the 2 effects

                  [DSPLOWPASS]
                 /x          \
        [DSPHEAD]             [DSPCHANNELMIXER]
                 \y          /
                  [DSPCHORUS]
    */
    result = FMOD_DSP_AddInput(dsplowpass, dspchannelmixer, NULL);  /* Null for connection - we dont care about it. */
    ERRCHECK(result);
    result = FMOD_DSP_AddInput(dspchorus, dspchannelmixer, NULL);   /* Null for connection - we dont care about it. */
    ERRCHECK(result);

    /*
        Now the drumloop will be twice as loud, because it is being split into 2, then recombined at the end.
        What we really want is to only feed the dspchannelmixer->dsplowpass through the left speaker, and 
        dspchannelmixer->dspchorus to the right speaker.
        We can do that simply by setting the pan, or speaker levels of the connections.

                  [DSPLOWPASS]
                 /x=1,0      \
        [DSPHEAD]             [DSPCHANNELMIXER]
                 \y=0,1      /
                  [DSPCHORUS]
    */
    {
        float leftinputon[2]  = { 1.0f, 0.0f };
        float rightinputon[2] = { 0.0f, 1.0f };
        float inputsoff[2]    = { 0.0f, 0.0f };

        result = FMOD_DSPConnection_SetLevels(dsplowpassconnection, FMOD_SPEAKER_FRONT_LEFT, leftinputon, 2);
        ERRCHECK(result);
        result = FMOD_DSPConnection_SetLevels(dsplowpassconnection, FMOD_SPEAKER_FRONT_RIGHT, inputsoff, 2);
        ERRCHECK(result);

        result = FMOD_DSPConnection_SetLevels(dspchorusconnection, FMOD_SPEAKER_FRONT_LEFT, inputsoff, 2);
        ERRCHECK(result);
        result = FMOD_DSPConnection_SetLevels(dspchorusconnection, FMOD_SPEAKER_FRONT_RIGHT, rightinputon, 2);
        ERRCHECK(result);
    }

    result = FMOD_DSP_SetBypass(dsplowpass, TRUE);
    result = FMOD_DSP_SetBypass(dspchorus, TRUE);

    result = FMOD_DSP_SetActive(dsplowpass, TRUE);
    result = FMOD_DSP_SetActive(dspchorus, TRUE);

    /*
        Main loop.
    */
    do
    {
        if (_kbhit())
        {
            key = _getch();

            switch (key)
            {
                case 'l' : 
                case 'L' : 
                {
                    static int reverb = FALSE;

                    FMOD_DSP_SetBypass(dsplowpass, reverb);

                    reverb = !reverb;
                    break;
                }
                case 'r' : 
                case 'R' : 
                {
                    static int chorus = FALSE;

                    FMOD_DSP_SetBypass(dspchorus, chorus);

                    chorus = !chorus;
                    break;
                }
                case '[' :
                {
                    FMOD_Channel_GetPan(channel, &pan);
                    pan -= 0.1f;
                    if (pan < -1)
                    {
                        pan = -1;
                    }
                    FMOD_Channel_SetPan(channel, pan);
                    break;
                }
                case ']' :
                {
                    FMOD_Channel_GetPan(channel, &pan);
                    pan += 0.1f;
                    if (pan > 1)
                    {
                        pan = 1;
                    }
                    FMOD_Channel_SetPan(channel, pan);
                    break;
                }
            }
        }

        FMOD_System_Update(system);

        {
            int  channelsplaying = 0;

            FMOD_System_GetChannelsPlaying(system, &channelsplaying);

            printf("Channels Playing %2d : Pan = %.02f\r", channelsplaying, pan);
        }

        Sleep(10);

    } while (key != 27);

    printf("\n");

    /*
        Shut down
    */
    result = FMOD_Sound_Release(sound);
    ERRCHECK(result);

    result = FMOD_DSP_Release(dsplowpass);
    ERRCHECK(result);
    result = FMOD_DSP_Release(dspchorus);
    ERRCHECK(result);

    result = FMOD_System_Close(system);
    ERRCHECK(result);
    result = FMOD_System_Release(system);
    ERRCHECK(result);

    return 0;
}