<commit_before>#include <CoreFoundation/CoreFoundation.h>

#include "SFBAudioEngine/AudioDecoder.h"
#include "SFBAudioEngine/AudioMetadata.h"
#include "SFBAudioEngine/AudioPlayer.h"
#include "SFBAudioEngine/DSPAudioPlayer.h"

#include "CAStreamBasicDescription.h"

#include <unistd.h>

static CFArrayRef
CreateOutputDeviceArray()
{
	UInt32 specifierSize = 0;
	OSStatus status = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &specifierSize, NULL);
	if(kAudioHardwareNoError != status) {
		printf("AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices) failed: %i\n", status);
		return NULL;
	}

	UInt32 deviceCount = static_cast<UInt32>(specifierSize / sizeof(AudioDeviceID));

	AudioDeviceID *audioDevices = static_cast<AudioDeviceID *>(calloc(1, specifierSize));
	if(NULL == audioDevices) {
		puts("Unable to allocate memory");
		return NULL;
	}

	status = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &specifierSize, audioDevices);
	if(kAudioHardwareNoError != status) {
		printf("AudioHardwareGetProperty (kAudioHardwarePropertyDevices) failed: %i\n", status);
		free(audioDevices), audioDevices = NULL;
		return NULL;
	}

	CFMutableArrayRef outputDeviceArray = CFArrayCreateMutable(kCFAllocatorDefault, deviceCount, &kCFTypeArrayCallBacks);
	if(NULL == outputDeviceArray) {
		puts("CFArrayCreateMutable failed");
		free(audioDevices), audioDevices = NULL;
		return NULL;
	}

	// Iterate through all the devices and determine which are output-capable
	for(UInt32 i = 0; i < deviceCount; ++i) {
		// Query device UID
		CFStringRef deviceUID = NULL;
		specifierSize = sizeof(deviceUID);
		status = AudioDeviceGetProperty(audioDevices[i], 0, FALSE, kAudioDevicePropertyDeviceUID, &specifierSize, &deviceUID);
		if(kAudioHardwareNoError != status) {
			printf("AudioDeviceGetProperty (kAudioDevicePropertyDeviceUID) failed: %i\n", status);
			continue;
		}

		// Query device name
		CFStringRef deviceName = NULL;
		specifierSize = sizeof(deviceName);
		status = AudioDeviceGetProperty(audioDevices[i], 0, FALSE, kAudioDevicePropertyDeviceNameCFString, &specifierSize, &deviceName);
		if(kAudioHardwareNoError != status) {
			printf("AudioDeviceGetProperty (kAudioDevicePropertyDeviceNameCFString) failed: %i\n", status);
			continue;
		}

		// Query device manufacturer
		CFStringRef deviceManufacturer = NULL;
		specifierSize = sizeof(deviceManufacturer);
		status = AudioDeviceGetProperty(audioDevices[i], 0, FALSE, kAudioDevicePropertyDeviceManufacturerCFString, &specifierSize, &deviceManufacturer);
		if(kAudioHardwareNoError != status) {
			printf("AudioDeviceGetProperty (kAudioDevicePropertyDeviceManufacturerCFString) failed: %i\n", status);
			continue;
		}

		// Determine if the device is an output device (it is an output device if it has output channels)
		specifierSize = 0;
		status = AudioDeviceGetPropertyInfo(audioDevices[i], 0, FALSE, kAudioDevicePropertyStreamConfiguration, &specifierSize, NULL);
		if(kAudioHardwareNoError != status) {
			printf("AudioDeviceGetPropertyInfo (kAudioDevicePropertyStreamConfiguration) failed: %i\n", status);
			continue;
		}

		AudioBufferList *bufferList = static_cast<AudioBufferList *>(calloc(1, specifierSize));
		if(NULL == bufferList) {
			puts("Unable to allocate memory");
			break;
		}

		status = AudioDeviceGetProperty(audioDevices[i], 0, FALSE, kAudioDevicePropertyStreamConfiguration, &specifierSize, bufferList);
		if(kAudioHardwareNoError != status || 0 == bufferList->mNumberBuffers) {
			printf("AudioDeviceGetProperty (kAudioDevicePropertyStreamConfiguration) failed: %i\n", status);
			free(bufferList), bufferList = NULL;
			continue;
		}

		free(bufferList), bufferList = NULL;

		// Add a dictionary for this device to the array of output devices
		CFStringRef keys	[]	= { CFSTR("deviceUID"),		CFSTR("deviceName"),	CFSTR("deviceManufacturer") };
		CFStringRef values	[]	= { deviceUID,				deviceName,				deviceManufacturer };

		CFDictionaryRef deviceDictionary = CFDictionaryCreate(kCFAllocatorDefault,
															  reinterpret_cast<const void **>(keys),
															  reinterpret_cast<const void **>(values),
															  3,
															  &kCFTypeDictionaryKeyCallBacks,
															  &kCFTypeDictionaryValueCallBacks);

		CFArrayAppendValue(outputDeviceArray, deviceDictionary);
	}

	free(audioDevices), audioDevices = NULL;

	// Return a non-mutable copy of the array
	CFArrayRef copy = CFArrayCreateCopy(kCFAllocatorDefault, outputDeviceArray);
	CFRelease(outputDeviceArray), outputDeviceArray = NULL;

	return copy;
}

static void
PrintStreamsForDeviceID(AudioDeviceID deviceID)
{
	AudioObjectShow(deviceID);

	UInt32 mixable = 0xFFFF;
	UInt32 specifierSize = sizeof(mixable);
	OSStatus result = AudioDeviceGetProperty(deviceID,
											 0,
											 FALSE,
											 kAudioDevicePropertySupportsMixing,
											 &specifierSize,
											 &mixable);

	if(noErr != result)
		fprintf(stderr, "AudioDeviceGetProperty (kAudioDevicePropertySupportsMixing) failed: %i\n", result);

	printf("Device supports mixing: %s\n", mixable ? "Yes" : "No");

	result = AudioDeviceGetPropertyInfo(deviceID,
										0,
										FALSE,
										kAudioDevicePropertyStreams,
										&specifierSize,
										NULL);

	if(noErr != result) {
		fprintf(stderr, "AudioDeviceGetPropertyInfo (kAudioDevicePropertyStreams) failed: %i\n", result);
		return;
	}

	UInt32 streamCount = static_cast<UInt32>(specifierSize / sizeof(AudioStreamID));

	AudioStreamID audioStreams [streamCount];

	result = AudioDeviceGetProperty(deviceID,
									0,
									FALSE,
									kAudioDevicePropertyStreams,
									&specifierSize,
									audioStreams);

	if(noErr != result) {
		fprintf(stderr, "AudioDeviceGetProperty (kAudioDevicePropertyStreams) failed: %i\n", result);
		return;
	}

	printf("\nDevice has %d streams\n", streamCount);

	for(UInt32 i = 0; i < streamCount; ++i) {
		AudioStreamID streamID = audioStreams[i];

		AudioObjectShow(streamID);

		result = AudioStreamGetPropertyInfo(streamID,
											0,
											kAudioStreamPropertyAvailableVirtualFormats,
											&specifierSize,
											NULL);

		if(noErr != result) {
			fprintf(stderr, "AudioStreamGetPropertyInfo (kAudioStreamPropertyAvailableVirtualFormats) failed: %i\n", result);
			continue;
		}

		UInt32 virtualFormatCount = static_cast<UInt32>(specifierSize / sizeof(AudioStreamRangedDescription));

		AudioStreamRangedDescription virtualFormats [virtualFormatCount];

		result = AudioStreamGetProperty(streamID,
										0,
										kAudioStreamPropertyAvailableVirtualFormats,
										&specifierSize,
										virtualFormats);

		if(noErr != result) {
			fprintf(stderr, "AudioStreamGetProperty (kAudioStreamPropertyAvailableVirtualFormats) failed: %i\n", result);
			continue;
		}

		printf("\nAudioStream %x Virtual Formats:\n",streamID);
		for(UInt32 j = 0; j < virtualFormatCount; ++j) {
			CAStreamBasicDescription sd = virtualFormats[j].mFormat;
			sd.Print(stdout);
			printf("reserved: %i\n", sd.mReserved);
		}

		result = AudioStreamGetPropertyInfo(streamID,
											0,
											kAudioStreamPropertyAvailablePhysicalFormats,
											&specifierSize,
											NULL);

		if(noErr != result) {
			fprintf(stderr, "AudioStreamGetPropertyInfo (kAudioStreamPropertyAvailablePhysicalFormats) failed: %i\n", result);
			continue;
		}

		UInt32 physicalFormatCount = static_cast<UInt32>(specifierSize / sizeof(AudioStreamRangedDescription));

		AudioStreamRangedDescription physicalFormats [physicalFormatCount];

		result = AudioStreamGetProperty(streamID,
										0,
										kAudioStreamPropertyAvailablePhysicalFormats,
										&specifierSize,
										physicalFormats);

		if(noErr != result) {
			fprintf(stderr, "AudioStreamGetProperty (kAudioStreamPropertyAvailablePhysicalFormats) failed: %i\n", result);
			continue;
		}

		printf("\nAudioStream %x Physical Formats:\n",streamID);
		for(UInt32 j = 0; j < physicalFormatCount; ++j) {
			CAStreamBasicDescription sd = physicalFormats[j].mFormat;
			sd.Print(stdout);
		}
	}
}

static void
PrintStreamsForDeviceUID(CFStringRef deviceUID)
{
	assert(NULL != deviceUID);

	AudioDeviceID deviceID = kAudioDeviceUnknown;
	AudioValueTranslation translation;

	translation.mInputData			= &deviceUID;
	translation.mInputDataSize		= sizeof(deviceUID);
	translation.mOutputData			= &deviceID;
	translation.mOutputDataSize		= sizeof(deviceID);

	UInt32 specifierSize			= sizeof(translation);

	OSStatus result = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID,
											   &specifierSize,
											   &translation);

	if(noErr != result) {
		fprintf(stderr, "AudioHardwareGetProperty (kAudioHardwarePropertyDeviceForUID) failed: %i", result);
		return;
	}

	PrintStreamsForDeviceID(deviceID);
}

static void
PrintStreamFormatsForDeviceID(AudioDeviceID deviceID)
{
	OSStatus result;
	UInt32 specifierSize;

	result = AudioDeviceGetPropertyInfo(deviceID,
										0,
										FALSE,
										kAudioDevicePropertyStreams,
										&specifierSize,
										NULL);

	if(noErr != result) {
		fprintf(stderr, "AudioDeviceGetPropertyInfo (kAudioDevicePropertyStreams) failed: %i\n", result);
		return;
	}

	UInt32 streamCount = static_cast<UInt32>(specifierSize / sizeof(AudioStreamID));

	AudioStreamID audioStreams [streamCount];

	result = AudioDeviceGetProperty(deviceID,
									0,
									FALSE,
									kAudioDevicePropertyStreams,
									&specifierSize,
									audioStreams);

	if(noErr != result) {
		fprintf(stderr, "AudioDeviceGetProperty (kAudioDevicePropertyStreams) failed: %i\n", result);
		return;
	}

	for(UInt32 i = 0; i < streamCount; ++i) {
		AudioStreamID streamID = audioStreams[i];

		CAStreamBasicDescription virtualFormat;
		specifierSize = sizeof(virtualFormat);

		result = AudioStreamGetProperty(streamID,
										0,
										kAudioStreamPropertyVirtualFormat,
										&specifierSize,
										&virtualFormat);

		if(noErr != result) {
			fprintf(stderr, "AudioStreamGetProperty (kAudioStreamPropertyVirtualFormat) failed: %i\n", result);
			continue;
		}

		printf("Current virtual format: ");
		virtualFormat.Print(stdout);

		CAStreamBasicDescription physicalFormat;
		specifierSize = sizeof(physicalFormat);

		result = AudioStreamGetProperty(streamID,
										0,
										kAudioStreamPropertyPhysicalFormat,
										&specifierSize,
										&physicalFormat);

		if(noErr != result) {
			fprintf(stderr, "AudioStreamGetProperty (kAudioStreamPropertyPhysicalFormat) failed: %i\n", result);
			continue;
		}

		printf("Current physical format: ");
		physicalFormat.Print(stdout);
	}
}

