<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX600 グループ　GLCDC　I/O 制御
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX65x/glcdc.hpp"
#include "common/delay.hpp"

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  GLCDC I/O 制御
		@param[in]	GLC		glcdc クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class GLC>
	class glcdc_io {
	public:

		struct cfg_t {
			uint8_t	clksrc;
			uint8_t	clock_div_ratio;
			bool	serial;
			bool	sync_edge;

			cfg_t() : clksrc(0), clock_div_ratio(0), serial(false),
				sync_edge(false)
			{ }
		};

	private:

		void set_clock_(const cfg_t& t)
		{
			GLC::PANELCLK.CLKSEL = t.clksrc;
			GLC::PANELCLK.DCDR   = t.clock_div_ratio;

			GLC::PANELCLK.PIXSEL = t.serial;

			GLC::PANELCLK.CLKEN = 1;

			while(GLC::BGMON.SWRST() == 0) {
				asm("nop");
			}
		}

		void set_hsync_(glcdc_tcon_pin_t tcon, glcdc_timing_t const * const p_timing, glcdc_signal_polarity_t polarity)
		{
#if 0
    		switch(tcon) {
        case GLCDC_TCON_PIN_1:
            GLCDC.TCONSTVB2.BIT.SEL = (uint32_t)GLCDC_TCON_SIGNAL_SELECT_STHA_HS; /* Hsync(STHA) -> TCON1 */
        break;
        case GLCDC_TCON_PIN_2:
            GLCDC.TCONSTHA2.BIT.SEL = (uint32_t)GLCDC_TCON_SIGNAL_SELECT_STHA_HS; /* Hsync(STHA) -> TCON2 */
        break;
        case GLCDC_TCON_PIN_3:
            GLCDC.TCONSTHB2.BIT.SEL = (uint32_t)GLCDC_TCON_SIGNAL_SELECT_STHA_HS; /* Hsync(STHA) -> TCON3 */
        break;
        case GLCDC_TCON_PIN_0: /* Intentionally go though to the default case */
        default:
            GLCDC.TCONSTVA2.BIT.SEL = (uint32_t)GLCDC_TCON_SIGNAL_SELECT_STHA_HS; /* Hsync(STHA) -> TCON0 */
        break;
    }

    /* Polarity of a signal select */
    /* TCONSTHA2 - Horizontal Timing Setting Register A2
    b31:b9 Reserved - These bits are read as 0. Writing to these bits have no effect.
    b8     HSSEL    - STHy Signal Reference Timing Select. - Select HS signal or
                      the TCONTIM.OFFSET[10:0] bits as reference for signal generation.
    b7:b5  Reserved - These bits are read as 0. Writing to these bits have no effect.
    b4     INV      - STHy Signal Polarity Inversion. - Do not invert the STHy signal or Invert the STHy signal.
    b3     Reserved - These bits are read as 0. Writing to these bits have no effect.
    b2:b0  SEL[2:0] - Output Signal Select. - Select as STVA, STVB, STHA, STHB or DE */
    GLCDC.TCONSTHA2.BIT.INV = (uint32_t)polarity; /* Hsync(STHA) -> Invert or Not Invert */

    /* Hsync beginning position */
    GLCDC.TCONSTHA1.BIT.HS = 0;    /* No delay */
    GLCDC.TCONSTHA2.BIT.HSSEL = 0; /* Select input Hsync as reference */

    /* HSync Width Setting */
    GLCDC.TCONSTHA1.BIT.HW = p_timing->sync_width & TCON_STHx1_HW_MASK;
#endif
		}

		void set_sync_signal_(const cfg_t& t)
		{
			GLC::CLKPHASE.LCDEDG   = t.sync_edge;
			GLC::CLKPHASE.TCON0EDG = t.sync_edge;
			GLC::CLKPHASE.TCON1EDG = t.sync_edge;
			GLC::CLKPHASE.TCON2EDG = t.sync_edge;
			GLC::CLKPHASE.TCON3EDG = t.sync_edge;

			GLC::TCONTIM.OFFSET = 0;  // 1 pixel
			GLC::TCONTIM.HALF   = 0;  // 1 pixel (No delay)

//			set_hsync_(t.tcon_hsync, &p_cfg->output.htiming, p_cfg->output.hsync_polarity);
//    r_glcdc_vsync_set (p_cfg->output.tcon_vsync, &p_cfg->output.vtiming, p_cfg->output.vsync_polarity);
//    r_glcdc_data_enable_set (p_cfg->output.tcon_de, &p_cfg->output.vtiming, &p_cfg->output.htiming, p_cfg->output.data_enable_polarity);
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		 */
		//-----------------------------------------------------------------//
		glcdc_io() noexcept
		{ }

		//-----------------------------------------------------------------//
		/*!
			@brief	開始
		 */
		//-----------------------------------------------------------------//
		void start() noexcept
		{
			// Set the BGEN.SWRST bit to 1 to release the GLCDC from a software reset
			GLC::BGEN.SWRST = 0;
			utils::delay::milli_second(10);
			GLC::BGEN.SWRST = 1;

			// Set the frequency of the LCD_CLK and PXCLK to suit the format
			// and set the PANELCLK.CLKEN bit to 1
			// Select PLL clock, 240 / 24 = 10 MHz, No frequency division, Enable LCD_CLK output
			GLC::PANELCLK = GLC::PANELCLK.DCDR.b(0b011000) | GLC::PANELCLK.CLKEN.b() |
				GLC::PANELCLK.CLKSEL.b();

			// Definition of Background Screen
			// Horizontal cycle (whole control screen)
			// Vertical cycle (whole control screen)

			// glcdc_cfg.output.htiming.front_porch = 5;
			GLC::TCONSTHA1.HS = 5;  // Horizontal Synchronization Signal Assertion Position

			// glcdc_cfg.output.vtiming.front_porch = 8;
			GLC::TCONSTVA1.VS = 8;  // Vertical Synchronization Signal Assertion Position

			// glcdc_cfg.output.htiming.back_porch = 40;
			GLC::TCONSTHA1.HW = 40;
                        // Horizontal Active Pixel Start Position (min. 6 pixels)

#if 0
  glcdc_cfg.output.vtiming.back_porch = 8;
  glcdc_cfg.output.htiming.display_cyc = XSIZE_PHYS;              // Horizontal Active Pixel Width
  glcdc_cfg.output.vtiming.display_cyc = YSIZE_PHYS;              // Vertical Active Display Width
  glcdc_cfg.output.htiming.sync_width = 1;        				  // Vertical Active Display Start Position (min. 3 lines)
  glcdc_cfg.output.vtiming.sync_width = 1;

  //
  // Graphic 1 configuration
  //
  glcdc_cfg.input[GLCDC_FRAME_LAYER_1].p_base = NULL;			  // Disable Graphics 1

  //
  // Graphic 2 configuration
  //
  													  	  	  	  // Enable reading of the frame buffer
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].p_base = (uint32_t *)_aBufferPTR[0];   // Specify the start address of the frame buffer
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].offset = LINE_OFFSET;      // Offset value from the end address of the line to the start address of the next line
  																  // Single Line Data Transfer Count
  																  // Single Frame Line Count
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].format = COLOR_FORMAT;     // Frame Buffer Color Format RGB565
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].visible = true;
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].blend_control = GLCDC_BLEND_CONTROL_NONE;	// Display Screen Control (current graphics)
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].frame_edge = false;        // Rectangular Alpha Blending Area Frame Display Control
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].frame_edge = false;        // Graphics Area Frame Display Control
  																  // Alpha Blending Control (Per-pixel alpha blending)
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].coordinate.y = 0;          // Graphics Area Vertical Start Position
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].vsize = YSIZE_PHYS;        // Graphics Area Vertical Width
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].coordinate.x = 0;          // Graphics Area Horizontal Start Position
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].hsize = XSIZE_PHYS;        // Graphics Area Horizontal Width
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].start_coordinate.x = 0;    // Rectangular Alpha Blending Area Vertical Start Position
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].end_coordinate.x= YSIZE_PHYS; // Rectangular Alpha Blending Area Vertical Width
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].start_coordinate.y = 0;    // Rectangular Alpha Blending Area Horizontal Start Position
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].end_coordinate.y= XSIZE_PHYS; // Rectangular Alpha Blending Area Horizontal Width
  																  // Graphic 2 Register Value Reflection Enable
  //
  // Timing configuration
  //
  //   Horizontal Synchronization Signal Reference Timing Offset (not support)
  //   Signal Reference Timing Select (not support)
  //   STVB Signal Assertion Timing
  //   STVB Signal Pulse Width
  //   STHB Signal Pulse Width
  glcdc_cfg.output.tcon_vsync = GLCDC_TCON_PIN_0;           // TCON0 Output Signal Select STVA (VSYNC)
  glcdc_cfg.output.tcon_hsync = GLCDC_TCON_PIN_2;           // TCON2 Output Signal Select STHA (HSYNC)
  glcdc_cfg.output.tcon_de    = GLCDC_TCON_PIN_3;           // TCON3 Output Signal Select DE (DEN)
  glcdc_cfg.output.data_enable_polarity = GLCDC_SIGNAL_POLARITY_HIACTIVE;
  glcdc_cfg.output.hsync_polarity = GLCDC_SIGNAL_POLARITY_LOACTIVE;
  glcdc_cfg.output.vsync_polarity = GLCDC_SIGNAL_POLARITY_LOACTIVE;
  glcdc_cfg.output.sync_edge = GLCDC_SIGNAL_SYNC_EDGE_RISING;
  //
  // Output interface
  //
  //   Serial RGB Data Output Delay Control (0 cycles) (not support)
  //   Serial RGB Scan Direction Select (forward) (not support)
  //   Pixel Clock Division Control (no division)
  glcdc_cfg.output.format = GLCDC_OUT_FORMAT_16BITS_RGB565; // Output Data Format Select (RGB565)
  glcdc_cfg.output.color_order = GLCDC_COLOR_ORDER_RGB; ///**/GLCDC_COLOR_ORDER_BGR;  	// Pixel Order Control (B-G-R)
  glcdc_cfg.output.endian = GLCDC_ENDIAN_LITTLE;  			// Bit Endian Control (Little endian)
  //
  // Brightness Adjustment
  //
  glcdc_cfg.output.brightness.b = _BRIGHTNESS;  // B
  glcdc_cfg.output.brightness.g = _BRIGHTNESS;  // G
  glcdc_cfg.output.brightness.r = _BRIGHTNESS;  // R
  //
  // Contrast Adjustment Value
  //
  glcdc_cfg.output.contrast.b = _CONTRAST;  // B
  glcdc_cfg.output.contrast.g = _CONTRAST;  // G
  glcdc_cfg.output.contrast.r = _CONTRAST;  // R
  //
  // Disable Gamma
  //
  glcdc_cfg.output.gamma.enable = false;
  //
  // Disable Chromakey
  //
  glcdc_cfg.chromakey[GLCDC_FRAME_LAYER_2].enable = false;
  //
  // Disable Dithering
  //
  glcdc_cfg.output.dithering.dithering_on = false;
  //
  // CLUT Adjustment Value
  //
  glcdc_cfg.clut[GLCDC_FRAME_LAYER_2].enable = false;
  //
  // Enable VPOS ISR
  //
  //   Detecting Scanline Setting
  glcdc_cfg.detection.vpos_detect = true;		         	// Enable detection of specified line notification in graphic 2
  glcdc_cfg.interrupt.vpos_enable = true;		           	// Enable VPOS interrupt request
  //   Interrupt Priority Level (r_glcdc_rx_config.h)
  //   Interrupt Request Enable
  //   Clears the STMON.VPOS flag
  //   VPOS (line detection)
  glcdc_cfg.detection.gr1uf_detect = false;
  glcdc_cfg.detection.gr2uf_detect = false;
  glcdc_cfg.interrupt.gr1uf_enable = false;
  glcdc_cfg.interrupt.gr2uf_enable = false;
  //
  // Set function to be called on VSYNC
  //
  glcdc_cfg.p_callback = (void (*)(glcdc_callback_args_t *))_VSYNC_ISR;

  runtime_cfg.blend = glcdc_cfg.blend[GLCDC_FRAME_LAYER_2];
  runtime_cfg.input = glcdc_cfg.input[GLCDC_FRAME_LAYER_2];
  runtime_cfg.chromakey = glcdc_cfg.chromakey[GLCDC_FRAME_LAYER_2];
  //
  // Register Dave2D interrupt
  //
  R_BSP_InterruptWrite(BSP_INT_SRC_AL1_DRW2D_DRW_IRQ, (bsp_int_cb_t)drw_int_isr);
  //
  // Register Reflection
  //
  ret = R_GLCDC_Open(&glcdc_cfg);
  if (ret != GLCDC_SUCCESS) {
	  while(1);
  }
  //
  // Init DMA
  //
  R_DMACA_Init();
  //
  // Extended Bus Master Priority Control Register
  //
  BSC.EBMAPCR.BIT.PR1SEL = 0;
  BSC.EBMAPCR.BIT.PR2SEL = 3;
  BSC.EBMAPCR.BIT.PR3SEL = 1;
  BSC.EBMAPCR.BIT.PR4SEL = 2;
  BSC.EBMAPCR.BIT.PR5SEL = 4;
}
#endif
		}

	};
}

