void QgsPointSample::addSamplePoints( QgsFeature& inputFeature, QgsVectorFileWriter& writer, int nPoints, double minDistance )
{
  if ( !inputFeature.constGeometry() )
    return;

  const QgsGeometry* geom = inputFeature.constGeometry();
  QgsRectangle geomRect = geom->boundingBox();
  if ( geomRect.isEmpty() )
  {
    return;
  }

  QgsSpatialIndex sIndex; //to check minimum distance
  QMap< QgsFeatureId, QgsPoint > pointMapForFeature;

  int nIterations = 0;
  int maxIterations = nPoints * 200;
  int points = 0;

  double randX = 0;
  double randY = 0;

  while ( nIterations < maxIterations && points < nPoints )
  {
    randX = (( double )mt_rand() / MD_RAND_MAX ) * geomRect.width() + geomRect.xMinimum();
    randY = (( double )mt_rand() / MD_RAND_MAX ) * geomRect.height() + geomRect.yMinimum();
    QgsPoint randPoint( randX, randY );
    QgsGeometry* ptGeom = QgsGeometry::fromPoint( randPoint );
    if ( ptGeom->within( geom ) && checkMinDistance( randPoint, sIndex, minDistance, pointMapForFeature ) )
    {
      //add feature to writer
      QgsFeature f( mNCreatedPoints );
      f.setAttribute( "id", mNCreatedPoints + 1 );
      f.setAttribute( "station_id", points + 1 );
      f.setAttribute( "stratum_id", inputFeature.id() );
      f.setGeometry( ptGeom );
      writer.addFeature( f );
      sIndex.insertFeature( f );
      pointMapForFeature.insert( mNCreatedPoints, randPoint );
      ++points;
      ++mNCreatedPoints;
    }
    else
    {
      delete ptGeom;
    }
    ++nIterations;
  }
}
Beispiel #2
0
static mrb_value
mrb_ary_sample(mrb_state *mrb, mrb_value ary)
{
  mrb_int n = 0;
  mrb_bool given;
  mt_state *random = NULL;
  mrb_int len = RARRAY_LEN(ary);

  mrb_get_args(mrb, "|i?d", &n, &given, &random, &mt_state_type);
  if (random == NULL) {
    random = get_random_state(mrb);
  }
  mrb_random_rand_seed(mrb, random);
  mt_rand(random);
  if (!given) {                 /* pick one element */
    switch (len) {
    case 0:
      return mrb_nil_value();
    case 1:
      return RARRAY_PTR(ary)[0];
    default:
      return RARRAY_PTR(ary)[mt_rand(random) % len];
    }
  }
  else {
    mrb_value result;
    mrb_int i, j;

    if (n < 0) mrb_raise(mrb, E_ARGUMENT_ERROR, "negative sample number");
    if (n > len) n = len;
    result = mrb_ary_new_capa(mrb, n);
    for (i=0; i<n; i++) {
      mrb_int r;

      for (;;) {
      retry:
        r = mt_rand(random) % len;

        for (j=0; j<i; j++) {
          if (mrb_fixnum(RARRAY_PTR(result)[j]) == r) {
            goto retry;         /* retry if duplicate */
          }
        }
        break;
      }
      RARRAY_PTR(result)[i] = mrb_fixnum_value(r);
      RARRAY_LEN(result)++;
    }
    for (i=0; i<n; i++) {
      RARRAY_PTR(result)[i] = RARRAY_PTR(ary)[mrb_fixnum(RARRAY_PTR(result)[i])];
    }
    return result;
  }
}
void JE_setupStars( void )
{
	int z;

	for (z = MAX_STARS; z--; )
	{
		starDat[z].sLoc = (mt_rand() % 320) + (mt_rand() % 200) * VGAScreen->pitch;
		starDat[z].sMov = ((mt_rand() % 3) + 2) * VGAScreen->pitch;
		starDat[z].sC = (mt_rand() % 16) + (9 * 16);
	}
}
Beispiel #4
0
char *make_salt() {
	static char salt[6];
	int i;
	for (i=0; i<5; i++)
		salt[i] = (char)((mt_rand() % 78) + 48);
	salt[5] = '\0';
	return(salt);
}
Beispiel #5
0
int main(int argc, char** argv)
{
	if (argc < 2) {
		std::cerr << "Usage: " << argv[0] << " range1 [-][range2] [-][range3] ..." << std::endl << std::endl;
		std::cerr << "This tool will aggregate all the given ranges and will write a random order of the corresponding IP." << std::endl << std::endl;
		std::cerr << "where range can be described as:" << std::endl;
		std::cerr << "\tCIDR notation:\t192.168.1.0/24" << std::endl;
		std::cerr << "\tRanges:\t\t10.4-5.8.9-250" << std::endl;
		std::cerr << "\tSingle IP:\t192.168.1.10" << std::endl << std::endl;
		std::cerr << "A '-' symbol before any range will remove it from the final set." << std::endl;
		return 1;
	}

	leeloo::ip_list_intervals l;
	for (int i = 1; i < argc; i++) {
		const char* const ip_range = argv[i];
		bool ret;
		if (strlen(ip_range) <= 1) {
			ret = false;
		}
		else
		if (ip_range[0] == '-') {
			ret = l.remove(&ip_range[1]);
		}
		else {
			ret = l.add(ip_range);
		}

		if (!ret) {
			std::cerr << "Warning: '" << ip_range << "' is an invalid IP range." << std::endl;
		}
	}

	// Aggregate all IPs
	l.aggregate();

	std::cerr << "Number of IPs after aggregation: " << l.size() << std::endl;

	l.create_index_cache(256);

	// Initialize a random generator
	boost::random::mt19937 mt_rand(time(NULL));

	l.random_sets(16, 
		[](const uint32_t* ips, const size_t n)
		{
			for (size_t i = 0; i < n; i++) {
				struct in_addr addr;
				addr.s_addr = htonl(ips[i]);
				std::cout << inet_ntoa(addr) << std::endl;
			}
		},
		leeloo::random_engine<uint32_t>(mt_rand));

	return 0;
}
Beispiel #6
0
int main()
{
	boost::random::mt19937 mt_rand(time(NULL));
	u128_list_intervals li;
	li.add(u128(10), u128(20));
	li.aggregate();
	li.random_sets<leeloo::uni>(16, [](u128 const* buf, size_t const n) { },
			leeloo::random_engine<uint32_t>(mt_rand));

	return 0;
}
Beispiel #7
0
static mrb_value mrb_random_mt_rand(mrb_state *mrb, mt_state *t, mrb_value max)
{ 
  mrb_value value;

  if (mrb_fixnum(max) == 0) {
    value = mrb_float_value(mrb, mt_rand_real(t));
  } else {
    value = mrb_fixnum_value(mt_rand(t) % mrb_fixnum(max));
  }

  return value;
}
Beispiel #8
0
static mrb_value mrb_random_mt_srand(mrb_state *mrb, mt_state *t, mrb_value seed)
{ 
  if (mrb_nil_p(seed)) {
    seed = mrb_fixnum_value(time(NULL) + mt_rand(t));
    if (mrb_fixnum(seed) < 0) {
      seed = mrb_fixnum_value( 0 - mrb_fixnum(seed));
    }
  }

  mt_srand(t, (unsigned) mrb_fixnum(seed));

  return seed;
}
Beispiel #9
0
Board::Board() : side(WHITE), xside(BLACK), side_castle(3), xside_castle(3), ep(-1) {
	color = init_color;
	pieces = init_pieces;

	// initialize hash constants using a Mersenne twister to generate random 64-bit ints
	std::mt19937_64 mt_rand(time(0));
	for (int c = 0; c < 2; ++c) {
		for (int p = 0; p < 6; ++p) {
			for (int s = 0; s < 64; ++s) {
				hash_board[c][p][s] = mt_rand();
			}
		}
	}
	hash_side = mt_rand();
	for (int s = 0; s < 64; ++s) {
		hash_ep[s] = mt_rand();
	}
	for (int sc = 0; sc < 4; ++sc) {
		for (int xc = 0; xc < 4; ++xc) {
			hash_castle[sc][xc] = mt_rand();
		}
	}
}
Beispiel #10
0
bool sort_test() {
	{
		std::vector<size_t> l1;
		std::vector<size_t> l2(l1);
		std::sort(l1.begin(), l1.end());
		tpie::tiny::sort(l2.begin(), l2.end());
		if (l1 != l2) return false;
	}

	{
		std::vector<size_t> l1{42};
		std::vector<size_t> l2(l1);
		std::sort(l1.begin(), l1.end());
		tpie::tiny::sort(l2.begin(), l2.end());
		if (l1 != l2) return false;
	}

	
	{
		std::vector<size_t> l1{11, 32};
		std::vector<size_t> l2(l1);
		std::sort(l1.begin(), l1.end(), std::greater<size_t>());
		tpie::tiny::sort(l2.begin(), l2.end(), std::greater<size_t>());
		if (l1 != l2) return false;
	}

	{
		std::mt19937 mt_rand(42);
		std::vector<size_t> l1;
		for (size_t i=0; i < 100; ++i) l1.push_back(mt_rand());
		std::vector<size_t> l2(l1);
		std::sort(l1.begin(), l1.end());
		tpie::tiny::sort(l2.begin(), l2.end());
		if (l1 != l2) return false;
	}
	return true;
}
Beispiel #11
0
map* init_map(int sideX, int sideY, int scale){

    int x, y;
    unsigned int i, count = 0;
    int aux = 0;
    unsigned int n;
    void **word_adresses;
    word *pt_aux = malloc(sizeof(word));;
    map *_map = malloc(sizeof(map));
    _map->latice_size = sideX * sideY;
    _map->sideX       = sideX;
    _map->sideY       = sideY; 
    _map->scale       = scale;
    _map->lattice     = malloc(_map->latice_size * sizeof( neuron));
    mt_seed ();

    if ((n = get_list(pt_aux)))
    {
        printf("n: %d\n", n);
        word_adresses = malloc(n * sizeof(void *));
        while (pt_aux != NULL)
        {
            x = mt_rand() %sideX;
            y = mt_rand() %sideY;
            init_neuron(_map->lattice, x, y, pt_aux->frames, pt_aux->n, pt_aux->name);
            word_adresses[count++] = pt_aux;
            pt_aux = pt_aux->next;
        }
        printf("count: %d\n", count);
        for (i = 0; i < count; i++)
            free(word_adresses[i]);
        free(word_adresses);
    }

    return _map;
}
void JE_loadConfiguration( void )
{
	FILE *fi;
	int z;
	JE_byte *p;
	int y;
	
	fi = dir_fopen_warn(get_user_directory(), "tyrian.cfg", "rb");
	if (fi && ftell_eof(fi) == 20 + sizeof(keySettings))
	{
		/* SYN: I've hardcoded the sizes here because the .CFG file format is fixed
		   anyways, so it's not like they'll change. */
		background2 = 0;
		efread(&background2, 1, 1, fi);
		efread(&gameSpeed, 1, 1, fi);
		
		efread(&inputDevice_, 1, 1, fi);
		efread(&jConfigure, 1, 1, fi);
		
		efread(&versionNum, 1, 1, fi);
		
		efread(&processorType, 1, 1, fi);
		efread(&midiPort, 1, 1, fi);
		efread(&soundEffects, 1, 1, fi);
		efread(&gammaCorrection, 1, 1, fi);
		efread(&difficultyLevel, 1, 1, fi);
		
		efread(joyButtonAssign, 1, 4, fi);
		
		efread(&tyrMusicVolume, 2, 1, fi);
		efread(&fxVolume, 2, 1, fi);
		
		efread(inputDevice, 1, 2, fi);
		
		efread(keySettings, sizeof(*keySettings), COUNTOF(keySettings), fi);
		
		fclose(fi);
	}
	else
	{
		printf("\nInvalid or missing TYRIAN.CFG! Continuing using defaults.\n\n");
		
		soundEffects = 1;
		memcpy(&keySettings, &defaultKeySettings, sizeof(keySettings));
		background2 = true;
		tyrMusicVolume = fxVolume = 128;
		gammaCorrection = 0;
		processorType = 3;
		gameSpeed = 4;
	}
	
	load_opentyrian_config();
	
	if (tyrMusicVolume > 255)
		tyrMusicVolume = 255;
	if (fxVolume > 255)
		fxVolume = 255;
	
	JE_calcFXVol();
	
	set_volume(tyrMusicVolume, fxVolume);
	
	fi = dir_fopen_warn(get_user_directory(), "tyrian.sav", "rb");
	if (fi)
	{

		fseek(fi, 0, SEEK_SET);
		efread(saveTemp, 1, sizeof(saveTemp), fi);
		JE_decryptSaveTemp();

		/* SYN: The original mostly blasted the save file into raw memory. However, our lives are not so
		   easy, because the C struct is necessarily a different size. So instead we have to loop
		   through each record and load fields manually. *emo tear* :'( */

		p = saveTemp;
		for (z = 0; z < SAVE_FILES_NUM; z++)
		{
			memcpy(&saveFiles[z].encode, p, sizeof(JE_word)); p += 2;
			saveFiles[z].encode = SDL_SwapLE16(saveFiles[z].encode);
			
			memcpy(&saveFiles[z].level, p, sizeof(JE_word)); p += 2;
			saveFiles[z].level = SDL_SwapLE16(saveFiles[z].level);
			
			memcpy(&saveFiles[z].items, p, sizeof(JE_PItemsType)); p += sizeof(JE_PItemsType);
			
			memcpy(&saveFiles[z].score, p, sizeof(JE_longint)); p += 4;
			saveFiles[z].score = SDL_SwapLE32(saveFiles[z].score);
			
			memcpy(&saveFiles[z].score2, p, sizeof(JE_longint)); p += 4;
			saveFiles[z].score2 = SDL_SwapLE32(saveFiles[z].score2);
			
			/* SYN: Pascal strings are prefixed by a byte holding the length! */
			memset(&saveFiles[z].levelName, 0, sizeof(saveFiles[z].levelName));
			memcpy(&saveFiles[z].levelName, &p[1], *p);
			p += 10;
			
			/* This was a BYTE array, not a STRING, in the original. Go fig. */
			memcpy(&saveFiles[z].name, p, 14);
			p += 14;
			
			memcpy(&saveFiles[z].cubes, p, sizeof(JE_byte)); p++;
			memcpy(&saveFiles[z].power, p, sizeof(JE_byte) * 2); p += 2;
			memcpy(&saveFiles[z].episode, p, sizeof(JE_byte)); p++;
			memcpy(&saveFiles[z].lastItems, p, sizeof(JE_PItemsType)); p += sizeof(JE_PItemsType);
			memcpy(&saveFiles[z].difficulty, p, sizeof(JE_byte)); p++;
			memcpy(&saveFiles[z].secretHint, p, sizeof(JE_byte)); p++;
			memcpy(&saveFiles[z].input1, p, sizeof(JE_byte)); p++;
			memcpy(&saveFiles[z].input2, p, sizeof(JE_byte)); p++;
			
			/* booleans were 1 byte in pascal -- working around it */
			Uint8 temp;
			memcpy(&temp, p, 1); p++;
			saveFiles[z].gameHasRepeated = temp != 0;
			
			memcpy(&saveFiles[z].initialDifficulty, p, sizeof(JE_byte)); p++;
			
			memcpy(&saveFiles[z].highScore1, p, sizeof(JE_longint)); p += 4;
			saveFiles[z].highScore1 = SDL_SwapLE32(saveFiles[z].highScore1);
			
			memcpy(&saveFiles[z].highScore2, p, sizeof(JE_longint)); p += 4;
			saveFiles[z].highScore2 = SDL_SwapLE32(saveFiles[z].highScore2);
			
			memset(&saveFiles[z].highScoreName, 0, sizeof(saveFiles[z].highScoreName));
			memcpy(&saveFiles[z].highScoreName, &p[1], *p);
			p += 30;
			
			memcpy(&saveFiles[z].highScoreDiff, p, sizeof(JE_byte)); p++;
		}

		/* SYN: This is truncating to bytes. I have no idea what this is doing or why. */
		/* TODO: Figure out what this is about and make sure it isn't broked. */
		editorLevel = (saveTemp[SIZEOF_SAVEGAMETEMP - 5] << 8) | saveTemp[SIZEOF_SAVEGAMETEMP - 6];

		fclose(fi);
	} else {
		/* We didn't have a save file! Let's make up random stuff! */
		editorLevel = 800;

		for (z = 0; z < 100; z++)
		{
			saveTemp[SAVE_FILES_SIZE + z] = initialItemAvail[z];
		}

		for (z = 0; z < SAVE_FILES_NUM; z++)
		{
			saveFiles[z].level = 0;

			for (y = 0; y < 14; y++)
			{
				saveFiles[z].name[y] = ' ';
			}
			saveFiles[z].name[14] = 0;

			saveFiles[z].highScore1 = ((mt_rand() % 20) + 1) * 1000;

			if (z % 6 > 2)
			{
				saveFiles[z].highScore2 = ((mt_rand() % 20) + 1) * 1000;
				strcpy(saveFiles[z].highScoreName, defaultTeamNames[mt_rand() % 22]);
			} else {
				strcpy(saveFiles[z].highScoreName, defaultHighScoreNames[mt_rand() % 34]);
			}
		}
	}
	
	JE_initProcessorType();
}
int QgsTransectSample::createSample( QProgressDialog* pd )
{
  Q_UNUSED( pd );

  if ( !mStrataLayer || !mStrataLayer->isValid() )
  {
    return 1;
  }

  if ( !mBaselineLayer || !mBaselineLayer->isValid() )
  {
    return 2;
  }

  //stratum id is not necessarily an integer
  QVariant::Type stratumIdType = QVariant::Int;
  if ( !mStrataIdAttribute.isEmpty() )
  {
    stratumIdType = mStrataLayer->pendingFields().field( mStrataIdAttribute ).type();
  }

  //create vector file writers for output
  QgsFields outputPointFields;
  outputPointFields.append( QgsField( "id", stratumIdType ) );
  outputPointFields.append( QgsField( "station_id", QVariant::Int ) );
  outputPointFields.append( QgsField( "stratum_id", stratumIdType ) );
  outputPointFields.append( QgsField( "station_code", QVariant::String ) );
  outputPointFields.append( QgsField( "start_lat", QVariant::Double ) );
  outputPointFields.append( QgsField( "start_long", QVariant::Double ) );

  QgsVectorFileWriter outputPointWriter( mOutputPointLayer, "utf-8", outputPointFields, QGis::WKBPoint,
                                         &( mStrataLayer->crs() ) );
  if ( outputPointWriter.hasError() != QgsVectorFileWriter::NoError )
  {
    return 3;
  }

  outputPointFields.append( QgsField( "bearing", QVariant::Double ) ); //add bearing attribute for lines
  QgsVectorFileWriter outputLineWriter( mOutputLineLayer, "utf-8", outputPointFields, QGis::WKBLineString,
                                        &( mStrataLayer->crs() ) );
  if ( outputLineWriter.hasError() != QgsVectorFileWriter::NoError )
  {
    return 4;
  }

  QgsFields usedBaselineFields;
  usedBaselineFields.append( QgsField( "stratum_id", stratumIdType ) );
  usedBaselineFields.append( QgsField( "ok", QVariant::String ) );
  QgsVectorFileWriter usedBaselineWriter( mUsedBaselineLayer, "utf-8", usedBaselineFields, QGis::WKBLineString,
                                          &( mStrataLayer->crs() ) );
  if ( usedBaselineWriter.hasError() != QgsVectorFileWriter::NoError )
  {
    return 5;
  }

  //debug: write clipped buffer bounds with stratum id to same directory as out_point
  QFileInfo outputPointInfo( mOutputPointLayer );
  QString bufferClipLineOutput = outputPointInfo.absolutePath() + "/out_buffer_clip_line.shp";
  QgsFields bufferClipLineFields;
  bufferClipLineFields.append( QgsField( "id", stratumIdType ) );
  QgsVectorFileWriter bufferClipLineWriter( bufferClipLineOutput, "utf-8", bufferClipLineFields, QGis::WKBLineString, &( mStrataLayer->crs() ) );

  //configure distanceArea depending on minDistance units and output CRS
  QgsDistanceArea distanceArea;
  distanceArea.setSourceCrs( mStrataLayer->crs().srsid() );
  if ( mMinDistanceUnits == Meters )
  {
    distanceArea.setEllipsoidalMode( true );
  }
  else
  {
    distanceArea.setEllipsoidalMode( false );
  }

  //possibility to transform output points to lat/long
  QgsCoordinateTransform toLatLongTransform( mStrataLayer->crs(), QgsCoordinateReferenceSystem( 4326, QgsCoordinateReferenceSystem::EpsgCrsId ) );

  //init random number generator
  mt_srand( QTime::currentTime().msec() );

  QgsFeatureRequest fr;
  fr.setSubsetOfAttributes( QStringList() << mStrataIdAttribute << mMinDistanceAttribute << mNPointsAttribute, mStrataLayer->pendingFields() );
  QgsFeatureIterator strataIt = mStrataLayer->getFeatures( fr );

  QgsFeature fet;
  int nTotalTransects = 0;
  int nFeatures = 0;

  if ( pd )
  {
    pd->setMaximum( mStrataLayer->featureCount() );
  }

  while ( strataIt.nextFeature( fet ) )
  {
    if ( pd )
    {
      pd->setValue( nFeatures );
    }
    if ( pd && pd->wasCanceled() )
    {
      break;
    }

    if ( !fet.constGeometry() )
    {
      continue;
    }
    const QgsGeometry* strataGeom = fet.constGeometry();

    //find baseline for strata
    QVariant strataId = fet.attribute( mStrataIdAttribute );
    QgsGeometry* baselineGeom = findBaselineGeometry( strataId.isValid() ? strataId : -1 );
    if ( !baselineGeom )
    {
      continue;
    }

    double minDistance = fet.attribute( mMinDistanceAttribute ).toDouble();
    double minDistanceLayerUnits = minDistance;
    //if minDistance is in meters and the data in degrees, we need to apply a rough conversion for the buffer distance
    double bufferDist = bufferDistance( minDistance );
    if ( mMinDistanceUnits == Meters && mStrataLayer->crs().mapUnits() == QGis::DecimalDegrees )
    {
      minDistanceLayerUnits = minDistance / 111319.9;
    }

    QgsGeometry* clippedBaseline = strataGeom->intersection( baselineGeom );
    if ( !clippedBaseline || clippedBaseline->wkbType() == QGis::WKBUnknown )
    {
      delete clippedBaseline;
      continue;
    }
    QgsGeometry* bufferLineClipped = clipBufferLine( strataGeom, clippedBaseline, bufferDist );
    if ( !bufferLineClipped )
    {
      delete clippedBaseline;
      continue;
    }

    //save clipped baseline to file
    QgsFeature blFeature;
    blFeature.setGeometry( *clippedBaseline );
    blFeature.setAttribute( "stratum_id", strataId );
    blFeature.setAttribute( "ok", "f" );
    usedBaselineWriter.addFeature( blFeature );

    //start loop to create random points along the baseline
    int nTransects = fet.attribute( mNPointsAttribute ).toInt();
    int nCreatedTransects = 0;
    int nIterations = 0;
    int nMaxIterations = nTransects * 50;

    QgsSpatialIndex sIndex; //to check minimum distance
    QMap< QgsFeatureId, QgsGeometry* > lineFeatureMap;

    while ( nCreatedTransects < nTransects && nIterations < nMaxIterations )
    {
      double randomPosition = (( double )mt_rand() / MD_RAND_MAX ) * clippedBaseline->length();
      QgsGeometry* samplePoint = clippedBaseline->interpolate( randomPosition );
      ++nIterations;
      if ( !samplePoint )
      {
        continue;
      }
      QgsPoint sampleQgsPoint = samplePoint->asPoint();
      QgsPoint latLongSamplePoint = toLatLongTransform.transform( sampleQgsPoint );

      QgsFeature samplePointFeature;
      samplePointFeature.setGeometry( samplePoint );
      samplePointFeature.setAttribute( "id", nTotalTransects + 1 );
      samplePointFeature.setAttribute( "station_id", nCreatedTransects + 1 );
      samplePointFeature.setAttribute( "stratum_id", strataId );
      samplePointFeature.setAttribute( "station_code", strataId.toString() + "_" + QString::number( nCreatedTransects + 1 ) );
      samplePointFeature.setAttribute( "start_lat", latLongSamplePoint.y() );
      samplePointFeature.setAttribute( "start_long", latLongSamplePoint.x() );

      //find closest point on clipped buffer line
      QgsPoint minDistPoint;

      int afterVertex;
      if ( bufferLineClipped->closestSegmentWithContext( sampleQgsPoint, minDistPoint, afterVertex ) < 0 )
      {
        continue;
      }

      //bearing between sample point and min dist point (transect direction)
      double bearing = distanceArea.bearing( sampleQgsPoint, minDistPoint ) / M_PI * 180.0;

      QgsPolyline sampleLinePolyline;
      QgsPoint ptFarAway( sampleQgsPoint.x() + ( minDistPoint.x() - sampleQgsPoint.x() ) * 1000000,
                          sampleQgsPoint.y() + ( minDistPoint.y() - sampleQgsPoint.y() ) * 1000000 );
      QgsPolyline lineFarAway;
      lineFarAway << sampleQgsPoint << ptFarAway;
      QgsGeometry* lineFarAwayGeom = QgsGeometry::fromPolyline( lineFarAway );
      QgsGeometry* lineClipStratum = lineFarAwayGeom->intersection( strataGeom );
      if ( !lineClipStratum )
      {
        delete lineFarAwayGeom; delete lineClipStratum;
        continue;
      }

      //cancel if distance between sample point and line is too large (line does not start at point
      if ( lineClipStratum->distance( *samplePoint ) > 0.000001 )
      {
        delete lineFarAwayGeom; delete lineClipStratum;
        continue;
      }

      //if lineClipStratum is a multiline, take the part line closest to sampleQgsPoint
      if ( lineClipStratum->wkbType() == QGis::WKBMultiLineString
           || lineClipStratum->wkbType() == QGis::WKBMultiLineString25D )
      {
        QgsGeometry* singleLine = closestMultilineElement( sampleQgsPoint, lineClipStratum );
        if ( singleLine )
        {
          delete lineClipStratum;
          lineClipStratum = singleLine;
        }
      }

      //cancel if length of lineClipStratum is too small
      double transectLength = distanceArea.measure( lineClipStratum );
      if ( transectLength < mMinTransectLength )
      {
        delete lineFarAwayGeom; delete lineClipStratum;
        continue;
      }

      //search closest existing profile. Cancel if dist < minDist
      if ( otherTransectWithinDistance( lineClipStratum, minDistanceLayerUnits, minDistance, sIndex, lineFeatureMap, distanceArea ) )
      {
        delete lineFarAwayGeom; delete lineClipStratum;
        continue;
      }

      QgsFeatureId fid( nCreatedTransects );
      QgsFeature sampleLineFeature( fid );
      sampleLineFeature.setGeometry( lineClipStratum );
      sampleLineFeature.setAttribute( "id", nTotalTransects + 1 );
      sampleLineFeature.setAttribute( "station_id", nCreatedTransects + 1 );
      sampleLineFeature.setAttribute( "stratum_id", strataId );
      sampleLineFeature.setAttribute( "station_code", strataId.toString() + "_" + QString::number( nCreatedTransects + 1 ) );
      sampleLineFeature.setAttribute( "start_lat", latLongSamplePoint.y() );
      sampleLineFeature.setAttribute( "start_long", latLongSamplePoint.x() );
      sampleLineFeature.setAttribute( "bearing", bearing );
      outputLineWriter.addFeature( sampleLineFeature );

      //add point to file writer here.
      //It can only be written if the corresponding transect has been as well
      outputPointWriter.addFeature( samplePointFeature );

      sIndex.insertFeature( sampleLineFeature );
      Q_NOWARN_DEPRECATED_PUSH
      lineFeatureMap.insert( fid, sampleLineFeature.geometryAndOwnership() );
      Q_NOWARN_DEPRECATED_POP

      delete lineFarAwayGeom;
      ++nTotalTransects;
      ++nCreatedTransects;
    }
    delete clippedBaseline;

    QgsFeature bufferClipFeature;
    bufferClipFeature.setGeometry( bufferLineClipped );
    bufferClipFeature.setAttribute( "id", strataId );
    bufferClipLineWriter.addFeature( bufferClipFeature );
    //delete bufferLineClipped;

    //delete all line geometries in spatial index
    QMap< QgsFeatureId, QgsGeometry* >::iterator featureMapIt = lineFeatureMap.begin();
    for ( ; featureMapIt != lineFeatureMap.end(); ++featureMapIt )
    {
      delete( featureMapIt.value() );
    }
    lineFeatureMap.clear();
    delete baselineGeom;

    ++nFeatures;
  }

  if ( pd )
  {
    pd->setValue( mStrataLayer->featureCount() );
  }

  return 0;
}
Beispiel #14
0
int main(int argc, const char *argv[])
{
    unsigned int i,j;
    unsigned long int elapsed_time;
    unsigned long int times[10];
    double mean, var;

    struct timespec tp1, tp2;

    printf("#======================================#\n");
    printf("|    Speed tests for the generators    |\n");
    printf("#======================================#\n");
    printf("#======================================#\n");
    printf("| The tests consists in measuring the  |\n");
    printf("| time it takes to each generator to   |\n");
    printf("| generate 10 million random numbers   |\n");
    printf("|                                      |\n");
    printf("+--------------------------------------+\n");
    printf("| 32 Bits                              |\n");
    printf("+--------------------------------------+\n");

#if ISAAC_RAND || RANDS_USE_ALL
    isaac_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 10000000; i++)
            isaac_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| ISAAC:               %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