static void
PrintStreamFormatsForDeviceUID(CFStringRef deviceUID)
{
	assert(NULL != deviceUID);

	AudioDeviceID deviceID = kAudioDeviceUnknown;
	AudioValueTranslation translation;

	translation.mInputData			= &deviceUID;
	translation.mInputDataSize		= sizeof(deviceUID);
	translation.mOutputData			= &deviceID;
	translation.mOutputDataSize		= sizeof(deviceID);

	UInt32 specifierSize			= sizeof(translation);

	OSStatus result = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID,
											   &specifierSize,
											   &translation);

	if(noErr != result) {
		fprintf(stderr, "AudioHardwareGetProperty (kAudioHardwarePropertyDeviceForUID) failed: %i", result);
		return;
	}

	PrintStreamFormatsForDeviceID(deviceID);
}

static void
decodingStarted(void					*context,
				const AudioDecoder		*decoder)
{
#pragma unused(context)
	printf("Decoding started: ");
	CFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));
}

static void
decodingFinished(void					*context,
				 const AudioDecoder		*decoder)
{
#pragma unused(context)
	printf("Decoding finished: ");
	CFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));
}

static void
renderingStarted(void					*context,
				 const AudioDecoder		*decoder)
{
#pragma unused(context)
	printf("Rendering started: ");
	CFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));
}

static void
renderingFinished(void					*context,
				  const AudioDecoder		*decoder)
{
#pragma unused(context)
	printf("Rendering finished: ");
	CFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));
}

static void usage(const char *argv0)
{
	assert(NULL != argv0);

	fprintf(stderr, "Usage: %s file [file ...]", argv0);
}

//#include <getopt.h>
//
///* Flag set by ‘--verbose’. */
//static int verbose_flag;
//
//static struct option long_options [] = {
//	/* These options set a flag. */
//	{"verbose", no_argument,       &verbose_flag, 1},
//	{"brief",   no_argument,       &verbose_flag, 0},
//	/* These options don't set a flag.
//	 We distinguish them by their indices. */
//	{"add",     no_argument,       0, 'a'},
//	{"append",  no_argument,       0, 'b'},
//	{"delete",  required_argument, 0, 'd'},
//	{"create",  required_argument, 0, 'c'},
//	{"file",    required_argument, 0, 'f'},
//	{0, 0, 0, 0}
//};

int main(int argc, char *argv [])
{
//	for(;;) {
//		/* getopt_long stores the option index here. */
//		int option_index = 0;
//
//		int c = getopt_long(argc,
//							argv,
//							"abc:d:f:",
//							long_options,
//							&option_index);
//
//		/* Detect the end of the options. */
//		if (c == -1)
//			break;
//
//		switch(c) {
//			case 0:
//				/* If this option set a flag, do nothing else now. */
//				if(long_options[option_index].flag != 0)
//					break;
//				printf("option %s", long_options[option_index].name);
//				if(optarg)
//					printf (" with arg %s", optarg);
//				printf ("\n");
//				break;
//
//			case 'a':
//				puts("option -a\n");
//				break;
//
//			case 'b':
//				puts("option -b\n");
//				break;
//
//			case 'c':
//				printf("option -c with value `%s'\n", optarg);
//				break;
//
//			case 'd':
//				printf("option -d with value `%s'\n", optarg);
//				break;
//
//			case 'f':
//				printf("option -f with value `%s'\n", optarg);
//				break;
//
//			case '?':
//				/* getopt_long already printed an error message. */
//				break;
//
//			default:
//				abort();
//		}
//	}
//
//	/* Instead of reporting ‘--verbose’
//	 and ‘--brief’ as they are encountered,
//	 we report the final status resulting from them. */
//	if(verbose_flag)
//		puts("verbose flag is set");
//
//	/* Print any remaining command line arguments (not options). */
//	if(optind < argc) {
//		printf("non-option ARGV-elements: ");
//		while(optind < argc)
//			printf ("%s ", argv[optind++]);
//		putchar('\n');
//	}
//
//	return EXIT_SUCCESS;
//
//

	if(1 == argc) {
		printf("Usage: %s file [file ...]", argv[0]);
		return EXIT_FAILURE;
	}

//	CFArrayRef outputDevices = CreateOutputDeviceArray();
//	CFShow(outputDevices);
//	CFRelease(outputDevices), outputDevices = NULL;
//	return 1;
	AudioPlayer player;

	Float32 volume;
	if(player.GetMasterVolume(volume))
		printf("Master Volume: %f\n", volume);

	if(player.GetVolumeForChannel(1, volume))
		printf("Channel 1 Volume: %f\n", volume);

//	if(false == player.SetOutputDeviceUID(CFSTR("SoundflowerEngine:0")))
	if(false == player.SetOutputDeviceUID(CFSTR("AppleUSBAudioEngine:Wavelength Audio,ltd:Proton USBDAC:(C) 2009 Wavelength Audio, ltd.:1")))
//	if(false == player.SetOutputDeviceUID(CFSTR("AppleUSBAudioEngine:Texas Instruments:Benchmark 1.0:fd111000:1")))
		puts("Couldn't set output device UID");

	if(false == player.StartHoggingOutputDevice())
		puts("Couldn't hog output device");

	CAStreamBasicDescription asbd, oldFormat, vFormat;

	puts("====================");

	if(player.GetOutputStreamPhysicalFormat(oldFormat)) {
		printf("Original physical format: ");
		oldFormat.Print(stdout);
	}

	if(player.GetOutputStreamVirtualFormat(vFormat)) {
		printf("Original virtual format:  ");
		vFormat.Print(stdout);
	}

	puts("====================");

	asbd.mFormatID			= kAudioFormatLinearPCM;
	asbd.mFormatFlags		= kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked | kAudioFormatFlagIsNonMixable;
	asbd.mBitsPerChannel	= 24;
	asbd.mChannelsPerFrame	= 2;
	asbd.mSampleRate		= 44100;
	asbd.mFramesPerPacket	= 1;
	asbd.mBytesPerFrame		= 6;
	asbd.mBytesPerPacket	= 6;
	asbd.mReserved			= 0;

	if(false == player.SetOutputStreamPhysicalFormat(asbd))
		puts("Couldn't set physical format");
//	else
//		asbd.Print(stderr);

	while(0 < --argc) {

		const char *path = *++argv;

		CFURLRef fileURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(path), strlen(path), FALSE);

		AudioMetadata *metadata = AudioMetadata::CreateMetadataForURL(fileURL);
		if(NULL == metadata)
			puts("Couldn't create metadata");

//		13:33:52 - 17:21:06
//		AudioDecoder *decoder = AudioDecoder::CreateDecoderForURLRegion(fileURL,
//																		static_cast<SInt64>(44100*((13*60) + 33 + (52./75))),
//																		static_cast<UInt32>(44100*(3*60 + 47 + (14./75))),
//																		0);
		AudioDecoder *decoder = AudioDecoder::CreateDecoderForURL(fileURL);
		if(NULL == decoder) {
			puts("Couldn't create decoder");
			continue;
		}

		decoder->SetDecodingStartedCallback(decodingStarted, NULL);
		decoder->SetDecodingFinishedCallback(decodingFinished, NULL);
		decoder->SetRenderingStartedCallback(renderingStarted, NULL);
		decoder->SetRenderingFinishedCallback(renderingFinished, NULL);

		if(false == player.Enqueue(decoder))
			puts("Couldn't enqueue");
	}

	player.Play();

	while(player.IsPlaying() && 30 > player.GetCurrentTime()) {
		CFRunLoopRunInMode(kCFRunLoopDefaultMode, 2, true);

		printf("%.2f / %.2f [%.2f]\n", player.GetCurrentTime(), player.GetTotalTime(), player.GetRemainingTime());
	}

	player.Stop();

	// Restore the old format
	if(false == player.SetOutputStreamPhysicalFormat(oldFormat))
		puts("Couldn't restore physical format");

	if(false == player.StopHoggingOutputDevice())
		puts("Couldn't stop hogging output device");

	return EXIT_SUCCESS;
}
<commit_msg>Turned Example into a bare-bones command line player<commit_after>/*
 *  Copyright (C) 2009, 2010 Stephen F. Booth <me@sbooth.org>
 *  All Rights Reserved
 */

#include <CoreFoundation/CoreFoundation.h>

#include "SFBAudioEngine/AudioDecoder.h"
#include "SFBAudioEngine/AudioPlayer.h"
#include "SFBAudioEngine/DSPAudioPlayer.h"

#include <unistd.h>

static void
decodingStarted(void					*context,
				const AudioDecoder		*decoder)
{
#pragma unused(context)
	printf("Decoding started: ");
	CFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));
}

static void
decodingFinished(void					*context,
				 const AudioDecoder		*decoder)
{
#pragma unused(context)
	printf("Decoding finished: ");
	CFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));
}

static void
renderingStarted(void					*context,
				 const AudioDecoder		*decoder)
{
#pragma unused(context)
	printf("Rendering started: ");
	CFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));
}

static void
renderingFinished(void					*context,
				  const AudioDecoder		*decoder)
{
#pragma unused(context)
	printf("Rendering finished: ");
	CFShow(const_cast<CFURLRef>(const_cast<AudioDecoder *>(decoder)->GetURL()));
}

int main(int argc, char *argv [])
{
	if(1 == argc) {
		printf("Usage: %s file [file ...]", argv[0]);
		return EXIT_FAILURE;
	}

	AudioPlayer player;

	while(0 < --argc) {
		const char *path = *++argv;
		CFURLRef fileURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault,
																   reinterpret_cast<const UInt8 *>(path),
																   strlen(path),
																   FALSE);

		AudioDecoder *decoder = AudioDecoder::CreateDecoderForURL(fileURL);

		CFRelease(fileURL), fileURL = NULL;

		if(NULL == decoder) {
			puts("Couldn't create decoder");
			continue;
		}

		decoder->SetDecodingStartedCallback(decodingStarted, NULL);
		decoder->SetDecodingFinishedCallback(decodingFinished, NULL);
		decoder->SetRenderingStartedCallback(renderingStarted, NULL);
		decoder->SetRenderingFinishedCallback(renderingFinished, NULL);

		if(false == player.Enqueue(decoder)) {
			puts("Couldn't enqueue decoder");
			delete decoder, decoder = NULL;
		}
	}

	player.Play();

	// Display progress every 2 seconds
	while(player.IsPlaying()) {
		CFRunLoopRunInMode(kCFRunLoopDefaultMode, 2, true);

		printf("%.2f / %.2f [%.2f]\n", player.GetCurrentTime(), player.GetTotalTime(), player.GetRemainingTime());
	}

	player.Stop();

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before><commit_msg>cid#983376 Dereference before null check<commit_after><|endoftext|>


<commit_before>#include <stdexcept>
#include <string>

#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/TransformStamped.h>
#include <goal_sender_msgs/ApplyGoals.h>
#include <goal_sender_msgs/GoalSequence.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <move_base_msgs/MoveBaseGoal.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <tf2_ros/transform_listener.h>

inline double squaring_distance(const geometry_msgs::Point& a, const geometry_msgs::Point& b) {
  const auto x {a.x - b.x};
  const auto y {a.y - b.y};
  return x*x + y*y;
}

/**
 * Waypoint update service manager
 */
class WaypointManager
{
public:
  bool operator()(goal_sender_msgs::ApplyGoals::Request& req,
                  goal_sender_msgs::ApplyGoals::Response& res){
    sequence_ = req.goal_sequence;
    res.success = true;
    res.message = "update waypoints";
    return true;
  }

  const geometry_msgs::Point& point() const
  {
    if (is_end()) throw std::logic_error {"range error: Please check is_end() before point()"};
    return now_goal->position;
  }

  const geometry_msgs::Quaternion& quaternion() const
  {
    if (is_end()) throw std::logic_error {"range error: Please check is_end() before radius()"};
    return now_goal->oriantation;
  }

  double radius() const
  {
    if (is_end()) throw std::logic_error {"range error: Please check is_end() before radius()"};
    return now_goal->radius;
  }

  bool next()
  {
    if (is_end()) throw std::logic_error {"range error: Please check is_end() before next()"}; // wrong way.
    if (++now_goal == sequence_.waypoints.end())
      return false; // correct way: this is last one.
    return true;
  }

  bool is_end() const noexcept
  {
    return sequence_.waypoints.end() == now_goal;
  }

  explicit operator bool() noexcept
  {
    return !is_end();
  }