<commit_msg>update: cleanup<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX600 グループ　GLCDC　I/O 制御
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX65x/glcdc.hpp"
#include "common/delay.hpp"

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  GLCDC I/O 制御
		@param[in]	GLC		glcdc クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class GLC>
	class glcdc_io {
	public:

		struct cfg_t {
			uint8_t	clksrc;
			uint8_t	clock_div_ratio;
			bool	serial;
			bool	sync_edge;

			cfg_t() : clksrc(0), clock_div_ratio(0), serial(false),
				sync_edge(false)
			{ }
		};

	private:

		void set_clock_(const cfg_t& t)
		{
			GLC::PANELCLK.CLKSEL = t.clksrc;
			GLC::PANELCLK.DCDR   = t.clock_div_ratio;

			GLC::PANELCLK.PIXSEL = t.serial;

			GLC::PANELCLK.CLKEN = 1;

			while(GLC::BGMON.SWRST() == 0) {
				asm("nop");
			}
		}

#if 0
		void set_hsync_(glcdc_tcon_pin_t tcon, glcdc_timing_t const * const p_timing, glcdc_signal_polarity_t polarity)
		{
#if 0
    		switch(tcon) {
        case GLCDC_TCON_PIN_1:
            GLCDC.TCONSTVB2.BIT.SEL = (uint32_t)GLCDC_TCON_SIGNAL_SELECT_STHA_HS; /* Hsync(STHA) -> TCON1 */
        break;
        case GLCDC_TCON_PIN_2:
            GLCDC.TCONSTHA2.BIT.SEL = (uint32_t)GLCDC_TCON_SIGNAL_SELECT_STHA_HS; /* Hsync(STHA) -> TCON2 */
        break;
        case GLCDC_TCON_PIN_3:
            GLCDC.TCONSTHB2.BIT.SEL = (uint32_t)GLCDC_TCON_SIGNAL_SELECT_STHA_HS; /* Hsync(STHA) -> TCON3 */
        break;
        case GLCDC_TCON_PIN_0: /* Intentionally go though to the default case */
        default:
            GLCDC.TCONSTVA2.BIT.SEL = (uint32_t)GLCDC_TCON_SIGNAL_SELECT_STHA_HS; /* Hsync(STHA) -> TCON0 */
        break;
    }

    /* Polarity of a signal select */
    /* TCONSTHA2 - Horizontal Timing Setting Register A2
    b31:b9 Reserved - These bits are read as 0. Writing to these bits have no effect.
    b8     HSSEL    - STHy Signal Reference Timing Select. - Select HS signal or
                      the TCONTIM.OFFSET[10:0] bits as reference for signal generation.
    b7:b5  Reserved - These bits are read as 0. Writing to these bits have no effect.
    b4     INV      - STHy Signal Polarity Inversion. - Do not invert the STHy signal or Invert the STHy signal.
    b3     Reserved - These bits are read as 0. Writing to these bits have no effect.
    b2:b0  SEL[2:0] - Output Signal Select. - Select as STVA, STVB, STHA, STHB or DE */
    GLCDC.TCONSTHA2.BIT.INV = (uint32_t)polarity; /* Hsync(STHA) -> Invert or Not Invert */

    /* Hsync beginning position */
    GLCDC.TCONSTHA1.BIT.HS = 0;    /* No delay */
    GLCDC.TCONSTHA2.BIT.HSSEL = 0; /* Select input Hsync as reference */

    /* HSync Width Setting */
    GLCDC.TCONSTHA1.BIT.HW = p_timing->sync_width & TCON_STHx1_HW_MASK;
#endif
		}
#endif

		void set_sync_signal_(const cfg_t& t)
		{
			GLC::CLKPHASE.LCDEDG   = t.sync_edge;
			GLC::CLKPHASE.TCON0EDG = t.sync_edge;
			GLC::CLKPHASE.TCON1EDG = t.sync_edge;
			GLC::CLKPHASE.TCON2EDG = t.sync_edge;
			GLC::CLKPHASE.TCON3EDG = t.sync_edge;

			GLC::TCONTIM.OFFSET = 0;  // 1 pixel
			GLC::TCONTIM.HALF   = 0;  // 1 pixel (No delay)

//			set_hsync_(t.tcon_hsync, &p_cfg->output.htiming, p_cfg->output.hsync_polarity);
//    r_glcdc_vsync_set (p_cfg->output.tcon_vsync, &p_cfg->output.vtiming, p_cfg->output.vsync_polarity);
//    r_glcdc_data_enable_set (p_cfg->output.tcon_de, &p_cfg->output.vtiming, &p_cfg->output.htiming, p_cfg->output.data_enable_polarity);
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		 */
		//-----------------------------------------------------------------//
		glcdc_io() noexcept
		{ }

		//-----------------------------------------------------------------//
		/*!
			@brief	開始
		 */
		//-----------------------------------------------------------------//
		void start() noexcept
		{
			// Set the BGEN.SWRST bit to 1 to release the GLCDC from a software reset
			GLC::BGEN.SWRST = 0;
			utils::delay::milli_second(10);
			GLC::BGEN.SWRST = 1;

			// Set the frequency of the LCD_CLK and PXCLK to suit the format
			// and set the PANELCLK.CLKEN bit to 1
			// Select PLL clock, 240 / 24 = 10 MHz, No frequency division, Enable LCD_CLK output
			GLC::PANELCLK = GLC::PANELCLK.DCDR.b(0b011000) | GLC::PANELCLK.CLKEN.b() |
				GLC::PANELCLK.CLKSEL.b();

			// Definition of Background Screen
			// Horizontal cycle (whole control screen)
			// Vertical cycle (whole control screen)

			// glcdc_cfg.output.htiming.front_porch = 5;
			GLC::TCONSTHA1.HS = 5;  // Horizontal Synchronization Signal Assertion Position

			// glcdc_cfg.output.vtiming.front_porch = 8;
			GLC::TCONSTVA1.VS = 8;  // Vertical Synchronization Signal Assertion Position

			// glcdc_cfg.output.htiming.back_porch = 40;
			GLC::TCONSTHA1.HW = 40;
                        // Horizontal Active Pixel Start Position (min. 6 pixels)

#if 0
  glcdc_cfg.output.vtiming.back_porch = 8;
  glcdc_cfg.output.htiming.display_cyc = XSIZE_PHYS;              // Horizontal Active Pixel Width
  glcdc_cfg.output.vtiming.display_cyc = YSIZE_PHYS;              // Vertical Active Display Width
  glcdc_cfg.output.htiming.sync_width = 1;        				  // Vertical Active Display Start Position (min. 3 lines)
  glcdc_cfg.output.vtiming.sync_width = 1;

  //
  // Graphic 1 configuration
  //
  glcdc_cfg.input[GLCDC_FRAME_LAYER_1].p_base = NULL;			  // Disable Graphics 1

  //
  // Graphic 2 configuration
  //
  													  	  	  	  // Enable reading of the frame buffer
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].p_base = (uint32_t *)_aBufferPTR[0];   // Specify the start address of the frame buffer
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].offset = LINE_OFFSET;      // Offset value from the end address of the line to the start address of the next line
  																  // Single Line Data Transfer Count
  																  // Single Frame Line Count
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].format = COLOR_FORMAT;     // Frame Buffer Color Format RGB565
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].visible = true;
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].blend_control = GLCDC_BLEND_CONTROL_NONE;	// Display Screen Control (current graphics)
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].frame_edge = false;        // Rectangular Alpha Blending Area Frame Display Control
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].frame_edge = false;        // Graphics Area Frame Display Control
  																  // Alpha Blending Control (Per-pixel alpha blending)
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].coordinate.y = 0;          // Graphics Area Vertical Start Position
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].vsize = YSIZE_PHYS;        // Graphics Area Vertical Width
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].coordinate.x = 0;          // Graphics Area Horizontal Start Position
  glcdc_cfg.input[GLCDC_FRAME_LAYER_2].hsize = XSIZE_PHYS;        // Graphics Area Horizontal Width
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].start_coordinate.x = 0;    // Rectangular Alpha Blending Area Vertical Start Position
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].end_coordinate.x= YSIZE_PHYS; // Rectangular Alpha Blending Area Vertical Width
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].start_coordinate.y = 0;    // Rectangular Alpha Blending Area Horizontal Start Position
  glcdc_cfg.blend[GLCDC_FRAME_LAYER_2].end_coordinate.y= XSIZE_PHYS; // Rectangular Alpha Blending Area Horizontal Width
  																  // Graphic 2 Register Value Reflection Enable
  //
  // Timing configuration
  //
  //   Horizontal Synchronization Signal Reference Timing Offset (not support)
  //   Signal Reference Timing Select (not support)
  //   STVB Signal Assertion Timing
  //   STVB Signal Pulse Width
  //   STHB Signal Pulse Width
  glcdc_cfg.output.tcon_vsync = GLCDC_TCON_PIN_0;           // TCON0 Output Signal Select STVA (VSYNC)
  glcdc_cfg.output.tcon_hsync = GLCDC_TCON_PIN_2;           // TCON2 Output Signal Select STHA (HSYNC)
  glcdc_cfg.output.tcon_de    = GLCDC_TCON_PIN_3;           // TCON3 Output Signal Select DE (DEN)
  glcdc_cfg.output.data_enable_polarity = GLCDC_SIGNAL_POLARITY_HIACTIVE;
  glcdc_cfg.output.hsync_polarity = GLCDC_SIGNAL_POLARITY_LOACTIVE;
  glcdc_cfg.output.vsync_polarity = GLCDC_SIGNAL_POLARITY_LOACTIVE;
  glcdc_cfg.output.sync_edge = GLCDC_SIGNAL_SYNC_EDGE_RISING;
  //
  // Output interface
  //
  //   Serial RGB Data Output Delay Control (0 cycles) (not support)
  //   Serial RGB Scan Direction Select (forward) (not support)
  //   Pixel Clock Division Control (no division)
  glcdc_cfg.output.format = GLCDC_OUT_FORMAT_16BITS_RGB565; // Output Data Format Select (RGB565)
  glcdc_cfg.output.color_order = GLCDC_COLOR_ORDER_RGB; ///**/GLCDC_COLOR_ORDER_BGR;  	// Pixel Order Control (B-G-R)
  glcdc_cfg.output.endian = GLCDC_ENDIAN_LITTLE;  			// Bit Endian Control (Little endian)
  //
  // Brightness Adjustment
  //
  glcdc_cfg.output.brightness.b = _BRIGHTNESS;  // B
  glcdc_cfg.output.brightness.g = _BRIGHTNESS;  // G
  glcdc_cfg.output.brightness.r = _BRIGHTNESS;  // R
  //
  // Contrast Adjustment Value
  //
  glcdc_cfg.output.contrast.b = _CONTRAST;  // B
  glcdc_cfg.output.contrast.g = _CONTRAST;  // G
  glcdc_cfg.output.contrast.r = _CONTRAST;  // R
  //
  // Disable Gamma
  //
  glcdc_cfg.output.gamma.enable = false;
  //
  // Disable Chromakey
  //
  glcdc_cfg.chromakey[GLCDC_FRAME_LAYER_2].enable = false;
  //
  // Disable Dithering
  //
  glcdc_cfg.output.dithering.dithering_on = false;
  //
  // CLUT Adjustment Value
  //
  glcdc_cfg.clut[GLCDC_FRAME_LAYER_2].enable = false;
  //
  // Enable VPOS ISR
  //
  //   Detecting Scanline Setting
  glcdc_cfg.detection.vpos_detect = true;		         	// Enable detection of specified line notification in graphic 2
  glcdc_cfg.interrupt.vpos_enable = true;		           	// Enable VPOS interrupt request
  //   Interrupt Priority Level (r_glcdc_rx_config.h)
  //   Interrupt Request Enable
  //   Clears the STMON.VPOS flag
  //   VPOS (line detection)
  glcdc_cfg.detection.gr1uf_detect = false;
  glcdc_cfg.detection.gr2uf_detect = false;
  glcdc_cfg.interrupt.gr1uf_enable = false;
  glcdc_cfg.interrupt.gr2uf_enable = false;
  //
  // Set function to be called on VSYNC
  //
  glcdc_cfg.p_callback = (void (*)(glcdc_callback_args_t *))_VSYNC_ISR;

  runtime_cfg.blend = glcdc_cfg.blend[GLCDC_FRAME_LAYER_2];
  runtime_cfg.input = glcdc_cfg.input[GLCDC_FRAME_LAYER_2];
  runtime_cfg.chromakey = glcdc_cfg.chromakey[GLCDC_FRAME_LAYER_2];
  //
  // Register Dave2D interrupt
  //
  R_BSP_InterruptWrite(BSP_INT_SRC_AL1_DRW2D_DRW_IRQ, (bsp_int_cb_t)drw_int_isr);
  //
  // Register Reflection
  //
  ret = R_GLCDC_Open(&glcdc_cfg);
  if (ret != GLCDC_SUCCESS) {
	  while(1);
  }
  //
  // Init DMA
  //
  R_DMACA_Init();
  //
  // Extended Bus Master Priority Control Register
  //
  BSC.EBMAPCR.BIT.PR1SEL = 0;
  BSC.EBMAPCR.BIT.PR2SEL = 3;
  BSC.EBMAPCR.BIT.PR3SEL = 1;
  BSC.EBMAPCR.BIT.PR4SEL = 2;
  BSC.EBMAPCR.BIT.PR5SEL = 4;
}
#endif
		}

	};
}