#if ISAAC_X64_RAND || RANDS_USE_ALL
    isaac_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 5000000; i++)
            isaac_x64_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| ISAAC (64bits):      %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

#if PR_RAND || RANDS_USE_ALL
    pr_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 10000000; i++)
            pr_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| Parisi-Rapuano:      %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

#if __SSE2__
#if PR_SSE_RAND || RANDS_USE_ALL
    pr_sse_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 10000000; i++)
            pr_sse_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| Parisi-Rapuano SSE:  %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif
#endif

    srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 10000000; i++)
            rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| Rand (stdlib):       %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);

#if MT_RAND || RANDS_USE_ALL
    mt_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 10000000; i++)
            mt_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| Mersenne Twister:    %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

#if WELL_RAND || RANDS_USE_ALL
    well_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 10000000; i++)
            well_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| WELL512:             %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

#if WELL_X64_RAND || RANDS_USE_ALL
    well_x64_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 5000000; i++)
            well_x64_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| WELL512 (64bits):    %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

#if XOR_RAND || RANDS_USE_ALL
    xor_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 10000000; i++)
            xor_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| Xorshift:            %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

    // END OF 32 BITS
    
    printf("+--------------------------------------+\n");
    printf("+--------------------------------------+\n");
    printf("| 64 Bits                              |\n");
    printf("+--------------------------------------+\n");