  [[deprecated]]
  const goal_sender_msgs::Waypoint& get() const
  {
    if (is_end()) throw std::logic_error {"range error: Please check is_end() before get()"};
    return *now_goal;
  }

private:
  goal_sender_msgs::GoalSequence sequence_;
  decltype(sequence_.waypoints)::iterator now_goal;
};

/**
 * Tf lookup API
 */
class TfPositionManager
{
public:
  explicit TfPositionManager(tf2_ros::Buffer& tfBuffer) // buffer is lvalue
    : buffer_ {tfBuffer}
  {
  }

  geometry_msgs::Point operator()(std::string parent, std::string child) const
  {
    const auto ts {buffer_.lookupTransform(parent, child, ros::Time(0))};
    geometry_msgs::Point point;
    point.x = ts.transform.translation.x;
    point.y = ts.transform.translation.y;
    return point;
  }

private:
  const tf2_ros::Buffer& buffer_;
};

class GoalSender
{
public:
  using MoveBaseActionClient = actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction>;

  GoalSender(WaypointManager& point_manager,
             MoveBaseActionClient& move_base_client,
             TfPositionManager lookupper)
    : point_manager_ {point_manager},
      move_base_client_ {move_base_client},
      lookupper_ {lookupper}
  {
  }

  void once()
  {
    if (!point_manager_)
      return; // no work
    if (is_reach()) {
      point_manager_.next();
      send_goal();
    }
  }

private:
  bool is_reach() const
  {
    const auto robot_point {lookupper_("/map", "/base_link")};
    const auto waypoint_point {point_manager_.point()};
    const auto sqr_distance {squaring_distance(robot_point, waypoint_point)};

    const auto radius {point_manager_.radius()};
    const auto sqr_radius {radius * radius};

    if (sqr_distance < sqr_radius) // into valid range
      return true;
    return false;
  }

  void send_goal() const
  {
    if (!point_manager_) { // finish waypoint
      move_base_client_.cancelGoal(); // cancel moveing
      ROS_INFO("Finish waypoints");
      return;
    }

    move_base_msgs::MoveBaseGoal goal;
    goal.target_pose.pose.position = point_manager_.point();
    goal.target_pose.pose.orientation = point_manager_.quaternion();
    goal.target_pose.header.frame_id = "/map";
    goal.target_pose.header.stamp = ros::Time::now();
    move_base_client_.sendGoal(goal); // send waypoint
  }

  WaypointManager& point_manager_;
  MoveBaseActionClient& move_base_client_;
  TfPositionManager lookupper_;
};

int main(int argc, char** argv)
{
  ros::init(argc, argv, "goal_sender");
  ros::NodeHandle nh {};

  WaypointManager point_manager {};
  ros::ServiceServer srv {
      nh.advertiseService<goal_sender_msgs::ApplyGoals::Request,
                          goal_sender_msgs::ApplyGoals::Response>(
          "apply_goals", point_manager)};

  tf2_ros::Buffer tfBuffer;
  tf2_ros::TransformListener tfListener {tfBuffer};
  TfPositionManager lookupper {tfBuffer};

  GoalSender::MoveBaseActionClient move_base_client {"move_base", true};
  move_base_client.waitForServer();

  GoalSender goal_sender {point_manager, move_base_client, lookupper};

  ros::Rate rate {10};
  while (ros::ok()) {
    ros::spinOnce();
    goal_sender.once();
  }
}
<commit_msg>Fix typo on error message<commit_after>#include <stdexcept>
#include <string>

#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/TransformStamped.h>
#include <goal_sender_msgs/ApplyGoals.h>
#include <goal_sender_msgs/GoalSequence.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <move_base_msgs/MoveBaseGoal.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <tf2_ros/transform_listener.h>

inline double squaring_distance(const geometry_msgs::Point& a, const geometry_msgs::Point& b) {
  const auto x {a.x - b.x};
  const auto y {a.y - b.y};
  return x*x + y*y;
}

/**
 * Waypoint update service manager
 */
class WaypointManager
{
public:
  bool operator()(goal_sender_msgs::ApplyGoals::Request& req,
                  goal_sender_msgs::ApplyGoals::Response& res){
    sequence_ = req.goal_sequence;
    res.success = true;
    res.message = "update waypoints";
    return true;
  }

  const geometry_msgs::Point& point() const
  {
    if (is_end()) throw std::logic_error {"range error: Please check is_end() before point()"};
    return now_goal->position;
  }

  const geometry_msgs::Quaternion& quaternion() const
  {
    if (is_end()) throw std::logic_error {"range error: Please check is_end() before quaternion()"};
    return now_goal->oriantation;
  }

  double radius() const
  {
    if (is_end()) throw std::logic_error {"range error: Please check is_end() before radius()"};
    return now_goal->radius;
  }

  bool next()
  {
    if (is_end()) throw std::logic_error {"range error: Please check is_end() before next()"}; // wrong way.
    if (++now_goal == sequence_.waypoints.end())
      return false; // correct way: this is last one.
    return true;
  }

  bool is_end() const noexcept
  {
    return sequence_.waypoints.end() == now_goal;
  }

  explicit operator bool() noexcept
  {
    return !is_end();
  }

  [[deprecated]]
  const goal_sender_msgs::Waypoint& get() const
  {
    if (is_end()) throw std::logic_error {"range error: Please check is_end() before get()"};
    return *now_goal;
  }

private:
  goal_sender_msgs::GoalSequence sequence_;
  decltype(sequence_.waypoints)::iterator now_goal;
};

/**
 * Tf lookup API
 */
class TfPositionManager
{
public:
  explicit TfPositionManager(tf2_ros::Buffer& tfBuffer) // buffer is lvalue
    : buffer_ {tfBuffer}
  {
  }

  geometry_msgs::Point operator()(std::string parent, std::string child) const
  {
    const auto ts {buffer_.lookupTransform(parent, child, ros::Time(0))};
    geometry_msgs::Point point;
    point.x = ts.transform.translation.x;
    point.y = ts.transform.translation.y;
    return point;
  }

private:
  const tf2_ros::Buffer& buffer_;
};

class GoalSender
{
public:
  using MoveBaseActionClient = actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction>;

  GoalSender(WaypointManager& point_manager,
             MoveBaseActionClient& move_base_client,
             TfPositionManager lookupper)
    : point_manager_ {point_manager},
      move_base_client_ {move_base_client},
      lookupper_ {lookupper}
  {
  }

  void once()
  {
    if (!point_manager_)
      return; // no work
    if (is_reach()) {
      point_manager_.next();
      send_goal();
    }
  }

private:
  bool is_reach() const
  {
    const auto robot_point {lookupper_("/map", "/base_link")};
    const auto waypoint_point {point_manager_.point()};
    const auto sqr_distance {squaring_distance(robot_point, waypoint_point)};

    const auto radius {point_manager_.radius()};
    const auto sqr_radius {radius * radius};

    if (sqr_distance < sqr_radius) // into valid range
      return true;
    return false;
  }

  void send_goal() const
  {
    if (!point_manager_) { // finish waypoint
      move_base_client_.cancelGoal(); // cancel moveing
      ROS_INFO("Finish waypoints");
      return;
    }

    move_base_msgs::MoveBaseGoal goal;
    goal.target_pose.pose.position = point_manager_.point();
    goal.target_pose.pose.orientation = point_manager_.quaternion();
    goal.target_pose.header.frame_id = "/map";
    goal.target_pose.header.stamp = ros::Time::now();
    move_base_client_.sendGoal(goal); // send waypoint
  }

  WaypointManager& point_manager_;
  MoveBaseActionClient& move_base_client_;
  TfPositionManager lookupper_;
};

int main(int argc, char** argv)
{
  ros::init(argc, argv, "goal_sender");
  ros::NodeHandle nh {};

  WaypointManager point_manager {};
  ros::ServiceServer srv {
      nh.advertiseService<goal_sender_msgs::ApplyGoals::Request,
                          goal_sender_msgs::ApplyGoals::Response>(
          "apply_goals", point_manager)};

  tf2_ros::Buffer tfBuffer;
  tf2_ros::TransformListener tfListener {tfBuffer};
  TfPositionManager lookupper {tfBuffer};

  GoalSender::MoveBaseActionClient move_base_client {"move_base", true};
  move_base_client.waitForServer();

  GoalSender goal_sender {point_manager, move_base_client, lookupper};

  ros::Rate rate {10};
  while (ros::ok()) {
    ros::spinOnce();
    goal_sender.once();
  }
}
<|endoftext|>


<commit_before><commit_msg>Fix my wrong logic in row info iteration.<commit_after><|endoftext|>


<commit_before><commit_msg>also ifCOUNT2 return type is always number<commit_after><|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageIOBaseTest.cxx
  Language:  C++
  Date:      $Date$xgoto-l

  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImageIOBase.h"
#include "itkMetaImageIO.h"