<|endoftext|>


<commit_before>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.

// Copyright (c) 2016 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/cameras/Camera_Spherical.hpp"
#include "openMVG/cameras/Camera_Pinhole.hpp"

#include "openMVG/image/image_io.hpp"
#include "openMVG/image/sample.hpp"

#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/vectorGraphics/svgDrawer.hpp"

#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

using namespace std;
using namespace svg;

/// Compute a rectilinear camera focal from a given angular desired FoV
double focalFromPinholeHeight
(
  int h,
  double thetaMax = openMVG::D2R(60) // Camera FoV
)
{
  float f = 1.f;
  while ( thetaMax < atan2( h / (2 * f) , 1))
  {
    ++f;
  }
  return f;
}

// Convert spherical panorama to rectilinear images
int main(int argc, char **argv)
{
  CmdLine cmd;

  std::string
    s_directory_in,
    s_directory_out;
  int
    image_resolution = 1200,
    nb_split = 5;

  // required
  cmd.add( make_option('i', s_directory_in, "input_dir") );
  cmd.add( make_option('o', s_directory_out, "output_dir") );
  // Optional
  cmd.add( make_option('r', image_resolution, "image_resolution") );
  cmd.add( make_option('n', nb_split, "nb_split") );
  cmd.add( make_switch('D', "demo_mode") );

  try {
    if (argc == 1) throw std::string("Invalid command line parameter.");
    cmd.process(argc, argv);
  } catch (const std::string& s) {
    std::cerr << "Usage: " << argv[0] << '\n'
    << "[-i|--input_dir] the path where the spherical panoramic images are saved \n"
    << "[-o|--output_dir] the path where output rectilinear image will be saved \n"
    << " OPTIONAL:\n"
    << "[-r|--image_resolution] the rectilinear image size (default:" << image_resolution << ") \n"
    << "[-n|--nb_split] the number of rectilinear image along the X axis (default:" << nb_split << ") \n"
    << "[-D|--demo_mode] switch parameter, export a SVG file that simulate asked rectilinear\n"
    << "  frustum configuration on the spherical image.\n"
    << std::endl;
  }

  // Input parameter checking

  if (image_resolution < 0)
  {
    std::cerr << "image_resolution must be larger than 0" << std::endl;
    return EXIT_FAILURE;
  }
  if (nb_split < 0)
  {
    std::cerr << "nb_split must be larger than 0" << std::endl;
    return EXIT_FAILURE;
  }
  if (s_directory_in.empty() || s_directory_out.empty())
  {
    std::cerr << "input_dir and output_dir option must not be empty" << std::endl;
    return EXIT_FAILURE;
  }

  if (!stlplus::is_folder(s_directory_out))
  {
    if (!stlplus::folder_create(s_directory_out))
    {
      std::cerr << "Cannot create the output_dir directory" << std::endl;
      return EXIT_FAILURE;
    }
  }

  // List images from the input directory
  const std::vector<std::string> vec_filenames
    = stlplus::folder_wildcard(s_directory_in, "*.jpg", false, true);

  if (vec_filenames.empty())
  {
    std::cerr << "Did not find any jpg image in the provided input_dir" << std::endl;
    return EXIT_FAILURE;
  }

  using namespace openMVG;

  //-----------------
  //-- Create N rectilinear cameras
  //     (according the number of asked split along the X axis)
  //-- For each camera
  //   -- Forward mapping
  //   -- Save resulting images to disk
  //-----------------

  //-- Simulate a camera with many rotations along the Y axis
  const int pinhole_width = image_resolution, pinhole_height = image_resolution;
  const double focal = focalFromPinholeHeight(pinhole_height, openMVG::D2R(120.0/2.0));
  const openMVG::cameras::Pinhole_Intrinsic pinhole_camera(
    //w, h, focal, ppx, ppy
    pinhole_width, pinhole_height, focal, pinhole_width/2., pinhole_height/2.);

  const double alpha = (M_PI * 2.0) / static_cast<double>(nb_split); // 360 / split_count
  std::vector<Mat3> camera_rotations;
  for (int i = 0; i < nb_split; ++i)
  {
    camera_rotations.emplace_back(RotationAroundY(alpha * i));
  }

  if (cmd.used('D')) // Demo mode:
  {
    // Create a spherical camera:
    const int pano_width = 4096, pano_height = pano_width / 2;
    const openMVG::cameras::Intrinsic_Spherical sphere_camera(pano_width, pano_height);

    svgDrawer svgStream(pano_width, pano_height);
    svgStream.drawLine(0, 0, pano_width, pano_height, svgStyle());
    svgStream.drawLine(pano_width, 0, 0, pano_height, svgStyle());

    //--> For each cam, reproject the image borders onto the panoramic image

    for (const Mat3 & cam_rotation : camera_rotations)
    {
      // Draw the shot border with the givenStep:
      const int step = 10;
      // Store the location of the pinhole bearing vector projection in the spherical image
      Vec2 sphere_proj;

      // Vertical rectilinear image border:
      for (double j = 0; j <= image_resolution; j += image_resolution/(double)step)
      {
        // Project the pinhole bearing vector to the sphere
        sphere_proj = sphere_camera.project(cam_rotation * pinhole_camera(Vec2(0., j)));
        svgStream.drawCircle(sphere_proj.x(), sphere_proj.y(), 4, svgStyle().fill("green"));

        sphere_proj = sphere_camera.project(cam_rotation * pinhole_camera(Vec2(image_resolution, j)));
        svgStream.drawCircle(sphere_proj.x(), sphere_proj.y(), 4, svgStyle().fill("green"));
      }
      // Horizontal rectilinear image border:
      for (double j = 0; j <= image_resolution; j += image_resolution/(double)step)
      {
        sphere_proj = sphere_camera.project(cam_rotation * pinhole_camera(Vec2(j, 0.)));
        svgStream.drawCircle(sphere_proj.x(), sphere_proj.y(), 4, svgStyle().fill("yellow"));

        sphere_proj = sphere_camera.project(cam_rotation * pinhole_camera(Vec2(j, image_resolution)));
        svgStream.drawCircle(sphere_proj.x(), sphere_proj.y(), 4, svgStyle().fill("yellow"));
      }
    }

    std::ofstream svgFile( stlplus::create_filespec(s_directory_out, "test.svg" ));
    svgFile << svgStream.closeSvgFile().str();

    return EXIT_SUCCESS;
  }

  //-- For each input image extract multiple pinhole images
  for (const std::string & filename_it : vec_filenames)
  {
    image::Image<image::RGBColor> spherical_image;
    if (!ReadImage(stlplus::create_filespec(s_directory_in, filename_it).c_str(), &spherical_image))
    {
      std::cerr << "Cannot read the image: " << stlplus::create_filespec(s_directory_in, filename_it) << std::endl;
      continue;
    }

    const openMVG::cameras::Intrinsic_Spherical sphere_camera(spherical_image.Width(), spherical_image.Height());

    const image::Sampler2d<image::SamplerLinear> sampler;
    image::Image<image::RGBColor> sampled_image(image_resolution, image_resolution, image::BLACK);

    size_t index = 0;
    for (const Mat3 & cam_rotation : camera_rotations)
    {
      sampled_image.fill(image::BLACK);

      // Backward mapping:
      // - Find for each pixels of the pinhole image where it comes from the panoramic image
      for (int j = 0; j < sampled_image.Height(); ++j)
      {
        for (int i = 0; i < sampled_image.Width(); ++i)
        {
          const Vec2 sphere_proj = sphere_camera.project(cam_rotation * pinhole_camera(Vec2(i, j)));
          sampled_image(j, i) = sampler(spherical_image, sphere_proj.y(), sphere_proj.x());
        }
      }
      //-- save image
      const std::string basename = stlplus::basename_part(filename_it);

      std::cout << basename << " cam index: " << index << std::endl;

      std::ostringstream os;
      os << s_directory_out << "/" << basename << "_" << index << ".jpg";
      WriteImage(os.str().c_str(), sampled_image);

      ++index;
    }
  }

  std::ofstream fileFocalOut(stlplus::create_filespec(s_directory_out, "focal.txt"));
  fileFocalOut << focal;
  fileFocalOut.close();

  return EXIT_SUCCESS;
}
<commit_msg>[samples] Add a fov option to image_spherical_to_pinholes/main_pano_converter.cpp #1593<commit_after>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.