#if ISAAC_RAND || RANDS_USE_ALL
    isaac_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 20000000; i++)
            isaac_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| ISAAC:               %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

#if ISAAC_X64_RAND || RANDS_USE_ALL
    isaac_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 10000000; i++)
            isaac_x64_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| ISAAC (64bits):      %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

#if PR_RAND || RANDS_USE_ALL
    pr_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 20000000; i++)
            pr_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| Parisi-Rapuano:      %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

#if __SSE2__
#if PR_SSE_RAND || RANDS_USE_ALL
    pr_sse_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 20000000; i++)
            pr_sse_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| Parisi-Rapuano SSE:  %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif
#endif

    srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 20000000; i++)
            rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| Rand (stdlib):       %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);

#if MT_RAND || RANDS_USE_ALL
    mt_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 20000000; i++)
            mt_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| Mersenne Twister:    %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

#if WELL_RAND || RANDS_USE_ALL
    well_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 20000000; i++)
            well_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| WELL512:             %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

#if WELL_X64_RAND || RANDS_USE_ALL
    well_x64_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 10000000; i++)
            well_x64_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| WELL512 (64bits):    %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

#if XOR_RAND || RANDS_USE_ALL
    xor_srand(time(NULL));
    for(j = 0; j < 10; j++)
    {
        clock_gettime(CLOCK_MONOTONIC,&tp1);
        for(i = 0; i < 20000000; i++)
            xor_rand();
        clock_gettime(CLOCK_MONOTONIC,&tp2);
        elapsed_time = (unsigned long) (tp2.tv_sec-tp1.tv_sec)*1000000000 + \
                       (unsigned long) tp2.tv_nsec-tp1.tv_nsec;
        times[j] = elapsed_time;
    }
    calc_mean_var(&mean,&var,times);

    printf("| Xorshift:            %.4lf ± %.4lf |\n",mean/1e9, sqrt(var)/1e9);