int itkImageIOBaseTest(int ac, char* av[])
{
  typedef itk::ImageIOBase                 BaseReaderType;
  typedef BaseReaderType                   BaseReaderPointerType;

  typedef itk::MetaImageIO                 ReaderType;
  typedef ReaderType::Pointer              ReaderPointerType;

  itk::MetaImageIO::Pointer reader = itk::MetaImageIO::New();
  reader->SetNumberOfDimensions(3);

  bool gotException = false;
  try
    {
    reader->SetDimensions(3,1.0);
    }
  catch ( itk::ExceptionObject& e )
    {
    std::cerr << "Caught expected exception " << e << std::endl;
    gotException = true;
    }
  if (!gotException)
    {
    std::cerr << "Failed to catch expected exception in method SetDimensions"
              << std::endl;
    return EXIT_FAILURE;
    }

  gotException = false;
  try
    {
    reader->SetOrigin(3,1.0);
    }
  catch ( itk::ExceptionObject& e )
    {
    std::cerr << "Caught expected exception " << e << std::endl;
    gotException = true;
    }
  if (!gotException)
    {
    std::cerr << "Failed to catch expected exception in method SetOrigin"
              << std::endl;
    return EXIT_FAILURE;
    }

  gotException = false;
  try
    {
    reader->SetSpacing(3,1.0);
    }
  catch ( itk::ExceptionObject& e )
    {
    std::cerr << "Caught expected exception " << e << std::endl;
    gotException = true;
    }
  if (!gotException)
    {
    std::cerr << "Failed to catch expected exception in method SetSpacing"
              << std::endl;
    return EXIT_FAILURE;
    }

  gotException = false;
  try
    {
    std::vector<double> direction(3);
    direction[0] = 1.0;
    direction[1] = 1.0;
    direction[2] = 1.0;
    reader->SetDirection(3,direction);
    }
  catch ( itk::ExceptionObject& e )
    {
    std::cerr << "Caught expected exception " << e << std::endl;
    gotException = true;
    }
  if (!gotException)
    {
    std::cerr << "Failed to catch expected exception in method SetDirection"
              << std::endl;
    return EXIT_FAILURE;
    }

  gotException = false;
  try
    {
    vnl_vector<double> direction(3);
    direction[0] = 1.0;
    direction[1] = 1.0;
    direction[2] = 1.0;
    reader->SetDirection(3,direction);
    }
  catch ( itk::ExceptionObject& e )
    {
    std::cerr << "Caught expected exception " << e << std::endl;
    gotException = true;
    }
  if (!gotException)
    {
    std::cerr << "Failed to catch expected exception in method SetDirection"
              << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<commit_msg>COMP: Removing unused parameters from the arguments of the main() function.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageIOBaseTest.cxx
  Language:  C++
  Date:      $Date$xgoto-l

  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImageIOBase.h"
#include "itkMetaImageIO.h"

int itkImageIOBaseTest( int , char * [] )
{
  typedef itk::ImageIOBase                 BaseReaderType;
  typedef BaseReaderType                   BaseReaderPointerType;

  typedef itk::MetaImageIO                 ReaderType;
  typedef ReaderType::Pointer              ReaderPointerType;

  itk::MetaImageIO::Pointer reader = itk::MetaImageIO::New();
  reader->SetNumberOfDimensions(3);

  bool gotException = false;
  try
    {
    reader->SetDimensions(3,1.0);
    }
  catch ( itk::ExceptionObject& e )
    {
    std::cerr << "Caught expected exception " << e << std::endl;
    gotException = true;
    }
  if (!gotException)
    {
    std::cerr << "Failed to catch expected exception in method SetDimensions"
              << std::endl;
    return EXIT_FAILURE;
    }

  gotException = false;
  try
    {
    reader->SetOrigin(3,1.0);
    }
  catch ( itk::ExceptionObject& e )
    {
    std::cerr << "Caught expected exception " << e << std::endl;
    gotException = true;
    }
  if (!gotException)
    {
    std::cerr << "Failed to catch expected exception in method SetOrigin"
              << std::endl;
    return EXIT_FAILURE;
    }

  gotException = false;
  try
    {
    reader->SetSpacing(3,1.0);
    }
  catch ( itk::ExceptionObject& e )
    {
    std::cerr << "Caught expected exception " << e << std::endl;
    gotException = true;
    }
  if (!gotException)
    {
    std::cerr << "Failed to catch expected exception in method SetSpacing"
              << std::endl;
    return EXIT_FAILURE;
    }

  gotException = false;
  try
    {
    std::vector<double> direction(3);
    direction[0] = 1.0;
    direction[1] = 1.0;
    direction[2] = 1.0;
    reader->SetDirection(3,direction);
    }
  catch ( itk::ExceptionObject& e )
    {
    std::cerr << "Caught expected exception " << e << std::endl;
    gotException = true;
    }
  if (!gotException)
    {
    std::cerr << "Failed to catch expected exception in method SetDirection"
              << std::endl;
    return EXIT_FAILURE;
    }

  gotException = false;
  try
    {
    vnl_vector<double> direction(3);
    direction[0] = 1.0;
    direction[1] = 1.0;
    direction[2] = 1.0;
    reader->SetDirection(3,direction);
    }
  catch ( itk::ExceptionObject& e )
    {
    std::cerr << "Caught expected exception " << e << std::endl;
    gotException = true;
    }
  if (!gotException)
    {
    std::cerr << "Failed to catch expected exception in method SetDirection"
              << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "FPSRoleLocal.h"
#include "Creature.h"

CFPSRoleLocal::CFPSRoleLocal(void)
{
	m_nCharMode = 0;
	m_nMuzzleBone = -1;
	m_nUpdateMove = 0;
}

CFPSRoleLocal::~CFPSRoleLocal(void)
{
	delete m_pActorBase;
}

CFPSRoleLocal::CFPSRoleLocal(void)
{
	m_nCharMode = 0;
	m_nMuzzleBone = -1;
	m_nUpdateMove = 0;
}

int CFPSRoleLocal::Init(int nRoleID,const char* strCharFile)
{
	CFPSRole::Init(nRoleID, strCharFile);

	m_pCreature->SetupBody(1, 1);

	return 1;
}
<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "FPSRoleLocal.h"
#include "Creature.h"

CFPSRoleLocal::CFPSRoleLocal(void)
{
	m_nCharMode = 0;
	m_nMuzzleBone = -1;
	m_nUpdateMove = 0;
}

CFPSRoleLocal::~CFPSRoleLocal(void)
{
	delete m_pActorBase;
}

CFPSRoleLocal::CFPSRoleLocal(void)
{
	m_nCharMode = 0;
	m_nMuzzleBone = -1;
	m_nUpdateMove = 0;
}

int CFPSRoleLocal::Init(int nRoleID,const char* strCharFile)
{
	CFPSRole::Init(nRoleID, strCharFile);

	m_pCreature->SetupBody(1, 1);

	m_pCreature->SetHighShadow(1);
	SetupArms(2, 0);

	m_pActorBase = new CActorBase();
	m_pActorBase->SetEnabled(1);
	return 1;
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////
//
// NAME
//  FeatureAlign.cpp -- image registration using feature matching
//
// SEE ALSO
//  FeatureAlign.h      longer description
//
// Based on code by Richard Szeliski, 2001.
// (modified for CSE576 Spring 2005, and for CS4670, Fall 2012-2013)
//
///////////////////////////////////////////////////////////////////////////

#include "ImageLib/ImageLib.h"
#include "FeatureAlign.h"
#include "SVD.h"

#include <math.h>
#include <iostream>

CTransform3x3 ComputeHomography(const FeatureSet &f1, const FeatureSet &f2,
                                const vector<FeatureMatch> &matches)
{
    int numMatches = (int) matches.size();

    // first, we will compute the A matrix in the homogeneous linear equations Ah = 0
    int numRows = 2 * numMatches; // number of rows of A
    const int numCols = 9;        // number of columns of A

    // this allocates space for the A matrix
    AMatrixType A = AMatrixType::Zero(numRows, numCols);

    for (int i = 0; i < numMatches; i++) {
        const FeatureMatch &m = matches[i];
        const Feature &a = f1[m.id1];
        const Feature &b = f2[m.id2];

        // BEGIN TODO
        // fill in the matrix A in this loop.
        // To access an element of A, use parentheses, e.g. A(0,0)

		// Note that A is a (2n x 9) matrix
		// We can easily fill in A according to the lecture
		// Row 2i
		A(2*i, 0) = a.x;
		A(2*i, 1) = a.y;
		A(2*i, 2) = 1;
		A(2*i, 3) = 0;
		A(2*i, 4) = 0;
		A(2*i, 5) = 0;
		A(2*i, 6) = -b.x * a.x;
		A(2*i, 7) = -b.x * a.y;
		A(2*i, 8) = -b.x;

		// Row 2i+1
		A(2*i+1, 0) = 0;
		A(2*i+1, 1) = 0;
		A(2*i+1, 2) = 0;
		A(2*i+1, 3) = a.x;
		A(2*i+1, 4) = a.y;
		A(2*i+1, 5) = 1;
		A(2*i+1, 6) = -b.y * a.x;
		A(2*i+1, 7) = -b.y * a.y;
		A(2*i+1, 8) = -b.y;

        // END TODO
    }

    // Compute the SVD of the A matrix and get out the matrix V^T and the vector of singular values
    AMatrixType Vt;
    VectorXd sv;
    SVD(A, Vt, sv);

    CTransform3x3 H;
    // BEGIN TODO
    // fill the homography H with the appropriate elements of the SVD
    // To extract, for instance, the V matrix, use svd.matrixV()

	// Find the smallest sv first
	// minSv: smallest sv value
	// minSvIdx: smallest sv index
	double minSv = sv[0];
	int minSvIdx = 0;
	for (int i = 1; i < 9; i++) {
		if (sv[i] < minSv) {
			minSv = sv[i];
			minSvIdx = i;
		}
	}
	// Rank(A) = 8 => H = a v_n  (a is a constant)
	// v_n corresponds to the smallest sv
	H[0][0] = Vt(minSvIdx,0) / Vt(minSvIdx,8);
	H[0][1] = Vt(minSvIdx,1) / Vt(minSvIdx,8);
	H[0][2] = Vt(minSvIdx,2) / Vt(minSvIdx,8);
	H[1][0] = Vt(minSvIdx,3) / Vt(minSvIdx,8);
	H[1][1] = Vt(minSvIdx,4) / Vt(minSvIdx,8);
	H[1][2] = Vt(minSvIdx,5) / Vt(minSvIdx,8);
	H[2][0] = Vt(minSvIdx,6) / Vt(minSvIdx,8);
	H[2][1] = Vt(minSvIdx,7) / Vt(minSvIdx,8);
	H[2][2] = Vt(minSvIdx,8) / Vt(minSvIdx,8);

    // END TODO

    return H;
}

/******************* TO DO *********************
 * alignPair:
 *	INPUT:
 *		f1, f2: source feature sets
 *		matches: correspondences between f1 and f2
 *               Each match in 'matches' contains two feature ids of
 *               matching features, id1 (in f1) and id2 (in f2).
 *		m: motion model
 *		nRANSAC: number of RANSAC iterations
 *		RANSACthresh: RANSAC distance threshold
 *		M: transformation matrix (output)
 *
 *	OUTPUT:
 *		repeat for nRANSAC iterations:
 *			choose a minimal set of feature matches
 *			estimate the transformation implied by these matches
 *			count the number of inliers
 *		for the transformation with the maximum number of inliers,
 *		compute the least squares motion estimate using the inliers,
 *		and store it in M
 */
int alignPair(const FeatureSet &f1, const FeatureSet &f2,
          const vector<FeatureMatch> &matches, MotionModel m,
          int nRANSAC, double RANSACthresh, CTransform3x3& M)
{
    // BEGIN TODO
    // Write this entire method.  You need to handle two types of
    // motion models, pure translations (m == eTranslation) and
    // full homographies (m == eHomography).  However, you should
    // only have one outer loop to perform the RANSAC code, as
    // the use of RANSAC is almost identical for both cases.
    //
    // Your homography handling code should call ComputeHomography.
    // This function should also call countInliers and, at the end,
    // leastSquaresFit.
printf("TODO: %s:%d\n", __FILE__, __LINE__);

    // END TODO

    return 0;
}

/******************* TO DO *********************
 * countInliers:
 *	INPUT:
 *		f1, f2: source feature sets
 *		matches: correspondences between f1 and f2
 *		m: motion model
 *               Each match in 'matches' contains two feature ids of
 *               matching features, id1 (in f1) and id2 (in f2).
 *		M: transformation matrix
 *		RANSACthresh: RANSAC distance threshold
 *		inliers: inlier feature IDs
 *	OUTPUT:
 *		transform the features in f1 by M
 *
 *		count the number of features in f1 for which the transformed
 *		feature is within Euclidean distance RANSACthresh of its match
 *		in f2
 *
 *		store these features IDs in inliers
 *
 */
int countInliers(const FeatureSet &f1, const FeatureSet &f2,
                 const vector<FeatureMatch> &matches, MotionModel m,
                 CTransform3x3 M, double RANSACthresh, vector<int> &inliers)
{
    inliers.clear();

    for (unsigned int i = 0; i < matches.size(); i++) {
        // BEGIN TODO
        // determine if the ith matched feature f1[id1-1], when transformed by M,
        // is within RANSACthresh of its match in f2
        //
        // if so, append i to inliers
printf("TODO: %s:%d\n", __FILE__, __LINE__);

        // END TODO
    }

    return (int) inliers.size();
}

/******************* TO DO *********************
 * leastSquaresFit:
 *	INPUT:
 *		f1, f2: source feature sets
 *		matches: correspondences between f1 and f2
 *		m: motion model
 *      inliers: inlier match indices (indexes into 'matches' array)
 *		M: transformation matrix (output)
 *	OUTPUT:
 *		compute the transformation from f1 to f2 using only the inliers
 *		and return it in M
 */
int leastSquaresFit(const FeatureSet &f1, const FeatureSet &f2,
            const vector<FeatureMatch> &matches, MotionModel m,
            const vector<int> &inliers, CTransform3x3& M)
{
    // This function needs to handle two possible motion models,
    // pure translations and full homographies.

    switch (m) {
        case eTranslate: {
            // for spherically warped images, the transformation is a
            // translation and only has two degrees of freedom
            //
            // therefore, we simply compute the average translation vector
            // between the feature in f1 and its match in f2 for all inliers
            double u = 0;
            double v = 0;

            for (int i=0; i < (int) inliers.size(); i++) {
			    // BEGIN TODO
			    // use this loop to compute the average translation vector
			    // over all inliers
printf("TODO: %s:%d\n", __FILE__, __LINE__);

                // END TODO
            }

            u /= inliers.size();
            v /= inliers.size();

            M = CTransform3x3::Translation((float) u, (float) v);

            break;
        }

        case eHomography: {
			M = CTransform3x3();

            // BEGIN TODO
		    // Compute a homography M using all inliers.
		    // This should call ComputeHomography.
printf("TODO: %s:%d\n", __FILE__, __LINE__);

            // END TODO

            break;
        }
    }

    return 0;
}

<commit_msg>alignPair done<commit_after>///////////////////////////////////////////////////////////////////////////
//
// NAME
//  FeatureAlign.cpp -- image registration using feature matching
//
// SEE ALSO
//  FeatureAlign.h      longer description
//
// Based on code by Richard Szeliski, 2001.
// (modified for CSE576 Spring 2005, and for CS4670, Fall 2012-2013)
//
///////////////////////////////////////////////////////////////////////////

#include "ImageLib/ImageLib.h"
#include "FeatureAlign.h"
#include "SVD.h"

#include <math.h>
#include <iostream>

CTransform3x3 ComputeHomography(const FeatureSet &f1, const FeatureSet &f2,
                                const vector<FeatureMatch> &matches)
{
    int numMatches = (int) matches.size();

    // first, we will compute the A matrix in the homogeneous linear equations Ah = 0
    int numRows = 2 * numMatches; // number of rows of A
    const int numCols = 9;        // number of columns of A

    // this allocates space for the A matrix
    AMatrixType A = AMatrixType::Zero(numRows, numCols);

    for (int i = 0; i < numMatches; i++) {
        const FeatureMatch &m = matches[i];
        const Feature &a = f1[m.id1];
        const Feature &b = f2[m.id2];

        // BEGIN TODO
        // fill in the matrix A in this loop.
        // To access an element of A, use parentheses, e.g. A(0,0)

		// Note that A is a (2n x 9) matrix
		// We can easily fill in A according to the lecture
		// Row 2i
		A(2*i, 0) = a.x;
		A(2*i, 1) = a.y;
		A(2*i, 2) = 1;
		A(2*i, 3) = 0;
		A(2*i, 4) = 0;
		A(2*i, 5) = 0;
		A(2*i, 6) = -b.x * a.x;
		A(2*i, 7) = -b.x * a.y;
		A(2*i, 8) = -b.x;

		// Row 2i+1
		A(2*i+1, 0) = 0;
		A(2*i+1, 1) = 0;
		A(2*i+1, 2) = 0;
		A(2*i+1, 3) = a.x;
		A(2*i+1, 4) = a.y;
		A(2*i+1, 5) = 1;
		A(2*i+1, 6) = -b.y * a.x;
		A(2*i+1, 7) = -b.y * a.y;
		A(2*i+1, 8) = -b.y;

        // END TODO
    }

    // Compute the SVD of the A matrix and get out the matrix V^T and the vector of singular values
    AMatrixType Vt;
    VectorXd sv;
    SVD(A, Vt, sv);

    CTransform3x3 H;
    // BEGIN TODO
    // fill the homography H with the appropriate elements of the SVD
    // To extract, for instance, the V matrix, use svd.matrixV()

	// Find the smallest sv first
	// minSv: smallest sv value
	// minSvIdx: smallest sv index
	double minSv = sv[0];
	int minSvIdx = 0;
	for (int i = 0; i < (int)sv.size(); i++) {
		if (sv[i] < minSv && sv[i] > 0) {
			minSv = sv[i];
			minSvIdx = i;
		}
	}
	// Rank(A) = 8 => H = a v_n  (a is a constant)
	// v_n corresponds to the smallest sv
	H[0][0] = Vt(minSvIdx,0) / Vt(minSvIdx,8);
	H[0][1] = Vt(minSvIdx,1) / Vt(minSvIdx,8);
	H[0][2] = Vt(minSvIdx,2) / Vt(minSvIdx,8);
	H[1][0] = Vt(minSvIdx,3) / Vt(minSvIdx,8);
	H[1][1] = Vt(minSvIdx,4) / Vt(minSvIdx,8);
	H[1][2] = Vt(minSvIdx,5) / Vt(minSvIdx,8);
	H[2][0] = Vt(minSvIdx,6) / Vt(minSvIdx,8);
	H[2][1] = Vt(minSvIdx,7) / Vt(minSvIdx,8);
	H[2][2] = Vt(minSvIdx,8) / Vt(minSvIdx,8);

    // END TODO

    return H;
}

/******************* TO DO *********************
 * alignPair:
 *	INPUT:
 *		f1, f2: source feature sets
 *		matches: correspondences between f1 and f2
 *               Each match in 'matches' contains two feature ids of
 *               matching features, id1 (in f1) and id2 (in f2).
 *		m: motion model
 *		nRANSAC: number of RANSAC iterations
 *		RANSACthresh: RANSAC distance threshold
 *		M: transformation matrix (output)
 *
 *	OUTPUT:
 *		repeat for nRANSAC iterations:
 *			choose a minimal set of feature matches
 *			estimate the transformation implied by these matches
 *			count the number of inliers
 *		for the transformation with the maximum number of inliers,
 *		compute the least squares motion estimate using the inliers,
 *		and store it in M
 */
int alignPair(const FeatureSet &f1, const FeatureSet &f2,
          const vector<FeatureMatch> &matches, MotionModel m,
          int nRANSAC, double RANSACthresh, CTransform3x3& M)
{
    // BEGIN TODO
    // Write this entire method.  You need to handle two types of
    // motion models, pure translations (m == eTranslation) and
    // full homographies (m == eHomography).  However, you should
    // only have one outer loop to perform the RANSAC code, as
    // the use of RANSAC is almost identical for both cases.
    //
    // Your homography handling code should call ComputeHomography.
    // This function should also call countInliers and, at the end,
    // leastSquaresFit.

	// Generate a random seed
	// srand(unsigned int(time(NULL)));

	// Save maximum inliers
	// maxInlierCnt: maximum number of inliers
	// maxInliers: inlier feature ids of f1
	int maxInlierCnt = 0;
	vector<int> maxInliers;

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

		// Number of features
		int numF = matches.size();

		// Number of samples
		int numS;
		switch (m) {
			case eTranslate:
				numS = 1;
				break;
			case eHomography:
				numS = 4;
				break;
		}

		vector<FeatureMatch> randMatches;
		int cnt = 0;
		while (cnt < numS) {
			// Randomly pick a pair from the feature list that isn't in the list
			int rdn = rand() % numF;
			FeatureMatch curFeature = matches[rdn];
			// Check if this match is already selected
			bool selected = false;
			for (int j = 0; j < (int)randMatches.size(); j++) {
				if (randMatches[j].id1 == curFeature.id1 && randMatches[j].id2 == curFeature.id2) {
					selected = true;
				}
			}
			// If not, push it to the sample space
			if (!selected) {
				randMatches.push_back(curFeature);
				cnt++;
			}
		}
		// Get the transform
		CTransform3x3 M;
		// Translation
		if (numS ==1) {
			FeatureMatch match = randMatches[0];
			M[0][0] = 1;
			M[0][1] = 0;
			M[0][2] = f2[match.id2].x - f1[match.id1].x;
			M[1][0] = 0;
			M[1][1] = 1;
			M[1][2] = f2[match.id2].y - f1[match.id2].y;
			M[2][0] = 0;
			M[2][1] = 0;
			M[2][2] = 1;
		}
		// Homography
		else {
			M = ComputeHomography(f1, f2, randMatches);
		}
		// Count inliers matching this homography
		vector<int> curInliers;
		int numInliers = countInliers(f1, f2, matches, m, M, RANSACthresh, curInliers);
		// Update maximum inliers
		if (numInliers > maxInlierCnt) {
			maxInlierCnt = numInliers;
			maxInliers.clear();
			for (int k = 0; k < numInliers; k++) {
				maxInliers.push_back(curInliers[k]);
			}
		}
	}
	// Call leastSquaresFit
	if (leastSquaresFit(f1, f2, matches, m, maxInliers, M) != 0) {
		cout << "ERROR: leastSquaresFit exits abnormally!" << endl;
		return -1;
	}
    // END TODO

    return 0;
}

/******************* TO DO *********************
 * countInliers:
 *	INPUT:
 *		f1, f2: source feature sets
 *		matches: correspondences between f1 and f2
 *		m: motion model
 *               Each match in 'matches' contains two feature ids of
 *               matching features, id1 (in f1) and id2 (in f2).
 *		M: transformation matrix
 *		RANSACthresh: RANSAC distance threshold
 *		inliers: inlier feature IDs
 *	OUTPUT:
 *		transform the features in f1 by M
 *
 *		count the number of features in f1 for which the transformed
 *		feature is within Euclidean distance RANSACthresh of its match
 *		in f2
 *
 *		store these features IDs in inliers
 *
 */
int countInliers(const FeatureSet &f1, const FeatureSet &f2,
                 const vector<FeatureMatch> &matches, MotionModel m,
                 CTransform3x3 M, double RANSACthresh, vector<int> &inliers)
{
    inliers.clear();

    for (unsigned int i = 0; i < matches.size(); i++) {
        // BEGIN TODO
        // determine if the ith matched feature f1[id1-1], when transformed by M,
        // is within RANSACthresh of its match in f2
        //
        // if so, append i to inliers
printf("TODO: %s:%d\n", __FILE__, __LINE__);

        // END TODO
    }

    return (int) inliers.size();
}

/******************* TO DO *********************
 * leastSquaresFit:
 *	INPUT:
 *		f1, f2: source feature sets
 *		matches: correspondences between f1 and f2
 *		m: motion model
 *      inliers: inlier match indices (indexes into 'matches' array)
 *		M: transformation matrix (output)
 *	OUTPUT:
 *		compute the transformation from f1 to f2 using only the inliers
 *		and return it in M
 */
int leastSquaresFit(const FeatureSet &f1, const FeatureSet &f2,
            const vector<FeatureMatch> &matches, MotionModel m,
            const vector<int> &inliers, CTransform3x3& M)
{
    // This function needs to handle two possible motion models,
    // pure translations and full homographies.

    switch (m) {
        case eTranslate: {
            // for spherically warped images, the transformation is a
            // translation and only has two degrees of freedom
            //
            // therefore, we simply compute the average translation vector
            // between the feature in f1 and its match in f2 for all inliers
            double u = 0;
            double v = 0;

            for (int i=0; i < (int) inliers.size(); i++) {
			    // BEGIN TODO
			    // use this loop to compute the average translation vector
			    // over all inliers
printf("TODO: %s:%d\n", __FILE__, __LINE__);

                // END TODO
            }

            u /= inliers.size();
            v /= inliers.size();

            M = CTransform3x3::Translation((float) u, (float) v);

            break;
        }

        case eHomography: {
			M = CTransform3x3();

            // BEGIN TODO
		    // Compute a homography M using all inliers.
		    // This should call ComputeHomography.
printf("TODO: %s:%d\n", __FILE__, __LINE__);

            // END TODO

            break;
        }
    }

    return 0;
}

<|endoftext|>


<commit_before>/**
  MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight
  Project home: https://github.com/puuu/MQTT433gateway/

  The MIT License (MIT)

  Copyright (c) 2017 Jan Losinski

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation files
  (the "Software"), to deal in the Software without restriction,
  including without limitation the rights to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell copies of the Software,
  and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

#include <ESP8266WebServer.h>
#include <WString.h>

#include <ArduinoJson.h>
#include <ArduinoSimpleLogging.h>

#include "../../dist/index.html.gz.h"
#include "ConfigWebServer.h"

const char PROGMEM PLAIN[] = "plain";
const char PROGMEM TEXT_PLAIN[] = "text/plain";
const char PROGMEM TEXT_HTML[] = "text/html";
const char PROGMEM APPLICATION_JSON[] = "application/json";

const char PROGMEM URL_ROOT[] = "/";
const char PROGMEM URL_SYSTEM[] = "/system";
const char PROGMEM URL_CONFIG[] = "/config";
const char PROGMEM URL_PROTOCOLS[] = "/protocols";
const char PROGMEM URL_DEBUG[] = "/debug";
const char PROGMEM URL_FIRMWARE[] = "/firmware";

void ConfigWebServer::begin() {
  server.on(FPSTR(URL_ROOT), authenticated([this]() {
              Logger.debug.println(F("Webserver: frontend request"));
              server.sendHeader(F("Content-Encoding"), F("gzip"));
              server.setContentLength(index_html_gz_len);
              server.send(200, FPSTR(TEXT_HTML), "");
              server.sendContent_P(index_html_gz, index_html_gz_len);
            }));

  server.on(FPSTR(URL_SYSTEM), HTTP_GET, authenticated([this]() {
              Logger.debug.println(F("Webserver: system GET"));
              server.send_P(200, TEXT_PLAIN, PSTR("POST your commands here"));
            }));

  server.on(
      FPSTR(URL_SYSTEM), HTTP_POST,
      authenticated(std::bind(&::ConfigWebServer::onSystemCommand, this)));

  server.on(FPSTR(URL_CONFIG), HTTP_GET, authenticated([&]() {
              Logger.debug.println(F("Webserver: config GET"));
              onConfigGet();
            }));

  server.on(FPSTR(URL_CONFIG), HTTP_PUT, authenticated([&]() {
              Logger.debug.println(F("Webserver: config PUT"));
              settings.deserialize(server.arg(FPSTR(PLAIN)));
              settings.save();
              onConfigGet();
            }));

  server.on(FPSTR(URL_PROTOCOLS), HTTP_GET, authenticated([this]() {
              Logger.debug.println(F("Webserver: protocols GET"));
              if (protocolProvider) {
                server.send(200, FPSTR(APPLICATION_JSON), protocolProvider());
              } else {
                Logger.warning.println(F("No protocolProvider avaiable."));
                server.send_P(200, APPLICATION_JSON, PSTR("[]"));
              }
            }));

  server.on(FPSTR(URL_DEBUG), HTTP_GET, authenticated([&]() {
              Logger.debug.println(F("Webserver: debug GET"));
              onDebugFlagGet();
            }));

  server.on(FPSTR(URL_DEBUG), HTTP_PUT,
            authenticated(std::bind(&::ConfigWebServer::onDebugFlagSet, this)));

  server.on(FPSTR(URL_FIRMWARE), HTTP_GET, authenticated([this]() {
              Logger.debug.println(F("Webserver: firmware GET"));
              server.send(
                  200, FPSTR(APPLICATION_JSON),
                  String(F("{\"version\":\"" QUOTE(FIRMWARE_VERSION) "\",")) +
                      F("\"chipId\":\"") + String(ESP.getChipId(), HEX) +
                      F("\"}"));
            }));

  server.on(
      FPSTR(URL_FIRMWARE), HTTP_POST,
      authenticated(std::bind(&::ConfigWebServer::onFirmwareFinish, this)),
      std::bind(&::ConfigWebServer::onFirmwareUpload, this));

  Logger.debug.println(F("Starting webserver and websocket server."));
  wsLogTarget.begin();
  server.begin();
}

void ConfigWebServer::registerSystemCommandHandler(
    const String& command, const ConfigWebServer::SystemCommandCb& cb) {
  systemCommandHandlers.emplace_front(command, cb);
}

void ConfigWebServer::registerDebugFlagHandler(
    const String& state, const ConfigWebServer::DebugFlagGetCb& getState,
    const ConfigWebServer::DebugFlagSetCb& setState) {
  debugFlagHandlers.emplace_front(state, getState, setState);
}

void ConfigWebServer::onConfigGet() {
  String buff;
  settings.serialize(buff, true, false);
  server.send(200, FPSTR(APPLICATION_JSON), buff);
}

void ConfigWebServer::onSystemCommand() {
  Logger.debug.println(F("Webserver: system POST"));
  DynamicJsonBuffer buffer;
  JsonObject& request = buffer.parse(server.arg(FPSTR(PLAIN)));

  if (!request.success()) {
    server.send_P(400, TEXT_PLAIN, PSTR("Cannot parse command!"));
    return;
  }

  if (!request.containsKey(F("command"))) {
    server.send_P(400, TEXT_PLAIN, PSTR("No command found!"));
    return;
  }

  for (const auto& systemCommandHandler : systemCommandHandlers) {
    if (systemCommandHandler.command == request[F("command")]) {
      server.send_P(200, TEXT_PLAIN, PSTR("Run command!"));
      systemCommandHandler.cb();
      return;
    }
  }

  server.send_P(400, TEXT_PLAIN, PSTR("Unknown command"));
}

void ConfigWebServer::onDebugFlagSet() {
  Logger.debug.println(F("Webserver: debug PUT"));
  DynamicJsonBuffer buffer;
  JsonObject& request = buffer.parse(server.arg(FPSTR(PLAIN)));

  if (request.success()) {
    for (const auto& debugFlagHandler : debugFlagHandlers) {
      if (request.containsKey(debugFlagHandler.name)) {
        debugFlagHandler.setState(request[debugFlagHandler.name].as<bool>());
        Logger.debug.print(F("Set debug flag "));
        Logger.debug.print(debugFlagHandler.name);
        Logger.debug.print(F(": "));
        Logger.debug.println(request[debugFlagHandler.name].as<bool>());
      }
    }
  } else {
    Logger.error.println(F("Cannot parse debug flag as json object!"));
  }
  onDebugFlagGet();
}

void ConfigWebServer::onDebugFlagGet() {
  DynamicJsonBuffer buffer;
  JsonObject& root = buffer.createObject();

  for (const auto& debugFlagHandler : debugFlagHandlers) {
    root[debugFlagHandler.name] = debugFlagHandler.getState();
  }
  String result;
  root.printTo(result);
  server.send(200, FPSTR(APPLICATION_JSON), result);
}

void ConfigWebServer::onFirmwareFinish() {
  server.sendHeader(F("Connection"), F("close"));

  Logger.info.println(F("Got an update. Rebooting..."));
  if (Update.hasError()) {
    server.send_P(
        200, TEXT_PLAIN,
        PSTR("Update failed. More information can be found on the serial "
             "console. \n\nDevice will reboot with old firmware. Please "
             "reconnect and try to flash again."));
  } else {
    server.sendHeader(F("Refresh"), F("20; URL=/"));
    server.send_P(200, TEXT_PLAIN,
                  PSTR("Update successful.\n\nDevice will reboot and try "
                       "to reconnect in 20 seconds."));
  }
  delay(500);
  ESP.restart();
}

void ConfigWebServer::onFirmwareUpload() {
  static bool authenticate = false;
  HTTPUpload& upload = server.upload();
  wsLogTarget.loop();

  if (upload.status == UPLOAD_FILE_START) {
    authenticate = server.authenticate(ADMIN_USERNAME,
                                       this->settings.configPassword.c_str());
    if (!authenticate) {
      return;
    }
    Logger.info.println(F("Webserver: firmware upload started"));
    Serial.setDebugOutput(true);

    if (otaHook) {
      otaHook();
    }

    Logger.debug.print(F("Update: "));
    Logger.debug.println(upload.filename.c_str());
    Logger.debug.print(F("Free heap: "));
    Logger.debug.println(ESP.getFreeHeap());
    uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
    if (!Update.begin(maxSketchSpace)) {  // start with max available size
      Update.printError(Serial);
    }
  } else if (upload.status == UPLOAD_FILE_WRITE && authenticate) {
    if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
      Update.printError(Serial);
    }
  } else if (upload.status == UPLOAD_FILE_END && authenticate) {
    if (Update.end(true)) {  // true to set the size to the current progress
      Logger.debug.print(F("Update Success: "));
      Logger.debug.println(upload.totalSize);
    } else {
      Update.printError(Serial);
    }
    Serial.setDebugOutput(false);
  }
  yield();
}

void ConfigWebServer::loop() {
  wsLogTarget.loop();
  server.handleClient();
}

Print& ConfigWebServer::logTarget() { return wsLogTarget; }

ESP8266WebServer::THandlerFunction ConfigWebServer::authenticated(
    const ESP8266WebServer::THandlerFunction& handler) {
  return [=]() {
    if (!server.authenticate(ADMIN_USERNAME,
                             this->settings.configPassword.c_str())) {
      server.requestAuthentication(DIGEST_AUTH, nullptr,
                                   F("Authentication required!"));
      Logger.warning.println(F("Webserver: Authentication failed."));
    } else {
      handler();
    }
  };
}
<commit_msg>WebServer: do not proceed on errors during update<commit_after>/**
  MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight
  Project home: https://github.com/puuu/MQTT433gateway/

  The MIT License (MIT)

  Copyright (c) 2017 Jan Losinski

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation files
  (the "Software"), to deal in the Software without restriction,
  including without limitation the rights to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell copies of the Software,
  and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

#include <ESP8266WebServer.h>
#include <WString.h>

#include <ArduinoJson.h>
#include <ArduinoSimpleLogging.h>

#include "../../dist/index.html.gz.h"
#include "ConfigWebServer.h"

const char PROGMEM PLAIN[] = "plain";
const char PROGMEM TEXT_PLAIN[] = "text/plain";
const char PROGMEM TEXT_HTML[] = "text/html";
const char PROGMEM APPLICATION_JSON[] = "application/json";

const char PROGMEM URL_ROOT[] = "/";
const char PROGMEM URL_SYSTEM[] = "/system";
const char PROGMEM URL_CONFIG[] = "/config";
const char PROGMEM URL_PROTOCOLS[] = "/protocols";
const char PROGMEM URL_DEBUG[] = "/debug";
const char PROGMEM URL_FIRMWARE[] = "/firmware";

void ConfigWebServer::begin() {
  server.on(FPSTR(URL_ROOT), authenticated([this]() {
              Logger.debug.println(F("Webserver: frontend request"));
              server.sendHeader(F("Content-Encoding"), F("gzip"));
              server.setContentLength(index_html_gz_len);
              server.send(200, FPSTR(TEXT_HTML), "");
              server.sendContent_P(index_html_gz, index_html_gz_len);
            }));

  server.on(FPSTR(URL_SYSTEM), HTTP_GET, authenticated([this]() {
              Logger.debug.println(F("Webserver: system GET"));
              server.send_P(200, TEXT_PLAIN, PSTR("POST your commands here"));
            }));

  server.on(
      FPSTR(URL_SYSTEM), HTTP_POST,
      authenticated(std::bind(&::ConfigWebServer::onSystemCommand, this)));

  server.on(FPSTR(URL_CONFIG), HTTP_GET, authenticated([&]() {
              Logger.debug.println(F("Webserver: config GET"));
              onConfigGet();
            }));

  server.on(FPSTR(URL_CONFIG), HTTP_PUT, authenticated([&]() {
              Logger.debug.println(F("Webserver: config PUT"));
              settings.deserialize(server.arg(FPSTR(PLAIN)));
              settings.save();
              onConfigGet();
            }));

  server.on(FPSTR(URL_PROTOCOLS), HTTP_GET, authenticated([this]() {
              Logger.debug.println(F("Webserver: protocols GET"));
              if (protocolProvider) {
                server.send(200, FPSTR(APPLICATION_JSON), protocolProvider());
              } else {
                Logger.warning.println(F("No protocolProvider avaiable."));
                server.send_P(200, APPLICATION_JSON, PSTR("[]"));
              }
            }));

  server.on(FPSTR(URL_DEBUG), HTTP_GET, authenticated([&]() {
              Logger.debug.println(F("Webserver: debug GET"));
              onDebugFlagGet();
            }));

  server.on(FPSTR(URL_DEBUG), HTTP_PUT,
            authenticated(std::bind(&::ConfigWebServer::onDebugFlagSet, this)));

  server.on(FPSTR(URL_FIRMWARE), HTTP_GET, authenticated([this]() {
              Logger.debug.println(F("Webserver: firmware GET"));
              server.send(
                  200, FPSTR(APPLICATION_JSON),
                  String(F("{\"version\":\"" QUOTE(FIRMWARE_VERSION) "\",")) +
                      F("\"chipId\":\"") + String(ESP.getChipId(), HEX) +
                      F("\"}"));
            }));

  server.on(
      FPSTR(URL_FIRMWARE), HTTP_POST,
      authenticated(std::bind(&::ConfigWebServer::onFirmwareFinish, this)),
      std::bind(&::ConfigWebServer::onFirmwareUpload, this));

  Logger.debug.println(F("Starting webserver and websocket server."));
  wsLogTarget.begin();
  server.begin();
}

void ConfigWebServer::registerSystemCommandHandler(
    const String& command, const ConfigWebServer::SystemCommandCb& cb) {
  systemCommandHandlers.emplace_front(command, cb);
}

void ConfigWebServer::registerDebugFlagHandler(
    const String& state, const ConfigWebServer::DebugFlagGetCb& getState,
    const ConfigWebServer::DebugFlagSetCb& setState) {
  debugFlagHandlers.emplace_front(state, getState, setState);
}

void ConfigWebServer::onConfigGet() {
  String buff;
  settings.serialize(buff, true, false);
  server.send(200, FPSTR(APPLICATION_JSON), buff);
}

void ConfigWebServer::onSystemCommand() {
  Logger.debug.println(F("Webserver: system POST"));
  DynamicJsonBuffer buffer;
  JsonObject& request = buffer.parse(server.arg(FPSTR(PLAIN)));

  if (!request.success()) {
    server.send_P(400, TEXT_PLAIN, PSTR("Cannot parse command!"));
    return;
  }

  if (!request.containsKey(F("command"))) {
    server.send_P(400, TEXT_PLAIN, PSTR("No command found!"));
    return;
  }

  for (const auto& systemCommandHandler : systemCommandHandlers) {
    if (systemCommandHandler.command == request[F("command")]) {
      server.send_P(200, TEXT_PLAIN, PSTR("Run command!"));
      systemCommandHandler.cb();
      return;
    }
  }

  server.send_P(400, TEXT_PLAIN, PSTR("Unknown command"));
}

void ConfigWebServer::onDebugFlagSet() {
  Logger.debug.println(F("Webserver: debug PUT"));
  DynamicJsonBuffer buffer;
  JsonObject& request = buffer.parse(server.arg(FPSTR(PLAIN)));

  if (request.success()) {
    for (const auto& debugFlagHandler : debugFlagHandlers) {
      if (request.containsKey(debugFlagHandler.name)) {
        debugFlagHandler.setState(request[debugFlagHandler.name].as<bool>());
        Logger.debug.print(F("Set debug flag "));
        Logger.debug.print(debugFlagHandler.name);
        Logger.debug.print(F(": "));
        Logger.debug.println(request[debugFlagHandler.name].as<bool>());
      }
    }
  } else {
    Logger.error.println(F("Cannot parse debug flag as json object!"));
  }
  onDebugFlagGet();
}

void ConfigWebServer::onDebugFlagGet() {
  DynamicJsonBuffer buffer;
  JsonObject& root = buffer.createObject();

  for (const auto& debugFlagHandler : debugFlagHandlers) {
    root[debugFlagHandler.name] = debugFlagHandler.getState();
  }
  String result;
  root.printTo(result);
  server.send(200, FPSTR(APPLICATION_JSON), result);
}

void ConfigWebServer::onFirmwareFinish() {
  server.sendHeader(F("Connection"), F("close"));

  Logger.info.println(F("Got an update. Rebooting..."));
  if (Update.hasError()) {
    server.send_P(
        200, TEXT_PLAIN,
        PSTR("Update failed. More information can be found on the serial "
             "console. \n\nDevice will reboot with old firmware. Please "
             "reconnect and try to flash again."));
  } else {
    server.sendHeader(F("Refresh"), F("20; URL=/"));
    server.send_P(200, TEXT_PLAIN,
                  PSTR("Update successful.\n\nDevice will reboot and try "
                       "to reconnect in 20 seconds."));
  }
  delay(500);
  ESP.restart();
}

void ConfigWebServer::onFirmwareUpload() {
  static bool authenticate = false;
  static bool error = false;
  HTTPUpload& upload = server.upload();
  wsLogTarget.loop();

  if (upload.status == UPLOAD_FILE_START) {
    authenticate = server.authenticate(ADMIN_USERNAME,
                                       this->settings.configPassword.c_str());
    error = false;
    if (!authenticate) {
      return;
    }
    Logger.info.println(F("Webserver: firmware upload started"));
    Serial.setDebugOutput(true);

    if (otaHook) {
      otaHook();
    }

    Logger.debug.print(F("Update: "));
    Logger.debug.println(upload.filename.c_str());
    Logger.debug.print(F("Free heap: "));
    Logger.debug.println(ESP.getFreeHeap());
    uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
    if (!Update.begin(maxSketchSpace)) {  // start with max available size
      Update.printError(Serial);
    }
  } else if (upload.status == UPLOAD_FILE_WRITE && authenticate && !error) {
    if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
      error = true;
      Update.printError(Serial);
    }
  } else if (upload.status == UPLOAD_FILE_END && authenticate && !error) {
    if (Update.end(true)) {  // true to set the size to the current progress
      Logger.debug.print(F("Update Success: "));
      Logger.debug.println(upload.totalSize);
    } else {
      Update.printError(Serial);
    }
    Serial.setDebugOutput(false);
  }
  yield();
}

void ConfigWebServer::loop() {
  wsLogTarget.loop();
  server.handleClient();
}

Print& ConfigWebServer::logTarget() { return wsLogTarget; }

ESP8266WebServer::THandlerFunction ConfigWebServer::authenticated(
    const ESP8266WebServer::THandlerFunction& handler) {
  return [=]() {
    if (!server.authenticate(ADMIN_USERNAME,
                             this->settings.configPassword.c_str())) {
      server.requestAuthentication(DIGEST_AUTH, nullptr,
                                   F("Authentication required!"));
      Logger.warning.println(F("Webserver: Authentication failed."));
    } else {
      handler();
    }
  };
}
<|endoftext|>


<commit_before>/**
  MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight
  Project home: https://github.com/puuu/MQTT433gateway/

  The MIT License (MIT)

  Copyright (c) 2017 Jan Losinski

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation files
  (the "Software"), to deal in the Software without restriction,
  including without limitation the rights to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell copies of the Software,
  and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

#include <ArduinoJson.h>

#include "ConfigWebServer.h"

const char TEXT_PLAIN[] PROGMEM = "text/plain";
const char APPLICATION_JSON[] = "application/json";

void ConfigWebServer::begin(const Settings& settings) {
  server.on("/",
            [this]() { server.send(200, TEXT_PLAIN, F("Hello from rfESP")); });

  server.on("/", [this]() {
    server.send(200, TEXT_PLAIN, F("POST your commands here"));
  });

  server.on("/system", HTTP_POST,
            std::bind(&::ConfigWebServer::onSystemCommand, this));

  server.begin();
}

void ConfigWebServer::registerSystemCommandHandler(
    const String& command, const ConfigWebServer::SystemCommandCb& cb) {
  systemCommandHandlers.emplace_front(command, cb);
}

void ConfigWebServer::onSystemCommand() {
  DynamicJsonBuffer buffer;
  JsonObject& request = buffer.parse(server.arg("plain"));

  if (!request.success()) {
    server.send_P(400, TEXT_PLAIN, PSTR("Cannot parse command!"));
    return;
  }

  if (!request.containsKey("command")) {
    server.send_P(400, TEXT_PLAIN, PSTR("No command found!"));
    return;
  }

  for (const auto &systemCommandHandler : systemCommandHandlers) {
    if (systemCommandHandler.command == request["command"]) {
      server.send_P(200, TEXT_PLAIN, PSTR("Run command!"));
      systemCommandHandler.cb();
      return;
    }
  }

  server.send_P(400, TEXT_PLAIN, PSTR("Unknown command"));
}

void ConfigWebServer::handleClient() { server.handleClient(); }

void ConfigWebServer::updateSettings(const Settings& settings) {}
<commit_msg>Webserver: fix missing url route<commit_after>/**
  MQTT433gateway - MQTT 433.92 MHz radio gateway utilizing ESPiLight
  Project home: https://github.com/puuu/MQTT433gateway/

  The MIT License (MIT)

  Copyright (c) 2017 Jan Losinski

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation files
  (the "Software"), to deal in the Software without restriction,
  including without limitation the rights to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell copies of the Software,
  and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

#include <ArduinoJson.h>

#include "ConfigWebServer.h"

const char TEXT_PLAIN[] PROGMEM = "text/plain";
const char APPLICATION_JSON[] = "application/json";

void ConfigWebServer::begin(const Settings& settings) {
  server.on("/",
            [this]() { server.send(200, TEXT_PLAIN, F("Hello from rfESP")); });

  server.on("/system", [this]() {
    server.send(200, TEXT_PLAIN, F("POST your commands here"));
  });

  server.on("/system", HTTP_POST,
            std::bind(&::ConfigWebServer::onSystemCommand, this));

  server.begin();
}

void ConfigWebServer::registerSystemCommandHandler(
    const String& command, const ConfigWebServer::SystemCommandCb& cb) {
  systemCommandHandlers.emplace_front(command, cb);
}

void ConfigWebServer::onSystemCommand() {
  DynamicJsonBuffer buffer;
  JsonObject& request = buffer.parse(server.arg("plain"));

  if (!request.success()) {
    server.send_P(400, TEXT_PLAIN, PSTR("Cannot parse command!"));
    return;
  }

  if (!request.containsKey("command")) {
    server.send_P(400, TEXT_PLAIN, PSTR("No command found!"));
    return;
  }

  for (const auto &systemCommandHandler : systemCommandHandlers) {
    if (systemCommandHandler.command == request["command"]) {
      server.send_P(200, TEXT_PLAIN, PSTR("Run command!"));
      systemCommandHandler.cb();
      return;
    }
  }

  server.send_P(400, TEXT_PLAIN, PSTR("Unknown command"));
}

void ConfigWebServer::handleClient() { server.handleClient(); }

void ConfigWebServer::updateSettings(const Settings& settings) {}
<|endoftext|>


<commit_before>/*************************************************************************
 * Copyright            : (C) 2002 by Gav Wood <gav@kde.org>             *
 *                                                                       *
 * This program is free software; you can redistribute it and/or         *
 * modify it under the terms of the GNU General Public License as        *
 * published by the Free Software Foundation; either version 2 of        *
 * the License or (at your option) version 3 or any later version        *
 * accepted by the membership of KDE e.V. (or its successor approved     *
 * by the membership of KDE e.V.), which shall act as a proxy            *
 * defined in Section 14 of version 3 of the license.                    *
 *                                                                       *
 * This program is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 * GNU General Public License for more details.                          *
 *                                                                       *
 * You should have received a copy of the GNU General Public License     *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. *
 *************************************************************************/

/**
  * @author Gav Wood
  */

//                          main.cpp  -  Implementation of the main window

#include "irkick.h"

#include <kcmdlineargs.h>
#include <kuniqueapplication.h>

extern "C" KDE_EXPORT int kdemain(int argc, char *argv[])
{

    KAboutData *aboutData = new KAboutData("irkick", 0, ki18n("IRKick"), KDE::versionString(), ki18n("The KDE Infrared Remote Control Server"), KAboutData::License_GPL, ki18n("(c) 2003, Gav Wood"), ki18n("Control your desktop with your remote."), "http://utils.kde.org/projects/kdelirc");
    aboutData->addAuthor(ki18n("Gav Wood"), ki18n("Author"), "gav@kde.org");
    aboutData->addCredit(ki18n("Malte Starostik"), ki18n("Original LIRC interface code"), "malte.starostik@t-online.de");
    aboutData->addCredit(ki18n("Dirk Ziegelmeier"), ki18n("Ideas, concept code"), "dirk@ziegelmeier.net");
    aboutData->addCredit(ki18n("Zsolt Rizsanyi"), ki18n("Random patches"), "rizsanyi@myrealbox.com");
    aboutData->addCredit(ki18n("Antonio Larrosa Jiménez"), ki18n("Ideas"), "larrosa@kde.org");
    aboutData->addCredit(ki18n("Michael Zanetti"), ki18n("KDE4-Port and refactoring"), "michael_zanetti@gmx.net");
    aboutData->addCredit(ki18n("Frank Scheffold"), ki18n("KDE4-Port and refactoring"), "fscheffold@googlemail.com");

    KCmdLineArgs::init(argc, argv, aboutData);
    KUniqueApplication::addCmdLineOptions();
    KUniqueApplication app;
    app.setQuitOnLastWindowClosed(false);
    KGlobal::locale()->insertCatalog("kdelirc");
    app.disableSessionManagement();
    IRKick *theIRKick = new IRKick();
    int ret = app.exec();
    delete theIRKick;
    return ret;
}
<commit_msg>bumping the version numbers in /trunk, now that 4.3 has been branched<commit_after>/*************************************************************************
 * Copyright            : (C) 2002 by Gav Wood <gav@kde.org>             *
 *                                                                       *
 * This program is free software; you can redistribute it and/or         *
 * modify it under the terms of the GNU General Public License as        *
 * published by the Free Software Foundation; either version 2 of        *
 * the License or (at your option) version 3 or any later version        *
 * accepted by the membership of KDE e.V. (or its successor approved     *
 * by the membership of KDE e.V.), which shall act as a proxy            *
 * defined in Section 14 of version 3 of the license.                    *
 *                                                                       *
 * This program is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 * GNU General Public License for more details.                          *
 *                                                                       *
 * You should have received a copy of the GNU General Public License     *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. *
 *************************************************************************/

/**
  * @author Gav Wood
  */

//                          main.cpp  -  Implementation of the main window

#include "irkick.h"

#include <kcmdlineargs.h>
#include <kuniqueapplication.h>

extern "C" KDE_EXPORT int kdemain(int argc, char *argv[])
{

    KAboutData *aboutData = new KAboutData("irkick", 0, ki18n("IRKick"), KDE_VERSION_STRING, ki18n("The KDE Infrared Remote Control Server"), KAboutData::License_GPL, ki18n("(c) 2003, Gav Wood"), ki18n("Control your desktop with your remote."), "http://utils.kde.org/projects/kdelirc");
    aboutData->addAuthor(ki18n("Gav Wood"), ki18n("Author"), "gav@kde.org");
    aboutData->addCredit(ki18n("Malte Starostik"), ki18n("Original LIRC interface code"), "malte.starostik@t-online.de");
    aboutData->addCredit(ki18n("Dirk Ziegelmeier"), ki18n("Ideas, concept code"), "dirk@ziegelmeier.net");
    aboutData->addCredit(ki18n("Zsolt Rizsanyi"), ki18n("Random patches"), "rizsanyi@myrealbox.com");
    aboutData->addCredit(ki18n("Antonio Larrosa Jiménez"), ki18n("Ideas"), "larrosa@kde.org");
    aboutData->addCredit(ki18n("Michael Zanetti"), ki18n("KDE4-Port and refactoring"), "michael_zanetti@gmx.net");
    aboutData->addCredit(ki18n("Frank Scheffold"), ki18n("KDE4-Port and refactoring"), "fscheffold@googlemail.com");

    KCmdLineArgs::init(argc, argv, aboutData);
    KUniqueApplication::addCmdLineOptions();
    KUniqueApplication app;
    app.setQuitOnLastWindowClosed(false);
    KGlobal::locale()->insertCatalog("kdelirc");
    app.disableSessionManagement();
    IRKick *theIRKick = new IRKick();
    int ret = app.exec();
    delete theIRKick;
    return ret;
}
<|endoftext|>


<commit_before>#include "StartMenu.h"
#include <stdlib.h>
#include <time.h>
#include <fstream>
#include <iterator>

StartMenu::StartMenu(Input* input) : Superscene(input)
{
  hud = new Entity();
  hud->make2D();
  hud->scale  = glm::vec3(0.5,0.5,1);
  hud->setColor(glm::vec3(0,1,0));
  hud->position = glm::vec3(1024.0/3.0f,720/2.0f,0);
  this->addChild(hud);

  hud2 = new Entity();
  hud2->make2D();
  hud2->scale  = glm::vec3(0.5,0.5,1);
  hud2->setColor(glm::vec3(1,0,0));
  hud2->position = glm::vec3(1024 - 1024.0/3.0f,720/2.0f,0);
  this->addChild(hud2);
}

StartMenu::~StartMenu()
{

}

void StartMenu::Update(float deltaTime)
{
  if (Collision::intersectMouse2D(hud, glm::vec2(input->getMousePosition())) && input->getMouseKeyDown(0)) {
    sceneState = Superscene::NEXT;
  }
  if (Collision::intersectMouse2D(hud2, glm::vec2(input->getMousePosition())) && input->getMouseKeyDown(0)) {
    sceneState = Superscene::DESTROY;
  }
}
<commit_msg>Update documentation<commit_after>#include "StartMenu.h"
#include <stdlib.h>
#include <time.h>
#include <fstream>
#include <iterator>

StartMenu::StartMenu(Input* input) : Superscene(input)
{
  // Make a entity
  hud = new Entity();
  // Make it 2D (GUI element)
  hud->make2D();
  // Set the scale of this entity
  hud->scale  = glm::vec3(0.5,0.5,1);
  // Set the color of this entity
  hud->setColor(glm::vec3(0,1,0));
  // Set the position of this entity according to the screen size
  hud->position = glm::vec3(1024.0/3.0f,720/2.0f,0);
  // Add this entity to the list of children (rendertargets)
  this->addChild(hud);

  // See above
  hud2 = new Entity();
  hud2->make2D();
  hud2->scale  = glm::vec3(0.5,0.5,1);
  hud2->setColor(glm::vec3(1,0,0));
  hud2->position = glm::vec3(1024 - 1024.0/3.0f,720/2.0f,0);
  this->addChild(hud2);
}

StartMenu::~StartMenu()
{

}

void StartMenu::Update(float deltaTime)
{
  // If we click on this element
  if (Collision::intersectMouse2D(hud, glm::vec2(input->getMousePosition())) && input->getMouseKeyDown(0)) {
    // Switch to the next scene
    sceneState = Superscene::NEXT;
  }
  // If we click on this element
  if (Collision::intersectMouse2D(hud2, glm::vec2(input->getMousePosition())) && input->getMouseKeyDown(0)) {
     // Switch to the next scene
    sceneState = Superscene::DESTROY;
  }
}
<|endoftext|>


<commit_before>#include "myarea.h"
#include <cairomm/context.h>
#include <giomm/resource.h>
#include <gdkmm/general.h> // set_source_pixbuf()
#include <glibmm/fileutils.h>
#include <iostream>
#include <sys/mman.h>
#include <fcntl.h>

#define SHARED_FB "shared_fb"

MyArea::MyArea()
{
    shm_fd = -1;
    shm_buf = NULL;
  try
  {
    // The fractal image has been created by the XaoS program.
    // http://xaos.sourceforge.net
    //m_image = Gdk::Pixbuf::create_from_resource("/image/fractal_image.png");
    //m_image = Gdk::Pixbuf::create(Gdk::COLORSPACE_RGB, false, 8, 320, 200);

    //guint8* data = m_image->get_pixels();
    //    guint8* data = (guint8*)malloc(3*320*200);
    int shm_fd = shm_open(SHARED_FB, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
    if(shm_fd > 0) {
        ftruncate(shm_fd, 320*200*3);
        shm_buf = mmap(NULL, 320*200*3, PROT_READ|PROT_WRITE, MAP_SHARED, shm_fd, (off_t)0);
        if(shm_buf == MAP_FAILED) {
            fprintf(stderr, "mmap failed: %s\n", strerror(errno));
            shm_buf = NULL;
        }
    }
    else {
        fprintf(stderr, "shm_open failed: %s\n", strerror(errno));
    }

    if(shm_buf != NULL) {
        guint8* data = (guint8*)shm_buf;
        m_image = Gdk::Pixbuf::create_from_data(data, Gdk::COLORSPACE_RGB, false, 8, 320, 200, 320 * 3);

        for(int row = 0; row < 200; row++) {
            for(int col = 0; col < 320; col++) {
            //*data++ = row;
            *data++ = 0;
            *data++ = row;
            *data++ = row;
            }
        }
    }
    //memset(data, 128, 3 * sizeof(guint8) * 320 * 200);

  }
  catch(const Gio::ResourceError& ex)
  {
    //std::cerr << "ResourceError: " << ex.what() << std::endl;
  }
  catch(const Gdk::PixbufError& ex)
  {
    //std::cerr << "PixbufError: " << ex.what() << std::endl;
  }

  // Show at least a quarter of the image.
  if (m_image)
    set_size_request(m_image->get_width()/2, m_image->get_height()/2);
}

MyArea::~MyArea()
{
    fprintf(stdout, "exiting\n");
    if(shm_buf != NULL) {
        munmap(shm_buf, 320*200*3);
    }
    if(shm_fd > 0) {
        shm_unlink(SHARED_FB);
    }
}

bool MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
  if (!m_image)
    return false;

  Gtk::Allocation allocation = get_allocation();
  const int width = allocation.get_width();
  const int height = allocation.get_height();

  // Draw the image in the middle of the drawing area, or (if the image is
  // larger than the drawing area) draw the middle part of the image.
  Gdk::Cairo::set_source_pixbuf(cr, m_image,
    (width - m_image->get_width())/2, (height - m_image->get_height())/2);
  cr->paint();

  return true;
}
<commit_msg>close<commit_after>#include "myarea.h"
#include <cairomm/context.h>
#include <giomm/resource.h>
#include <gdkmm/general.h> // set_source_pixbuf()
#include <glibmm/fileutils.h>
#include <iostream>
#include <sys/mman.h>
#include <fcntl.h>

#define SHARED_FB "shared_fb"

MyArea::MyArea()
{
    shm_fd = -1;
    shm_buf = NULL;
  try
  {
    int shm_fd = shm_open(SHARED_FB, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
    if(shm_fd > 0) {
        ftruncate(shm_fd, 320*200*3);
        shm_buf = mmap(NULL, 320*200*3, PROT_READ|PROT_WRITE, MAP_SHARED, shm_fd, (off_t)0);
        if(shm_buf == MAP_FAILED) {
            fprintf(stderr, "mmap failed: %s\n", strerror(errno));
            shm_buf = NULL;
        }
    }
    else {
        fprintf(stderr, "shm_open failed: %s\n", strerror(errno));
    }

    if(shm_buf != NULL) {
        guint8* data = (guint8*)shm_buf;
        m_image = Gdk::Pixbuf::create_from_data(data, Gdk::COLORSPACE_RGB, false, 8, 320, 200, 320 * 3);

        for(int row = 0; row < 200; row++) {
            for(int col = 0; col < 320; col++) {
            //*data++ = row;
            *data++ = 0;
            *data++ = row;
            *data++ = row;
            }
        }
    }
    //memset(data, 128, 3 * sizeof(guint8) * 320 * 200);

  }
  catch(const Gio::ResourceError& ex)
  {
    //std::cerr << "ResourceError: " << ex.what() << std::endl;
  }
  catch(const Gdk::PixbufError& ex)
  {
    //std::cerr << "PixbufError: " << ex.what() << std::endl;
  }

  if (m_image) {
    set_size_request(m_image->get_width(), m_image->get_height());
  }
}

MyArea::~MyArea()
{
    if(shm_buf != NULL) {
        munmap(shm_buf, 320*200*3);
    }
    if(shm_fd > 0) {
        close(shm_fd);
        shm_unlink(SHARED_FB);
    }
}

bool MyArea::on_draw(const Cairo::RefPtr<Cairo::Context>& cr)
{
  if (!m_image)
    return false;

  Gtk::Allocation allocation = get_allocation();
  const int width = allocation.get_width();
  const int height = allocation.get_height();

  // Draw the image in the middle of the drawing area, or (if the image is
  // larger than the drawing area) draw the middle part of the image.
  Gdk::Cairo::set_source_pixbuf(cr, m_image,
    (width - m_image->get_width())/2, (height - m_image->get_height())/2);
  cr->paint();

  return true;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// A binary wrapper for QuicClient.  Connects to --hostname on
// --port and requests URLs specified on the command line.
//
// For example:
//  quic_client --port 6122 /index.html /favicon.ico

#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "net/base/ip_endpoint.h"
#include "net/tools/quic/quic_client.h"

int32 FLAGS_port = 6121;
std::string FLAGS_address = "127.0.0.1";
std::string FLAGS_hostname = "localhost";

int main(int argc, char *argv[]) {
  CommandLine::Init(argc, argv);

  base::AtExitManager exit_manager;

  net::IPAddressNumber addr;
  CHECK(net::ParseIPLiteralToNumber(FLAGS_address, &addr));
  net::tools::QuicClient client(
      net::IPEndPoint(addr, FLAGS_port), FLAGS_hostname);

  client.Initialize();

  if (!client.Connect()) return 1;

  client.SendRequestsAndWaitForResponse(argc, argv);
  return 0;
}
<commit_msg>Fix the commandline handling in quic_client.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// A binary wrapper for QuicClient.  Connects to --hostname or --address on
// --port and requests URLs specified on the command line.
//
// For example:
//  quic_client --port 6122 /index.html /favicon.ico

#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "net/base/ip_endpoint.h"
#include "net/tools/quic/quic_client.h"

int32 FLAGS_port = 6121;
std::string FLAGS_address = "127.0.0.1";
std::string FLAGS_hostname = "localhost";

int main(int argc, char *argv[]) {
  CommandLine::Init(argc, argv);
  CommandLine* line = CommandLine::ForCurrentProcess();
  if (line->HasSwitch("port")) {
    int port;
    if (base::StringToInt(line->GetSwitchValueASCII("port"), &port)) {
      FLAGS_port = port;
    }
  }
  if (line->HasSwitch("address")) {
    FLAGS_address = line->GetSwitchValueASCII("address");
  }
  if (line->HasSwitch("hostname")) {
    FLAGS_hostname = line->GetSwitchValueASCII("hostname");
  }
  LOG(INFO) << "server port: " << FLAGS_port
            << " address: " << FLAGS_address
            << " hostname: " << FLAGS_hostname;

  base::AtExitManager exit_manager;

  net::IPAddressNumber addr;
  CHECK(net::ParseIPLiteralToNumber(FLAGS_address, &addr));
  net::tools::QuicClient client(
      net::IPEndPoint(addr, FLAGS_port), FLAGS_hostname);

  client.Initialize();

  if (!client.Connect()) return 1;

  client.SendRequestsAndWaitForResponse(argc, argv);
  return 0;
}
<|endoftext|>