// Copyright (c) 2016 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/cameras/Camera_Spherical.hpp"
#include "openMVG/cameras/Camera_Pinhole.hpp"

#include "openMVG/image/image_io.hpp"
#include "openMVG/image/sample.hpp"

#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/vectorGraphics/svgDrawer.hpp"

#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

using namespace std;
using namespace svg;

/// Compute a rectilinear camera focal from a given angular desired FoV
double focalFromPinholeHeight
(
  int h,
  double thetaMax = openMVG::D2R(60) // Camera FoV
)
{
  float f = 1.f;
  while ( thetaMax < atan2( h / (2 * f) , 1))
  {
    ++f;
  }
  return f;
}

// Convert spherical panorama to rectilinear images
int main(int argc, char **argv)
{
  CmdLine cmd;

  std::string
    s_directory_in,
    s_directory_out;
  int
    image_resolution = 1024,
    nb_split = 5;
  float fov = 60.0;

  // required
  cmd.add( make_option('i', s_directory_in, "input_dir") );
  cmd.add( make_option('o', s_directory_out, "output_dir") );
  // Optional
  cmd.add( make_option('r', image_resolution, "image_resolution") );
  cmd.add( make_option('n', nb_split, "nb_split") );
  cmd.add( make_option('f', fov, "fov") );
  cmd.add( make_switch('D', "demo_mode") );

  try {
    if (argc == 1) throw std::string("Invalid command line parameter.");
    cmd.process(argc, argv);
  } catch (const std::string& s) {
    std::cerr << "Usage: " << argv[0] << '\n'
    << "[-i|--input_dir] the path where the spherical panoramic images are saved \n"
    << "[-o|--output_dir] the path where output rectilinear image will be saved \n"
    << " OPTIONAL:\n"
    << "[-r|--image_resolution] the rectilinear image size (default:" << image_resolution << ") \n"
    << "[-n|--nb_split] the number of rectilinear image along the X axis (default:" << nb_split << ") \n"
    << "[-f|--fov] the rectilinear camera FoV in degrees (default:" << fov << ") \n"
    << "[-D|--demo_mode] switch parameter, export a SVG file that simulate asked rectilinear\n"
    << "  frustum configuration on the spherical image.\n"
    << std::endl;
  }

  // Input parameter checking

  if (image_resolution < 0)
  {
    std::cerr << "image_resolution must be larger than 0" << std::endl;
    return EXIT_FAILURE;
  }
  if (nb_split < 0)
  {
    std::cerr << "nb_split must be larger than 0" << std::endl;
    return EXIT_FAILURE;
  }
  if (s_directory_in.empty() || s_directory_out.empty())
  {
    std::cerr << "input_dir and output_dir option must not be empty" << std::endl;
    return EXIT_FAILURE;
  }

  if (!stlplus::is_folder(s_directory_out))
  {
    if (!stlplus::folder_create(s_directory_out))
    {
      std::cerr << "Cannot create the output_dir directory" << std::endl;
      return EXIT_FAILURE;
    }
  }

  // List images from the input directory
  const std::vector<std::string> vec_filenames
    = stlplus::folder_wildcard(s_directory_in, "*.jpg", false, true);

  if (vec_filenames.empty())
  {
    std::cerr << "Did not find any jpg image in the provided input_dir" << std::endl;
    return EXIT_FAILURE;
  }

  using namespace openMVG;

  //-----------------
  //-- Create N rectilinear cameras
  //     (according the number of asked split along the X axis)
  //-- For each camera
  //   -- Forward mapping
  //   -- Save resulting images to disk
  //-----------------

  //-- Simulate a camera with many rotations along the Y axis
  const int pinhole_width = image_resolution, pinhole_height = image_resolution;
  const double focal = focalFromPinholeHeight(pinhole_height, openMVG::D2R(fov));
  const openMVG::cameras::Pinhole_Intrinsic pinhole_camera(
    //w, h, focal, ppx, ppy
    pinhole_width, pinhole_height, focal, pinhole_width/2., pinhole_height/2.);

  const double alpha = (M_PI * 2.0) / static_cast<double>(nb_split); // 360 / split_count
  std::vector<Mat3> camera_rotations;
  for (int i = 0; i < nb_split; ++i)
  {
    camera_rotations.emplace_back(RotationAroundY(alpha * i));
  }

  if (cmd.used('D')) // Demo mode:
  {
    // Create a spherical camera:
    const int pano_width = 4096, pano_height = pano_width / 2;
    const openMVG::cameras::Intrinsic_Spherical sphere_camera(pano_width, pano_height);

    svgDrawer svgStream(pano_width, pano_height);
    svgStream.drawLine(0, 0, pano_width, pano_height, svgStyle());
    svgStream.drawLine(pano_width, 0, 0, pano_height, svgStyle());

    //--> For each cam, reproject the image borders onto the panoramic image

    for (const Mat3 & cam_rotation : camera_rotations)
    {
      // Draw the shot border with the givenStep:
      const int step = 10;
      // Store the location of the pinhole bearing vector projection in the spherical image
      Vec2 sphere_proj;

      // Vertical rectilinear image border:
      for (double j = 0; j <= image_resolution; j += image_resolution/(double)step)
      {
        // Project the pinhole bearing vector to the sphere
        sphere_proj = sphere_camera.project(cam_rotation * pinhole_camera(Vec2(0., j)));
        svgStream.drawCircle(sphere_proj.x(), sphere_proj.y(), 4, svgStyle().fill("green"));

        sphere_proj = sphere_camera.project(cam_rotation * pinhole_camera(Vec2(image_resolution, j)));
        svgStream.drawCircle(sphere_proj.x(), sphere_proj.y(), 4, svgStyle().fill("green"));
      }
      // Horizontal rectilinear image border:
      for (double j = 0; j <= image_resolution; j += image_resolution/(double)step)
      {
        sphere_proj = sphere_camera.project(cam_rotation * pinhole_camera(Vec2(j, 0.)));
        svgStream.drawCircle(sphere_proj.x(), sphere_proj.y(), 4, svgStyle().fill("yellow"));

        sphere_proj = sphere_camera.project(cam_rotation * pinhole_camera(Vec2(j, image_resolution)));
        svgStream.drawCircle(sphere_proj.x(), sphere_proj.y(), 4, svgStyle().fill("yellow"));
      }
    }

    std::ofstream svgFile( stlplus::create_filespec(s_directory_out, "test.svg" ));
    svgFile << svgStream.closeSvgFile().str();

    return EXIT_SUCCESS;
  }

  //-- For each input image extract multiple pinhole images
  for (const std::string & filename_it : vec_filenames)
  {
    image::Image<image::RGBColor> spherical_image;
    if (!ReadImage(stlplus::create_filespec(s_directory_in, filename_it).c_str(), &spherical_image))
    {
      std::cerr << "Cannot read the image: " << stlplus::create_filespec(s_directory_in, filename_it) << std::endl;
      continue;
    }

    const openMVG::cameras::Intrinsic_Spherical sphere_camera(spherical_image.Width(), spherical_image.Height());

    const image::Sampler2d<image::SamplerLinear> sampler;
    //const image::Sampler2d<image::SamplerNearest> sampler;
    image::Image<image::RGBColor> sampled_image(image_resolution, image_resolution, image::BLACK);

    size_t index = 0;
    for (const Mat3 & cam_rotation : camera_rotations)
    {
      sampled_image.fill(image::BLACK);

      // Backward mapping:
      // - Find for each pixels of the pinhole image where it comes from the panoramic image
      for (int j = 0; j < sampled_image.Height(); ++j)
      {
        for (int i = 0; i < sampled_image.Width(); ++i)
        {
          Vec2 sphere_proj = sphere_camera.project(cam_rotation * pinhole_camera(Vec2(i, j)));
          if (spherical_image.Width() - sphere_proj.x() < 2)
          {
            sphere_proj.x() = - int(sphere_proj.x() - spherical_image.Width());
            sampled_image(j, i) = sampler(spherical_image, sphere_proj.y(), sphere_proj.x());
          }
          else
            sampled_image(j, i) = sampler(spherical_image, sphere_proj.y(), sphere_proj.x());
        }
      }
      //-- save image
      const std::string basename = stlplus::basename_part(filename_it);

      std::cout << basename << " cam index: " << index << std::endl;

      std::ostringstream os;
      os << s_directory_out << "/" << basename << "_" << index << ".jpg";
      WriteImage(os.str().c_str(), sampled_image);

      ++index;
    }
  }

  std::ofstream fileFocalOut(stlplus::create_filespec(s_directory_out, "focal.txt"));
  fileFocalOut << focal;
  fileFocalOut.close();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: score.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:30:10 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SCORE_HXX
#define _SCORE_HXX

#ifndef _SV_WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif

class ScoreWindow : public Window
{
    private:
        long            nHero;
        USHORT          nRockets;
        USHORT          nLives;
        long            nScore;
        long            nLevel;
        ResMgr*         pRes;

        BOOL            bPaintBack;

    public:
                        ScoreWindow(Window* pParent, WinBits bits,ResMgr* pRes);
                        ~ScoreWindow();
        virtual void    Paint(const Rectangle& rRect);
        void            SetHero(long nName);
        void            SetRockets(USHORT nWert);
        void            SetLives(USHORT nWert);
        void            SetScore(long nWert);
        void            SetLevel(long nWert);

        void            Show();
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.326); FILE MERGED 2005/09/05 15:13:35 rt 1.1.1.1.326.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: score.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 03:08:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SCORE_HXX
#define _SCORE_HXX

#ifndef _SV_WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif

class ScoreWindow : public Window
{
    private:
        long            nHero;
        USHORT          nRockets;
        USHORT          nLives;
        long            nScore;
        long            nLevel;
        ResMgr*         pRes;

        BOOL            bPaintBack;

    public:
                        ScoreWindow(Window* pParent, WinBits bits,ResMgr* pRes);
                        ~ScoreWindow();
        virtual void    Paint(const Rectangle& rRect);
        void            SetHero(long nName);
        void            SetRockets(USHORT nWert);
        void            SetLives(USHORT nWert);
        void            SetScore(long nWert);
        void            SetLevel(long nWert);

        void            Show();
};

#endif
<|endoftext|>


<commit_before>#include "sdlwrap.hpp"

namespace rs {
	// ----- Mutex -----
	Mutex::Mutex(): _mutex(SDL_CreateMutex()) {}
	Mutex::Mutex(Mutex&& m): _mutex(m._mutex) {
		m._mutex = nullptr;
	}
	Mutex::~Mutex() {
		if(_mutex)
			SDLEC_D(Warn, SDL_DestroyMutex, _mutex);
	}
	bool Mutex::lock() {
		return SDLEC_D(Trap, SDL_LockMutex, _mutex) == 0;
	}
	bool Mutex::try_lock() {
		// 単に他がロックしている時もTryLockが失敗するのでSDL_GetErrorによるエラーチェックはしない
		auto res = SDL_TryLockMutex(_mutex);
		// TryLockが失敗した時に後のエラーチェックに響くため、ここでリセット
		SDL_ClearError();
		return res == 0;
	}
	void Mutex::unlock() {
		SDLEC_D(Warn, SDL_UnlockMutex, _mutex);
	}
	SDL_mutex* Mutex::getMutex() {
		return _mutex;
	}

	// ----- UniLock -----
	UniLock::UniLock(Mutex& m):
		_mutex(&m), _bLocked(true)
	{
		m.lock();
	}
	UniLock::UniLock(Mutex& m, DeferLock_t):
		_mutex(&m), _bLocked(false)
	{}
	UniLock::UniLock(Mutex& m, AdoptLock_t):
		_mutex(&m), _bLocked(true)
	{}
	UniLock::UniLock(Mutex& m, TryLock_t):
		_mutex(&m), _bLocked(m.try_lock())
	{}
	UniLock::~UniLock() {
		unlock();
	}
	UniLock::UniLock(UniLock&& u): _mutex(u._mutex), _bLocked(u._bLocked) {
		u._mutex = nullptr;
		u._bLocked = false;
	}
	void UniLock::lock() {
		if(!_bLocked) {
			_mutex->lock();
			_bLocked = true;
		}
	}
	bool UniLock::tryLock() {
		if(!_bLocked)
			return _bLocked = _mutex->try_lock();
		return true;
	}
	void UniLock::unlock() {
		if(_bLocked) {
			_mutex->unlock();
			_bLocked = false;
		}
	}
	bool UniLock::isLocked() const {
		return _bLocked;
	}
	SDL_mutex* UniLock::getMutex() {
		if(_mutex)
			return _mutex->getMutex();
		return nullptr;
	}
	UniLock::operator bool() const {
		return isLocked();
	}

	// ----- CondV -----
	CondV::CondV(): _cond(SDL_CreateCond()) {}
	CondV::~CondV() {
		SDL_DestroyCond(_cond);
	}
	void CondV::wait(UniLock& u) {
		SDLEC_D(Trap, SDL_CondWait, _cond, u.getMutex());
	}
	bool CondV::wait_for(UniLock& u, uint32_t msec) {
		return SDLEC_D(Trap, SDL_CondWaitTimeout, _cond, u.getMutex(), msec) == 0;
	}
	void CondV::signal() {
		SDLEC_D(Trap, SDL_CondSignal, _cond);
	}
	void CondV::signal_all() {
		SDLEC_D(Trap, SDL_CondBroadcast, _cond);
	}
}
<commit_msg>SDL_LockMutexがエラーを返してもブレークせずエラーメッセージを出力するのみにした<commit_after>#include "sdlwrap.hpp"

namespace rs {
	// ----- Mutex -----
	Mutex::Mutex(): _mutex(SDL_CreateMutex()) {}
	Mutex::Mutex(Mutex&& m): _mutex(m._mutex) {
		m._mutex = nullptr;
	}
	Mutex::~Mutex() {
		if(_mutex)
			SDLEC_D(Warn, SDL_DestroyMutex, _mutex);
	}
	bool Mutex::lock() {
		return SDLEC_D(Warn, SDL_LockMutex, _mutex) == 0;
	}
	bool Mutex::try_lock() {
		// 単に他がロックしている時もTryLockが失敗するのでSDL_GetErrorによるエラーチェックはしない
		auto res = SDL_TryLockMutex(_mutex);
		// TryLockが失敗した時に後のエラーチェックに響くため、ここでリセット
		SDL_ClearError();
		return res == 0;
	}
	void Mutex::unlock() {
		SDLEC_D(Warn, SDL_UnlockMutex, _mutex);
	}
	SDL_mutex* Mutex::getMutex() {
		return _mutex;
	}

	// ----- UniLock -----
	UniLock::UniLock(Mutex& m):
		_mutex(&m), _bLocked(true)
	{
		m.lock();
	}
	UniLock::UniLock(Mutex& m, DeferLock_t):
		_mutex(&m), _bLocked(false)
	{}
	UniLock::UniLock(Mutex& m, AdoptLock_t):
		_mutex(&m), _bLocked(true)
	{}
	UniLock::UniLock(Mutex& m, TryLock_t):
		_mutex(&m), _bLocked(m.try_lock())
	{}
	UniLock::~UniLock() {
		unlock();
	}
	UniLock::UniLock(UniLock&& u): _mutex(u._mutex), _bLocked(u._bLocked) {
		u._mutex = nullptr;
		u._bLocked = false;
	}
	void UniLock::lock() {
		if(!_bLocked) {
			_mutex->lock();
			_bLocked = true;
		}
	}
	bool UniLock::tryLock() {
		if(!_bLocked)
			return _bLocked = _mutex->try_lock();
		return true;
	}
	void UniLock::unlock() {
		if(_bLocked) {
			_mutex->unlock();
			_bLocked = false;
		}
	}
	bool UniLock::isLocked() const {
		return _bLocked;
	}
	SDL_mutex* UniLock::getMutex() {
		if(_mutex)
			return _mutex->getMutex();
		return nullptr;
	}
	UniLock::operator bool() const {
		return isLocked();
	}

	// ----- CondV -----
	CondV::CondV(): _cond(SDL_CreateCond()) {}
	CondV::~CondV() {
		SDL_DestroyCond(_cond);
	}
	void CondV::wait(UniLock& u) {
		SDLEC_D(Trap, SDL_CondWait, _cond, u.getMutex());
	}
	bool CondV::wait_for(UniLock& u, uint32_t msec) {
		return SDLEC_D(Trap, SDL_CondWaitTimeout, _cond, u.getMutex(), msec) == 0;
	}
	void CondV::signal() {
		SDLEC_D(Trap, SDL_CondSignal, _cond);
	}
	void CondV::signal_all() {
		SDLEC_D(Trap, SDL_CondBroadcast, _cond);
	}
}
<|endoftext|>


<commit_before>/*
 FILNAMN: 		room.cc
 PROGRAMMERARE:	hanel742, eriek984, jened502, tobgr602, niker917, davha227
 SKAPAD DATUM:	2013-11-14
 BESKRIVNING:
 */

#include "room.h"
#include <QDir>
#include <QString>
#include <QDebug>

using namespace std;

// ----------------------------------
// Constructor
Room::Room(string inName,Master* master, Master* scrap){
    masterPointer = master;
    name = inName;
}

Room::Room(string inName,Master* master) {
    masterPointer = master;
    name = inName;
    this->setFilePath();
    this->readAllFromFile();
}

// ----------------------------------------
// Help functions

void ifRoomRemove(Room* inRoom) {
    User* userTemp = dynamic_cast<User*>(inRoom);

    if (userTemp == nullptr) {
        inRoom->masterPointer->removeRoom(inRoom->getName());
    }
}

void throwUp(Room* inRoom) {
    inRoom->chooseRoom(inRoom->parentRoom->parentRoom);
}

// ----------------------------------------
// Destructor

Room::~Room() {
    for_each(rooms.begin(), rooms.end(), ifRoomRemove);

    if ( parentRoom == nullptr) {
        rooms.clear();
    }
    else {

        parentRoom->removeRoom(this);

        for_each(rooms.begin(), rooms.end(), throwUp);
        parentRoom = nullptr;
    }

    masterPointer = nullptr;

}

// ----------------------------------------

unsigned int Room::getPosOfRoom(string name) const{
    for( unsigned int i = 0 ; i < rooms.size() ; i++) {
        if(rooms.at(i)->getName() == name){
            return i;
        }
    }
    throw logic_error("No such room in Rooms");
    return 0;
}

// ----------------------------------------
// Automatically called from child when child room is destroyed
void Room::removeRoom(Room* inRoom) {
    unsigned int pos = getPosOfRoom(inRoom->getName());
    rooms.at(pos) = nullptr;
    rooms.erase(rooms.begin() + pos);
}

// ----------------------------------

void Room::sendMessage(Message inMessage) {
    string to = inMessage.getTo();
    string from = inMessage.getFrom();

    try {
        getRoom(to)->receiveMessage(inMessage);
        getRoom(from)->receiveMessage(inMessage);
    } catch (...) {
        string temp = "No user named ";
        temp += to;
        temp += " in this room!";
        Message errorMessage(temp,name,from);
        getRoom(from)->receiveMessage(errorMessage);
    }

}

// ----------------------------------

void Room::listRooms(){
    for (unsigned int it = 0; it < rooms.size() ; it++){
        User* userTemp = dynamic_cast<User*>(rooms.at(it));
        if(userTemp == nullptr ){
            cout << rooms.at(it)->getName() << endl;
        }
    }
    return;
}

// ----------------------------------

void Room::listUsers(){
    for (unsigned int it = 0; it < rooms.size() ; it++){
        User* userTemp = dynamic_cast<User*>(rooms.at(it));
        if( userTemp == nullptr ){
            continue;
        }
        else{
            cout << rooms.at(it)->getName() << endl;
        }
    }
    return;
}

void Room::receiveMessage(Message inMessage) {
    string to = inMessage.getTo();
    if(to == name){
        log.push_back(inMessage);

        sendMessageAll(inMessage);
        saveToFile(inMessage);
    }
    else{
        sendMessage(inMessage);
    }
}

// ----------------------------------

void Room::sendMessageAll(Message inMessage) {

    for (unsigned int i = 0; i < rooms.size(); i++) {
        User* userTemp = dynamic_cast<User*>(rooms.at(i));
        if ( userTemp == nullptr ) {
            continue;
        }
        rooms.at(i)->receiveMessage(inMessage);
    }
}

// ----------------------------------

void Room::addRoom(Room* inRoom) {
    this->rooms.push_back(inRoom);
    inRoom->parentRoom = this;
}

// ----------------------------------

void Room::saveToFile(Message inMessage) {
    setFilePath();

    ofstream logfile;
    logfile.open (filepath, std::ios_base::app);

    logfile << inMessage.getServerTime() << endl << inMessage.getFrom() << endl;
    logfile << inMessage.getTo() << endl << inMessage.getMessage() << endl;

    logfile.close();
}
//-----------------------------------

void Room::setFilePath() {

    QDir dir = QDir::homePath();
    QString qAbsolutePath;
    string absolutePath;
    qAbsolutePath = dir.absolutePath();
    absolutePath = qAbsolutePath.toStdString();
    string today;
    today = absolutePath + "/ChattYlogs/" + name + currentDateTime().substr(0,10) + ".txt";

    if(not(filepath.empty()) && filepath != today )
    {
        log.clear();
        date = today;
    }

    if (!dir.cd("ChattYlogs")) {
        dir.mkpath("ChattYlogs");
        filepath = absolutePath + "/ChattYlogs/" + name + currentDateTime().substr(0,10) + ".txt";
    }
    else{
        dir.cd("ChattYlogs"); // for new rooms;
        filepath = absolutePath + "/ChattYlogs/" + name + currentDateTime().substr(0,10) + ".txt";
    }

}

// -----------------------------------
void Room::readAllFromFile() {
    log.clear();
    string line;
    ifstream logfile (filepath);

    if (logfile.is_open())
    {
        while (getline(logfile,line)) {
            string time = line;

            getline (logfile,line);
            string from = line;

            getline (logfile,line);
            string to = line;

            getline (logfile,line);
            string message = line;

            Message tempMessage(message,from,to,time);
            log.push_back(tempMessage);
        }
        logfile.close();
    }
    else {
        cout << "fel vid inläsning" << endl;
    }
}

// ------------------------------------

string Room::getName() {
    return name;
}

// ------------------------------------

void Room::createRoom(std::string inName){
	addRoom(masterPointer->createRoom(inName));
}

// ------------------------------------

Room* Room::getRoom(std::string name){
    for( unsigned int i = 0 ; i < rooms.size() ; i++) {
        if(rooms.at(i)->getName() == name){
            return rooms.at(i);
        }
    }
    throw logic_error("No such room in Rooms");

    return nullptr;
}

// -----------------------------------

Message Room::getMessage(unsigned int i){
    if (log.size() < i){
        throw logic_error{"No message at that position!"};
    }
    return log.at(i);
}

// -----------------------------------

void Room::chooseRoom(Room*) {
    throw logic_error{"You're a retard since you're trying to move a room."};
}

Room* Room::getParentRoom() {
    return parentRoom;
}

// -----------------------------------

vector<string> Room::getStruct() {
    vector<string> structure;

    if ( parentRoom != nullptr ) {
        structure.push_back(parentRoom->getName());
    }

    structure.push_back(name);
    structure.push_back("User");

    for (unsigned int i = 0; i < rooms.size() ; i++) {
        User* userTemp = dynamic_cast<User*>(rooms.at(i));
        if ( userTemp == nullptr ) {
            structure.insert(structure.begin(),rooms.at(i)->getName());
        }
        else {
            structure.push_back(rooms.at(i)->getName());
        }
    }

    return structure;
}

// -------------------------------------

void Room::requestStruct() {
    throw logic_error{"You're a retard since you're trying to do stuff to a room. You naughty naughty boy."};
}

// -----------------------------------
vector<Message> Room::readOldFromFile(unsigned int dayCounter) {
    vector<Message> returnLog;
    string line;

    int i = 0 - dayCounter;

    string oldFilePath = "";

    QDate oldDate;
    oldDate = QDate::currentDate();
    oldDate = oldDate.addDays(i);

    QString oldDateString = oldDate.toString("yyyy-MM-dd");

    QDir dir = QDir::homePath();

    dir.cd("ChattYlogs");
    QString qAbsolutePath = dir.absolutePath();
    string absolutePath = qAbsolutePath.toStdString();

    oldFilePath += absolutePath + "/" + name + oldDateString.toStdString() + ".txt";

    ifstream logfile (oldFilePath);

    if (logfile.is_open())
    {
        while (getline(logfile,line)) {
            string time = line;

            getline (logfile,line);
            string from = line;

            getline (logfile,line);
            string to = line;

            getline (logfile,line);
            string message = line;

            Message tempMessage(message, from, to, time);
            returnLog.push_back(tempMessage);
        }

        logfile.close();
        return returnLog;
    }
    else {
        string tempString;
        tempString += "No chatlogs for date " + oldDateString.toStdString() + " in this room.";

        Message tempMessage(tempString, name, name);
        returnLog.push_back(tempMessage);

        return returnLog;
    }
}

<commit_msg>Error i f you send message to yourself<commit_after>/*
 FILNAMN: 		room.cc
 PROGRAMMERARE:	hanel742, eriek984, jened502, tobgr602, niker917, davha227
 SKAPAD DATUM:	2013-11-14
 BESKRIVNING:
 */

#include "room.h"
#include <QDir>
#include <QString>
#include <QDebug>

using namespace std;

// ----------------------------------
// Constructor
Room::Room(string inName,Master* master, Master* scrap){
    masterPointer = master;
    name = inName;
}

Room::Room(string inName,Master* master) {
    masterPointer = master;
    name = inName;
    this->setFilePath();
    this->readAllFromFile();
}

// ----------------------------------------
// Help functions

void ifRoomRemove(Room* inRoom) {
    User* userTemp = dynamic_cast<User*>(inRoom);

    if (userTemp == nullptr) {
        inRoom->masterPointer->removeRoom(inRoom->getName());
    }
}

void throwUp(Room* inRoom) {
    inRoom->chooseRoom(inRoom->parentRoom->parentRoom);
}

// ----------------------------------------
// Destructor

Room::~Room() {
    for_each(rooms.begin(), rooms.end(), ifRoomRemove);

    if ( parentRoom == nullptr) {
        rooms.clear();
    }
    else {

        parentRoom->removeRoom(this);

        for_each(rooms.begin(), rooms.end(), throwUp);
        parentRoom = nullptr;
    }

    masterPointer = nullptr;

}

// ----------------------------------------

unsigned int Room::getPosOfRoom(string name) const{
    for( unsigned int i = 0 ; i < rooms.size() ; i++) {
        if(rooms.at(i)->getName() == name){
            return i;
        }
    }
    throw logic_error("No such room in Rooms");
    return 0;
}

// ----------------------------------------
// Automatically called from child when child room is destroyed
void Room::removeRoom(Room* inRoom) {
    unsigned int pos = getPosOfRoom(inRoom->getName());
    rooms.at(pos) = nullptr;
    rooms.erase(rooms.begin() + pos);
}

// ----------------------------------

void Room::sendMessage(Message inMessage) {
    string to = inMessage.getTo();
    string from = inMessage.getFrom();

    if (inMessage.getTo() == inMessage.getFrom()) {
        string temp = "Stop whispering in your own ear. Don't you have any friends to talk to?";
        Message errorMessage(temp,name,from);
        getRoom(from)->receiveMessage(errorMessage);
    }
    else {
        try {
            getRoom(to)->receiveMessage(inMessage);
            getRoom(from)->receiveMessage(inMessage);
        } catch (...) {
            string temp = "No user named ";
            temp += to;
            temp += " in this room!";
            Message errorMessage(temp,name,from);
            getRoom(from)->receiveMessage(errorMessage);
        }
    }
}

// ----------------------------------

void Room::listRooms(){
    for (unsigned int it = 0; it < rooms.size() ; it++){
        User* userTemp = dynamic_cast<User*>(rooms.at(it));
        if(userTemp == nullptr ){
            cout << rooms.at(it)->getName() << endl;
        }
    }
    return;
}

// ----------------------------------

void Room::listUsers(){
    for (unsigned int it = 0; it < rooms.size() ; it++){
        User* userTemp = dynamic_cast<User*>(rooms.at(it));
        if( userTemp == nullptr ){
            continue;
        }
        else{
            cout << rooms.at(it)->getName() << endl;
        }
    }
    return;
}

void Room::receiveMessage(Message inMessage) {
    string to = inMessage.getTo();
    if(to == name){
        log.push_back(inMessage);

        sendMessageAll(inMessage);
        saveToFile(inMessage);
    }
    else{
        sendMessage(inMessage);
    }
}

// ----------------------------------

void Room::sendMessageAll(Message inMessage) {

    for (unsigned int i = 0; i < rooms.size(); i++) {
        User* userTemp = dynamic_cast<User*>(rooms.at(i));
        if ( userTemp == nullptr ) {
            continue;
        }
        rooms.at(i)->receiveMessage(inMessage);
    }
}

// ----------------------------------

void Room::addRoom(Room* inRoom) {
    this->rooms.push_back(inRoom);
    inRoom->parentRoom = this;
}

// ----------------------------------

void Room::saveToFile(Message inMessage) {
    setFilePath();

    ofstream logfile;
    logfile.open (filepath, std::ios_base::app);

    logfile << inMessage.getServerTime() << endl << inMessage.getFrom() << endl;
    logfile << inMessage.getTo() << endl << inMessage.getMessage() << endl;

    logfile.close();
}
//-----------------------------------

void Room::setFilePath() {

    QDir dir = QDir::homePath();
    QString qAbsolutePath;
    string absolutePath;
    qAbsolutePath = dir.absolutePath();
    absolutePath = qAbsolutePath.toStdString();
    string today;
    today = absolutePath + "/ChattYlogs/" + name + currentDateTime().substr(0,10) + ".txt";

    if(not(filepath.empty()) && filepath != today )
    {
        log.clear();
        date = today;
    }

    if (!dir.cd("ChattYlogs")) {
        dir.mkpath("ChattYlogs");
        filepath = absolutePath + "/ChattYlogs/" + name + currentDateTime().substr(0,10) + ".txt";
    }
    else{
        dir.cd("ChattYlogs"); // for new rooms;
        filepath = absolutePath + "/ChattYlogs/" + name + currentDateTime().substr(0,10) + ".txt";
    }

}

// -----------------------------------
void Room::readAllFromFile() {
    log.clear();
    string line;
    ifstream logfile (filepath);

    if (logfile.is_open())
    {
        while (getline(logfile,line)) {
            string time = line;

            getline (logfile,line);
            string from = line;

            getline (logfile,line);
            string to = line;

            getline (logfile,line);
            string message = line;

            Message tempMessage(message,from,to,time);
            log.push_back(tempMessage);
        }
        logfile.close();
    }
    else {
        cout << "fel vid inläsning" << endl;
    }
}

// ------------------------------------

string Room::getName() {
    return name;
}

// ------------------------------------

void Room::createRoom(std::string inName){
	addRoom(masterPointer->createRoom(inName));
}

// ------------------------------------

Room* Room::getRoom(std::string name){
    for( unsigned int i = 0 ; i < rooms.size() ; i++) {
        if(rooms.at(i)->getName() == name){
            return rooms.at(i);
        }
    }
    throw logic_error("No such room in Rooms");

    return nullptr;
}

// -----------------------------------

Message Room::getMessage(unsigned int i){
    if (log.size() < i){
        throw logic_error{"No message at that position!"};
    }
    return log.at(i);
}

// -----------------------------------

void Room::chooseRoom(Room*) {
    throw logic_error{"You're a retard since you're trying to move a room."};
}

Room* Room::getParentRoom() {
    return parentRoom;
}

// -----------------------------------

vector<string> Room::getStruct() {
    vector<string> structure;

    if ( parentRoom != nullptr ) {
        structure.push_back(parentRoom->getName());
    }

    structure.push_back(name);
    structure.push_back("User");

    for (unsigned int i = 0; i < rooms.size() ; i++) {
        User* userTemp = dynamic_cast<User*>(rooms.at(i));
        if ( userTemp == nullptr ) {
            structure.insert(structure.begin(),rooms.at(i)->getName());
        }
        else {
            structure.push_back(rooms.at(i)->getName());
        }
    }

    return structure;
}

// -------------------------------------

void Room::requestStruct() {
    throw logic_error{"You're a retard since you're trying to do stuff to a room. You naughty naughty boy."};
}

// -----------------------------------
vector<Message> Room::readOldFromFile(unsigned int dayCounter) {
    vector<Message> returnLog;
    string line;

    int i = 0 - dayCounter;

    string oldFilePath = "";

    QDate oldDate;
    oldDate = QDate::currentDate();
    oldDate = oldDate.addDays(i);

    QString oldDateString = oldDate.toString("yyyy-MM-dd");

    QDir dir = QDir::homePath();

    dir.cd("ChattYlogs");
    QString qAbsolutePath = dir.absolutePath();
    string absolutePath = qAbsolutePath.toStdString();

    oldFilePath += absolutePath + "/" + name + oldDateString.toStdString() + ".txt";

    ifstream logfile (oldFilePath);

    if (logfile.is_open())
    {
        while (getline(logfile,line)) {
            string time = line;

            getline (logfile,line);
            string from = line;

            getline (logfile,line);
            string to = line;

            getline (logfile,line);
            string message = line;

            Message tempMessage(message, from, to, time);
            returnLog.push_back(tempMessage);
        }

        logfile.close();
        return returnLog;
    }
    else {
        string tempString;
        tempString += "No chatlogs for date " + oldDateString.toStdString() + " in this room.";

        Message tempMessage(tempString, name, name);
        returnLog.push_back(tempMessage);

        return returnLog;
    }
}

<|endoftext|>


<commit_before>#ifndef VEXCL_PROFILER_HPP
#define VEXCL_PROFILER_HPP

/*
The MIT License

Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru>

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.
*/

/**
 * \file   profiler.hpp
 * \author Denis Demidov <ddemidov@ksu.ru>
 * \brief  Simple OpenCL/Host profiler.
 */

#ifdef WIN32
#  pragma warning(push)
#  pragma warning(disable : 4267 4290)
#  define NOMINMAX
#endif

#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <memory>
#include <stack>
#include <vector>
#include <cassert>
#include <boost/chrono.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/global_fun.hpp>

#ifndef __CL_ENABLE_EXCEPTIONS
#  define __CL_ENABLE_EXCEPTIONS
#endif

#include <CL/cl.hpp>

namespace vex {

/// Class for gathering and printing OpenCL and Host profiling info.
class profiler {
    private:
        class profile_unit {
            public:
                profile_unit(std::string name) : length(0), hit(0), name(name) {}
                virtual ~profile_unit() {}

                double length;
                size_t hit;
                std::string name;

                boost::chrono::time_point<boost::chrono::high_resolution_clock> start;

                static std::string _name(const std::shared_ptr<profile_unit> &u) {
                    return u->name;
                }

                virtual void tic() {
                    start = boost::chrono::high_resolution_clock::now();
                }

                virtual double toc() {
                    double delta = boost::chrono::duration<double>(
                            boost::chrono::high_resolution_clock::now() - start).count();

                    length += delta;
                    hit++;

                    return delta;
                }

                boost::multi_index_container<
                    std::shared_ptr<profile_unit>,
                    boost::multi_index::indexed_by<
                        boost::multi_index::sequenced<>,
                        boost::multi_index::ordered_unique<boost::multi_index::global_fun<
                                const std::shared_ptr<profile_unit> &, std::string, _name>>
                    >
                > children;

                double children_time() const {
                    double tm = 0;

                    for(auto c = children.begin(); c != children.end(); c++)
                        tm += (*c)->length;

                    return tm;
                }

                uint max_line_width(uint level) const {
                    uint w = name.size() + level;

                    for(auto c = children.begin(); c != children.end(); c++)
                        w = std::max(w, (*c)->max_line_width(level + shift_width));

                    return w;
                }

                void print(std::ostream &out,
                        uint level, double total, uint width) const
                {
                    using namespace std;
                    out << "[" << setw(level) << "";
                    print_line(out, name, length, 100 * length / total, width - level);

                    if (!children.empty()) {
                        double sec = length - children_time();
                        double perc = 100 * sec / total;

                        if (perc > 1e-1) {
                            out << "[" << setw(level + 1) << "";
                            print_line(out, "self", sec, perc, width - level - 1);
                        }
                    }

                    for(auto c = children.begin(); c != children.end(); c++)
                        (*c)->print(out, level + shift_width, total, width);
                }

                void print_line(std::ostream &out, const std::string &name,
                        double time, double perc, uint width) const
                {
                    using namespace std;
                    out << name << ":";
                    out << setw(width - name.size()) << "";
                    out << setiosflags(ios::fixed);
                    out << setw(10) << setprecision(3) << time << " sec.";
                    out << "] (" << setprecision(2) << setw(6) << perc << "%)";
                    if(hit > 1) out << " (" << hit << "x)";
                    out << endl;
                }
            private:
                static const uint shift_width = 2U;
        };

        class cl_profile_unit : public profile_unit {
            public:
                cl_profile_unit(const std::string &name, const std::vector<cl::CommandQueue> &queue)
                    : profile_unit(name), queue(queue) {}

                void tic() {
                    for(auto q = queue.begin(); q != queue.end(); ++q)
                        q->finish();

                    profile_unit::tic();
                }

                double toc() {
                    for(auto q = queue.begin(); q != queue.end(); ++q)
                        q->finish();

                    return profile_unit::toc();
                }
            private:
                const std::vector<cl::CommandQueue> &queue;
                boost::chrono::time_point<boost::chrono::high_resolution_clock> start;
        };

    public:
        /// Constructor.
        /**
         * \param queue vector of command queues.
         * \param name  Optional name to be used when profiling info is printed.
         */
        profiler(
                const std::vector<cl::CommandQueue> &queue = std::vector<cl::CommandQueue>(),
                const std::string &name = "Profile"
                ) : queue(queue)
        {
            auto root = std::shared_ptr<profile_unit>(new profile_unit(name));
            root->tic();
            stack.push_back(root);
        }

    private:
        void tic(profile_unit *u) {
            assert(!stack.empty());
            auto top = stack.back();
            auto new_unit = std::shared_ptr<profile_unit>(u);
            auto unit = *top->children.push_back(new_unit).first;
            unit->tic();
            stack.push_back(unit);
        }

    public:
        /// Starts a CPU timer.
        /**
         * Also pushes named interval to the top of the profiler hierarchy.
         * \param name name of the measured interval.
         */
        void tic_cpu(const std::string &name) {
            tic(new profile_unit(name));
        }

        /// Enqueues a marker into each of the provided queues.
        /**
         * Also pushes named interval to the top of the profiler hierarchy.
         * \param name name of the measured interval.
         */
        void tic_cl(const std::string &name) {
            tic(new cl_profile_unit(name, queue));
        }

        /// Returns time since last tic.
        /**
         * Also removes interval from the top of the profiler hierarchy.
         */
        double toc(const std::string &) {
            assert(stack.size() > 1);

            double delta = stack.back()->toc();
            stack.pop_back();

            return delta;
        }

        /// Outputs profile to the provided stream.
        void print(std::ostream &out) {
            if(stack.size() != 1)
                out << "Warning! Profile is incomplete." << std::endl;

            auto root = stack.front();
            double length = root->toc();
            out << std::endl;
            root->print(out, 0, length, root->max_line_width(0));
        }

    private:
        const std::vector<cl::CommandQueue> &queue;
        std::deque<std::shared_ptr<profile_unit>> stack;
};

} // namespace vex

inline std::ostream& operator<<(std::ostream &os, vex::profiler &prof) {
    prof.print(os);
    return os;
}

#ifdef WIN32
#  pragma warning(pop)
#endif

// vim: et
#endif
<commit_msg>Removed unused field from cl_profile_unit<commit_after>#ifndef VEXCL_PROFILER_HPP
#define VEXCL_PROFILER_HPP

/*
The MIT License

Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru>

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.
*/

/**
 * \file   profiler.hpp
 * \author Denis Demidov <ddemidov@ksu.ru>
 * \brief  Simple OpenCL/Host profiler.
 */

#ifdef WIN32
#  pragma warning(push)
#  pragma warning(disable : 4267 4290)
#  define NOMINMAX
#endif

#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <memory>
#include <stack>
#include <vector>
#include <cassert>
#include <boost/chrono.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/global_fun.hpp>

#ifndef __CL_ENABLE_EXCEPTIONS
#  define __CL_ENABLE_EXCEPTIONS
#endif

#include <CL/cl.hpp>

namespace vex {

/// Class for gathering and printing OpenCL and Host profiling info.
class profiler {
    private:
        class profile_unit {
            public:
                profile_unit(std::string name) : length(0), hit(0), name(name) {}
                virtual ~profile_unit() {}

                double length;
                size_t hit;
                std::string name;

                boost::chrono::time_point<boost::chrono::high_resolution_clock> start;

                static std::string _name(const std::shared_ptr<profile_unit> &u) {
                    return u->name;
                }

                virtual void tic() {
                    start = boost::chrono::high_resolution_clock::now();
                }

                virtual double toc() {
                    double delta = boost::chrono::duration<double>(
                            boost::chrono::high_resolution_clock::now() - start).count();

                    length += delta;
                    hit++;

                    return delta;
                }

                boost::multi_index_container<
                    std::shared_ptr<profile_unit>,
                    boost::multi_index::indexed_by<
                        boost::multi_index::sequenced<>,
                        boost::multi_index::ordered_unique<boost::multi_index::global_fun<
                                const std::shared_ptr<profile_unit> &, std::string, _name>>
                    >
                > children;

                double children_time() const {
                    double tm = 0;

                    for(auto c = children.begin(); c != children.end(); c++)
                        tm += (*c)->length;

                    return tm;
                }

                uint max_line_width(uint level) const {
                    uint w = name.size() + level;

                    for(auto c = children.begin(); c != children.end(); c++)
                        w = std::max(w, (*c)->max_line_width(level + shift_width));

                    return w;
                }

                void print(std::ostream &out,
                        uint level, double total, uint width) const
                {
                    using namespace std;
                    out << "[" << setw(level) << "";
                    print_line(out, name, length, 100 * length / total, width - level);

                    if (!children.empty()) {
                        double sec = length - children_time();
                        double perc = 100 * sec / total;

                        if (perc > 1e-1) {
                            out << "[" << setw(level + 1) << "";
                            print_line(out, "self", sec, perc, width - level - 1);
                        }
                    }

                    for(auto c = children.begin(); c != children.end(); c++)
                        (*c)->print(out, level + shift_width, total, width);
                }

                void print_line(std::ostream &out, const std::string &name,
                        double time, double perc, uint width) const
                {
                    using namespace std;
                    out << name << ":";
                    out << setw(width - name.size()) << "";
                    out << setiosflags(ios::fixed);
                    out << setw(10) << setprecision(3) << time << " sec.";
                    out << "] (" << setprecision(2) << setw(6) << perc << "%)";
                    if(hit > 1) out << " (" << hit << "x)";
                    out << endl;
                }
            private:
                static const uint shift_width = 2U;
        };

        class cl_profile_unit : public profile_unit {
            public:
                cl_profile_unit(const std::string &name, const std::vector<cl::CommandQueue> &queue)
                    : profile_unit(name), queue(queue) {}

                void tic() {
                    for(auto q = queue.begin(); q != queue.end(); ++q)
                        q->finish();

                    profile_unit::tic();
                }

                double toc() {
                    for(auto q = queue.begin(); q != queue.end(); ++q)
                        q->finish();

                    return profile_unit::toc();
                }
            private:
                const std::vector<cl::CommandQueue> &queue;
        };

    public:
        /// Constructor.
        /**
         * \param queue vector of command queues.
         * \param name  Optional name to be used when profiling info is printed.
         */
        profiler(
                const std::vector<cl::CommandQueue> &queue = std::vector<cl::CommandQueue>(),
                const std::string &name = "Profile"
                ) : queue(queue)
        {
            auto root = std::shared_ptr<profile_unit>(new profile_unit(name));
            root->tic();
            stack.push_back(root);
        }

    private:
        void tic(profile_unit *u) {
            assert(!stack.empty());
            auto top = stack.back();
            auto new_unit = std::shared_ptr<profile_unit>(u);
            auto unit = *top->children.push_back(new_unit).first;
            unit->tic();
            stack.push_back(unit);
        }

    public:
        /// Starts a CPU timer.
        /**
         * Also pushes named interval to the top of the profiler hierarchy.
         * \param name name of the measured interval.
         */
        void tic_cpu(const std::string &name) {
            tic(new profile_unit(name));
        }

        /// Enqueues a marker into each of the provided queues.
        /**
         * Also pushes named interval to the top of the profiler hierarchy.
         * \param name name of the measured interval.
         */
        void tic_cl(const std::string &name) {
            tic(new cl_profile_unit(name, queue));
        }

        /// Returns time since last tic.
        /**
         * Also removes interval from the top of the profiler hierarchy.
         */
        double toc(const std::string &) {
            assert(stack.size() > 1);

            double delta = stack.back()->toc();
            stack.pop_back();

            return delta;
        }

        /// Outputs profile to the provided stream.
        void print(std::ostream &out) {
            if(stack.size() != 1)
                out << "Warning! Profile is incomplete." << std::endl;

            auto root = stack.front();
            double length = root->toc();
            out << std::endl;
            root->print(out, 0, length, root->max_line_width(0));
        }

    private:
        const std::vector<cl::CommandQueue> &queue;
        std::deque<std::shared_ptr<profile_unit>> stack;
};

} // namespace vex

inline std::ostream& operator<<(std::ostream &os, vex::profiler &prof) {
    prof.print(os);
    return os;
}

#ifdef WIN32
#  pragma warning(pop)
#endif

// vim: et
#endif
<|endoftext|>