#endif

    // END OF 64 BITS

    printf("+--------------------------------------+\n");
    
    return 0;
}
// Randomize
void MainWindow::on_pushButton_Randomize_pressed()
{
    ui->label_rom_randomized->clear();
    prng_seed[0] = spinBox_PRNG_Seed_1->value();
    prng_seed[1] = spinBox_PRNG_Seed_2->value();
    prng_seed[2] = spinBox_PRNG_Seed_3->value();
    prng_seed[3] = spinBox_PRNG_Seed_4->value();
    prng_seed[4] = spinBox_PRNG_Seed_5->value();
    prng_seed[5] = spinBox_PRNG_Seed_6->value();

    std::seed_seq seeds{prng_seed[0], prng_seed[1], prng_seed[2], prng_seed[3], prng_seed[4], prng_seed[5]};
    std::mt19937 mt_rand(seeds);
    mt_rand.discard(700000);

    // CPU Teams
    if(ui->checkBox_CPUTeams->isChecked()){
        if(ui->checkBox_Randomize_CPU_Sprites->isChecked()){
            randomize_cpu_sprites(mt_rand);
        }

        if(ui->checkBox_Randomize_CPU_Levels->isChecked()){
            randomize_cpu_level(mt_rand);
        }

        if(ui->checkBox_Randomize_CPU_Pkmn->isChecked()){
            randomize_cpu_init_pkmn();
            randomize_cpu_pkmn(mt_rand);
        }

        if(ui->checkBox_Randomize_CPU_Moves->isChecked()){
            randomize_cpu_moves(mt_rand);
        }

        if(ui->checkBox_Randomize_CPU_IVsEVs->isChecked()){
            randomize_cpu_iv_stat_exp(mt_rand);
        }

        if(ui->checkBox_Randomizer_CPU_Names->isChecked()){
            randomize_cpu_nicknames(mt_rand);
            randomize_cpu_trainer_names(mt_rand);
        }

        // Update display
        if(not_in_init){
            display_cpu_trainer_pkmn(ui->comboBox_CPU_Trainer->currentIndex());
        }
    }


    // Rental
    if(ui->checkBox_RentalPkmn->isChecked()){
        if(ui->checkBox_Randomize_Rental_Levels->isChecked()){
            randomize_rental_level(mt_rand);
        }

        if(ui->checkBox_Randomize_Rental_Pkmn->isChecked()){
            randomize_rental_init_pkmn();
            randomize_rental_pkmn(mt_rand);
        }

        if(ui->checkBox_Randomize_Rental_Moves->isChecked()){
            randomize_rental_moves(mt_rand);
        }

        if(ui->checkBox_Randomize_Rental_IVsEVs->isChecked()){
            randomize_rental_iv_stat_exp(mt_rand);
        }

        // Update display
        if(not_in_init){
            display_rental_pkmn((ui->comboBox_Rental_Page->currentIndex())*6);
        }
    }


    // Type chart
    if(ui->checkBox_Randomize_TypeChart->isChecked()){
        randomize_type_chart(mt_rand);
    }
    else{
        if(ui->checkBox_Ghost_vs_Psychic->isChecked()){
            type_chart[75].setType1(0x8);
            type_chart[75].setType2(0x18);
            type_chart[75].setMultiplier(20);
        }
        else{
            type_chart[75].setType1(0x8);
            type_chart[75].setType2(0x18);
            type_chart[75].setMultiplier(0);
        }

        if(ui->checkBox_Ice_vs_Fire->isChecked()){
            type_chart[81].setType1(0x19);
            type_chart[81].setType2(0x14);
            type_chart[81].setMultiplier(5);
        }
        else{
            type_chart[81].setType1(0x1A);
            type_chart[81].setType2(0x1A);
            type_chart[81].setMultiplier(20);
        }

        if(ui->checkBox_Bug_vs_Poison->isChecked()){
            type_chart[67].setType1(0x7);
            type_chart[67].setType2(0x3);
            type_chart[67].setMultiplier(5);
        }
        else{
            type_chart[67].setType1(0x7);
            type_chart[67].setType2(0x3);
            type_chart[67].setMultiplier(20);
        }
    }
    // Update display
    if(not_in_init){
        display_type_chart();
    }


    // New seeds
    if(ui->checkBox_FixedSeeds->isChecked()==false){
        prng_seed[0] = mt_rand();
        prng_seed[1] = mt_rand();
        prng_seed[2] = mt_rand();
        prng_seed[3] = mt_rand();
        prng_seed[4] = mt_rand();
        prng_seed[5] = mt_rand();

        spinBox_PRNG_Seed_1->setValue(prng_seed[0]);
        spinBox_PRNG_Seed_2->setValue(prng_seed[1]);
        spinBox_PRNG_Seed_3->setValue(prng_seed[2]);
        spinBox_PRNG_Seed_4->setValue(prng_seed[3]);
        spinBox_PRNG_Seed_5->setValue(prng_seed[4]);
        spinBox_PRNG_Seed_6->setValue(prng_seed[5]);

        buf8 = mt_rand()%16;
        if(buf8==0) ui->label_rom_randomized->setText("Randomized!");
        else if(buf8==1) ui->label_rom_randomized->setText("Randomized.");
        else if(buf8==2) ui->label_rom_randomized->setText("Randomized~");
        else if(buf8==3) ui->label_rom_randomized->setText("Randomized?");
        else if(buf8==4) ui->label_rom_randomized->setText("Done.");
        else if(buf8==5) ui->label_rom_randomized->setText("Complete.");
        else if(buf8==6) ui->label_rom_randomized->setText("gl hf");
        else if(buf8==7) ui->label_rom_randomized->setText("At your service.");
        else if(buf8==8) ui->label_rom_randomized->setText("Aight.");
        else if(buf8==9) ui->label_rom_randomized->setText("You got it.");
        else if(buf8==10) ui->label_rom_randomized->setText("Mersenne Twistered.");
        else if(buf8==11) ui->label_rom_randomized->setText("~Randomized~");
        else if(buf8==12) ui->label_rom_randomized->setText("Randomized ROM.");
        else if(buf8==13) ui->label_rom_randomized->setText("Good luck!");
        else if(buf8==14) ui->label_rom_randomized->setText("Have fun.");
        else if(buf8==15) ui->label_rom_randomized->setText("Enjoy your ROM!");
    }
    else{
        ui->label_rom_randomized->setText("Fixed randomization.");
    }
}
Beispiel #16
0
void * mysql_thread(int tid) {
	std::mt19937 mt_rand(time(0));

	thread_data_t *THD;
	THD=GloThrData[tid];

	// in this version, each mysql thread has just ONE connection
	// for now we use blocking API
	MYSQL *mysql;

	//MYSQL_STMT **stmt;

	// we intialize the local mapping : MySQL_STMTs_local()
	MySQL_STMTs_local *local_stmts=new MySQL_STMTs_local();

	// we initialize a MYSQL structure
	THD->mysql = mysql_init(NULL);
	mysql=THD->mysql;

	char buff[128];
	unsigned int bl=0;

	// we establish a connection to the database
	if (!mysql_real_connect(mysql,"127.0.0.1",USER,"",SCHEMA,3306,NULL,0)) {
		fprintf(stderr, "Failed to connect to database: Error: %s\n", mysql_error(mysql));
		exit(EXIT_FAILURE);
	}
	int i;

	// array of (MYSQL_STMT *) ; we don't use it in this version
	//stmt=(MYSQL_STMT **)malloc(sizeof(MYSQL_STMT*)*NUMPREP);
	
	MYSQL_STMT *stmt;
	{
	cpu_timer t;
	// in this loop we create only some the prepared statements
	for (i=0; i<NUMPREP/100; i++) {
		sprintf(buff,"SELECT %u + ?",(uint32_t)mt_rand()%NUMPRO);
		bl=strlen(buff);
		uint64_t hash=local_stmts->compute_hash(0,(char *)USER,(char *)SCHEMA,buff,bl);
		MySQL_STMT_Global_info *a=GloMyStmt->find_prepared_statement_by_hash(hash);
		if (a==NULL) { // no prepared statement was found in global
			stmt = mysql_stmt_init(mysql);
			if (!stmt) {
				fprintf(stderr, " mysql_stmt_init(), out of memory\n");
				exit(EXIT_FAILURE);
			}
			if (mysql_stmt_prepare(stmt, buff, bl)) { // the prepared statement is created
				fprintf(stderr, " mysql_stmt_prepare(), failed: %s\n" , mysql_stmt_error(stmt));
				exit(EXIT_FAILURE);
			}
			MySQL_STMT_Global_info *stmt_info=NULL;
			stmt_info=GloMyStmt->add_prepared_statement(0,(char *)USER,(char *)SCHEMA,buff,bl,stmt);
			uint32_t stmid=stmt_info->statement_id;
			if (NUMPRO < 32)
				fprintf(stdout, "SERVER_statement_id=%lu , PROXY_statement_id=%u\n", stmt->stmt_id, stmid);
			local_stmts->insert(stmid,stmt);
			}
	}
	fprintf(stdout, "Prepared statements: %u client, %u proxy/server. ", i, GloMyStmt->total_prepared_statements());
	fprintf(stdout, "Created in: ");
	}
	{
		unsigned int founds=0;
		cpu_timer t;
		for (i=0; i<NUMPREP*LOOPS; i++) {
			sprintf(buff,"SELECT %u + ?",(uint32_t)mt_rand()%NUMPRO);
			bl=strlen(buff);
			//uint64_t hash=local_stmts->compute_hash(0,(char *)USER,(char *)SCHEMA,buff,bl);
			//MySQL_STMT_Global_info *a=GloMyStmt->find_prepared_statement_by_hash(hash);
			//if (a) founds++;
		}
		fprintf(stdout, "Computed %u random strings in: ", i);
	}
	{
		unsigned int founds=0;
		cpu_timer t;
		for (i=0; i<NUMPREP*LOOPS; i++) {
			sprintf(buff,"SELECT %u + ?",(uint32_t)mt_rand()%NUMPRO);
			bl=strlen(buff);
			uint64_t hash=local_stmts->compute_hash(0,(char *)USER,(char *)SCHEMA,buff,bl);
			//MySQL_STMT_Global_info *a=GloMyStmt->find_prepared_statement_by_hash(hash);
			//if (a) founds++;
		}
		fprintf(stdout, "Computed %u hashes in: ", i);
	}
	{
		unsigned int founds=0;
		cpu_timer t;
		for (i=0; i<NUMPREP*LOOPS; i++) {
			sprintf(buff,"SELECT %u + ?",(uint32_t)mt_rand()%NUMPRO);
			bl=strlen(buff);
			uint64_t hash=local_stmts->compute_hash(0,(char *)USER,(char *)SCHEMA,buff,bl);
			MySQL_STMT_Global_info *a=GloMyStmt->find_prepared_statement_by_hash(hash);
			if (a) founds++;
		}
		fprintf(stdout, "Found    %u prepared statements searching by hash in: ", founds);
	}

	{
		unsigned int founds=0;
		unsigned int created=0;
		unsigned int executed=0;
		cpu_timer t;
		for (i=0; i<NUMPREP*LOOPS; i++) {
			sprintf(buff,"SELECT %u + ?",(uint32_t)mt_rand()%NUMPRO);
			bl=strlen(buff);
			uint64_t hash=local_stmts->compute_hash(0,(char *)USER,(char *)SCHEMA,buff,bl);
			MySQL_STMT_Global_info *a=GloMyStmt->find_prepared_statement_by_hash(hash);
			if (a) {
				// we have a prepared statement, we can run it
				MYSQL_STMT *stm=local_stmts->find(a->statement_id);
				if (stm) { // the statement exists in local
					run_stmt(stm,(uint32_t)mt_rand());
					founds++;
					executed++;
					local_stmts->erase(a->statement_id);
				} else { // the statement doesn't exist locally
					stmt = mysql_stmt_init(mysql);	
					if (!stmt) {
						fprintf(stderr, " mysql_stmt_init(), out of memory\n");
						exit(EXIT_FAILURE);
					}
					if (mysql_stmt_prepare(stmt, buff, bl)) { // the prepared statement is created
						fprintf(stderr, " mysql_stmt_prepare(), failed: %s\n" , mysql_stmt_error(stmt));
						exit(EXIT_FAILURE);
					}
					local_stmts->insert(a->statement_id,stmt);
					run_stmt(stmt,(uint32_t)mt_rand());
					created++;
					executed++;
					local_stmts->erase(a->statement_id);
				}
			} else { // no prepared statement was found in global
				stmt = mysql_stmt_init(mysql);	
				if (!stmt) {
					fprintf(stderr, " mysql_stmt_init(), out of memory\n");
					exit(EXIT_FAILURE);
				}
				if (mysql_stmt_prepare(stmt, buff, bl)) { // the prepared statement is created
					fprintf(stderr, " mysql_stmt_prepare(), failed: %s\n" , mysql_stmt_error(stmt));
					exit(EXIT_FAILURE);
				}
				MySQL_STMT_Global_info *stmt_info=NULL;
				stmt_info=GloMyStmt->add_prepared_statement(0,(char *)USER,(char *)SCHEMA,buff,bl,stmt);
				uint32_t stmid=stmt_info->statement_id;
				if (NUMPRO < 32)
					fprintf(stdout, "SERVER_statement_id=%lu , PROXY_statement_id=%u\n", stmt->stmt_id, stmid);
				local_stmts->insert(stmid,stmt);
				run_stmt(stmt,(uint32_t)mt_rand());
				created++;
				executed++;
				local_stmts->erase(stmid);
			}
		}
		fprintf(stdout, "Found %u , created %u and executed %u prepared statements in: ", founds, created, executed);
	}
/*
	{
		// for comparison, we run also queries in TEXT protocol
		cpu_timer t;
		for (i=0; i<NUMPREP*LOOPS; i++) {
			sprintf(buff,"SELECT %u + %u",i,(uint32_t)mt_rand()%NUMPRO);
			bl=strlen(buff);
			int rc=mysql_real_query(mysql,buff,bl);
			if (rc) {
				fprintf(stderr, " mysql_real_query(), failed: %s\n" , mysql_error(mysql));
				exit(EXIT_FAILURE);
			}
			MYSQL_RES *res=mysql_store_result(mysql);
			if (res==NULL) {
				fprintf(stderr, " mysql_store_result(), failed: %s\n" , mysql_error(mysql));
				exit(EXIT_FAILURE);
			}
			mysql_free_result(res);
		}
		fprintf(stdout, "Executed %u queries in: ", i);
	}
	return 0;
*/
}
Beispiel #17
0
bool set_test() {
	std::set<int> s1;
	tpie::tiny::set<int> s2;
	std::mt19937 mt_rand(42);

	TEST_ENSURE_EQUALITY(s1.empty(), s2.empty(), "empty");
	for (size_t i=0; i < 100; ++i) {
		size_t n=mt_rand();
		s1.insert(n);
		s2.insert(n);
	}

	TEST_ENSURE_EQUALITY(s1.empty(), s2.empty(), "");
	TEST_ENSURE_EQUALITY(s1.size(), s2.size(), "");
	TEST_ENSURE(my_equal(s1.begin(), s1.end(), s2.begin(), s2.end()), "begin");
	TEST_ENSURE(my_equal(s1.cbegin(), s1.cend(), s2.cbegin(), s2.cend()), "cbegin");
	TEST_ENSURE(my_equal(s1.rbegin(), s1.rend(), s2.rbegin(), s2.rend()), "rbegin");
	TEST_ENSURE(my_equal(s1.crbegin(), s1.crend(), s2.crbegin(), s2.crend()), "crbegin");
	TEST_ENSURE(s2.max_size() >= s2.size(), "max_size");
	TEST_ENSURE(s2.capacity() >= s2.size(), "capacity");
	// Make sure that all methods compile
	s2.reserve(0);
	s2.shrink_to_fit();
	tpie::unused(s2.key_comp());
	tpie::unused(s2.value_comp());
	tpie::unused(s2.get_allocator());

	s2.clear();
	TEST_ENSURE(s2.empty(), "empty");
	s2.insert({12, 11});
	TEST_ENSURE_EQUALITY(s2.count(11), 1, "count");
	TEST_ENSURE_EQUALITY(s2.count(10), 0, "count");
	s2.emplace(14);
	TEST_ENSURE_EQUALITY(s2.count(14), 1, "count");

	auto a1=s2.insert(16);
	TEST_ENSURE_EQUALITY(*a1.first, 16, "insert");
	TEST_ENSURE(a1.second, "insert");
	a1=s2.insert(16);
	TEST_ENSURE_EQUALITY(*a1.first, 16, "insert");
	TEST_ENSURE(!a1.second, "insert");
	TEST_ENSURE_EQUALITY(*s2.lower_bound(15), 16, "lower_bound");
	TEST_ENSURE_EQUALITY(*s2.lower_bound(14), 14, "lower_bound");
	TEST_ENSURE_EQUALITY(*s2.upper_bound(15), 16, "upper_bound");
	TEST_ENSURE_EQUALITY(*s2.upper_bound(14), 16, "upper_bound");
	auto a2=s2.equal_range(14);
	TEST_ENSURE_EQUALITY(*a2.first, 14, "equal_range");
	TEST_ENSURE_EQUALITY(*a2.second, 16, "equal_range");
	TEST_ENSURE_EQUALITY(*s2.find(14), 14, "find");
	TEST_ENSURE(s2.find(15) == s2.end(), "find");
	TEST_ENSURE_EQUALITY(s2.erase(11), 1, "erase");
	TEST_ENSURE_EQUALITY(s2.erase(10), 0, "erase");
	TEST_ENSURE_EQUALITY(s2.count(11), 0, "count");
	s2.erase(s2.find(14));
	TEST_ENSURE_EQUALITY(s2.count(14), 0, "count");

	tpie::tiny::set<int>::const_iterator i = s2.erase(s2.begin(), s2.end());
	tpie::tiny::set<int>::const_iterator j = s2.end();
	TEST_ENSURE(i == j, "erase");
	TEST_ENSURE(s2.empty(), "empty");
	return true;
}
void Benchmark(BenchStaticRTree &rtree, unsigned num_queries)
{
    std::mt19937 mt_rand(RANDOM_SEED);
    std::uniform_int_distribution<> lat_udist(WORLD_MIN_LAT, WORLD_MAX_LAT);
    std::uniform_int_distribution<> lon_udist(WORLD_MIN_LON, WORLD_MAX_LON);
    std::vector<FixedPointCoordinate> queries;
    for (unsigned i = 0; i < num_queries; i++)
    {
        queries.emplace_back(FixedPointCoordinate(lat_udist(mt_rand), lon_udist(mt_rand)));
    }

    {
        const unsigned num_results = 5;
        std::cout << "#### IncrementalFindPhantomNodeForCoordinate : " << num_results
                  << " phantom nodes"
                  << "\n";

        TIMER_START(query_phantom);
        std::vector<PhantomNode> phantom_node_vector;
        for (const auto &q : queries)
        {
            phantom_node_vector.clear();
            rtree.IncrementalFindPhantomNodeForCoordinate(q, phantom_node_vector, 3, num_results);
            phantom_node_vector.clear();
            rtree.IncrementalFindPhantomNodeForCoordinate(q, phantom_node_vector, 17, num_results);
        }
        TIMER_STOP(query_phantom);

        std::cout << "Took " << TIMER_MSEC(query_phantom) << " msec for " << num_queries
                  << " queries."
                  << "\n";
        std::cout << TIMER_MSEC(query_phantom) / ((double)num_queries) << " msec/query."
                  << "\n";

        std::cout << "#### LocateClosestEndPointForCoordinate"
                  << "\n";
    }

    TIMER_START(query_endpoint);
    FixedPointCoordinate result;
    for (const auto &q : queries)
    {
        rtree.LocateClosestEndPointForCoordinate(q, result, 3);
    }
    TIMER_STOP(query_endpoint);

    std::cout << "Took " << TIMER_MSEC(query_endpoint) << " msec for " << num_queries << " queries."
              << "\n";
    std::cout << TIMER_MSEC(query_endpoint) / ((double)num_queries) << " msec/query."
              << "\n";

    std::cout << "#### FindPhantomNodeForCoordinate"
              << "\n";

    TIMER_START(query_node);
    for (const auto &q : queries)
    {
        PhantomNode phantom;
        rtree.FindPhantomNodeForCoordinate(q, phantom, 3);
    }
    TIMER_STOP(query_node);

    std::cout << "Took " << TIMER_MSEC(query_node) << " msec for " << num_queries << " queries."
              << "\n";
    std::cout << TIMER_MSEC(query_node) / ((double)num_queries) << " msec/query."
              << "\n";

    {
        const unsigned num_results = 1;
        std::cout << "#### IncrementalFindPhantomNodeForCoordinate : " << num_results
                  << " phantom nodes"
                  << "\n";

        TIMER_START(query_phantom);
        std::vector<PhantomNode> phantom_node_vector;
        for (const auto &q : queries)
        {
            phantom_node_vector.clear();
            rtree.IncrementalFindPhantomNodeForCoordinate(q, phantom_node_vector, 3, num_results);
            phantom_node_vector.clear();
            rtree.IncrementalFindPhantomNodeForCoordinate(q, phantom_node_vector, 17, num_results);
        }
        TIMER_STOP(query_phantom);

        std::cout << "Took " << TIMER_MSEC(query_phantom) << " msec for " << num_queries
                  << " queries."
                  << "\n";
        std::cout << TIMER_MSEC(query_phantom) / ((double)num_queries) << " msec/query."
                  << "\n";

        std::cout << "#### LocateClosestEndPointForCoordinate"
                  << "\n";
    }
}
Beispiel #19
0
void JE_jukeboxGo( void )
{
	JE_boolean weirdMusic, weirdCurrent;
	JE_byte weirdSpeed = 0;
	char tempStr[64];

	JE_byte lastSong;
	JE_byte tempVolume;
	JE_boolean youStopped, drawText, quit, fade;


	weirdMusic = false;
	weirdCurrent = true;
	drawText = true;

	fx = false;
	fxNum = 1;

	lastSong = currentJukeboxSong;

	JE_fadeBlack(10);
	SDL_FillRect(VGAScreenSeg, NULL, 0x0);
	JE_showVGA();
	JE_updateColorsFast(vga_palette); //JE_fadeColor(10);

	JE_starlib_init();

	quit = false;
	fade = false;
	repeatedFade = false;

	tempVolume = tyrMusicVolume;
	youStopped = false;

	JE_wipeKey();

	do
	{
		tempScreenSeg = VGAScreenSeg;

		if (weirdMusic)
		{
			if (delaycount2() == 0)
			{
				setjasondelay2(weirdSpeed);
				
				if (weirdCurrent)
				{
					JE_setVol(tempVolume / 2, fxVolume);
				} else {
					JE_setVol(tempVolume, fxVolume);
				}
				
				weirdCurrent = !weirdCurrent;
			}
		}

		if (repeated && !repeatedFade)
		{
			fade = true;
			repeatedFade = true;
		}

		if ( ( (repeated && !fade) || !playing) && !youStopped)
		{
			currentJukeboxSong = ( mt_rand() % MUSIC_NUM );
			JE_playNewSong();
		}

		setdelay(1);
		
		push_joysticks_as_keyboard();
		service_SDL_events(true);

		JE_starlib_main();

		if (lastSong != currentJukeboxSong)
		{
			lastSong = currentJukeboxSong;
			JE_bar(50, 190, 250, 198, 0);
		}

		if (drawText)
		{
			tempScreenSeg = VGAScreenSeg;
			if (fx)
			{
				sprintf(tempStr, "%d %s", fxNum, soundTitle[fxNum - 1]);
				JE_bar(50, 190, 250, 198, 0);
				JE_outText(JE_fontCenter(tempStr, TINY_FONT), 190, tempStr, 1, 4);
			} else {
				sprintf(tempStr, "%d %s", currentJukeboxSong, musicTitle[currentJukeboxSong - 1]);
				JE_outText(JE_fontCenter(tempStr, TINY_FONT), 190, tempStr, 1, 4);
			}

			tempScreenSeg = VGAScreenSeg;
			JE_outText(JE_fontCenter("Press ESC to quit the jukebox.", TINY_FONT), 170, "Press ESC to quit the jukebox.", 1, 0);
			tempScreenSeg = VGAScreenSeg;
			JE_outText(JE_fontCenter("Arrow keys change the song being played.", TINY_FONT), 180, "Arrow keys change the song being played.", 1, 0);
		}

		JE_showVGA();
		
		wait_delay();

		if (fade)
		{
			if (volumeActive)
			{
				if (tempVolume > 5)
				{
					tempVolume -= 2;
					JE_setVol(tempVolume, fxVolume);
				} else {
					fade = false;
				}
			}
			else if (speed < 0xE000)
			{
				speed += 0x800;
			} else {
				speed = 0xE000;
				fade = false;
			}
			JE_resetTimerInt();
			JE_setTimerInt();
		}

		if (JE_mousePosition(&x, &y) > 0 || button[0])
		{
			quit = true;
			JE_wipeKey();
		}

		if (newkey)
		{
			JE_newSpeed();
			switch (lastkey_sym)
			{
			case SDLK_ESCAPE: /* quit jukebox */
			case SDLK_q:
				quit = true;
				break;
			case SDLK_r: /* restart song */
				JE_jukebox_selectSong(1);
				break;
			case SDLK_n: /* toggle continuous play */
				continuousPlay = !continuousPlay;
				break;
			case SDLK_v:
				volumeActive = !volumeActive;
				break;
			case SDLK_t: /* No idea what this is doing -- possibly resetting to default speed? */
				speed = 0x4300;
				JE_resetTimerInt();
				JE_setTimerInt();
				break;
			case SDLK_f:
				fade = !fade;
				break;
			case SDLK_COMMA: /* dec sound effect */
				fxNum = (fxNum - 1 < 1) ? SOUND_NUM + 9 : fxNum - 1;
				break;
			case SDLK_PERIOD: /* inc sound effect */
				fxNum = (fxNum + 1 > SOUND_NUM + 9) ? 1 : fxNum + 1;
				break;
			case SDLK_SLASH: /* switch to sfx mode */
				fx = !fx;
				break;
			case SDLK_SEMICOLON:
				JE_playSampleNum(fxNum);
				break;
			case SDLK_RETURN:
				currentJukeboxSong++;
				JE_playNewSong();
				youStopped = false;
				break;
			case SDLK_s:
				JE_jukebox_selectSong(0);
				youStopped = true;
				break;
			case SDLK_w:
				if (!weirdMusic)
				{
					weirdMusic = true;
					weirdSpeed = 10;
				}
				else if (weirdSpeed > 1)
				{
					weirdSpeed--;
				}
				else
				{
					weirdMusic = false;
					if (!fade)
					{
						JE_setVol(tempVolume, fxVolume);
					}
				}
				break;
			case SDLK_SPACE:
				drawText = !drawText;
				if (!drawText)
				{
					JE_bar(30, 170, 270, 198, 0);
				}
				break;
			case SDLK_LEFT:
			case SDLK_UP:
				currentJukeboxSong--;
				JE_playNewSong();
				youStopped = false;
				break;
			case SDLK_RIGHT:
			case SDLK_DOWN:
				currentJukeboxSong++;
				JE_playNewSong();
				youStopped = false;
				break;
			default:
				break;
			}
		}
	} while (!quit);
	
	JE_updateColorsFast(black); //JE_fadeBlack(10);
	JE_setVol(255, fxVolume);
}
Beispiel #20
0
static uint64_t unique_id() {
  return (((uint64_t) (time(NULL) & 0xffffffff)) << 32) |
         (mt_rand() & 0xffffffff);
}
Beispiel #21
0
/* Text is an array of strings terminated by a NULL */
void scroller_sine( const struct about_text_type text[] )
{
    bool ale = mt_rand() % 2;

    int visible_lines = vga_height / LINE_HEIGHT + 1;
    int current_line = -visible_lines;
    int y = 0;
    bool fade_in = true;

    struct coin_type {
        int x, y, vel, type, cur_frame;
        bool backwards;
    } coins[MAX_COINS];
    struct {
        int x, y, ay, vx, vy;
    } beer[MAX_BEER];

    if (ale)
    {
        memset(beer, 0, sizeof(beer));
    } else {
        for (int i = 0; i < MAX_COINS; i++)
        {
            coins[i].x = mt_rand() % (vga_width - 12);
            coins[i].y = mt_rand() % (vga_height - 20 - 14);

            coins[i].vel = (mt_rand() % 4) + 1;
            coins[i].type = mt_rand() % COUNTOF(coin_defs);
            coins[i].cur_frame = mt_rand() % coin_defs[coins[i].type].frame_count;
            coins[i].backwards = false;
        }
    }

    fade_black(10);

    wait_noinput(true, true, true);

    play_song(40); // BEER

    while (!JE_anyButton())
    {
        setdelay(3);

        JE_clr256(VGAScreen);

        if (!ale)
        {
            for (int i = 0; i < MAX_COINS/2; i++)
            {
                struct coin_type *coin = &coins[i];
                blit_sprite2(VGAScreen, coin->x, coin->y, eShapes5, coin_defs[coin->type].shape_num + coin->cur_frame);
            }
        }

        for (int i = 0; i < visible_lines; i++)
        {
            if (current_line + i >= 0)
            {
                if (text[current_line + i].text == NULL)
                {
                    break;
                }

                int line_x = VGAScreen->w / 2;
                int line_y = i * LINE_HEIGHT - y;

                // smooths edges on sine-wave text
                if (text[i + current_line].effect & 0x20)
                {
                    draw_font_hv(VGAScreen, line_x + 1, line_y, text[i + current_line].text, normal_font, centered, text[i + current_line].effect & 0x0f, -10);
                    draw_font_hv(VGAScreen, line_x - 1, line_y, text[i + current_line].text, normal_font, centered, text[i + current_line].effect & 0x0f, -10);
                }

                draw_font_hv(VGAScreen, line_x, line_y, text[i + current_line].text, normal_font, centered, text[i + current_line].effect & 0x0f, -4);

                if (text[i + current_line].effect & 0x10)
                {
                    for (int j = 0; j < LINE_HEIGHT; j++)
                    {
                        if (line_y + j >= 10 && line_y + j <= vga_height - 10)
                        {
                            int waver = sinf((((line_y + j) / 2) % 10) / 5.0f * M_PI) * 3;
                            memmove(&((Uint8 *)VGAScreen->pixels)[VGAScreen->pitch * (line_y + j) + waver],
                                    &((Uint8 *)VGAScreen->pixels)[VGAScreen->pitch * (line_y + j)],
                                    VGAScreen->pitch);
                        }
                    }
                }
            }
        }

        if (++y == LINE_HEIGHT)
        {
            y = 0;

            if (current_line < 0 || text[current_line].text != NULL)
                ++current_line;
            else
                current_line = -visible_lines;
        }

        if (!ale)
        {
            for (int i = MAX_COINS/2; i < MAX_COINS; i++)
            {
                struct coin_type *coin = &coins[i];
                blit_sprite2(VGAScreen, coin->x, coin->y, eShapes5, coin_defs[coin->type].shape_num + coin->cur_frame);
            }
        }

        fill_rectangle_xy(VGAScreen, 0, 0, vga_width - 1, 14, 0);
        fill_rectangle_xy(VGAScreen, 0, vga_height - 14, vga_width - 1, vga_height - 1, 0);

        if (!ale)
        {
            for (int i = 0; i < MAX_COINS; i++)
            {
                struct coin_type *coin = &coins[i];

                if (coin->backwards)
                {
                    coin->cur_frame--;
                } else {
                    coin->cur_frame++;
                }
                if (coin->cur_frame == coin_defs[coin->type].frame_count)
                {
                    if (coin_defs[coin->type].reverse_anim)
                    {
                        coin->backwards = true;
                        coin->cur_frame -= 2;
                    } else {
                        coin->cur_frame = 0;
                    }
                }
                if (coin->cur_frame == -1)
                {
                    coin->cur_frame = 1;
                    coin->backwards = false;
                }

                coin->y += coin->vel;
                if (coin->y > vga_height - 14)
                {
                    coin->x = mt_rand() % (vga_width - 12);
                    coin->y = 0;

                    coin->vel = (mt_rand() % 4) + 1;
                    coin->type = mt_rand() % COUNTOF(coin_defs);
                    coin->cur_frame = mt_rand() % coin_defs[coin->type].frame_count;
                }
            }
        } else {
            for (uint i = 0; i < COUNTOF(beer); i++)
            {
                while (beer[i].vx == 0)
                {
                    beer[i].x = mt_rand() % (vga_width - 24);
                    beer[i].y = mt_rand() % (vga_height - 28 - 50);

                    beer[i].vx = (mt_rand() % 5) - 2;
                }

                beer[i].vy++;

                if (beer[i].x + beer[i].vx > vga_width - 24 || beer[i].x + beer[i].vx < 0) // check if the beer hit the sides
                {
                    beer[i].vx = -beer[i].vx;
                }
                beer[i].x += beer[i].vx;

                if (beer[i].y + beer[i].vy > vga_height - 28) // check if the beer hit the bottom
                {
                    if ((beer[i].vy) < 8) // make sure the beer bounces!
                    {
                        beer[i].vy += mt_rand() % 2;
                    } else if (beer[i].vy > 16) { // make sure the beer doesn't bounce too high
                        beer[i].vy = 16;
                    }
                    beer[i].vy = -beer[i].vy + (mt_rand() % 3 - 1);

                    beer[i].x += (beer[i].vx > 0 ? 1 : -1) * (i % 2 ? 1 : -1);
                }
                beer[i].y += beer[i].vy;

                blit_sprite2x2(VGAScreen, beer[i].x, beer[i].y, eShapes5, BEER_SHAPE);
            }
        }

        JE_showVGA();

        if (fade_in)
        {
            fade_in = false;
            fade_palette(colors, 10, 0, 255);

            SDL_Color white = { 255, 255, 255 };
            set_colors(white, 254, 254);
        }

        wait_delay();
    }

    fade_black(10);
}
Beispiel #22
0
void jukebox( void )
{
	bool trigger_quit = false,  // true when user wants to quit
	     quitting = false;
	
	bool hide_text = false;

	bool fade_looped_songs = true, fading_song = false;
	bool stopped = false;

	bool fx = false;
	int fx_num = 0;

	int palette_fade_steps = 15;

	int diff[256][3];
	init_step_fade_palette(diff, vga_palette, 0, 255);

	JE_starlib_init();

	int fade_volume = tyrMusicVolume;
	
	for (; ; )
	{
		if (!stopped && !audio_disabled)
		{
			if (songlooped && fade_looped_songs)
				fading_song = true;

			if (fading_song)
			{
				if (fade_volume > 5)
				{
					fade_volume -= 2;
				}
				else
				{
					fade_volume = tyrMusicVolume;

					fading_song = false;
				}

				set_volume(fade_volume, fxVolume);
			}

			if (!playing || (songlooped && fade_looped_songs && !fading_song))
				play_song(mt_rand() % MUSIC_NUM);
		}

		setdelay(1);

		SDL_FillRect(VGAScreenSeg, NULL, 0);

		// starlib input needs to be rewritten
		JE_starlib_main();

		push_joysticks_as_keyboard();
		service_SDL_events(true);

		if (!hide_text)
		{
			char buffer[60];
			
			if (fx)
				snprintf(buffer, sizeof(buffer), "%d %s", fx_num + 1, soundTitle[fx_num]);
			else
				snprintf(buffer, sizeof(buffer), "%d %s", song_playing + 1, musicTitle[song_playing]);
			
			const int x = VGAScreen->w / 2;
			
#ifdef ANDROID
			draw_font_hv(VGAScreen, x, 170, "Press the Back button to quit the jukebox.",           small_font, centered, 1, 0);
			draw_font_hv(VGAScreen, x, 180, "Touch to change the song being played.", small_font, centered, 1, 0);
#else
			draw_font_hv(VGAScreen, x, 170, "Press ESC to quit the jukebox.",           small_font, centered, 1, 0);
			draw_font_hv(VGAScreen, x, 180, "Arrow keys change the song being played.", small_font, centered, 1, 0);
#endif
			draw_font_hv(VGAScreen, x, 190, buffer,                                     small_font, centered, 1, 4);
		}

		if (palette_fade_steps > 0)
			step_fade_palette(diff, palette_fade_steps--, 0, 255);
		
		JE_showVGA();

		wait_delay();

#ifdef ANDROID
		if (mousedown)
		{
			wait_noinput(true, true, true);
			newkey = true;
			if (mouse_x < 160)
				lastkey_sym = SDLK_LEFT;
			else
				lastkey_sym = SDLK_RIGHT;
		}
#else
		// quit on mouse click
		Uint16 x, y;
		if (JE_mousePosition(&x, &y) > 0)
			trigger_quit = true;
#endif

		if (newkey)
		{
			switch (lastkey_sym)
			{
			case SDLK_ESCAPE: // quit jukebox
			case SDLK_q:
				trigger_quit = true;
				break;

			case SDLK_SPACE:
				hide_text = !hide_text;
				break;

			case SDLK_f:
				fading_song = !fading_song;
				break;
			case SDLK_n:
				fade_looped_songs = !fade_looped_songs;
				break;

			case SDLK_SLASH: // switch to sfx mode
				fx = !fx;
				break;
			case SDLK_COMMA:
				if (fx && --fx_num < 0)
					fx_num = SAMPLE_COUNT - 1;
				break;
			case SDLK_PERIOD:
				if (fx && ++fx_num >= SAMPLE_COUNT)
					fx_num = 0;
				break;
			case SDLK_SEMICOLON:
				if (fx)
					JE_playSampleNum(fx_num + 1);
				break;

			case SDLK_LEFT:
			case SDLK_UP:
			case SDLK_LCTRL:
				play_song((song_playing > 0 ? song_playing : MUSIC_NUM) - 1);
				stopped = false;
				break;
			case SDLK_RETURN:
			case SDLK_RIGHT:
			case SDLK_DOWN:
			case SDLK_LALT:
				play_song((song_playing + 1) % MUSIC_NUM);
				stopped = false;
				break;
			case SDLK_s: // stop song
				stop_song();
				stopped = true;
				break;
			case SDLK_r: // restart song
				restart_song();
				stopped = false;
				break;

			default:
				break;
			}
		}
		
		// user wants to quit, start fade-out
		if (trigger_quit && !quitting)
		{
			palette_fade_steps = 15;
			
			SDL_Color black = { 0, 0, 0 };
			init_step_fade_solid(diff, black, 0, 255);
			
			quitting = true;
		}
		
		// if fade-out finished, we can finally quit
		if (quitting && palette_fade_steps == 0)
			break;
	}

	set_volume(tyrMusicVolume, fxVolume);
}