repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
Eslam-Abdo/STM32_ARM_drivers | 02-MCAL/10-DMA/DMA_program.c | <reponame>Eslam-Abdo/STM32_ARM_drivers
/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 17 OCT 2021 */
/*********************************************************************************/
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "DMA_private.h"
#include "DMA_config.h"
#include "DMA_interface.h"
#include "GPIO_interface.h"
|
Eslam-Abdo/STM32_ARM_drivers | 02-MCAL/07-UART/UART_config.h | /*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 11 OCT 2020 */
/*********************************************************************************/
#ifndef UART_CONFIG_H
#define UART_CONFIG_H
/************ USART BAUDRATE Option: ***********************/
/* UART1_BAUDRATE_9600 //for 72MHZ on APB2 bus */
/* UART1_BAUDRATE_115200 //for 72MHZ on APB2 bus */
#define BAUDRATE UART1_BAUDRATE_9600
#endif // UART_CONFIG_H
|
Eslam-Abdo/STM32_ARM_drivers | 02-MCAL/08-CAN/CAN_program.c | <reponame>Eslam-Abdo/STM32_ARM_drivers
/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 17 OCT 2020 */
/*********************************************************************************/
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "RCC_interface.h"
#include "NVIC_interface.h"
#include "GPIO_interface.h"
#include "AFIO_interface.h"
#include "CAN_interface.h"
#include "CAN_config.h"
#include "CAN_private.h"
uint32 CAN_ErrorCode = CAN_ERROR_NONE;
/** BoudRate value **/
CAN_BitTimingConfig CAN_bitRateConfig[7];
/*********************** CallBack array of function ***************************/
CAN_Interrupt_Callbacks CAN_TxMailboxCompleteCallback[3] = {&CAN_TxMailbox0CompleteCallback,
&CAN_TxMailbox1CompleteCallback,
&CAN_TxMailbox2CompleteCallback};
CAN_Interrupt_Callbacks CAN_TxMailboxAbortCallback[3] = {&CAN_TxMailbox0AbortCallback,
&CAN_TxMailbox1AbortCallback,
&CAN_TxMailbox2AbortCallback};
void CAN_voidInit(void)
{
/** Enable the CAN interface clock **/
RCC_voidEnableClock(RCC_APB1, APB1_CAN_EN);
/** Configure CAN pins **/
/* Remapping PINS CAN_RX mapped to PB8,
CAN_TX mapped to PB9 */
RCC_voidEnableClock(RCC_APB2, APB2_AFIO_EN);
AFIO_voidRemapPeripheralPins (CAN_REMAP);
/* Enable the clock for the CAN GPIOs */
RCC_voidEnableClock(RCC_APB2, APB2_GPIOB_EN);
GPIO_voidSetPinDirection(GPIOB, PIN8, INPUT_FLOATING); //RX
GPIO_voidSetPinDirection(GPIOB, PIN9, OUTPUT_SPEED_2MHZ_AFPP); //TX
/** exit CAN sleep mode **/
/* CLEAR SLEEP bit (SLEEP) */
CLR_BIT(CAN->MCR,1);
/* wait to exit sleep mode */
while (!(GET_BIT(CAN->MSR,1) == 0));
/** Set CAN Initialization mode **/
/* SET Initialization request BIT (INRQ) */
SET_BIT(CAN->MCR,0);
/* wait to enter in Initialization mode */
while(!(GET_BIT(CAN->MSR,0) == 1));
/** CHECK Transmit FIFO priority **/
#if TransmitFifoPriority == ENABLE
/* by the request order */
SET_BIT(CAN->MCR,2); //TXFP
#else
/* by the identifier of the message */
CLR_BIT(CAN->MCR,2); //TXFP
#endif
/** CHECK Receive FIFO locked mode **/
#if ReceiveFifoLocked == ENABLE
/* Receive FIFO locked against overrun.
Once a receive FIFO is full the next incoming message will be discarded. */
SET_BIT(CAN->MCR,3); //RFLM
#else
/* Receive FIFO not locked on overrun.
Once a receive FIFO is full the next incoming message will overwrite the previous one. */
CLR_BIT(CAN->MCR,3); //RFLM
#endif
/** CHECK automatic retransmission **/
#if AutoRetransmission == ENABLE
CLR_BIT(CAN->MCR,4); //NART
#else
SET_BIT(CAN->MCR,4); //NART
#endif
/** CHECK automatic wakeup mode **/
#if AutoBussOff == ENABLE
SET_BIT(CAN->MCR,5); //AWUM
#else
CLR_BIT(CAN->MCR,5); //AWUM
#endif
/** CHECK automatic bus-off management **/
#if AutoBussOff == ENABLE
SET_BIT(CAN->MCR,6); //ABOM
#else
CLR_BIT(CAN->MCR,6); //ABOM
#endif
/** CHECK Time triggered communication mode **/
#if TimeTriggeredMode == ENABLE
SET_BIT(CAN->MCR,7); //TTCM
#else
CLR_BIT(CAN->MCR,7); //TTCM
#endif
/** Set the bit timing register **/
WRITE_REG(CAN->BTR, (uint32) (MODE |
((CAN_bitRateConfig[BOUDRATE].TS2-1) << 20) |
((CAN_bitRateConfig[BOUDRATE].TS1-1) << 16) |
(CAN_bitRateConfig[BOUDRATE].BRP-1)));
}
void CAN_voidAddTxMsg( CAN_TxHeaderTypeDef *pTxHeader, uint8 Local_u8Data[])
{
uint32 local_u8TransmitMailbox; // which mailbox is empty to set Local_u8Data in it (read CODE bit in TSR register)
uint32 local_u32TSR; //transmit status register
local_u32TSR = READ_REG(CAN->TSR);
/* Check that all the Tx mailboxes are not full */
// while(1)
// {
if ( (GET_BIT(local_u32TSR, 26) != 0x0) || /* TME0 */
(GET_BIT (local_u32TSR,27) != 0x0) || /* TME1 */
(GET_BIT(local_u32TSR,28) != 0x0) ) /* TME2 */
{
/* Select an empty transmit mailbox */
local_u8TransmitMailbox = ((local_u32TSR >> 24) & 0x3); //(read CODE[1:0] bit in TSR register)
/* Check transmit mailbox value */
if (local_u8TransmitMailbox <=2)
{
/* Set up the Id */
if (pTxHeader->IDE == CAN_ID_STD)
{
CAN->TxMailBox[local_u8TransmitMailbox].TIR = ((pTxHeader->StdId << 21) |
pTxHeader->RTR);
}
else
{
CAN->TxMailBox[local_u8TransmitMailbox].TIR = ((pTxHeader->ExtId << 3) |
pTxHeader->IDE | pTxHeader->RTR);
}
/* Set up the DLC */
CAN->TxMailBox[local_u8TransmitMailbox].TDTR = (pTxHeader->DLC);
/* Set up the Transmit Global Time mode */
if (pTxHeader->TransmitGlobalTime == ENABLE)
{
SET_BIT(CAN->TxMailBox[local_u8TransmitMailbox].TDTR, 8);
}
/* Set up the Local_u8Data field */
WRITE_REG(CAN->TxMailBox[local_u8TransmitMailbox].TDHR,
((uint32)Local_u8Data[7] << 24) |
((uint32)Local_u8Data[6] << 16) |
((uint32)Local_u8Data[5] << 8 ) |
((uint32)Local_u8Data[4]));
WRITE_REG(CAN->TxMailBox[local_u8TransmitMailbox].TDLR,
((uint32)Local_u8Data[3] << 24) |
((uint32)Local_u8Data[2] << 16) |
((uint32)Local_u8Data[1] << 8 ) |
((uint32)Local_u8Data[0]));
/* Request transmission */
SET_BIT(CAN->TxMailBox[local_u8TransmitMailbox].TIR, 0);
// while(GET_BIT(CAN->TxMailBox[local_u8TransmitMailbox].TIR, 0) == 1); // clear by hardware when mailbox empty
}
// break;
// }
}
}
void CAN_voidStart(void)
{
/* CLEAR Initialization request BIT (INRQ) */
CLR_BIT(CAN->MCR,0);
/* wait to enter in Initialization mode */
while(!(GET_BIT(CAN->MSR,0) == 0));
}
void CAN_voidGetRxMsg(uint32 local_u8RxFifo, CAN_RxHeaderTypeDef *pRxHeader, uint8 Local_u8Data[])
{
/* Get Identifier extension */
pRxHeader->IDE = GET_BIT(CAN->FIFOMailBox[local_u8RxFifo].RIR,2);
if (pRxHeader->IDE == CAN_ID_STD)
{/* GET the Id */
pRxHeader->StdId = CAN->FIFOMailBox[local_u8RxFifo].RIR >> 21;
}
else
{
pRxHeader->ExtId = CAN->FIFOMailBox[local_u8RxFifo].RIR >> 3;
}
/* GET the RTR */
pRxHeader->RTR = GET_BIT(CAN->FIFOMailBox[local_u8RxFifo].RIR,1);
/* GET the DLC */
pRxHeader->DLC = (CAN->FIFOMailBox[local_u8RxFifo].RDTR & 0xF);
/* GET the (FMI) Filter Match Index */
pRxHeader->FilterMatchIndex = (CAN->FIFOMailBox[local_u8RxFifo].RDTR >> 8) & 0xFF;
/* GET the Time stamp */
pRxHeader->TimeStamp = (CAN->FIFOMailBox[local_u8RxFifo].RDTR >> 16) & 0XFFFF;
/* Get the data */
#if 0
Local_u8Data[0] = (uint8)((CAN->FIFOMailBox[local_u8RxFifo].RDLR ) & 0XFF);
Local_u8Data[1] = (uint8)((CAN->FIFOMailBox[local_u8RxFifo].RDLR >> 8 ) & 0XFF);
Local_u8Data[2] = (uint8)((CAN->FIFOMailBox[local_u8RxFifo].RDLR >> 16) & 0XFF);
Local_u8Data[3] = (uint8)((CAN->FIFOMailBox[local_u8RxFifo].RDLR >> 24) & 0XFF);
Local_u8Data[4] = (uint8)((CAN->FIFOMailBox[local_u8RxFifo].RDHR ) & 0XFF);
Local_u8Data[5] = (uint8)((CAN->FIFOMailBox[local_u8RxFifo].RDHR >> 8 ) & 0XFF);
Local_u8Data[6] = (uint8)((CAN->FIFOMailBox[local_u8RxFifo].RDHR >> 16) & 0XFF);
Local_u8Data[7] = (uint8)((CAN->FIFOMailBox[local_u8RxFifo].RDHR >> 24) & 0XFF);
#else
for(u8 i=0 ; i < 8 ; i++)
{/*clear buff*/
Local_u8Data[i] = 0;
}
for(u8 i=0 ; i < pRxHeader->DLC ; i++)
{
if (i<4)
Local_u8Data[i] = (uint8)((CAN->FIFOMailBox[local_u8RxFifo].RDLR >>(i*8) ) & 0XFF);
else
Local_u8Data[i] = (uint8)((CAN->FIFOMailBox[local_u8RxFifo].RDHR >>((i-4)*8) ) & 0XFF);
}
#endif
/* Release the FIFO */
if (local_u8RxFifo == CAN_RX_FIFO0)
{
/* Release RX FIFO 0 */
SET_BIT(CAN->RF0R, 5);
}
else
{
/* Release RX FIFO 1 */
SET_BIT(CAN->RF1R, 5);
}
}
/** CAN RX Pending **/
uint8 CAN_voidRXPending(uint8 local_u8RxFifo)
{
/* return the Rx FIFO message pending */
if (local_u8RxFifo == CAN_RX_FIFO0) /* Rx element is assigned to Rx FIFO 0 */
{
/* return value of the Rx FIFO 0 */
return (CAN->RF0R & 0X3);
}
else /* Rx element is assigned to Rx FIFO 1 */
{
/* return value of the Rx FIFO 1 */
return (CAN->RF1R & 0X3);
}
}
/** CAN CONFIG filter **/
void CAN_voidConfigFilter( CAN_FilterTypeDef *pFilterConfig)
{
/* Initialization mode for the filter */
SET_BIT(CAN->FMR, 0);
/* Convert filter number into bit position */
uint32 local_u32FilterBitPos = pFilterConfig->FilterBank ;
/* Filter Deactivation */
CLR_BIT(CAN->FA1R, pFilterConfig->FilterBank);
/* Filter Scale */
if (pFilterConfig->FilterScale == CAN_FILTERSCALE_16BIT)
{
/* 16-bit scale for the filter */
CLR_BIT(CAN->FS1R, local_u32FilterBitPos);
/* Filter mapping
* 15-8 7-5 4 3 2-0
* STID[10:3] STID[2:0] RTR IDE EXID[17:15]
* */
/* First 16-bit identifier and First 16-bit mask */
/* Or First 16-bit identifier and Second 16-bit identifier */
CAN->FilterBankRegister[pFilterConfig->FilterBank].FR1 =(
((pFilterConfig->FilterMaskIdLow & 0x0000FFFF) << 16) |
(pFilterConfig->FilterIdLow & 0x0000FFFF) );
/* Second 16-bit identifier and Second 16-bit mask */
/* Or Third 16-bit identifier and Fourth 16-bit identifier */
CAN->FilterBankRegister[pFilterConfig->FilterBank].FR2 =(
((pFilterConfig->FilterMaskIdHigh & 0x0000FFFF) << 16) |
(pFilterConfig->FilterIdHigh & 0x0000FFFF) );
}
else if (pFilterConfig->FilterScale == CAN_FILTERSCALE_32BIT)
{
/* 32-bit scale for the filter */
SET_BIT(CAN->FS1R, local_u32FilterBitPos);
/* Filter mapping
* 31-24 23-21 21-16 15-8 7-3 2 1 0
* STID[10:3] STID[2:0] EXID[17:13] EXID[12:5] EXID[4:0] IDE RTR 0
* */
/* 32-bit identifier or First 32-bit identifier */
CAN->FilterBankRegister[pFilterConfig->FilterBank].FR1 =(
((pFilterConfig->FilterIdHigh & 0x0000FFFF) << 16) |
(pFilterConfig->FilterIdLow & 0x0000FFFF));
/* 32-bit mask or Second 32-bit identifier */
CAN->FilterBankRegister[pFilterConfig->FilterBank].FR2 =(
((pFilterConfig->FilterMaskIdHigh & 0x0000FFFF) << 16) |
(pFilterConfig->FilterMaskIdLow & 0x0000FFFF));
}
/* Filter Mode */
if (pFilterConfig->FilterMode == CAN_FILTERMODE_IDMASK)
{
/* Id/Mask mode for the filter*/
CLR_BIT(CAN->FM1R, local_u32FilterBitPos);
}
else
{
/* Identifier list mode for the filter*/
SET_BIT(CAN->FM1R, local_u32FilterBitPos);
}
/* Filter FIFO assignment */
if (pFilterConfig->FilterFIFOAssignment == CAN_FILTER_FIFO0)
{
/* FIFO 0 assignation for the filter */
CLR_BIT(CAN->FFA1R, local_u32FilterBitPos);
}
else
{
/* FIFO 1 assignation for the filter */
SET_BIT(CAN->FFA1R, local_u32FilterBitPos);
}
/* Filter activation */
if (pFilterConfig->FilterActivation == ENABLE)
{
SET_BIT(CAN->FA1R, local_u32FilterBitPos);
}
/* Leave the initialisation mode for the filter */
CLR_BIT(CAN->FMR, 0);
}
uint32 CAN_voidGetErrorCode(void)
{
return CAN_ErrorCode;
}
/****************************************************************************
*
==============================================================================
##### CAN Interrupt functions #####
==============================================================================
*/
/*********** OPTION OF IRQn:
* CAN_TX_IRQn =>>>> CAN TX Interrupts
* CAN_RX0_IRQn =>>>> CAN RX0 (FIFO_0) Interrupts
* CAN_RX1_IRQn =>>>> CAN RX1 (FIFO_1) Interrupts
* CAN_SCE_IRQn =>>>> CAN SCE (Status Change Error) Interrupts
****************************/
/** Enable NVIC Interrupt **/
void CAN_voidInitInterput(IRQn_Type IRQn)
{ /* init interrput*/
NVIC_voidEnableInterrupt(IRQn);
NVIC_voidSetPendingFlag(IRQn);
}
/** Disanable NVIC Interrupt **/
void CAN_voidDeiniterputInit(IRQn_Type IRQn)
{ /* deinit interrput*/
NVIC_voidDisableInterrupt(IRQn);
NVIC_voidClearPendingFlag(IRQn);
}
void CAN_voidEnableInterrupt(uint32 local_u32ActiveITs)
{
CAN->IER |= local_u32ActiveITs;
}
void CAN_voidDisableInterrupt(uint32 local_u32ActiveITs)
{
CAN->IER &= ~ local_u32ActiveITs;
}
/****************************************************************************
*
==============================================================================
##### CAN Handler functions #####
==============================================================================
*/
/*************************** CAN TX Interrupt Handler *********************/
void CAN_voidTX_Interrupt_Handler(void)
{
CAN_ErrorCode = CAN_ERROR_NONE;
uint32 tsrflags = READ_REG(CAN->TSR);
/* Transmit Mailbox [0:2] management *****************************************/
for (uint8 local_u8TxBitPos = 0 ; local_u8TxBitPos <= 16 ; local_u8TxBitPos += 8 ) // local_u8TxBitPos refer to Position of RQCPx bit in TSR Register
{
if (GET_BIT(tsrflags, (local_u8TxBitPos)) != 0) /* RQCP: Request completed mailbox [0:2] */
{
/* Clear the Transmission Complete flag (and TXOK,ALST,TERR0 bits) */
SET_BIT(CAN->TSR, local_u8TxBitPos); /* RQCP: Request completed mailbox [0:2] */
if (GET_BIT(tsrflags, (local_u8TxBitPos + 1)) != 0) /* TXOK: Transmission OK of mailbox [0:2] */
{
/* Transmission Mailbox complete callback */
/* Call weak (surcharged) callback */
CAN_TxMailboxCompleteCallback[local_u8TxBitPos/8]();
}
else
{
if (GET_BIT(tsrflags, (local_u8TxBitPos + 2)) != 0) /* ALST: Arbitration lost for mailbox [0:2] */
{
/* Update error code */
switch (local_u8TxBitPos/8)
{
case 0 :
CAN_ErrorCode |= CAN_ERROR_TX_ALST0; break;
case 1 :
CAN_ErrorCode |= CAN_ERROR_TX_ALST1; break;
case 2 :
CAN_ErrorCode |= CAN_ERROR_TX_ALST2; break;
}
}
else if (GET_BIT(tsrflags, (local_u8TxBitPos + 3)) != 0) /* TERR: Transmission error of mailbox [0:2] */
{
/* Update error code */
CAN_ErrorCode |= CAN_ERROR_TX_TERR0;
switch (local_u8TxBitPos/8)
{
case 0 :
CAN_ErrorCode |= CAN_ERROR_TX_TERR0; break;
case 1 :
CAN_ErrorCode |= CAN_ERROR_TX_TERR1; break;
case 2 :
CAN_ErrorCode |= CAN_ERROR_TX_TERR2; break;
}
}
else /* ABRQ: Abort request for mailbox [0:2] */
{
/* Transmission Mailbox abort callback */
/* Call weak (surcharged) callback */
CAN_TxMailboxAbortCallback[local_u8TxBitPos/8]();
}
}
}
}
/* Call the Error call Back in case of Errors */
if (CAN_ErrorCode != CAN_ERROR_NONE)
{
/* Call Error callback function */
CAN_ErrorCallback();
}
}
/************************* CAN RX FIFO 0 Interrupt Handler *****************************/
void CAN_voidRX_FIFO0_Interrupt_Handler(void)
{
uint32 CAN_ErrorCode = CAN_ERROR_NONE;
uint32 interrupts = READ_REG(CAN->IER);
uint32 rf0rflags = READ_REG(CAN->RF0R);
/* Receive FIFO 0 overrun interrupt management *****************************/
if (GET_BIT(interrupts,3) != 0) /* FOVIE0: FIFO overrun interrupt enable */
{
if (GET_BIT(rf0rflags,4) != 0) /* FOVR0: FIFO 0 overrun */
{
/* Set CAN error code to Rx Fifo 0 overrun error */
CAN_ErrorCode |= CAN_ERROR_RX_FOV0;
/* Clear FIFO0 Overrun Flag */
SET_BIT(CAN->RF0R, 4);
}
}
/* Receive FIFO 0 full interrupt management ********************************/
if (GET_BIT(interrupts,2) != 0) /* FFIE0: FIFO full interrupt enable */
{
if (GET_BIT(rf0rflags,3) != 0) /* FULL0: FIFO 0 full */
{
/* Clear FIFO 0 full Flag */
SET_BIT(CAN->RF0R, 3);
/* Receive FIFO 0 full Callback */
/* Call weak (surcharged) callback */
CAN_RxFifo0FullCallback();
}
}
/* Receive FIFO 0 message pending interrupt management *********************/
if (GET_BIT(interrupts,1) != 0) /* FMPIE0: FIFO message pending interrupt enable */
{
/* Check if message is still pending */
if ((CAN->RF0R & 0x3) != 0) /* FMP0[1:0]: FIFO 0 message pending */
{
/* Receive FIFO 0 mesage pending Callback */
/* Call weak (surcharged) callback */
CAN_RxFifo0MsgPendingCallback();
}
}
/* Call the Error call Back in case of Errors */
if (CAN_ErrorCode != CAN_ERROR_NONE)
{
/* Call Error callback function */
CAN_ErrorCallback();
}
}
/************************* CAN RX FIFO 1 Interrupt Handler *****************************/
void CAN_voidRX_FIFO1_Interrupt_Handler(void)
{
uint32 CAN_ErrorCode = CAN_ERROR_NONE;
uint32 interrupts = READ_REG(CAN->IER);
uint32 rf1rflags = READ_REG(CAN->RF1R);
/* Receive FIFO 1 overrun interrupt management *****************************/
if (GET_BIT(interrupts,6) != 0) /* FOVIE1: FIFO overrun interrupt enable */
{
if (GET_BIT(rf1rflags,4) != 0) /* FOVR1: FIFO 1 overrun */
{
/* Set CAN error code to Rx Fifo 1 overrun error */
CAN_ErrorCode |= CAN_ERROR_RX_FOV1;
/* Clear FIFO1 Overrun Flag */
SET_BIT(CAN->RF1R, 4);
}
}
/* Receive FIFO 1 full interrupt management ********************************/
if (GET_BIT(interrupts,5) != 0) /* FFIE1: FIFO full interrupt enable */
{
if (GET_BIT(rf1rflags,3) != 0) /* FULL1: FIFO 1 full */
{
/* Clear FIFO 1 full Flag */
SET_BIT(CAN->RF1R, 3);
/* Receive FIFO 1 full Callback */
/* Call weak (surcharged) callback */
CAN_RxFifo1FullCallback();
}
}
/* Receive FIFO 1 message pending interrupt management *********************/
if (GET_BIT(interrupts,4) != 0) /* FMPIE1: FIFO message pending interrupt enable */
{
/* Check if message is still pending */
if ((CAN->RF1R & 0x3) != 0) /* FMP1[1:0]: FIFO 0 message pending */
{
/* Receive FIFO 1 mesage pending Callback */
/* Call weak (surcharged) callback */
CAN_RxFifo1MsgPendingCallback();
}
}
/* Call the Error call Back in case of Errors */
if (CAN_ErrorCode != CAN_ERROR_NONE)
{
/* Call Error callback function */
CAN_ErrorCallback();
}
}
/*************************** CAN SCE (Status Change Error) Interrupt Handler *********************/
void CAN_voidSCE_Interrupt_Handler(void)
{
CAN_ErrorCode = CAN_ERROR_NONE;
uint32 interrupts = READ_REG(CAN->IER);
uint32 msrflags = READ_REG(CAN->MSR);
uint32 esrflags = READ_REG(CAN->ESR);
/* Sleep interrupt management *********************************************/
if (GET_BIT(interrupts,17) != 0) /* SLKIE: Sleep interrupt enable */
{
if (GET_BIT(msrflags,4) != 0) /* SLAKI: Sleep acknowledge interrupt */
{
/* Clear Sleep interrupt Flag */
SET_BIT(CAN->MSR, 4); /* SLAKI: Sleep acknowledge interrupt */
/* Sleep Callback */
CAN_SleepCallback();
}
}
/* WakeUp interrupt management *********************************************/
if (GET_BIT(interrupts,16) != 0) /* WKUIE: Wakeup interrupt enable */
{
if (GET_BIT(msrflags,3) != 0) /* WKUI: Wakeup interrupt */
{
/* Clear WakeUp Flag */
SET_BIT(CAN->MSR, 3); /* WKUI: Wakeup interrupt */
/* WakeUp Callback */
CAN_WakeUpFromRxMsgCallback();
}
}
/* Error interrupts management *********************************************/
if (GET_BIT(interrupts,15) != 0) /* ERRIE: Error interrupt enable */
{
if (GET_BIT(msrflags,2) != 0) /* ERRI: Error interrupt */
{
/* Check Error Warning Flag */
if ((GET_BIT(interrupts,8) != 0) && /* EWGIE: Error warning interrupt enable*/
(GET_BIT(esrflags,0) != 0)) /* EWGF: Error warning flag */
{
/* Set CAN error code to Error Warning */
CAN_ErrorCode |= CAN_ERROR_EWG;
/* No need for clear of Error Warning Flag as read-only */
}
/* Check Error Passive Flag */
if ((GET_BIT(interrupts,9) != 0) && /* EPVIE: Error passive interrupt enable*/
(GET_BIT(esrflags,1) != 0)) /* EPVF: Error passive flag */
{
/* Set CAN error code to Error Passive */
CAN_ErrorCode |= CAN_ERROR_EPV;
/* No need for clear of Error Passive Flag as read-only */
}
/* Check Bus-off Flag */
if ((GET_BIT(interrupts,10) != 0) && /* BOFIE: Bus-off interrupt enable */
(GET_BIT(esrflags,2) != 0)) /* BOFF: Bus-off flag */
{
/* Set CAN error code to Bus-Off */
CAN_ErrorCode |= CAN_ERROR_BOF;
/* No need for clear of Error Bus-Off as read-only */
}
/* Check Last Error Code Flag */
if ((GET_BIT(interrupts,11) != 0) && /* LECIE: Last error code interrupt enable */
(((esrflags >> 4) & 0x7) != 0)) /* LEC[2:0]: Last error code */
{
switch ((esrflags >> 4) & 0x7) // 7=0b111 /* LEC[2:0]: Last error code */
{
case (0x1):
/* Set CAN error code to Stuff error */
CAN_ErrorCode |= CAN_ERROR_STF;
break;
case (0x2):
/* Set CAN error code to Form error */
CAN_ErrorCode |= CAN_ERROR_FOR;
break;
case (0x3):
/* Set CAN error code to Acknowledgement error */
CAN_ErrorCode |= CAN_ERROR_ACK;
break;
case (0x4):
/* Set CAN error code to Bit recessive error */
CAN_ErrorCode |= CAN_ERROR_BR;
break;
case (0x5):
/* Set CAN error code to Bit Dominant error */
CAN_ErrorCode |= CAN_ERROR_BD;
break;
case (0x6):
/* Set CAN error code to CRC error */
CAN_ErrorCode |= CAN_ERROR_CRC;
break;
default:
break;
}
/* Clear Last error code Flag */
CAN->ESR &= ~0x70; /* ERRI: Error interrupt */
}
}
/* Clear ERRI Flag */
SET_BIT(CAN->MSR, 2); /* ERRI: Error interrupt */
}
/* Call the Error call Back in case of Errors */
if (CAN_ErrorCode != CAN_ERROR_NONE)
{
/* Call Error callback function */
CAN_ErrorCallback();
}
}
/*
==============================================================================
##### Callback functions #####
==============================================================================
[..]
This subsection provides the following callback functions:
(+) CAN_TxMailboxCompleteCallback[3]
(+) CAN_TxMailboxAbortCallback[3]
(+) HAL_CAN_RxFifo0MsgPendingCallback
(+) HAL_CAN_RxFifo0FullCallback
(+) HAL_CAN_RxFifo1MsgPendingCallback
(+) HAL_CAN_RxFifo1FullCallback
(+) CAN_SleepCallback
(+) CAN_WakeUpFromRxMsgCallback
(+) CAN_ErrorCallback
*/
/************* Callbacks functions ************************/
__weak void CAN_TxMailbox0CompleteCallback()
{
}
__weak void CAN_TxMailbox1CompleteCallback()
{
}
__weak void CAN_TxMailbox2CompleteCallback()
{
}
__weak void CAN_TxMailbox0AbortCallback()
{
}
__weak void CAN_TxMailbox1AbortCallback()
{
}
__weak void CAN_TxMailbox2AbortCallback()
{
}
__weak void CAN_RxFifo0MsgPendingCallback()
{
}
__weak void CAN_RxFifo0FullCallback()
{
}
__weak void CAN_RxFifo1MsgPendingCallback()
{
}
__weak void CAN_RxFifo1FullCallback()
{
}
__weak void CAN_SleepCallback()
{
}
__weak void CAN_WakeUpFromRxMsgCallback()
{
}
__weak void CAN_ErrorCallback()
{
}
/*
* #######################################################################
* CAN_Interrupt_IRQHandler
* #######################################################################
*/
void USB_HP_CAN1_TX_IRQHandler(void) /* USB High Priority or CAN1 TX */
{
CAN_voidTX_Interrupt_Handler();
}
void USB_LP_CAN1_RX0_IRQHandler(void) /* USB Low Priority or CAN1 RX0 */
{
CAN_voidRX_FIFO0_Interrupt_Handler();
}
void CAN1_RX1_IRQHandler(void) /* CAN1 RX1 */
{
CAN_voidRX_FIFO1_Interrupt_Handler();
}
void CAN1_SCE_IRQHandler(void) /* CAN1 SCE */
{
CAN_voidSCE_Interrupt_Handler();
}
|
Eslam-Abdo/STM32_ARM_drivers | 02-MCAL/06-STK/STK_private.h | <gh_stars>1-10
/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 17 OCT 2020 */
/*********************************************************************************/
#ifndef STK_PRIVATE_H
#define STK_PRIVATE_H
/******************* Register Definition ***********************/
typedef struct
{
volatile uint32 CTRL;
volatile uint32 LOAD;
volatile uint32 VAL;
volatile uint32 CALIB;
}STK_t;
/******************* BASE Address Definition *********************/
#define STK_BASE_ADDRESS 0xE000E010 //define the boundary address of STK
#define STK ((volatile STK_t *) STK_BASE_ADDRESS)
#endif /* STK_PRIVATE_H */
|
Eslam-Abdo/STM32_ARM_drivers | 03-HAL/03-ESP8266/ESP8266_program.c | /*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 9 MAY 2021 */
/*********************************************************************************/
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include <string.h>
#include "STK_interface.h"
#include "USART_interface.h"
#include "ESP8266_interface.h"
#include "ESP8266_config.h"
#include "ESP8266_private.h"
/**
* AT Commands:
1* AT >> TEST
2* ATE0 >> STOP ECHO
3* AT+CWMODE=1 >>SET STATION MODE
4* AT+CWJAP="SSID","PASSWORD" >> CONNECT TO WIFI
5* AT+CIPSTART="TCP","IP",80 >> *replace ip with the website ip* to start connect on server
6* AT+CIPSEND=numOfBits+1 >>*replace numOfBits with number of http link bits* sto send data
7* GET http://iot-arm.freevar.com/status.txt >> put link of website
* >>> rebeat again from line num 7 OF "AT+CIPSTART" because connection will closed after recive data
* **note you recive data as form:
* +IPD,LengthOfData:content....CLOSED
*/
uint8 volatile Iterator;
uint8 volatile DataCome[200];
void ESP8266_voidInit(void)
{
USART_voidInit(UART1,115200);
STK_voidInit();
/* Sending AT Command To Check ESP8266 Is Working Or Not */
ESP8266_voidSendCmd("AT\r\n");
/* Clear ESP8266 Buffer */
ESP8266_voidClearBuffer();
/* Stop ECHO */
ESP8266_voidSendCmd("ATE0\r\n");
/* Clear ESP8266 Buffer */
ESP8266_voidClearBuffer();
/* Set station mode */
ESP8266_voidSendCmd("AT+CWMODE=1\r\n");
/* Clear ESP8266 Buffer */
ESP8266_voidClearBuffer();
}
void ESP8266_voidConnectToWiFi(uint8* SSID , uint8 * Password )
{
/* Clear ESP8266 Buffer */
ESP8266_voidClearBuffer();
ESP8266_voidSendCmd(("AT+CWJAP=" + SSID +',' + Password + "\r\n"),8000);
}
uint8 ESP8266_u8ValidateCmd(void)
{
uint8 Dummy = 0;
while (Dummy!=255)
{
Dummy = USART_charReceive(UART1);
DataCome[Iterator] = Dummy;
Iterator++;
}
/* check if receive ok */
if(DataCome[Iterator-3] == 'O' && DataCome[Iterator-2] == 'K') /* .... ok\n */
{
return 1;
}
else
{
return 0;
}
}
void ESP8266_voidClearBuffer ( void ){
u8 LOC_u8Iterator1 = 0 ;
Iterator = 0 ;
for( LOC_u8Iterator1 = 0 ; LOC_u8Iterator1 < 150 ; LOC_u8Iterator1++ ){
DataCome[ LOC_u8Iterator1 ] = 0 ;
}
}
void ESP8266_voidSendCmd(uint8* cmd,uint8 delay = 500)
{
u8 Local_u8Result = 0;
while(Local_u8Result == 1)
{
USART_voidTransmit(UART1,&cmd,STRING);
STK_voidDelay_ms(delay);
Local_u8Result = ESP8266_u8ValidateCmd;
}
}
|
Eslam-Abdo/STM32_ARM_drivers | 02-MCAL/06-STK/STK_program.c | <filename>02-MCAL/06-STK/STK_program.c
/*********************************************************************************/
/* Author : <NAME> */
/* Version : V02 */
/* Date : 19 NOV 2021 */
/*********************************************************************************/
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "STK_interface.h"
#include "STK_config.h"
#include "STK_private.h"
/* define Callback Global variable (pointer to function) */
static void (*STK_CallBack) (void);
/* define variable for interval mode */
static uint8 STk_u8ModeOfInterval;
/************* Function OF Initialize clock Source of STK **************************/
/* Apply clock choice from configuration file
* Disable SysTick Interrupt
* Disable SysTick
*/
void STK_voidInit (void)
{
#if STK_CLOCK_SRC == STK_SRC_AHB
/* Disable STK - Disable STK Interrupt - Set clock source AHB */
WRITE_REG(STK->CTRL,0x00000004);
#elif STK_CLOCK_SRC == STK_SRC_AHB_8
/* Disable STK - Disable STK Interrupt - Set clock source AHB/8 */
WRITE_REG(STK->CTRL,0);
#endif
}
/************* Function OF Set Busy Wait **************************/
/* This is function Like delay function stop the code until finish count
* for 8/8 MHz
* 1 count = 1 us
* 100 counts = 100 us
* 1000 counts = 1 ms
* and so on ...
*
* for 72/8 MHz
* 9 count = 1 us
* 900 counts = 100 us
* 9000 counts = 1 ms
* and so on ...
*/
void STK_voidSetBusyWait (uint32 Copy_u32Ticks)
{
/* Load ticks to load register */
WRITE_REG(STK->LOAD,Copy_u32Ticks);
/* Start Timer */
SET_BIT(STK->CTRL, 0);
/* Wait till flag is raised */
while( (GET_BIT(STK->CTRL, 16)) == 0);
/* Stop Timer */
CLR_BIT(STK->CTRL ,0);
WRITE_REG(STK->LOAD,0);
WRITE_REG(STK->VAL ,0);
}
/************* Function OF Set Interval Single **************************/
/* this function take ticks and function to do after ticks finished and do it once
* but don't stop the code until finish count
* 1 count = 1 us
* 100 counts = 100 us
* 1000 counts = 1 ms
* and so on ...
*
* for 72/8 MHz
* 9 count = 1 us
* 900 counts = 100 us
* 9000 counts = 1 ms
* and so on ...
*/
void STK_voidSetIntervalSingle (uint32 Copy_u32Ticks, void (*Copy_ptr) (void))
{
/* Load ticks to load register */
WRITE_REG(STK->LOAD,Copy_u32Ticks);
/* Start Timer */
SET_BIT(STK->CTRL, 0);
/* Save CallBack */
STK_CallBack = Copy_ptr;
/* Set Mode to Single */
STk_u8ModeOfInterval = STK_SINGLE_INTERVAL;
/* Enable STk Interrupt */
SET_BIT(STK->CTRL, 1);
}
/************* Function OF Set Interval Periodic **************************/
/* this function take ticks and function to do after ticks finished and do it many time until you call a function stop it
* but don't stop the code until finish count
* 1 count = 1 us
* 100 counts = 100 us
* 1000 counts = 1 ms
* and so on ...
*
* for 72/8 MHz
* 9 count = 1 us
* 900 counts = 100 us
* 9000 counts = 1 ms
* and so on ...
*/
void STK_voidSetIntervalPeriodic (uint32 Copy_u32Ticks, void (*Copy_ptr) (void))
{
/* Load ticks to load register */
WRITE_REG(STK->LOAD,Copy_u32Ticks);
/* Start Timer */
SET_BIT(STK->CTRL, 0);
/* Save CallBack */
STK_CallBack = Copy_ptr;
/* Set Mode to Period */
STk_u8ModeOfInterval = STK_PERIOD_INTERVAL;
/* Enable STk Interrupt */
SET_BIT(STK->CTRL, 1);
}
/************* Function OF Stop Interval **************************/
void STK_voidStopInterval (void)
{
/* Disable STk Interrupt */
CLR_BIT(STK->CTRL, 1);
/* Stop Timer */
CLR_BIT(STK->CTRL, 0);
STK->LOAD = 0 ;
STK->VAL = 0;
}
/************* Function OF Get Elaped Time **************************/
/* Return the number of thicks that done (load - val) */
uint32 STK_u32GetElapedTime (void)
{
uint32 Local_u32ElapsedTime;
Local_u32ElapsedTime = READ_REG(STK->LOAD) - READ_REG(STK->VAL);
return Local_u32ElapsedTime;
}
/************* Function OF Get Remaining Time **************************/
/* Return the number of thicks that will count (remaining time) (val) */
uint32 STK_u32GetRemainingTime (void)
{
uint32 Local_u32ElapsedTime;
Local_u32ElapsedTime = READ_REG(STK->VAL);
return Local_u32ElapsedTime;
}
/************* Function OF STK Interrupt **************************/
/* This is function call a STK_CallBack() function to do when interrupt */
void SysTick_Handler (void)
{
uint8 Local_u8Temporary;
if (STk_u8ModeOfInterval == STK_SINGLE_INTERVAL)
{ /* Stop Interval */
STK_voidStopInterval();
}
/* CallBack notification */
STK_CallBack();
/* Clear Interrupt Flag */
Local_u8Temporary = GET_BIT(STK->CTRL, 16);
}
/************* Function OF Delay_us **************************/
/* This is function is call from (STK_voidSetBusyWait()), it is delay function stop the code until finish count
* 1 count = 1 us
* 100 counts = 100 us
* 1000 counts = 1 ms
* and so on ...
*
* for 72/8 MHz
* 9 count = 1 us
* 900 counts = 100 us
* 9000 counts = 1 ms
* and so on ...
*/
void STK_voidDelay_ms (uint32 Copy_u32Ticks)
{
/* convert from ms to us as
* 1 ms = 1000 us for 8MHz
* 1 ms = 9000 us for 72MHz */
Copy_u32Ticks *= 9000;
STK_voidSetBusyWait(Copy_u32Ticks);
}
/************* Function OF START TIMER **************************/
/* This is function is start timer
* 1 count = 1 us
* 100 counts = 100 us
* 1000 counts = 1 ms
* and so on ...
*
* for 72/8 MHz
* 9 count = 1 us
* 900 counts = 100 us
* 9000 counts = 1 ms
* and so on ...
*/
void STK_voidStartTimer(u32 Copy_u32Ticks)
{
/* Load ticks to load register */
WRITE_REG(STK->LOAD,Copy_u32Ticks);
/* Start Timer */
SET_BIT(STK->CTRL, 0);
}
/**********************************************************************/
uint32 finish_micros,old_time_micros,finish_millis,old_time_millis;
uint64 elapsed_time_micros,elapsed_time_millis;
void overflow_micros()
{
elapsed_time_micros += 16000000/9.0 - old_time_micros;
old_time_micros =0;
}
void STK_voidStartMicros(void)
{
STK_voidSetIntervalPeriodic(16000000,overflow_micros);
}
uint64 Micros(void)
{
finish_micros = STK_u32GetElapedTime()/9.0;
elapsed_time_micros += finish_micros - old_time_micros;
old_time_micros = finish_micros;
return elapsed_time_micros;
}
void overflow_millis(){
elapsed_time_millis += 16000000/9000.0 - finish_millis;
old_time_millis =0;
}
void STK_voidStartMillis(void)
{
STK_voidSetIntervalPeriodic(16000000,overflow_millis);
}
uint64 Millis(void)
{
finish_millis = STK_u32GetElapedTime()/9000.0;
elapsed_time_millis += finish_millis - old_time_millis;
old_time_millis = finish_millis;
return elapsed_time_millis;
}
|
Eslam-Abdo/STM32_ARM_drivers | 02-MCAL/08-CAN/CAN_interface.h | <gh_stars>1-10
/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 17 OCT 2020 */
/*********************************************************************************/
#ifndef CAN_INTERFACE_H
#define CAN_INTERFACE_H
/** @defgroupCAN CAN_Activation CAN Activation **/
#define DISABLE 0
#define ENABLE 1
/** @defgroup CAN_identifier_type CAN Identifier Type **/
#define CAN_ID_STD ((uint32)(0x0)) /*!< Standard Id */
#define CAN_ID_EXT ((uint32)(0x4)) /*!< Extended Id */
/** @defgroup CAN_remote_transmission_request CAN Remote Transmission Request **/
#define CAN_RTR_DATA ((uint32)(0x0)) /*!< Data frame */
#define CAN_RTR_REMOTE ((uint32)(0x2)) /*!< Remote frame */
#define CAN_RTR_REMOTEFLAG ((uint32)(0x1)) /*!< Remote flag */
/** @defgroup CAN_receive_FIFO_number CAN Receive FIFO Number **/
#define CAN_RX_FIFO0 ((uint32)(0x0)) /*!< CAN receive FIFO 0 */
#define CAN_RX_FIFO1 ((uint32)(0x1)) /*!< CAN receive FIFO 1 */
/** @defgroup CAN_filter_FIFO CAN Filter FIFO **/
#define CAN_FILTER_FIFO0 ((uint32)(0x0)) /*!< Filter FIFO 0 assignment for filter x */
#define CAN_FILTER_FIFO1 ((uint32)(0x1)) /*!< Filter FIFO 1 assignment for filter x */
/** @defgroup CAN_filter_mode CAN Filter Mode **/
#define CAN_FILTERMODE_IDMASK ((uint32)(0x0)) /*!< Identifier mask mode */
#define CAN_FILTERMODE_IDLIST ((uint32)(0x1)) /*!< Identifier list mode */
/** @defgroup CAN_filter_scale CAN Filter Scale */
#define CAN_FILTERSCALE_16BIT ((uint32)(0x0)) /*!< Two 16-bit filters */
#define CAN_FILTERSCALE_32BIT ((uint32)(0x1)) /*!< One 32-bit filter */
/** @defgroup CAN_IRQn **/
#define CAN_TX_IRQn 19 /* CAN TX Interrupts*/
#define CAN_RX0_IRQn 20 /* CAN RX0 (FIFO_0) Interrupts */
#define CAN_RX1_IRQn 21 /* CAN RX1 (FIFO_1) Interrupts */
#define CAN_SCE_IRQn 22 /* CAN SCE (Status Change Error) Interrupts */
/**
* =============================================================================================
* ### CAN INE Bits definition
*=============================================================================================
**/
/** @defgroup CAN_Interrupts CAN Interrupts **/
/* Transmit Interrupt */
#define CAN_IER_TX_MAILBOX_EMPTY ((uint32)(0x1)) /*!< Transmit mailbox empty interrupt */
/* Receive Interrupts */
#define CAN_IER_RX_FIFO0_MSG_PENDING ((uint32)(0x2 )) /*!< FIFO 0 message pending interrupt */
#define CAN_IER_RX_FIFO0_FULL ((uint32)(0x4 )) /*!< FIFO 0 full interrupt */
#define CAN_IER_RX_FIFO0_OVERRUN ((uint32)(0x8 )) /*!< FIFO 0 overrun interrupt */
#define CAN_IER_RX_FIFO1_MSG_PENDING ((uint32)(0x10)) /*!< FIFO 1 message pending interrupt */
#define CAN_IER_RX_FIFO1_FULL ((uint32)(0x20)) /*!< FIFO 1 full interrupt */
#define CAN_IER_RX_FIFO1_OVERRUN ((uint32)(0x40)) /*!< FIFO 1 overrun interrupt */
/* Operating Mode Interrupts */
#define CAN_IER_WAKEUP (uint32)(1<<16)) /*!< Wake-up interrupt */
#define CAN_IER_SLEEP_ACK ((uint32)(1<<17)) /*!< Sleep acknowledge interrupt */
/* Error Interrupts */
#define CAN_IER_ERROR_WARNING ((uint32)(1<<8 )) /*!< Error warning interrupt */
#define CAN_IER_ERROR_PASSIVE ((uint32)(1<<9 )) /*!< Error passive interrupt */
#define CAN_IER_BUSOFF ((uint32)(1<<10)) /*!< Bus-off interrupt */
#define CAN_IER_LAST_ERROR_CODE ((uint32)(1<<11)) /*!< Last error code interrupt */
#define CAN_IER_ERROR ((uint32)(1<<15)) /*!< Error Interrupt */
/**
* =============================================================================================
* ### CAN ERROR definition
*=============================================================================================
**/
/** @defgroup CAN_Error_Code CAN Error Code **/
#define CAN_ERROR_NONE (0x00000000U) /*!< No error */
#define CAN_ERROR_EWG (0x00000001U) /*!< Protocol Error Warning */
#define CAN_ERROR_EPV (0x00000002U) /*!< Error Passive */
#define CAN_ERROR_BOF (0x00000004U) /*!< Bus-off error */
#define CAN_ERROR_STF (0x00000008U) /*!< Stuff error */
#define CAN_ERROR_FOR (0x00000010U) /*!< Form error */
#define CAN_ERROR_ACK (0x00000020U) /*!< Acknowledgment error */
#define CAN_ERROR_BR (0x00000040U) /*!< Bit recessive error */
#define CAN_ERROR_BD (0x00000080U) /*!< Bit dominant error */
#define CAN_ERROR_CRC (0x00000100U) /*!< CRC error */
#define CAN_ERROR_RX_FOV0 (0x00000200U) /*!< Rx FIFO0 overrun error */
#define CAN_ERROR_RX_FOV1 (0x00000400U) /*!< Rx FIFO1 overrun error */
#define CAN_ERROR_TX_ALST0 (0x00000800U) /*!< TxMailbox 0 transmit failure due to arbitration lost */
#define CAN_ERROR_TX_TERR0 (0x00001000U) /*!< TxMailbox 0 transmit failure due to transmit error */
#define CAN_ERROR_TX_ALST1 (0x00002000U) /*!< TxMailbox 1 transmit failure due to arbitration lost */
#define CAN_ERROR_TX_TERR1 (0x00004000U) /*!< TxMailbox 1 transmit failure due to transmit error */
#define CAN_ERROR_TX_ALST2 (0x00008000U) /*!< TxMailbox 2 transmit failure due to arbitration lost */
#define CAN_ERROR_TX_TERR2 (0x00010000U) /*!< TxMailbox 2 transmit failure due to transmit error */
/**
* =============================================================================================
* ### CAN structures definition
*=============================================================================================
**/
/** CAN Tx message header structure definition **/
typedef struct
{
uint32 StdId; /*!< Specifies the standard identifier.
This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF. */
uint32 ExtId; /*!< Specifies the extended identifier.
This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF. */
uint32 IDE; /*!< Specifies the type of identifier for the message that will be transmitted.
This parameter can be a value of @ref CAN_identifier_type */
uint32 RTR; /*!< Specifies the type of frame for the message that will be transmitted.
This parameter can be a value of @ref CAN_remote_transmission_request */
uint32 DLC; /*!< Specifies the length of the frame that will be transmitted.
This parameter must be a number between Min_Data = 0 and Max_Data = 8. */
uint8 TransmitGlobalTime; /*!< Specifies whether the time stamp counter value captured on start
of frame transmission, is sent in DATA6 and DATA7 replacing pData[6] and pData[7].
@note: Time Triggered Communication Mode must be enabled.
@note: DLC must be programmed as 8 bytes, in order these 2 bytes are sent.
This parameter can be set to ENABLE or DISABLE. */
} CAN_TxHeaderTypeDef;
/** CAN Rx message header structure definition **/
typedef struct
{
uint32 StdId; /*!< Specifies the standard identifier.
This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF. */
uint32 ExtId; /*!< Specifies the extended identifier.
This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF. */
uint32 IDE; /*!< Specifies the type of identifier for the message that will be transmitted.
This parameter can be a value of @ref CAN_identifier_type */
uint32 RTR; /*!< Specifies the type of frame for the message that will be transmitted.
This parameter can be a value of @ref CAN_remote_transmission_request */
uint32 DLC; /*!< Specifies the length of the frame that will be transmitted.
This parameter must be a number between Min_Data = 0 and Max_Data = 8. */
uint32 TimeStamp; /*!< Specifies the timestamp counter value captured on start of frame reception.
@note: Time Triggered Communication Mode must be enabled.
This parameter must be a number between Min_Data = 0 and Max_Data = 0xFFFF. */
uint32 FilterMatchIndex; /*!< Specifies the index of matching acceptance filter element.
This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF. */
} CAN_RxHeaderTypeDef;
/**
* @brief CAN filter configuration structure definition
*/
typedef struct
{
uint32 FilterIdHigh; /*!< Specifies the filter identification number (MSBs for a 32-bit
configuration, first one for a 16-bit configuration).
This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */
uint32 FilterIdLow; /*!< Specifies the filter identification number (LSBs for a 32-bit
configuration, second one for a 16-bit configuration).
This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */
uint32 FilterMaskIdHigh; /*!< Specifies the filter mask number or identification number,
according to the mode (MSBs for a 32-bit configuration,
first one for a 16-bit configuration).
This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */
uint32 FilterMaskIdLow; /*!< Specifies the filter mask number or identification number,
according to the mode (LSBs for a 32-bit configuration,
second one for a 16-bit configuration).
This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */
uint32 FilterFIFOAssignment; /*!< Specifies the FIFO (0 or 1U) which will be assigned to the filter.
This parameter can be a value of @ref CAN_filter_FIFO */
uint32 FilterBank; /*!< Specifies the filter bank which will be initialized.
For single CAN instance(14 dedicated filter banks),
this parameter must be a number between Min_Data = 0 and Max_Data = 13. */
uint32 FilterMode; /*!< Specifies the filter mode to be initialized.
This parameter can be a value of @ref CAN_filter_mode */
uint32 FilterScale; /*!< Specifies the filter scale.
This parameter can be a value of @ref CAN_filter_scale */
uint32 FilterActivation; /*!< Enable or disable the filter.
This parameter can be a value of @ref CAN_Activation */
} CAN_FilterTypeDef;
/*************** Function definition ******************/
void CAN_voidInit(void);
void CAN_voidStart(void);
void CAN_voidAddTxMsg( CAN_TxHeaderTypeDef *pTxHeader, uint8 Local_u8Data[]);
void CAN_voidGetRxMsg(uint32 local_u8RxFifo, CAN_RxHeaderTypeDef *pRxHeader, uint8 Local_u8Data[]);
uint8 CAN_voidRXPending(uint8 local_u8RxFifo);
void CAN_voidConfigFilter( CAN_FilterTypeDef *pFilterConfig);
uint32 CAN_voidGetErrorCode(void);
/********************** Interrupt functions *******************/
void CAN_voidInitInterput(IRQn_Type IRQn);
void CAN_voidDeinterputInit(IRQn_Type IRQn);
void CAN_voidEnableInterrupt(uint32 local_u32ActiveITs);
void CAN_voidDisableInterrupt(uint32 local_u32ActiveITs);
void CAN_voidRX_FIFO0_Interrupt_Handler(void);
void CAN_voidRX_FIFO1_Interrupt_Handler(void);
void CAN_voidSCE_Interrupt_Handler(void); /* Status Change Error Interrupt Handler */
/************* Callbacks functions ************************/
void CAN_TxMailbox0CompleteCallback();
void CAN_TxMailbox1CompleteCallback();
void CAN_TxMailbox2CompleteCallback();
void CAN_TxMailbox0AbortCallback();
void CAN_TxMailbox1AbortCallback();
void CAN_TxMailbox2AbortCallback();
void CAN_RxFifo0MsgPendingCallback();
void CAN_RxFifo0FullCallback();
void CAN_RxFifo1MsgPendingCallback();
void CAN_RxFifo1FullCallback();
void CAN_SleepCallback();
void CAN_WakeUpFromRxMsgCallback();
void CAN_ErrorCallback();
#endif /* CAN_INTERFACE_H */
|
Eslam-Abdo/STM32_ARM_drivers | 02-MCAL/10-DMA/DMA_config.h | /*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 17 OCT 2021 */
/*********************************************************************************/
#ifndef DMA_CONFIG_H_
#define DMA_CONFIG_H_
/****************
* ADDRESSING:
* I2C_ADDRMODE_7BIT
* I2C_ADDRMODE_10BIT
*
**************/
#define I2C1_ADDRESSING I2C_ADDRMODE_7BIT
#define I2C2_ADDRESSING I2C_ADDRMODE_7BIT
#endif /* DMA_CONFIG_H_ */
|
Eslam-Abdo/STM32_ARM_drivers | 02-MCAL/09-I2C/I2C_private.h | <filename>02-MCAL/09-I2C/I2C_private.h
/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 7 JUN 2021 */
/*********************************************************************************/
#ifndef I2C_PRIVATE_H
#define I2C_PRIVATE_H
typedef struct {
volatile u32 CR1 ;
volatile u32 CR2 ;
volatile u32 OAR1 ;
volatile u32 OAR2 ;
volatile u32 DR ;
volatile u32 SR1 ;
volatile u32 SR2 ;
volatile u32 CCR ;
volatile u32 TRISE ;
}I2C_t;
/******************* BASE Address Definition *********************/
#define I2C1_BASE_ADDRESS 0x40005400 //define the boundary address of I2C1
#define I2C2_BASE_ADDRESS 0x40005800 //define the boundary address of I2C2
#define I2C1 ( ( volatile I2C_t* ) I2C1_BASE_ADDRESS )
#define I2C2 ( ( volatile I2C_t* ) I2C2_BASE_ADDRESS )
#endif /* I2C_PRIVATE_H */
|
Eslam-Abdo/STM32_ARM_drivers | 01-LIB/02-BIT_MATH/BIT_MATH.h | /*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 22 SEP 2020 */
/*********************************************************************************/
#ifndef BIT_MATH_H
#define BIT_MATH_H
#define SET_BIT(VAR,BIT) VAR |= (1 << (BIT))
#define CLR_BIT(VAR,BIT) VAR &= ~(1 << (BIT))
#define GET_BIT(VAR,BIT) ((VAR >> BIT) & 1 )
#define TOG_BIT(VAR,BIT) VAR ^= (1 << (BIT))
#define WRITE_REG(REG, VAL) ((REG) = (VAL))
#define READ_REG(REG) ((REG))
#endif // BIT_MATH_H
|
Eslam-Abdo/STM32_ARM_drivers | 03-HAL/02-7_SEG/7_SEG_program.c | <filename>03-HAL/02-7_SEG/7_SEG_program.c<gh_stars>1-10
/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 25 SEP 2020 */
/*********************************************************************************/
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "GPIO_interface.h"
#include "7_SEG_interface.h"
#include "7_SEG_config.h"
#include "7_SEG_private.h"
void _7_SEG_voidInit(uint8 Copy_u8Port)
{
GPIO_voidSetPinDirection(Copy_u8Port, PIN0, OUTPUT_SPEED_10MHZ_PP);
GPIO_voidSetPinDirection(Copy_u8Port, PIN1, OUTPUT_SPEED_10MHZ_PP);
GPIO_voidSetPinDirection(Copy_u8Port, PIN2, OUTPUT_SPEED_10MHZ_PP);
GPIO_voidSetPinDirection(Copy_u8Port, PIN3, OUTPUT_SPEED_10MHZ_PP);
GPIO_voidSetPinDirection(Copy_u8Port, PIN4, OUTPUT_SPEED_10MHZ_PP);
GPIO_voidSetPinDirection(Copy_u8Port, PIN5, OUTPUT_SPEED_10MHZ_PP);
GPIO_voidSetPinDirection(Copy_u8Port, PIN6, OUTPUT_SPEED_10MHZ_PP);
}
/********** Copy_u8Port : select port GPIOA or GPIOB
Copy_u8CommonType : select 7-SEG type COMMON_CATHODE or COMMON_ANODE
Copy_u8DisplayNum : display number from 0 to 9
NOTE: if need you change pins number check "7_SEG_config.h"
**************/
void _7_SEG_voidDisplay(uint8 Copy_u8Port, uint8 Copy_u8DisplayNum)
{
switch(Copy_u8DisplayNum)
{
case 0:
/****************** _
| |
|_| ****************/
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN0, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN1, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN2, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN3, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN4, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN5, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN6, SEVEN_SEG_LOW);
break;
case 1:
/******************
|
| ****************/
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN0, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN1, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN2, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN3, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN4, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN5, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN6, SEVEN_SEG_LOW);
break;
case 2:
/****************** _
_|
|_ ****************/
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN0, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN1, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN2, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN3, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN4, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN5, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN6, SEVEN_SEG_HIGH);
break;
case 3:
/****************** _
_|
_| ****************/
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN0, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN1, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN2, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN3, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN4, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN5, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN6, SEVEN_SEG_HIGH);
break;
case 4:
/******************
|_|
| ****************/
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN0, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN1, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN2, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN3, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN4, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN5, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN6, SEVEN_SEG_HIGH);
break;
case 5:
/****************** _
|_
_| ****************/
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN0, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN1, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN2, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN3, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN4, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN5, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN6, SEVEN_SEG_HIGH);
break;
case 6:
/****************** _
|_
|_| ****************/
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN0, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN1, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN2, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN3, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN4, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN5, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN6, SEVEN_SEG_HIGH);
break;
case 7:
/****************** _
|
| ****************/
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN0, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN1, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN2, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN3, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN4, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN5, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN6, SEVEN_SEG_LOW);
break;
case 8:
/****************** _
|_|
|_| ****************/
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN0, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN1, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN2, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN3, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN4, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN5, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN6, SEVEN_SEG_HIGH);
break;
case 9:
/****************** _
|_|
_| ****************/
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN0, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN1, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN2, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN3, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN4, SEVEN_SEG_LOW);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN5, SEVEN_SEG_HIGH);
GPIO_voidSetPinValue(Copy_u8Port, SEVEN_SEG_PIN6, SEVEN_SEG_HIGH);
break;
default : break;
}
}
|
Eslam-Abdo/STM32_ARM_drivers | 02-MCAL/10-DMA/DMA_private.h | /*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 17 OCT 2021 */
/*********************************************************************************/
#ifndef I2C_PRIVATE_H_
#define I2C_PRIVATE_H_
#include "STD_TYPES.h"
typedef struct {
volatile u32 CR1 ;
volatile u32 CR2 ;
volatile u32 OAR1 ;
volatile u32 OAR2 ;
volatile u32 DR ;
volatile u32 SR1 ;
volatile u32 SR2 ;
volatile u32 CCR ;
volatile u32 TRISE ;
}I2C_t;
#define I2C1 ( ( volatile I2C_t* ) 0x40005400 )
#define I2C2 ( ( volatile I2C_t* ) 0x40005800 )
#endif /* I2C_PRIVATE_H_ */
|
Eslam-Abdo/STM32_ARM_drivers | 02-MCAL/05-AFIO/AFIO_interface.h | /*********************************************************************************/
/* Author : <NAME> */
/* Version : V02 */
/* Date : 19 NOV 2021 */
/*********************************************************************************/
#ifndef AFIO_INTERFACE_H
#define AFIO_INTERFACE_H
#define SPI1_REMAP 0
#define I2C1_REMAP 1
#define UART1_REMAP 2
#define UART2_REMAP 3
#define UART3_REMAP 4
#define TIM1_REMAP 6
#define TIM2_REMAP 8
#define TIM3_REMAP 10
#define TIM4_REMAP 12
#define CAN_REMAP 13
/*************** Function definition ******************/
void AFIO_voidSetEXTIConfiguration (uint8 Copy_u8EXTI_Line, uint8 Copy_u8PortMap);
void AFIO_voidRemapPeripheralPins (uint8 Copy_u8Port);
#endif // AFIO_INTERFACE_H
|
Eslam-Abdo/STM32_ARM_drivers | 02-MCAL/09-I2C/I2C_program.c | /*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 7 JUN 2021 */
/*********************************************************************************/
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "GPIO_interface.h"
#include "I2C_private.h"
#include "I2C_config.h"
#include "I2C_interface.h"
volatile I2C_t *i2cx;
void I2C_generate_start_condition(u8 I2C_Type)
{
if(I2C_Type == MI2C1)
{
i2cx = I2C1;
}else if(I2C_Type == MI2C2)
{
i2cx = I2C2;
}
SET_BIT(i2cx->CR1, I2C_REG_CR1_START_GEN);
}
void I2C_generate_stop_condition(u8 I2C_Type)
{
if(I2C_Type == MI2C1)
{
i2cx = I2C1;
}else if(I2C_Type == MI2C2)
{
i2cx = I2C2;
}
SET_BIT(i2cx->CR1, I2C_REG_CR1_STOP_GEN);
}
void I2C_slave_Check_StopBit(u8 I2C_Type)
{
if(I2C_Type == MI2C1)
{
i2cx = I2C1;
}else if(I2C_Type == MI2C2)
{
i2cx = I2C2;
}
// for slave rx , with ACK
while( GET_BIT(i2cx->SR1, I2C_REG_SR1_STOP_DETECTION_FLAG) == 0);
clear_stop_flag();
}
void I2C_init(u8 I2C_Type,u32 I2C_CLOCK, u16 OwnAddress1)
{
if(I2C_Type == MI2C1)
{
i2cx = I2C1;
/* GPIO init */
GPIO_voidSetPinDirection(GPIOB,PIN6,OUTPUT_SPEED_50MHZ_AFOD); /* configure PB6 and PB7 as alt. func. open drain */
GPIO_voidSetPinDirection(GPIOB,PIN7,OUTPUT_SPEED_50MHZ_AFOD); /* configure PB6 and PB7 as alt. func. open drain */
I2C_set_addressing_mode(I2C1_ADDRESSING);
}else if(I2C_Type == MI2C2)
{
i2cx = I2C2;
GPIO_voidSetPinDirection(GPIOB,PIN10,OUTPUT_SPEED_50MHZ_AFOD); /* configure PB10 and PB11 as alt. func. open drain */
GPIO_voidSetPinDirection(GPIOB,PIN11,OUTPUT_SPEED_50MHZ_AFOD); /* configure PB10 and PB11 as alt. func. open drain */
I2C_set_addressing_mode(I2C2_ADDRESSING);
}
I2C_disable_peripheral();
I2C_clk_init( I2C_CLOCK,I2C_FM_DUTY_2);
I2C_set_addressing_mode(I2C1_ADDRESSING);
I2C_manage_ack(I2C_ACK_ENABLE);
I2C_manage_clock_stretch(I2C_ENABLE_CLK_STRETCH);
I2C_set_own_address1(OwnAddress1);
I2C_enable_peripheral();
}
void I2C_master_tx(u8 I2C_Type,u8 address,u8* data,u8 len)
{
if(I2C_Type == MI2C1)
{
i2cx = I2C1;
}else if(I2C_Type == MI2C2)
{
i2cx = I2C2;
}
//while( is_bus_busy() ); //need to include timeout
/* Disable Pos */
CLR_BIT(i2cx->CR1, I2C_REG_CR1_POS);
/* enable ACK */
I2C_manage_ack(I2C_ACK_ENABLE);
I2C_generate_start_condition(I2C_Type);
/* wait till sb is set */
while( ! i2c_wait_untill_sb_set() );
//clear_sb_flag
I2C_send_addr_first(address,I2C_ADDREES_WRITE);
while ( ! i2c_wait_untill_addr_set() );
clear_addr_flag();
u8 size = len; /* reused in onther state */
while(size>0)
{
u32 timeout = 0;
while( ( GET_BIT(i2cx->SR1, I2C_REG_SR1_TXE_FLAG) == 0 ) && ( timeout < 100000 ) ) { timeout++; } /* wait TXE =1*/
i2cx->DR = data[len - size];
size--;
if(( GET_BIT(i2cx->SR1,I2C_REG_SR1_BTF_FLAG) == 0 ) && ( size != 0 ) )//BTF
{
i2cx->DR = data[len - size];
size--;
}
timeout = 0;
while( ( GET_BIT(i2cx->SR1,I2C_REG_SR1_BTF_FLAG) == 0 ) && ( timeout < 100000 ) ) { timeout++; } //wait BTF (data send)
}
}
void I2C_master_rx(u8 I2C_Type, u16 address, u8 *pData, u8 len)
{
if(I2C_Type == MI2C1)
{
i2cx = I2C1;
}else if(I2C_Type == MI2C2)
{
i2cx = I2C2;
}
// while( is_bus_busy() ); //need to include timeout
/* Disable Pos */
CLR_BIT(i2cx->CR1, I2C_REG_CR1_POS);
/* enable ACK */
I2C_manage_ack(I2C_ACK_ENABLE);
/* Prepare transfer parameters */
u8* pBuffPtr = pData;
u8 XferCount = len;
u8 XferSize = XferCount;
I2C_generate_start_condition(I2C_Type);
/* wait till sb is set */
while( ! i2c_wait_untill_sb_set() );
//clear_sb_flag
I2C_send_addr_first(address,I2C_ADDREES_READ);
while ( ! i2c_wait_untill_addr_set() );
/* ---------- Start Read Data -------------------- */
if (XferSize == 0U)
{
/* Clear ADDR flag */
clear_addr_flag();
/* Generate Stop */
I2C_generate_stop_condition(I2C_Type);
}
else if (XferSize == 1U)
{
/* Disable Acknowledge */
I2C_manage_ack(I2C_ACK_DISABLE);
/* Clear ADDR flag */
clear_addr_flag();
/* Generate Stop */
I2C_generate_stop_condition(I2C_Type);
}
else if (XferSize == 2U)
{
/* Enable Pos */
SET_BIT(i2cx->CR1, I2C_REG_CR1_POS);
/* Clear ADDR flag */
clear_addr_flag();
/* Disable Acknowledge */
I2C_manage_ack(I2C_ACK_DISABLE);
}
else
{ /* XferSize > 2U */
/* Enable Acknowledge */
I2C_manage_ack(I2C_ACK_ENABLE);
/* Clear ADDR flag */
clear_addr_flag();
}
while (XferSize > 0U)
{
if (XferSize <= 3U)
{
/* One byte */
if (XferSize == 1U)
{
/* Wait until RXNE flag is set */
while ( GET_BIT(i2cx->SR1,I2C_REG_SR1_RXNE_FLAG) == 0 );
/* Read data from DR */
*pBuffPtr = (u8)i2cx->DR;
/* Increment Buffer pointer */
pBuffPtr++;
/* Update counter */
XferSize--;
XferCount--;
}
/* Two bytes */
else if (XferSize == 2U)
{
/* Wait until BTF flag is set */
while (GET_BIT(i2cx->SR1,I2C_REG_SR1_BTF_FLAG) != 1);
/* Generate Stop */
I2C_generate_stop_condition(I2C_Type);
/* Read data from DR */
*pBuffPtr = (u8)i2cx->DR;
/* Increment Buffer pointer */
pBuffPtr++;
/* Update counter */
XferSize--;
XferCount--;
/* Read data from DR */
*pBuffPtr = (u8)i2cx->DR;
/* Increment Buffer pointer */
pBuffPtr++;
/* Update counter */
XferSize--;
XferCount--;
}
/* 3 Last bytes */
else
{
/* Wait until BTF flag is set */
u32 timeout=0;
while( ( GET_BIT(i2cx->SR1,I2C_REG_SR1_BTF_FLAG) == 0 ) && ( timeout < 100000 ) ) { timeout++; }
/* Disable Acknowledge */
I2C_manage_ack(I2C_ACK_DISABLE);
/* Read data from DR */
*pBuffPtr = (u8)i2cx->DR;
/* Increment Buffer pointer */
pBuffPtr++;
/* Update counter */
XferSize--;
XferCount--;
timeout=0;
/* Wait until BTF flag is set */
while( ( GET_BIT(i2cx->SR1,I2C_REG_SR1_BTF_FLAG) == 0 ) && ( timeout < 100000 ) ) { timeout++; }
/* Generate Stop */
SET_BIT(i2cx->CR1, 9);
/* Read data from DR */
*pBuffPtr = (u8)i2cx->DR;
/* Increment Buffer pointer */
pBuffPtr++;
/* Update counter */
XferSize--;
XferCount--;
/* Read data from DR */
*pBuffPtr = (u8)i2cx->DR;
/* Increment Buffer pointer */
pBuffPtr++;
/* Update counter */
XferSize--;
XferCount--;
}
}
else /* XferSize > 3*/
{
/* Wait until RXNE flag is set */
while (GET_BIT(i2cx->SR1,I2C_REG_SR1_RXNE_FLAG) == 0 );
/* Read data from DR */
*pBuffPtr = (u8)i2cx->DR;
/* Increment Buffer pointer */
pBuffPtr++;
/* Update counter */
XferSize--;
XferCount--;
}
}
}
void I2C_slave_tx(u8 I2C_Type,u8* data,u8 len)
{
if(I2C_Type == MI2C1)
{
i2cx = I2C1;
}else if(I2C_Type == MI2C2)
{
i2cx = I2C2;
}
//while( is_bus_busy() ); //need to include timeout
/* Disable Pos */
CLR_BIT(i2cx->CR1, I2C_REG_CR1_POS);
/* enable ACK */
I2C_manage_ack(I2C_ACK_ENABLE);
/* Wait until ADDR flag is set */
while(GET_BIT(i2cx->SR1,I2C_REG_SR1_ADDR_MATCHED_FLAG)==0);
/* Clear ADDR flag */
clear_addr_flag();
if ( GET_BIT(i2cx->SR2, I2C_REG_SR2_TRA_FLAG ) == I2C_TX_MODE)
{
u8 size = len;
while(size>0)
{
i2cx->DR = data[len-size];
while( GET_BIT(i2cx->SR1 ,I2C_REG_SR1_TXE_FLAG) == 0 ); //waiting for TxE
size--;
}
}
if ( GET_BIT(i2cx->SR1,I2C_REG_SR1_AF_FAILURE_FLAG) == 1 ) //AF bit for tx
{
CLR_BIT(i2cx->SR1,I2C_REG_SR1_AF_FAILURE_FLAG); //clear AF bit
}
}
void I2C_slave_rx(u8 I2C_Type,u8* buff, u8 len)
{
if(I2C_Type == MI2C1)
{
i2cx = I2C1;
}else if(I2C_Type == MI2C2)
{
i2cx = I2C2;
}
//while( is_bus_busy() ); //need to include timeout
/* Disable Pos */
CLR_BIT(i2cx->CR1, I2C_REG_CR1_POS);
/* enable ACK */
I2C_manage_ack(I2C_ACK_ENABLE);
/* Wait until ADDR flag is set */
while(GET_BIT(i2cx->SR1,I2C_REG_SR1_ADDR_MATCHED_FLAG)==0);
/* Clear ADDR flag */
clear_addr_flag();
if ( GET_BIT(i2cx->SR2, I2C_REG_SR2_TRA_FLAG ) == I2C_RX_MODE)
{
u8 size = len;
while(size>0)
{
while( GET_BIT(i2cx->SR1, I2C_REG_SR1_RXNE_FLAG ) == 0 ); //waiting for RxNE
buff[len-size] = i2cx->DR;
size--;
}
}
}
static void I2C_enable_peripheral(void)
{
SET_BIT(i2cx->CR1, I2C_REG_CR1_ENABLE_I2C);
}
static void I2C_disable_peripheral(void)
{
CLR_BIT(i2cx->CR1, I2C_REG_CR1_ENABLE_I2C);
}
static void I2C_rest_peripheral(void)
{
SET_BIT(i2cx->CR1,15);// SWRST: Software reset
CLR_BIT(i2cx->CR1,15);// SWRST: Software reset
}
static void I2C_set_own_address1( u32 own_address)
{
i2cx->OAR1 &= ~( 0x7f << 1);
i2cx->OAR1 |= (own_address << 1);
}
static void I2C_manage_clock_stretch( u32 no_stretch)
{
if(no_stretch)
{
SET_BIT(i2cx->CR1,I2C_REG_CR1_NOSTRETCH);
}else
{
CLR_BIT(i2cx->CR1,I2C_REG_CR1_NOSTRETCH);
}
}
static void I2C_configure_ccr( u32 pclk, u32 clkspeed, u32 duty_cycle)
{
u32 ccr;
if(clkspeed <= 100000)
{
/* configure ccr for standard mode */
ccr = ( pclk * 1000000) / (clkspeed << 1);
}else
{
if(duty_cycle == I2C_FM_DUTY_2)
{
ccr = ( pclk * 1000000)/(3 * clkspeed);
}else if(duty_cycle == I2C_FM_DUTY_16BY9)
{
/* this is to reach 400khz in fm mode */
ccr = ( pclk * 1000000)/(25 * clkspeed);
}
}
i2cx->CCR |= ccr;
}
static void I2C_rise_time_configuration(u32 pclk, u32 ClockSpeed)
{
/*---------------------------- I2Cx TRISE Configuration --------------------*/
/* Configure I2Cx: Rise Time */
// hi2c->Instance->TRISE = I2C_RISE_TIME(freqrange, hi2c->Init.ClockSpeed);
u32 trise;
if( ClockSpeed <= 100000)
{
trise = pclk +1;
}else
{
trise = (((pclk * 300) / 1000) + 1);
}
i2cx->TRISE &= ~(0x3F);
i2cx->TRISE |= trise;
}
static void I2C_set_clk_mode(u8 I2C_Mode)
{
if (I2C_Mode == I2C_ENABLE_FM)
{
SET_BIT(i2cx->CCR, I2C_REG_CCR_ENABLE_FM);
}
else
{
CLR_BIT(i2cx->CCR, I2C_REG_CCR_ENABLE_FM);
}
}
static void I2C_set_fm_mode_duty_cycle(u32 duty_cycle)
{
if(duty_cycle == I2C_FM_DUTY_16BY9 )
{
SET_BIT(i2cx->CCR,I2C_REG_CCR_DUTY);
}else
{
CLR_BIT(i2cx->CCR,I2C_REG_CCR_DUTY);
}
}
static void I2C_clk_init ( u32 clkspeed, u32 duty_cycle)
{
u32 pclk = I2C_PERIPHERAL_CLK_FREQ_36MHZ;
i2cx->CR2 |= (pclk );
I2C_rise_time_configuration(pclk, clkspeed);
I2C_configure_ccr(pclk,clkspeed,duty_cycle);
if( clkspeed <= 100000)
{
I2C_set_clk_mode(I2C_ENABLE_SM);
}else
{
I2C_set_clk_mode(I2C_ENABLE_FM);
I2C_set_fm_mode_duty_cycle(duty_cycle);
}
}
static void I2C_set_addressing_mode( u32 adr_mode)
{
if(adr_mode == I2C_ADDRMODE_10BI)
SET_BIT(i2cx->OAR1, I2C_REG_OAR1_ADDRMODE);
else
CLR_BIT(i2cx->OAR1, I2C_REG_OAR1_ADDRMODE);
}
static void I2C_manage_ack( u32 ack_noack)
{
if(ack_noack == I2C_ACK_ENABLE)
SET_BIT(i2cx->CR1, I2C_REG_CR1_ACK);
else
CLR_BIT(i2cx->CR1, I2C_REG_CR1_ACK);
}
static u8 is_bus_busy(void)
{
if(GET_BIT(i2cx->SR2, I2C_REG_SR2_BUS_BUSY_FLAG) )
return 1;
else
return 0;
}
static u8 i2c_wait_untill_sb_set(void)
{
//EV5: SB=1, cleared by reading SR1 register followed by writing DR register with Address.
if (GET_BIT(i2cx->SR1 , I2C_REG_SR1_SB_FLAG ))
{
return 1 ;
}
return 0;
}
static u8 i2c_wait_untill_addr_set(void)
{
//EV6: ADDR=1, cleared by reading SR1 register followed by reading SR2.
if (GET_BIT(i2cx->SR1 , I2C_REG_SR1_ADDR_SENT_FLAG ))
{
return 1 ;
}
return 0;
}
static void I2C_send_addr_first( u8 address, u8 addr_type)
{
if(addr_type == I2C_ADDREES_READ)
{
address = ((address << 1) | 0x1); /* addr+Read(1) */
}
else
{
address = (address << 1); /* addr+Write(0) */
}
i2cx->DR = address;
}
static void clear_addr_flag(void)
{
u16 val;
val = i2cx->SR1;
val = i2cx->SR2;
}
static void clear_stop_flag(void)
{ /* (READ SR1 then WRITE CR1 */
u16 val;
val = i2cx->SR1;
SET_BIT(i2cx->CR1 , I2C_REG_SR1_SB_FLAG);
}
|
Eslam-Abdo/STM32_ARM_drivers | 03-HAL/02-7_SEG/7_SEG_interface.h | <gh_stars>1-10
/*********************************************************************************/
/* Author : <NAME> */
/* Version : V01 */
/* Date : 25 SEP 2020 */
/*********************************************************************************/
#ifndef _7_SEG_INTERFACE_H
#define _7_SEG_INTERFACE_H
/*************** Common Type definition *******************/
#define COMMON_ANODE 0
#define COMMON_CATHODE 1
/*************** Function definition ******************/
void _7_SEG_voidInit (uint8 Copy_u8Port);
void _7_SEG_voidDisplay (uint8 Copy_u8Port, uint8 Copy_u8DisplayNum);
#endif // _7_SEG_INTERFACE_H
|
Eslam-Abdo/STM32_ARM_drivers | 02-MCAL/01-RCC/RCC_private.h | <gh_stars>1-10
/*********************************************************************************/
/* Author : <NAME> */
/* Version : V02 */
/* Date : 17 NOV 2021 */
/*********************************************************************************/
#ifndef RCC_PRIVATE_H
#define RCC_PRIVATE_H
/******************* Register Definition ***********************/
typedef struct {
volatile uint32 CR ;
volatile uint32 CFGR ;
volatile uint32 CIR ;
volatile uint32 APB2RSTR ;
volatile uint32 APB1RSTR ;
volatile uint32 AHBENR ;
volatile uint32 APB2ENR ;
volatile uint32 APB1ENR ;
volatile uint32 BDCR ;
volatile uint32 CSR ;
}RCC_t;
/******************* BASE Address Definition *********************/
#define RCC_BASE_ADDRESS 0x40021000 //define the boundary address of RCC
#define RCC ( ( volatile RCC_t* ) RCC_BASE_ADDRESS)
#endif // RCC_PRIVATE_H
|
maany/Sceptre_Myo_URC | SceptreVM/sceptre.h | /*
Author : <NAME>
This header file defines the wrappers from MyoController and IRRemote libraries
*/
#ifndef SPECTRE_H
#define SCEPTRE_H
#include "IRremote.h"
#include "IRremoteInt.h"
#include "MyoController.h"
#define SCEPTRE_NO_OF_DEVICES 1
#define GESTURE_MAP_SIZE 5
//===============================
// Gesture to Array Index Mapping
//===============================
#define DOUBLE_TAP 0
#define FIST 1
#define WAVE_IN 2
#define WAVE_OUT 3
#define FINGER_SPREAD 4
class Myo {
MyoController myoController;
public:
Myo();
Myo(const Myo &myo);
int getGestureCode();
};
// Storage for the recorded code
class Code {
public:
Code(const Code &code);
Code();
int codeType = -1; // The type of code
unsigned long codeValue; // The code value if not raw
unsigned int* rawCodes; // The durations if raw
int codeLen= -1; // The length of the code
int toggle = 0; // The RC5/6 toggle state
~Code();
};
// Represents a remote controlled device such as TV, AC etc
class Device {
int id;
public:
static int superId;
Device();
Device(char* name);
char* name;
Code* gestureCodeMap;
};
// It combines myo and IR tranciever module and represents the final wearable device capable of
// sending and receiving ir signals
class Sceptre {
private:
Device* deviceList;
int activeDeviceIndex = 0;
IRsend irsend;
// int processing_previous_mapping_request = 0;
public:
Code* tempCode;
int tempGestureCode;
Myo myo;
decode_results results;
IRrecv irrecv; // decodes the incoming signal
Sceptre(int recv_pin);
int addDevice(Device device);
Device* getActiveDevice();
int activateDevice(Device* device);
void sendCode(int repeat);
Code* storeCode(decode_results *results); // turns on mapping request and returns the code to be mapped
void saveCurrentMapping();
Code* decodeAndGetCode();
};
void resetMyoDebugPinsCPP(int mode);
#endif
|
nnn1590/spritely | tutorials/add_title/nds/game_state.h | <reponame>nnn1590/spritely
// game_state.h
// Global structure to record all game state.
// This file was automatically generated by Spritely
#ifndef _GAME_STATE_H_
#define _GAME_STATE_H_
#include "sprites.h"
#include "background_maps.h"
// The levels in our game.
const int kLevel_Title = 0;
const int kLevel_1 = 1;
// The objects in our game.
// Only 128 objects (0-127) can be defined at any time.
const int kObj_Player = 0;
// The GameState class holds all of the global game state information.
class GameState {
public:
// Constructor
// This method initializes the game state.
GameState();
// SetupStage
// Set up the stage (backgrounds, sprites) for the each level.
void SetupStage(int level);
void SetupStage_Title();
void SetupStage_Level1();
// Update
// This is called continuously to update the game to the next state.
void Update();
void Update_Title();
void Update_Level1();
private:
// The current level of the game.
int _level;
// The (x,y) location of the object representing the player.
int _xPlayer, _yPlayer;
};
#endif // _GAME_STATE_H_
|
fkuehne/box-ios-sdk-v2 | BoxSDK/Categories/NSJSONSerialization+BoxAdditions.h | //
// NSJSONSerialization+BoxAdditions.h
// BoxSDK
//
// Created on 8/19/13.
// Copyright (c) 2013 Box. All rights reserved.
//
#import <Foundation/Foundation.h>
/**
* The BoxAdditions category on NSJSONSerialization provides a class method for ensuring
* that an object extracted from a decoded JSON object is of the expected type.
*
* This category is used by BoxModel subclasses to extract properties from [BoxModel rawResponseJSON].
*/
@interface NSJSONSerialization (BoxAdditions)
/** @name Reflection helpers */
/**
* Ensure that the object at `key` in `dictionary` is a member of the expected class.
* `NSNull` may be specified as an allowable value. This method may return nil if `key`
* is not present in `dictionary`.
*
* @param key The key to lookup in `dictionary`.
* @param dictionary A dictionary resulting from deserializing a JSON object.
* @param cls The expected class of the value at key.
* @param nullAllowed If true, `NSNull` is an allowable value. Property getters that pass
* `YES` for this parameter should have the return type of `id`.
*
* @return The object at `key` in `dictionary` if expectations are satisfied; `nil` otherwise.
*/
+ (id)box_ensureObjectForKey:(NSString *)key inDictionary:(NSDictionary *)dictionary hasExpectedType:(Class)cls nullAllowed:(BOOL)nullAllowed;
/**
* Ensure that the object at `key` in `dictionary` is a member of the expected class.
* `NSNull` may be converted to nil. This method may return nil if `key`
* is not present in `dictionary`.
*
* @param key The key to lookup in `dictionary`.
* @param dictionary A dictionary resulting from deserializing a JSON object.
* @param cls The expected class of the value at key.
* @param nullAllowed If true, `NSNull` is an allowable value. Property getters that pass
* `YES` for this parameter should have the return type of `id`.
* @param suppressNullAsNil If true and nullAllowed is true, `NSNull` will be converted to `nil`.
*
* @return The object at `key` in `dictionary` if expectations are satisfied; `nil` otherwise.
*/
+ (id)box_ensureObjectForKey:(NSString *)key inDictionary:(NSDictionary *)dictionary hasExpectedType:(Class)cls nullAllowed:(BOOL)nullAllowed suppressNullAsNil:(BOOL)suppressNullAsNil;
@end
|
fkuehne/box-ios-sdk-v2 | BoxSDK/FolderPicker/BoxItemPickerViewController.h | //
// BoxItemPickerViewController.h
// BoxSDK
//
// Created on 5/1/13.
// Copyright (c) 2013 Box Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <BoxSDK/BoxItemPickerTableViewController.h>
#if TARGET_OS_IOS
#import <BoxSDK/BoxAuthorizationViewController.h>
#endif
typedef NS_ENUM(NSUInteger, BoxItemPickerObjectType) {
BoxItemPickerObjectTypeFile,
BoxItemPickerObjectTypeFolder,
BoxItemPickerObjectTypeFileAndFolder
};
@class BoxFolder;
@class BoxFile;
/**
* The BOXItemPickerDelegate protocol allows your application to interact with a
* BoxItemPickerViewController and respond to the user selecting an item from
* their Box account.
*
* The folder picker returns BoxModel objects to your delegate, which you can then
* use to make API calls with the SDK.
*/
@protocol BOXItemPickerDelegate <NSObject>
/**
* The user wants do dismiss the itemPicker
*
* @param controller The controller that was cancelled.
*/
- (void)itemPickerControllerDidCancel:(BoxItemPickerViewController *)controller;
@optional
/**
* The user has selected a file.
* @param controller The BoxItemPickerViewController used.
* @param file The file picked by the user.
*/
- (void)itemPickerController:(BoxItemPickerViewController *)controller didSelectBoxFile:(BoxFile *)file;
/**
* The user has selected a folder.
* @param controller The BoxItemPickerViewController used.
* @param folder The folder picked by the user.
*/
- (void)itemPickerController:(BoxItemPickerViewController *)controller didSelectBoxFolder:(BoxFolder *)folder;
@end
/**
* BoxItemPickerViewController is a UI widget that allows quick and easy integration with Box.
* Displaying a BoxItemPickerViewController provides a file browser and enables users to select
* a file or folder from their Box account.
*
* The BoxItemPickerViewController handles OAuth2 authentication by itself if you do not wish
* to authenticate users independently.
*
* The BoxItemPickerViewController makes extensive use of thumbnail support in the Box V2 API.
* Additionally, it can display assets from the BoxSDKResources bundle and if you wish to use
* the folder picker, you should include this bundle in your app.
*
* Selection events are handled by the BoxFolderPickerDelegate delegate protocol.
*/
#if TARGET_OS_IOS
@interface BoxItemPickerViewController : UIViewController <BoxItemPickerTableViewControllerDelegate, BoxAuthorizationViewControllerDelegate>
#else
@interface BoxItemPickerViewController : UIViewController <BoxItemPickerTableViewControllerDelegate>
#endif
@property (nonatomic, readwrite, weak) id<BOXItemPickerDelegate> delegate;
/**
* Allows you to customize the number of items that will be downloaded in a row.
* Default value in 100.
*/
@property (nonatomic, readwrite, assign) NSUInteger numberOfItemsPerPage;
/**
* The type of item this itemPicker allows the user to select
*/
@property (nonatomic, readwrite, assign) BoxItemPickerObjectType selectableObjectType;
/**
* Initializes an itemPicker according to the caching options provided as parameters. This
* folder picker is bound to one instance of the BoxSDK and thus, one BoxOAuth2Session.
*
* @param sdk The SDK which the folder picker uses to perform API calls.
* @param rootFolderID The root folder where to start browsing.
* @param thumbnailsEnabled Enables/disables thumbnail management. If set to NO, only file icons will be displayed.
* @param cachedThumbnailsPath The absolute path where the user wants to store the cached thumbnails.
* If set to nil, the folder picker will not cache the thumbnails, only download them on the fly.
* @param selectableObjectType The type of item the itemPicker should allow the selection for.
* @return A BoxItemPickerViewController.
*/
- (id)initWithSDK:(BoxSDK *)sdk rootFolderID:(NSString *)rootFolderID thumbnailsEnabled:(BOOL)thumbnailsEnabled cachedThumbnailsPath:(NSString *)cachedThumbnailsPath selectableObjectType:(BoxItemPickerObjectType)selectableObjectType;
/**
* Purges the cache folder specified in the cachedThumbnailsPath parameter of the
* initWithFolderID:enableThumbnails:cachedThumbnailsPath: method.
*/
- (void)purgeCache;
@end
|
Naithar/NHSelectorView | Example/NHSelectionView/NAppDelegate.h | <filename>Example/NHSelectionView/NAppDelegate.h
//
// NAppDelegate.h
// NHSelectionView
//
// Created by Naithar on 10/08/2015.
// Copyright (c) 2015 Naithar. All rights reserved.
//
@import UIKit;
@interface NAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
Naithar/NHSelectorView | Example/NHSelectionView/NViewController.h | //
// NViewController.h
// NHSelectionView
//
// Created by Naithar on 10/08/2015.
// Copyright (c) 2015 Naithar. All rights reserved.
//
@import UIKit;
@interface NViewController : UIViewController
@end
|
Naithar/NHSelectorView | Pod/Classes/NHSelectorView.h | //
// NHSelectorView.h
// Pods
//
// Created by <NAME> on 08.10.15.
//
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, NHSelectorViewSelectionStyle) {
NHSelectorViewSelectionStyleDefault,
NHSelectorViewSelectionStyleLine,
};
NS_ASSUME_NONNULL_BEGIN
@class NHSelectorView;
@protocol NHSelectorViewDelegate <NSObject>
- (void)nhSelectorView:(NHSelectorView *)selectorView didChangeIndexTo:(NSInteger)index;
@end
@interface NHSelectorView : UIView
@property (nonatomic, assign) BOOL shouldReset;
@property (nonatomic, weak) id<NHSelectorViewDelegate> delegate;
@property (nonatomic, assign) CGSize selectionSize;
@property (nonatomic, strong, readonly) UIView *selectionView;
@property (nonatomic, strong, readonly) UIView *separatorView;
@property (nonatomic, strong, null_resettable) UIFont *font;
@property (nonatomic, assign, readonly) NSInteger selectedIndex;
@property (nonatomic, assign) NHSelectorViewSelectionStyle selectionStyle;
- (void)setItems:(nullable NSArray *)items;
- (void)setColor:(UIColor *)color forState:(UIControlState)state;
- (void)setSelectedIndex:(NSInteger)selectedIndex animated:(BOOL)animated;
@end
NS_ASSUME_NONNULL_END
|
qimin/pymatgen | dependencies/spglib-1.3.1/src/spglib.c | <filename>dependencies/spglib-1.3.1/src/spglib.c
/* spglib.c */
/* Copyright (C) 2008 <NAME> */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "spglib.h"
#include "refinement.h"
#include "cell.h"
#include "lattice.h"
#include "mathfunc.h"
#include "pointgroup.h"
#include "primitive.h"
#include "spacegroup.h"
#include "symmetry.h"
#include "kpoint.h"
#include "spin.h"
static SpglibDataset * get_dataset(SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec);
static int get_symmetry(int rotation[][3][3],
double translation[][3],
const int max_size,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec);
static int get_symmetry_with_collinear_spin(int rotation[][3][3],
double translation[][3],
const int max_size,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const double spins[],
const int num_atom,
const double symprec);
static int get_multiplicity(SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec);
static int find_primitive(double lattice[3][3],
double position[][3],
int types[],
const int num_atom,
const double symprec);
static int get_international(char symbol[11],
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec);
static int get_schoenflies(char symbol[7],
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[], const int num_atom,
const double symprec);
static int refine_cell(double lattice[3][3],
double position[][3],
int types[],
const int num_atom,
const double symprec);
static int get_ir_kpoints(int map[],
SPGCONST double kpoints[][3],
const int num_kpoint,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const int is_time_reversal,
const double symprec);
static int get_ir_reciprocal_mesh(int grid_point[][3],
int map[],
const int mesh[3],
const int is_shift[3],
const int is_time_reversal,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec);
static int get_stabilized_reciprocal_mesh(int grid_point[][3],
int map[],
const int mesh[3],
const int is_shift[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3],
const int num_q,
SPGCONST double qpoints[][3],
const double symprec);
static SpglibTriplets * get_triplets_reciprocal_mesh(const int mesh[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3],
const double symprec);
static int get_triplets_reciprocal_mesh_at_q(int weights[],
int grid_points[][3],
int third_q[],
const int grid_point,
const int mesh[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3],
const double symprec);
static int extract_triplets_reciprocal_mesh_at_q(int triplets_at_q[][3],
int weight_triplets_at_q[],
const int fixed_grid_number,
const int num_triplets,
SPGCONST int triplets[][3],
const int mesh[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3]);
SpglibDataset * spg_get_dataset(SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec)
{
sym_set_angle_tolerance(-1.0);
return get_dataset(lattice,
position,
types,
num_atom,
symprec);
}
SpglibDataset * spgat_get_dataset(SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec,
const double angle_tolerance)
{
sym_set_angle_tolerance(angle_tolerance);
return get_dataset(lattice,
position,
types,
num_atom,
symprec);
}
void spg_free_dataset(SpglibDataset *dataset)
{
if (dataset->n_operations > 0) {
free(dataset->rotations);
dataset->rotations = NULL;
free(dataset->translations);
dataset->translations = NULL;
}
if (! (dataset->wyckoffs == NULL)) {
free(dataset->wyckoffs);
dataset->wyckoffs = NULL;
}
if (! (dataset->equivalent_atoms == NULL)) {
free(dataset->equivalent_atoms);
dataset->equivalent_atoms = NULL;
}
free(dataset);
dataset = NULL;
}
int spg_get_symmetry(int rotation[][3][3],
double translation[][3],
const int max_size,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec)
{
sym_set_angle_tolerance(-1.0);
return get_symmetry(rotation,
translation,
max_size,
lattice,
position,
types,
num_atom,
symprec);
}
int spgat_get_symmetry(int rotation[][3][3],
double translation[][3],
const int max_size,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec,
const double angle_tolerance)
{
sym_set_angle_tolerance(angle_tolerance);
return get_symmetry(rotation,
translation,
max_size,
lattice,
position,
types,
num_atom,
symprec);
}
int spg_get_symmetry_with_collinear_spin(int rotation[][3][3],
double translation[][3],
const int max_size,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const double spins[],
const int num_atom,
const double symprec)
{
sym_set_angle_tolerance(-1.0);
return get_symmetry_with_collinear_spin(rotation,
translation,
max_size,
lattice,
position,
types,
spins,
num_atom,
symprec);
}
int spgat_get_symmetry_with_collinear_spin(int rotation[][3][3],
double translation[][3],
const int max_size,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const double spins[],
const int num_atom,
const double symprec,
const double angle_tolerance)
{
sym_set_angle_tolerance(angle_tolerance);
return get_symmetry_with_collinear_spin(rotation,
translation,
max_size,
lattice,
position,
types,
spins,
num_atom,
symprec);
}
int spg_get_multiplicity(SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec)
{
sym_set_angle_tolerance(-1.0);
return get_multiplicity(lattice,
position,
types,
num_atom,
symprec);
}
int spgat_get_multiplicity(SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec,
const double angle_tolerance)
{
sym_set_angle_tolerance(angle_tolerance);
return get_multiplicity(lattice,
position,
types,
num_atom,
symprec);
}
int spg_get_smallest_lattice(double smallest_lattice[3][3],
SPGCONST double lattice[3][3],
const double symprec)
{
return lat_smallest_lattice_vector(smallest_lattice, lattice, symprec);
}
int spg_find_primitive(double lattice[3][3],
double position[][3],
int types[],
const int num_atom,
const double symprec)
{
sym_set_angle_tolerance(-1.0);
return find_primitive(lattice,
position,
types,
num_atom,
symprec);
}
int spgat_find_primitive(double lattice[3][3],
double position[][3],
int types[],
const int num_atom,
const double symprec,
const double angle_tolerance)
{
sym_set_angle_tolerance(angle_tolerance);
return find_primitive(lattice,
position,
types,
num_atom,
symprec);
}
int spg_get_international(char symbol[11],
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec)
{
sym_set_angle_tolerance(-1.0);
return get_international(symbol,
lattice,
position,
types,
num_atom,
symprec);
}
int spgat_get_international(char symbol[11],
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec,
const double angle_tolerance)
{
sym_set_angle_tolerance(angle_tolerance);
return get_international(symbol,
lattice,
position,
types,
num_atom,
symprec);
}
int spg_get_schoenflies(char symbol[7],
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec)
{
sym_set_angle_tolerance(-1.0);
return get_schoenflies(symbol,
lattice,
position,
types,
num_atom,
symprec);
}
int spgat_get_schoenflies(char symbol[7],
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec,
const double angle_tolerance)
{
sym_set_angle_tolerance(angle_tolerance);
return get_schoenflies(symbol,
lattice,
position,
types,
num_atom,
symprec);
}
int spg_get_pointgroup(char symbol[6],
int trans_mat[3][3],
SPGCONST int rotations[][3][3],
const int num_rotations)
{
int ptg_num;
double tmp_trans_mat[3][3];
Pointgroup ptgroup;
ptg_num = ptg_get_pointgroup_number_by_rotations(rotations,
num_rotations);
ptgroup = ptg_get_pointgroup(ptg_num);
strcpy(symbol, ptgroup.symbol);
ptg_get_transformation_matrix(tmp_trans_mat,
rotations,
num_rotations);
mat_cast_matrix_3d_to_3i(trans_mat, tmp_trans_mat);
return ptg_num + 1;
}
int spg_refine_cell(double lattice[3][3],
double position[][3],
int types[],
const int num_atom,
const double symprec)
{
sym_set_angle_tolerance(-1.0);
return refine_cell(lattice,
position,
types,
num_atom,
symprec);
}
int spgat_refine_cell(double lattice[3][3],
double position[][3],
int types[],
const int num_atom,
const double symprec,
const double angle_tolerance)
{
sym_set_angle_tolerance(angle_tolerance);
return refine_cell(lattice,
position,
types,
num_atom,
symprec);
}
int spg_get_ir_kpoints(int map[],
SPGCONST double kpoints[][3],
const int num_kpoint,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const int is_time_reversal,
const double symprec)
{
sym_set_angle_tolerance(-1.0);
return get_ir_kpoints(map,
kpoints,
num_kpoint,
lattice,
position,
types,
num_atom,
is_time_reversal,
symprec);
}
int spg_get_ir_reciprocal_mesh(int grid_point[][3],
int map[],
const int mesh[3],
const int is_shift[3],
const int is_time_reversal,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec)
{
sym_set_angle_tolerance(-1.0);
return get_ir_reciprocal_mesh(grid_point,
map,
mesh,
is_shift,
is_time_reversal,
lattice,
position,
types,
num_atom,
symprec);
}
int spg_get_stabilized_reciprocal_mesh(int grid_point[][3],
int map[],
const int mesh[3],
const int is_shift[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3],
const int num_q,
SPGCONST double qpoints[][3],
const double symprec)
{
return get_stabilized_reciprocal_mesh(grid_point,
map,
mesh,
is_shift,
is_time_reversal,
num_rot,
rotations,
num_q,
qpoints,
symprec);
}
SpglibTriplets * spg_get_triplets_reciprocal_mesh(const int mesh[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3],
const double symprec)
{
return get_triplets_reciprocal_mesh(mesh,
is_time_reversal,
num_rot,
rotations,
symprec);
}
void spg_free_triplets(SpglibTriplets * spg_triplets)
{
free(spg_triplets->triplets);
spg_triplets->triplets = NULL;
free(spg_triplets->weights);
spg_triplets->weights = NULL;
free(spg_triplets);
free(spg_triplets->mesh_points);
spg_triplets->mesh_points = NULL;
spg_triplets = NULL;
}
int spg_get_triplets_reciprocal_mesh_at_q(int weights[],
int grid_points[][3],
int third_q[],
const int grid_point,
const int mesh[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3],
const double symprec)
{
return get_triplets_reciprocal_mesh_at_q(weights,
grid_points,
third_q,
grid_point,
mesh,
is_time_reversal,
num_rot,
rotations,
symprec);
}
int spg_extract_triplets_reciprocal_mesh_at_q(int triplets_at_q[][3],
int weight_triplets_at_q[],
const int fixed_grid_number,
const int num_triplets,
SPGCONST int triplets[][3],
const int mesh[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3])
{
return extract_triplets_reciprocal_mesh_at_q(triplets_at_q,
weight_triplets_at_q,
fixed_grid_number,
num_triplets,
triplets,
mesh,
is_time_reversal,
num_rot,
rotations);
}
static SpglibDataset * get_dataset(SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec)
{
int i, j;
int *mapping_table, *wyckoffs, *equiv_atoms, *equiv_atoms_prim;
double tolerance;
Spacegroup spacegroup;
SpglibDataset *dataset;
Cell *cell, *primitive;
double inv_mat[3][3];
Symmetry *symmetry;
dataset = (SpglibDataset*) malloc(sizeof(SpglibDataset));
cell = cel_alloc_cell(num_atom);
cel_set_cell(cell, lattice, position, types);
mapping_table = (int*) malloc(sizeof(int) * cell->size);
primitive = prm_get_primitive_with_mapping_table(mapping_table,
cell,
symprec);
tolerance = prm_get_current_tolerance();
spacegroup = spa_get_spacegroup_with_primitive(primitive, tolerance);
if (spacegroup.number > 0) {
/* Spacegroup type, transformation matrix, origin shift */
dataset->spacegroup_number = spacegroup.number;
dataset->hall_number = spacegroup.hall_number;
strcpy(dataset->international_symbol, spacegroup.international_short);
strcpy(dataset->hall_symbol, spacegroup.hall_symbol);
mat_inverse_matrix_d3(inv_mat, lattice, tolerance);
mat_multiply_matrix_d3(dataset->transformation_matrix,
inv_mat,
spacegroup.bravais_lattice);
mat_copy_vector_d3(dataset->origin_shift, spacegroup.origin_shift);
/* Wyckoff positions */
wyckoffs = (int*) malloc(sizeof(int) * primitive->size);
equiv_atoms_prim = (int*) malloc(sizeof(int) * primitive->size);
for (i = 0; i < primitive->size; i++) {
wyckoffs[i] = -1;
equiv_atoms_prim[i] = -1;
}
ref_get_Wyckoff_positions(wyckoffs,
equiv_atoms_prim,
primitive,
&spacegroup,
tolerance);
dataset->n_atoms = cell->size;
dataset->wyckoffs = (int*) malloc(sizeof(int) * cell->size);
for (i = 0; i < cell->size; i++) {
dataset->wyckoffs[i] = wyckoffs[mapping_table[i]];
}
free(wyckoffs);
wyckoffs = NULL;
/* Equivalent atoms */
dataset->equivalent_atoms = (int*) malloc(sizeof(int) * cell->size);
equiv_atoms = (int*) malloc(sizeof(int) * primitive->size);
for (i = 0; i < primitive->size; i++) {
for (j = 0; j < cell->size; j++) {
if (mapping_table[j] == equiv_atoms_prim[i]) {
equiv_atoms[i] = j;
break;
}
}
}
for (i = 0; i < cell->size; i++) {
dataset->equivalent_atoms[i] = equiv_atoms[mapping_table[i]];
}
free(equiv_atoms);
equiv_atoms = NULL;
free(equiv_atoms_prim);
equiv_atoms_prim = NULL;
/* Symmetry operations */
symmetry = ref_get_refined_symmetry_operations(cell,
primitive,
&spacegroup,
tolerance);
dataset->rotations = (int (*)[3][3]) malloc(sizeof(int[3][3]) * symmetry->size);
dataset->translations = (double (*)[3]) malloc(sizeof(double[3]) * symmetry->size);
dataset->n_operations = symmetry->size;
for (i = 0; i < symmetry->size; i++) {
mat_copy_matrix_i3(dataset->rotations[i], symmetry->rot[i]);
mat_copy_vector_d3(dataset->translations[i], symmetry->trans[i]);
}
sym_free_symmetry(symmetry);
} else {
dataset->spacegroup_number = 0;
}
free(mapping_table);
mapping_table = NULL;
cel_free_cell(primitive);
if (dataset->spacegroup_number == 0) {
strcpy(dataset->international_symbol, "");
strcpy(dataset->hall_symbol, "");
dataset->origin_shift[0] = 0;
dataset->origin_shift[1] = 0;
dataset->origin_shift[2] = 0;
dataset->n_atoms = 0;
dataset->wyckoffs = NULL;
dataset->equivalent_atoms = NULL;
dataset->n_operations = 0;
dataset->rotations = NULL;
dataset->translations = NULL;
}
cel_free_cell(cell);
return dataset;
}
static int get_symmetry(int rotation[][3][3],
double translation[][3],
const int max_size,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec)
{
int i, j, size;
Symmetry *symmetry;
Cell *cell;
cell = cel_alloc_cell(num_atom);
cel_set_cell(cell, lattice, position, types);
symmetry = sym_get_operation(cell, symprec);
if (symmetry->size > max_size) {
fprintf(stderr, "spglib: Indicated max size(=%d) is less than number ", max_size);
fprintf(stderr, "spglib: of symmetry operations(=%d).\n", symmetry->size);
sym_free_symmetry(symmetry);
return 0;
}
for (i = 0; i < symmetry->size; i++) {
mat_copy_matrix_i3(rotation[i], symmetry->rot[i]);
for (j = 0; j < 3; j++) {
translation[i][j] = symmetry->trans[i][j];
}
}
size = symmetry->size;
cel_free_cell(cell);
sym_free_symmetry(symmetry);
return size;
}
static int get_symmetry_with_collinear_spin(int rotation[][3][3],
double translation[][3],
const int max_size,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const double spins[],
const int num_atom,
const double symprec)
{
int i, j, size;
Symmetry *symmetry;
Cell *cell;
cell = cel_alloc_cell(num_atom);
cel_set_cell(cell, lattice, position, types);
symmetry = spn_get_collinear_operation(cell, spins, symprec);
if (symmetry->size > max_size) {
fprintf(stderr, "spglib: Indicated max size(=%d) is less than number ", max_size);
fprintf(stderr, "spglib: of symmetry operations(=%d).\n", symmetry->size);
sym_free_symmetry(symmetry);
return 0;
}
for (i = 0; i < symmetry->size; i++) {
mat_copy_matrix_i3(rotation[i], symmetry->rot[i]);
for (j = 0; j < 3; j++) {
translation[i][j] = symmetry->trans[i][j];
}
}
size = symmetry->size;
cel_free_cell(cell);
sym_free_symmetry(symmetry);
return size;
}
static int get_multiplicity(SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec)
{
Symmetry *symmetry;
Cell *cell;
int size;
cell = cel_alloc_cell(num_atom);
cel_set_cell(cell, lattice, position, types);
symmetry = sym_get_operation(cell, symprec);
size = symmetry->size;
cel_free_cell(cell);
sym_free_symmetry(symmetry);
return size;
}
static int find_primitive(double lattice[3][3],
double position[][3],
int types[],
const int num_atom,
const double symprec)
{
int i, j, num_prim_atom=0;
Cell *cell, *primitive;
cell = cel_alloc_cell(num_atom);
cel_set_cell(cell, lattice, position, types);
/* find primitive cell */
primitive = prm_get_primitive(cell, symprec);
if (primitive->size == cell->size) { /* Already primitive */
num_prim_atom = 0;
} else { /* Primitive cell was found. */
num_prim_atom = primitive->size;
if (num_prim_atom < num_atom && num_prim_atom > 0 ) {
mat_copy_matrix_d3(lattice, primitive->lattice);
for (i = 0; i < primitive->size; i++) {
types[i] = primitive->types[i];
for (j=0; j<3; j++) {
position[i][j] = primitive->position[i][j];
}
}
}
}
cel_free_cell(primitive);
cel_free_cell(cell);
return num_prim_atom;
}
static int get_international(char symbol[11],
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec)
{
Cell *cell;
Spacegroup spacegroup;
cell = cel_alloc_cell(num_atom);
cel_set_cell(cell, lattice, position, types);
spacegroup = spa_get_spacegroup(cell, symprec);
if (spacegroup.number > 0) {
strcpy(symbol, spacegroup.international_short);
}
cel_free_cell(cell);
return spacegroup.number;
}
static int get_schoenflies(char symbol[7],
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec)
{
Cell *cell;
Spacegroup spacegroup;
cell = cel_alloc_cell(num_atom);
cel_set_cell(cell, lattice, position, types);
spacegroup = spa_get_spacegroup(cell, symprec);
if (spacegroup.number > 0) {
strcpy(symbol, spacegroup.schoenflies);
}
cel_free_cell(cell);
return spacegroup.number;
}
static int refine_cell(double lattice[3][3],
double position[][3],
int types[],
const int num_atom,
const double symprec)
{
int i, num_atom_bravais;
Cell *cell, *bravais;
cell = cel_alloc_cell(num_atom);
cel_set_cell(cell, lattice, position, types);
bravais = ref_refine_cell(cell, symprec);
cel_free_cell(cell);
if (bravais->size > 0) {
mat_copy_matrix_d3(lattice, bravais->lattice);
num_atom_bravais = bravais->size;
for (i = 0; i < bravais->size; i++) {
types[i] = bravais->types[i];
mat_copy_vector_d3(position[i], bravais->position[i]);
}
} else {
num_atom_bravais = 0;
}
cel_free_cell(bravais);
return num_atom_bravais;
}
static int get_ir_kpoints(int map[],
SPGCONST double kpoints[][3],
const int num_kpoint,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const int is_time_reversal,
const double symprec)
{
Symmetry *symmetry;
Cell *cell;
int num_ir_kpoint;
cell = cel_alloc_cell(num_atom);
cel_set_cell(cell, lattice, position, types);
symmetry = sym_get_operation(cell, symprec);
num_ir_kpoint = kpt_get_irreducible_kpoints(map,
kpoints,
num_kpoint,
symmetry,
is_time_reversal,
symprec);
cel_free_cell(cell);
sym_free_symmetry(symmetry);
return num_ir_kpoint;
}
static int get_ir_reciprocal_mesh(int grid_point[][3],
int map[],
const int mesh[3],
const int is_shift[3],
const int is_time_reversal,
SPGCONST double lattice[3][3],
SPGCONST double position[][3],
const int types[],
const int num_atom,
const double symprec)
{
Symmetry *symmetry;
Cell *cell;
int num_ir;
cell = cel_alloc_cell(num_atom);
cel_set_cell(cell, lattice, position, types);
symmetry = sym_get_operation(cell, symprec);
num_ir = kpt_get_irreducible_reciprocal_mesh(grid_point,
map,
mesh,
is_shift,
is_time_reversal,
symmetry);
cel_free_cell(cell);
sym_free_symmetry(symmetry);
return num_ir;
}
static int get_stabilized_reciprocal_mesh(int grid_point[][3],
int map[],
const int mesh[3],
const int is_shift[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3],
const int num_q,
SPGCONST double qpoints[][3],
const double symprec)
{
MatINT *rot_real;
int i, num_ir;
rot_real = mat_alloc_MatINT(num_rot);
for (i = 0; i < num_rot; i++) {
mat_copy_matrix_i3(rot_real->mat[i], rotations[i]);
}
num_ir = kpt_get_stabilized_reciprocal_mesh(grid_point,
map,
mesh,
is_shift,
is_time_reversal,
rot_real,
num_q,
qpoints,
symprec);
mat_free_MatINT(rot_real);
return num_ir;
}
static SpglibTriplets * get_triplets_reciprocal_mesh(const int mesh[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3],
const double symprec)
{
int i, j, num_grid;
MatINT *rot_real;
Triplets *tps;
SpglibTriplets *spg_triplets;
num_grid = mesh[0] * mesh[1] * mesh[2];
rot_real = mat_alloc_MatINT(num_rot);
for (i = 0; i < num_rot; i++) {
mat_copy_matrix_i3(rot_real->mat[i], rotations[i]);
}
tps = kpt_get_triplets_reciprocal_mesh(mesh,
is_time_reversal,
rot_real,
symprec);
mat_free_MatINT(rot_real);
spg_triplets = (SpglibTriplets*) malloc(sizeof(SpglibTriplets));
spg_triplets->size = tps->size;
spg_triplets->triplets = (int (*)[3]) malloc(sizeof(int[3]) * tps->size);
spg_triplets->weights = (int*) malloc(sizeof(int) * tps->size);
spg_triplets->mesh_points = (int (*)[3]) malloc(sizeof(int[3]) * num_grid);
for (i = 0; i < 3; i++) {
spg_triplets->mesh[i] = tps->mesh[i];
}
for (i = 0; i < num_grid; i++) {
for (j = 0; j < 3; j++) {
spg_triplets->mesh_points[i][j] = tps->mesh_points[i][j];
}
}
for (i = 0; i < tps->size; i++) {
for (j = 0; j < 3; j++) {
spg_triplets->triplets[i][j] = tps->triplets[i][j];
}
spg_triplets->weights[i] = tps->weights[i];
}
kpt_free_triplets(tps);
return spg_triplets;
}
static int get_triplets_reciprocal_mesh_at_q(int weights[],
int grid_points[][3],
int third_q[],
const int grid_point,
const int mesh[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3],
const double symprec)
{
MatINT *rot_real;
int i, num_ir;
rot_real = mat_alloc_MatINT(num_rot);
for (i = 0; i < num_rot; i++) {
mat_copy_matrix_i3(rot_real->mat[i], rotations[i]);
}
num_ir = kpt_get_ir_triplets_at_q(weights,
grid_points,
third_q,
grid_point,
mesh,
is_time_reversal,
rot_real,
symprec);
mat_free_MatINT(rot_real);
return num_ir;
}
static int extract_triplets_reciprocal_mesh_at_q(int triplets_at_q[][3],
int weight_triplets_at_q[],
const int fixed_grid_number,
const int num_triplets,
SPGCONST int triplets[][3],
const int mesh[3],
const int is_time_reversal,
const int num_rot,
SPGCONST int rotations[][3][3])
{
MatINT *rot_real;
int i, num_ir;
rot_real = mat_alloc_MatINT(num_rot);
for (i = 0; i < num_rot; i++) {
mat_copy_matrix_i3(rot_real->mat[i], rotations[i]);
}
num_ir = kpt_extract_triplets_reciprocal_mesh_at_q(triplets_at_q,
weight_triplets_at_q,
fixed_grid_number,
num_triplets,
triplets,
mesh,
is_time_reversal,
rot_real);
mat_free_MatINT(rot_real);
return num_ir;
}
|
sergak01/binary-parser | main.h | #include <node.h>
#include <node_buffer.h>
#include <node_object_wrap.h>
#include <algorithm>
#include <bitset>
#include <chrono>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using v8::Array;
using v8::ArrayBuffer;
using v8::Context;
using v8::Exception;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::MaybeLocal;
using v8::Name;
using v8::NewStringType;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;
struct BytesOrder {
int startPos;
int count;
int newPos;
bool operator<(const BytesOrder& i) {
return newPos < i.newPos;
}
};
struct ValueParser {
std::string type;
std::string name;
int bitsCount;
std::vector<BytesOrder> reOrder;
};
struct parseResult {
std::string name;
unsigned long value;
};
typedef enum UIntLength { _8 = 8, _16 = 16, _32 = 32 } IntLength;
#ifndef MAIN_H
#define MAIN_H
class BinaryParser : public node::ObjectWrap {
private:
explicit BinaryParser();
~BinaryParser();
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ParseBits(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ParseASCII(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ParseUTF8(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ParseInt(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ParseInt8(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ParseInt16(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ParseInt(const v8::FunctionCallbackInfo<v8::Value>& args, IntLength length);
static void ParseFloat(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ParseUInt(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ParseUInt8(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ParseUInt16(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ParseUInt(const v8::FunctionCallbackInfo<v8::Value>& args, UIntLength length);
static void BitsBack(const v8::FunctionCallbackInfo<v8::Value>& args);
static void BitsSkip(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Parse(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Persistent<v8::Function> constructor;
std::vector<ValueParser> parser_;
public:
static void Init(v8::Local<v8::Object> exports);
};
#endif |
lingxiao/good-great-excellent | .stack-work/dist/x86_64-osx/Cabal-1.22.5.0/build/autogen/cabal_macros.h | <gh_stars>1-10
/* DO NOT EDIT: This file is automatically generated by Cabal */
/* package HUnit-1.3.1.1 */
#define VERSION_HUnit "1.3.1.1"
#define MIN_VERSION_HUnit(major1,major2,minor) (\
(major1) < 1 || \
(major1) == 1 && (major2) < 3 || \
(major1) == 1 && (major2) == 3 && (minor) <= 1)
/* package attoparsec-0.13.0.2 */
#define VERSION_attoparsec "0.13.0.2"
#define MIN_VERSION_attoparsec(major1,major2,minor) (\
(major1) < 0 || \
(major1) == 0 && (major2) < 13 || \
(major1) == 0 && (major2) == 13 && (minor) <= 0)
/* package base-4.8.2.0 */
#define VERSION_base "4.8.2.0"
#define MIN_VERSION_base(major1,major2,minor) (\
(major1) < 4 || \
(major1) == 4 && (major2) < 8 || \
(major1) == 4 && (major2) == 8 && (minor) <= 2)
/* package bytestring-0.10.6.0 */
#define VERSION_bytestring "0.10.6.0"
#define MIN_VERSION_bytestring(major1,major2,minor) (\
(major1) < 0 || \
(major1) == 0 && (major2) < 10 || \
(major1) == 0 && (major2) == 10 && (minor) <= 6)
/* package conduit-1.2.7 */
#define VERSION_conduit "1.2.7"
#define MIN_VERSION_conduit(major1,major2,minor) (\
(major1) < 1 || \
(major1) == 1 && (major2) < 2 || \
(major1) == 1 && (major2) == 2 && (minor) <= 7)
/* package conduit-combinators-1.0.4 */
#define VERSION_conduit_combinators "1.0.4"
#define MIN_VERSION_conduit_combinators(major1,major2,minor) (\
(major1) < 1 || \
(major1) == 1 && (major2) < 0 || \
(major1) == 1 && (major2) == 0 && (minor) <= 4)
/* package conduit-extra-1.1.13.2 */
#define VERSION_conduit_extra "1.1.13.2"
#define MIN_VERSION_conduit_extra(major1,major2,minor) (\
(major1) < 1 || \
(major1) == 1 && (major2) < 1 || \
(major1) == 1 && (major2) == 1 && (minor) <= 13)
/* package containers-0.5.6.2 */
#define VERSION_containers "0.5.6.2"
#define MIN_VERSION_containers(major1,major2,minor) (\
(major1) < 0 || \
(major1) == 0 && (major2) < 5 || \
(major1) == 0 && (major2) == 5 && (minor) <= 6)
/* package directory-1.2.2.0 */
#define VERSION_directory "1.2.2.0"
#define MIN_VERSION_directory(major1,major2,minor) (\
(major1) < 1 || \
(major1) == 1 && (major2) < 2 || \
(major1) == 1 && (major2) == 2 && (minor) <= 2)
/* package filepath-1.4.0.0 */
#define VERSION_filepath "1.4.0.0"
#define MIN_VERSION_filepath(major1,major2,minor) (\
(major1) < 1 || \
(major1) == 1 && (major2) < 4 || \
(major1) == 1 && (major2) == 4 && (minor) <= 0)
/* package mtl-2.2.1 */
#define VERSION_mtl "2.2.1"
#define MIN_VERSION_mtl(major1,major2,minor) (\
(major1) < 2 || \
(major1) == 2 && (major2) < 2 || \
(major1) == 2 && (major2) == 2 && (minor) <= 1)
/* package resourcet-1.1.7.5 */
#define VERSION_resourcet "1.1.7.5"
#define MIN_VERSION_resourcet(major1,major2,minor) (\
(major1) < 1 || \
(major1) == 1 && (major2) < 1 || \
(major1) == 1 && (major2) == 1 && (minor) <= 7)
/* package split-0.2.3.1 */
#define VERSION_split "0.2.3.1"
#define MIN_VERSION_split(major1,major2,minor) (\
(major1) < 0 || \
(major1) == 0 && (major2) < 2 || \
(major1) == 0 && (major2) == 2 && (minor) <= 3)
/* package text-1.2.2.1 */
#define VERSION_text "1.2.2.1"
#define MIN_VERSION_text(major1,major2,minor) (\
(major1) < 1 || \
(major1) == 1 && (major2) < 2 || \
(major1) == 1 && (major2) == 2 && (minor) <= 2)
/* package zlib-0.6.1.1 */
#define VERSION_zlib "0.6.1.1"
#define MIN_VERSION_zlib(major1,major2,minor) (\
(major1) < 0 || \
(major1) == 0 && (major2) < 6 || \
(major1) == 0 && (major2) == 6 && (minor) <= 1)
/* package time-1.5.0.1 */
#define VERSION_time "1.5.0.1"
#define MIN_VERSION_time(major1,major2,minor) (\
(major1) < 1 || \
(major1) == 1 && (major2) < 5 || \
(major1) == 1 && (major2) == 5 && (minor) <= 0)
/* package transformers-0.4.2.0 */
#define VERSION_transformers "0.4.2.0"
#define MIN_VERSION_transformers(major1,major2,minor) (\
(major1) < 0 || \
(major1) == 0 && (major2) < 4 || \
(major1) == 0 && (major2) == 4 && (minor) <= 2)
/* tool alex-3.1.4 */
#define TOOL_VERSION_alex "3.1.4"
#define MIN_TOOL_VERSION_alex(major1,major2,minor) (\
(major1) < 3 || \
(major1) == 3 && (major2) < 1 || \
(major1) == 3 && (major2) == 1 && (minor) <= 4)
/* tool cpphs-1.19.2 */
#define TOOL_VERSION_cpphs "1.19.2"
#define MIN_TOOL_VERSION_cpphs(major1,major2,minor) (\
(major1) < 1 || \
(major1) == 1 && (major2) < 19 || \
(major1) == 1 && (major2) == 19 && (minor) <= 2)
/* tool gcc-4.2.1 */
#define TOOL_VERSION_gcc "4.2.1"
#define MIN_TOOL_VERSION_gcc(major1,major2,minor) (\
(major1) < 4 || \
(major1) == 4 && (major2) < 2 || \
(major1) == 4 && (major2) == 2 && (minor) <= 1)
/* tool ghc-7.10.3 */
#define TOOL_VERSION_ghc "7.10.3"
#define MIN_TOOL_VERSION_ghc(major1,major2,minor) (\
(major1) < 7 || \
(major1) == 7 && (major2) < 10 || \
(major1) == 7 && (major2) == 10 && (minor) <= 3)
/* tool ghc-pkg-7.10.3 */
#define TOOL_VERSION_ghc_pkg "7.10.3"
#define MIN_TOOL_VERSION_ghc_pkg(major1,major2,minor) (\
(major1) < 7 || \
(major1) == 7 && (major2) < 10 || \
(major1) == 7 && (major2) == 10 && (minor) <= 3)
/* tool haddock-2.16.1 */
#define TOOL_VERSION_haddock "2.16.1"
#define MIN_TOOL_VERSION_haddock(major1,major2,minor) (\
(major1) < 2 || \
(major1) == 2 && (major2) < 16 || \
(major1) == 2 && (major2) == 16 && (minor) <= 1)
/* tool happy-1.19.5 */
#define TOOL_VERSION_happy "1.19.5"
#define MIN_TOOL_VERSION_happy(major1,major2,minor) (\
(major1) < 1 || \
(major1) == 1 && (major2) < 19 || \
(major1) == 1 && (major2) == 19 && (minor) <= 5)
/* tool hpc-0.67 */
#define TOOL_VERSION_hpc "0.67"
#define MIN_TOOL_VERSION_hpc(major1,major2,minor) (\
(major1) < 0 || \
(major1) == 0 && (major2) < 67 || \
(major1) == 0 && (major2) == 67 && (minor) <= 0)
/* tool hsc2hs-0.67 */
#define TOOL_VERSION_hsc2hs "0.67"
#define MIN_TOOL_VERSION_hsc2hs(major1,major2,minor) (\
(major1) < 0 || \
(major1) == 0 && (major2) < 67 || \
(major1) == 0 && (major2) == 67 && (minor) <= 0)
/* tool hscolour-1.22 */
#define TOOL_VERSION_hscolour "1.22"
#define MIN_TOOL_VERSION_hscolour(major1,major2,minor) (\
(major1) < 1 || \
(major1) == 1 && (major2) < 22 || \
(major1) == 1 && (major2) == 22 && (minor) <= 0)
/* tool pkg-config-0.28 */
#define TOOL_VERSION_pkg_config "0.28"
#define MIN_TOOL_VERSION_pkg_config(major1,major2,minor) (\
(major1) < 0 || \
(major1) == 0 && (major2) < 28 || \
(major1) == 0 && (major2) == 28 && (minor) <= 0)
#define CURRENT_PACKAGE_KEY "goodg_7yTcpPp20HH7TrsrNkfgsn"
|
vanessavvp/DAA-pr8-maximum-diversity-problem | include/element.h | <gh_stars>1-10
/**
* PROJECT HEADER
* @file element.h
* @author: <NAME>
* Contact: <EMAIL>
* @date: 02/05/2021
* Subject: Diseño y Análisis de Algoritmos
* Practice: Numberº8
* Purpose: Maximum Diversity Problem
*/
#ifndef ELEMENT_H
#define ELEMENT_H
#include <iostream>
#include <vector>
#pragma once
class Element {
public:
Element() {};
Element(int dimensionK);
~Element() {};
std::vector<double> getCoordinates() const;
int getDimensionK() const;
double getCoordinate(int index);
void addCoordinate(double newCoordinate);
std::string printFile();
void print();
double& operator[](int index);
bool operator==(const Element& element) const;
private:
std::vector<double> coordinates_;
int dimensionK_;
};
#endif // !ELEMENT_H |
vanessavvp/DAA-pr8-maximum-diversity-problem | include/interChange.h | /**
* PROJECT HEADER
* @input interChange.h
* @author: <NAME>
* Contact: <EMAIL>
* @date: 02/05/2021
* Subject: Diseño y Análisis de Algoritmos
* Practice: Numberº8
* Purpose: Maximum Diversity Problem
*/
#ifndef INTER_CHANGE_H
#define INTER_CHANGE_H
#include "./solution.h"
#include "./localSearch.h"
#pragma once
class InterChange : public LocalSearch {
public:
InterChange() {}
~InterChange() {}
std::vector<Solution> generateNeighbours(Solution generatedSolution, std::vector<Element> initialX);
};
#endif // !INTER_CHANGE_H |
vanessavvp/DAA-pr8-maximum-diversity-problem | include/problem.h | /**
* PROJECT HEADER
* @file problem.h
* @author: <NAME>
* Contact: <EMAIL>
* @date: 02/05/2021
* Subject: Diseño y Análisis de Algoritmos
* Practice: Numberº8
* Purpose: Maximum Diversity Problem
*/
#ifndef PROBLEM_H
#define PROBLEM_H
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstring>
#include <iomanip>
#include <locale>
#include <cmath>
#include "./element.h"
#include "./solution.h"
#include "./algorithm.h"
#pragma once
class Algorithm;
class Problem {
public:
Problem(){};
Problem(std::string& inputFileName);
~Problem() {};
int getNumberOfElementsN();
int getDimensionK();
std::vector<Element> getInitialX();
Solution getSolution();
void setAlgorithm(Algorithm* algorithm);
double getEuclideanDistance(Element first, Element second);
void execute(int solutionSizeM);
void readFile(std::string& inputFileName);
void printInitialX();
void printSolution();
private:
int numberOfElementsN_;
int dimensionK_;
std::vector<Element> initialX_;
Algorithm* algorithm_;
Solution solution_;
};
#endif // !PROBLEM_H |
vanessavvp/DAA-pr8-maximum-diversity-problem | include/formulas.h | /**
* PROJECT HEADER
* @file formulas.cc
* @author: <NAME>
* Contact: <EMAIL>
* @date: 02/05/2021
* Subject: Diseño y Análisis de Algoritmos
* Practice: Numberº8
* Purpose: Maximum Diversity Problem
*/
#include <cmath>
#include "./element.h"
/**
* Returns the calculus of the euclidean distance between two given elements
**/
double calculateEuclideanDistance(Element first, Element second);
|
vanessavvp/DAA-pr8-maximum-diversity-problem | include/node.h | /**
* PROJECT HEADER
* @file nodet.h
* @author: <NAME>
* Contact: <EMAIL>
* @date: 16/05/2021
* Subject: Diseño y Análisis de Algoritmos
* Practice: Numberº8
* Purpose: Maximum Diversity Problem
*/
#ifndef NODE_H
#define NODE_H
#include <iostream>
#include "./solution.h"
#pragma once
template <typename TYPE>
class Node {
public:
Node() {};
Node(Solution solution, int depth = 0) {
depth_ = depth;
solution_ = solution;
}
int getDepth() const {
return depth_;
}
void setDepth(int depth) {
depth_ = depth;
}
Solution getSolution() const {
return solution_;
}
bool operator ==(const Node<TYPE>& a) {
if ((a.getSolution() == solution_) && (a.getDepth() == depth_)) {
return true;
}
return false;
}
private:
int depth_;
Solution solution_;
};
#endif // !NODE_H |
vanessavvp/DAA-pr8-maximum-diversity-problem | include/solution.h | /**
* PROJECT HEADER
* @file solution.h
* @author: <NAME>
* Contact: <EMAIL>
* @date: 02/05/2021
* Subject: Diseño y Análisis de Algoritmos
* Practice: Numberº8
* Purpose: Maximum Diversity Problem
*/
#ifndef SOLUTION_H
#define SOLUTION_H
#include <iostream>
#include <vector>
#include "./element.h"
#include "./formulas.h"
#pragma once
class Solution {
public:
Solution() {};
Solution(int dimensionK, int numberOfElementsN);
~Solution() {};
std::vector<Element> getSolution() const;
void addElementToSolution(Element newElement);
double calculateObjectiveFunction();
double getZ() const;
int size();
void resize(int size);
std::string printFile();
void print();
bool operator ==(const Solution& solution);
bool operator!=(const Solution& solution);
Element& operator[](int index);
private:
std::vector<Element> solution_;
int dimensionK_;
int numberOfElementsN_;
double z_;
};
#endif // !SOLUTION_H |
vanessavvp/DAA-pr8-maximum-diversity-problem | include/branchAndBound.h | /**
* PROJECT HEADER
* @file branchAndBound.h
* @author: <NAME>
* Contact: <EMAIL>
* @date: 15/05/2021
* Subject: Diseño y Análisis de Algoritmos
* Practice: Numberº8
* Purpose: Maximum Diversity Problem
*/
#ifndef BRANCH_AND_BOUND_H
#define BRANCH_AND_BOUND_H
#define MAX_FLOAT 159874.23
#include <algorithm>
#include <iostream>
#include <vector>
#include <tuple>
#include "./algorithm.h"
#include "./problem.h"
#include "./node.h"
#pragma once
class BranchAndBound : public Algorithm {
public:
BranchAndBound(Algorithm* initialSolutionAlgorithm);
void setAlgorithm(Algorithm* initialSolutionAlgorithm);
int getAmountOfNodes();
std::vector<Node<Solution>> generateLeaf(Problem problem, Solution parent, int depth, int solutionSizeM);
Solution generateBestSolution(std::vector<Element> initialX, Solution selectedElement, int solutionSizeM);
Solution execute(Problem problem, int solutionSizeM);
std::vector<Node<Solution>> sortByOption(std::vector<Node<Solution>>& activeNodes);
void setOption(int option);
private:
Algorithm* otherAlgorithm_;
int amountOfNodes_;
std::vector<Node<Solution>> activeNodes_;
int option_;
};
#endif // !BRANCH_AND_BOUND_H |
vanessavvp/DAA-pr8-maximum-diversity-problem | include/greedy.h | /**
* PROJECT HEADER
* @file greedy.h
* @author: <NAME>
* Contact: <EMAIL>
* @date: 02/05/2021
* Subject: Diseño y Análisis de Algoritmos
* Practice: Numberº8
* Purpose: Maximum Diversity Problem
*/
#ifndef GREEDY_H
#define GREEDY_H
#include <iostream>
#include "./algorithm.h"
#include "./problem.h"
#include "./formulas.h"
#include "./localSearch.h"
#pragma once
class Greedy : public Algorithm {
public:
Greedy() {};
~Greedy() {}
Solution execute(Problem problem, int solutionSizeM);
};
#endif // !GREEDY_H
|
vanessavvp/DAA-pr8-maximum-diversity-problem | include/algorithm.h | /**
* PROJECT HEADER
* @file algorithm.h
* @author: <NAME>
* Contact: <EMAIL>
* @date: 02/05/2021
* Subject: Diseño y Análisis de Algoritmos
* Practice: Numberº8
* Purpose: Maximum Diversity Problem
*/
#ifndef ALGORITHM_H
#define ALGORITHM_H
#include <iostream>
#include <utility>
#include "./solution.h"
#pragma once
class Problem;
class Algorithm {
public:
virtual ~Algorithm() = default;
virtual Solution execute(Problem problem, int solutionSizeM) = 0;
Element calculateGravityCenter(std::vector<Element> elements);
};
#endif // !ALGORITHM_H |
vanessavvp/DAA-pr8-maximum-diversity-problem | include/GRASP.h | /**
* PROJECT HEADER
* @file GRASP.h
* @author: <NAME>
* Contact: <EMAIL>
* @date: 02/05/2021
* Subject: Diseño y Análisis de Algoritmos
* Practice: Numberº8
* Purpose: Maximum Diversity Problem
*/
#ifndef GRASP_H
#define GRASP_H
#include <iostream>
#include "./algorithm.h"
#include "./problem.h"
#include "./formulas.h"
#include "./localSearch.h"
#pragma once
typedef std::pair<int, double> farthestElement;
class GRASP : public Algorithm {
public:
GRASP() {};
~GRASP() {};
void setK();
void setK(int k);
void setIterations(int iterations);
void setLocalSearch(LocalSearch* localSearch);
void setStopCriteria(bool stopCriteria);
int getK();
int getIterations();
bool getStopCriteria();
std::vector<farthestElement> bestKValues(std::vector<farthestElement> distances);
Solution constructivePhase(Problem problem, int solutionSizeM);
Solution execute(Problem problem, int solutionSizeM);
private:
int k_;
int iterations_;
bool iterationsWithImprovement_;
LocalSearch* localSearch_;
};
#endif // !GRASP_H |
gurki/lightpainting | src/timer.h | <gh_stars>0
#ifndef TIMER_H
#define TIMER_H
#include <iostream>
#include <chrono>
class Timer
{
public:
Timer(); // start timer
void tic(); // start or reset the timer
double tac(); // return seconds since start
double toc(); // print and return seconds since start
private:
std::chrono::high_resolution_clock::time_point then_;
};
#endif
|
gurki/lightpainting | src/keys.h | <filename>src/keys.h
#ifndef KEYS_H
#define KEYS_H
#include <unordered_set>
class Keys
{
public:
Keys();
void down( const int key );
bool isPressed( const int key ) const;
private:
std::unordered_set<int> pressed_;
};
#endif
|
DavyVan/MiniCaffe | minicaffe/layer.h | /***
* @file layer.h
* @author <NAME>
* @brief Define the abstract base class of all layers.
* @date 20/Feb/2019
*/
#ifndef _LAYER_H_
#define _LAYER_H_
#include <vector>
#include "seqnet.h"
#include "blob.h"
using namespace std;
/***
* @brief The common abstract base class of all layers, which only contains the most basic attributes about a layer.
*
*/
class Layer
{
public:
char* name; /**< The name of this layer. */
// Obsoleted @3/8/2019
// vector<Blob*> left_blobs; /**< Multiple input/output blobs. Left means input for inference and output for bp. */
// vector<Blob*> right_blobs; /**< Multiple output/output blobs. Right means output for inference and input for bp.*/
virtual int init()=0;
virtual void infer(vector<Blob*> lefts, vector<Blob*> rights)=0;
virtual void infer_gpu(vector<Blob*> lefts, vector<Blob*> right);
virtual void bp(vector<Blob*> lefts, vector<Blob*> rights)=0;
virtual void bp_gpu(vector<Blob*> lefts, vector<Blob*> rights);
/***
* @brief Calculate the outputs' dimensions given inputs' dimensions.
* This function is used by @Net to construct Blobs, and layer itself.
* If this is input layer, ignore the input.
*
* @param intputs_dims [in] Dimensions of input blobs. [batchSize0, x0, y0, z0, batchSize1, x1, y1, z1, ...] if more than one blob
* @param outputs_dims [out] Dimensions of output blobs. It has the same format as @inputs_dims
*/
virtual void get_outputs_dimensions(int inputs_dims[], const int numInputs, int outputs_dims[], const int numOutputs)=0;
virtual bool check_dimensions()=0;
protected:
/***
* @brief Constructor of Layers' base class.
* Accept layer's name.
*/
Layer(char* name);
/***
* @brief Add itself to @Net
* It is implemented as a member function to ensure that a instance must be constructed before we can add a layer to net.
* It is designed to be called from wrapper.
*
* @param net The model user created.
* @param lefts Blobs on the left. Instantiation of Blobs will take place in @Net so we only need string identifiers.
* Actually, lefts are already constructed when adding the previous layer.
* @param numLefts Number of left blobs.
* @param rights Blobs on the right. Instantiation of Blobs will take place in @Net so we only need string identifiers.
* @param numRights Number of right blobs.
*
* @return Error code.
*/
int add_to_net(Net* net, const char* lefts[], const int numLefts, const char* rights[], const int numRights);
};
#endif |
DavyVan/MiniCaffe | minicaffe/minicaffe.h | <reponame>DavyVan/MiniCaffe
#ifndef _MINICAFFE_H_
#define _MINICAFFE_H_
#include "layers/conv_layer.h"
#include "layers/fc_layer.h"
#include "layers/input_layer.h"
#include "layers/mnist_generator.h"
#include "layers/relu_layer.h"
#include "layers/sigmoid_cross_entropy_loss.h"
#include "pooling.h"
#include "normalization.h"
#include "seqnet.h"
#include "blob.h"
#endif
|
DavyVan/MiniCaffe | minicaffe/blob.h | <reponame>DavyVan/MiniCaffe
/***
* @file blob.h
* @author <NAME>
* @brief Defines the Blob class.
* @date 20/Feb/2019
*/
#ifndef _BLOB_H_
#define _BLOB_H_
#include <cstdlib>
#include <cstring>
// #include "layer.h"
class Layer;
/***
* @brief Blob class, where the data actually stored.
*
*/
class Blob
{
public:
char* name=NULL; /**< Blob's name */
int batchSize; /**< Batch size that current blob contains. This is the 1st dimension of blob. */
int x; /**< x dimension. Blob describes a 3D matrix. This is the 2nd dimension of blob*/
int y; /**< y dimension. Blob describes a 3D matrix. This is the 3rd dimension of blob*/
int z; /**< z dimension. Blob describes a 3D matrix. This is the 4th dimension of blob */
int sizeofEle; /**< Size in bytes of each element. */
float* _data = NULL; /**< Where actually the data stored. We now only consider float type. */
Layer* left_layer = NULL; /**< Connected layer on the left. One blob can only have one left layer. */
Layer* right_layer = NULL; /**< Connected layer on the right. One blob can only have one right layer. */
/***
* @brief Constructor. Call this when you don't know the size of blob
*
* @param name Name of blob.
* @param sizeofEle sizeof element. Default is float(4)
*/
Blob(const char* name, int sizeofEle=4);
/***
* @brief Constructor. Call this when you are aware of each dimensions of blob
*
* @param name Name of blob
* @param batchSize 1st dimension, see @Blob::batchSize.
* @param x 2nd dimension, see @Blob::x.
* @param y 3rd dimension, see @Blob::y.
* @param z 4th dimension, see @Blob::z.
* @param sizeofEle Size of each element, see @Blob::sizeofEle.
*
*/
Blob(const char* name, int batchSize, int x, int y, int z, int sizeofEle=4);
/***
* @brief No-param constructor.
* This is a placeholder function and not suppose to be used in practice.
*/
Blob();
/***
* @brief De-constructor.
* Free all allocated memory.
*
*/
~Blob();
int get_ele_num();
/***
* @brief Initialize current blob.
* Allocate memory space and assign the first value.
*
* @return Exit code
*/
int init();
Blob(const Blob &rhs);
Blob operator=(const Blob&);
float &operator()(int batch_pos,int x_pos, int y_pos, int z_pos);
inline void reset(){
memset(_data,0,get_ele_num()*sizeofEle);
}
inline void free_data(){
delete [] _data;
}
};
#endif |
DavyVan/MiniCaffe | minicaffe/layers/input_layer.h | /***
* @file input_layer.h
* @author <NAME>
* @brief Header file of input_layer
* @date 02/Mar/2019
*/
#ifndef MAIN_INPUT_LAYER_H
#define MAIN_INPUT_LAYER_H
#include "../layer.h"
#include "../blob.h"
class InputLayer : public Layer
{
public:
InputLayer(char* name);
void infer(vector<Blob*> lefts, vector<Blob*> rights);
void bp(vector<Blob*> lefts, vector<Blob*> rights);
void infer_gpu(vector<Blob*> lefts, vector<Blob*> rights);
void bp_gpu(vector<Blob*> lefts, vector<Blob*> rights);
void get_outputs_dimensions(int inputs_dims[], const int numInputs, int outputs_dims[], const int numOutputs);
bool check_dimensions();
int init();
};
#endif //MAIN_INPUT_LAYER_H
|
DavyVan/MiniCaffe | minicaffe/layers/conv_layer.h | //
// Created by mingchen on 3/2/19.
//
#ifndef MAIN_CONV_LAYER_H
#define MAIN_CONV_LAYER_H
#include "../layer.h"
#include "../blob.h"
#include <string>
class ConvLayer: public Layer {
public:
ConvLayer(char* name,int in_width, int in_height,int kernel_size, int in_channels, int out_channels,
int w_stride,int h_stride);
void infer(std::vector<Blob*> lefts, std::vector<Blob*> rights);
void bp(std::vector<Blob*> lefts, std::vector<Blob*> rights);
void infer_gpu(std::vector<Blob*> lefts, std::vector<Blob*> rights);
void bp_gpu(std::vector<Blob*> lefts, std::vector<Blob*> rights);
void get_outputs_dimensions(int inputs_dims[], const int numInputs, int outputs_dims[], const int numOutputs);
bool check_dimensions();
int init();
// orgrinized as output_channel*kernel_x*kernel_y*input_channel
Blob weights;
private:
// orgrinized as output_channel*kernel_x*kernel_y*input_channel
Blob delta;
float* bias;
float* delta_bias;
int kernel_size;
int in_width;
int in_height;
int in_channels;
int out_channels;
int w_stride;
int h_stride;
int out_width;
int out_height;
void update(int batchSize);
void conv( Blob &input, Blob &kernel,Blob &output,int w_stride, int h_stride);
void manage_mem_and_conv(Blob &input, Blob &kernel, Blob &output, int w_stride, int h_stride, float* bias=NULL);
};
#endif //MAIN_CONV_LAYER_H
|
DavyVan/MiniCaffe | minicaffe/seqnet.h | /***
* @file seqnet.h
* @author <NAME>
* @brief New Net
* @date 08/Mar/2019
*/
#ifdef _NET_H_
#error net.h is obsoleted. Do not use it anywhere.
#endif
#ifndef _SEQNET_H_
#define _SEQNET_H_
#include <vector>
#include "blob.h"
#include "layers/mnist_generator.h"
#ifdef TEST_ENABLED
#include "gtest/gtest_prod.h"
#endif
using std::vector;
class Layer;
class SeqNet
{
public:
/***
* @brief Non-arg constructor. Keep it for test.
*
*/
SeqNet(int batchsize=32);
/***
* @brief Instantiate with generator.
*
* @param generator The generator.
*/
SeqNet(MnistGenerator* generator, int batchsize=32);
/***
* @brief Change the data generator.
*
* @param generator The generator.
*/
void update_generator(MnistGenerator* generator);
/***
* @brief Add new layer to this net.
* This function will create necessary blobs to connect layers. It will firstly check the tail pointer by lefts' name and then search the net if not match.
* If any designated lefts do not exist, function will report and abort. If any right blob has the same name as existed blob, report and abort.
* NOTICE: Some limitations apply, please see README
*
* @param layer The layer to be added to this net.
* @param lefts The name set of left blobs.
* @param numLefts The number of left blobs.
* @param rights The name set of right blobs.
* @param numRights The number of right blobs.
*
* @return The error code.
*/
int add_layer(Layer* layer, const char* lefts[], const int numLefts, const char* rights[], const int numRights);
/***
* @brief Initialize neural network before running.
* Call init() of each blob and layer.
*
* @return The error code. 0 for normal.
*/
int init();
/***
* @brief Do forward.
* 1. Reset all blobs
* 2. Generate a new batch of samples
* 3. Iterate each layer and call infer()
* (a) find lefts and rights blobs
* (b) call infer()
*/
void infer(bool gpu_enabled=false);
/***
* @brief Do backward propagation
*
*/
void bp(bool gpu_enabled=false);
/***
* @brief Training process consists of inference and BP.
* Call infer() and bp()
*
*/
void train(int iteration, bool gpu_enabled=false);
/***
* @brief return a copy of the required blob.
*
*/
Blob* get_output(const char* name);
/***
* @brief Return the batchsize
*
* @return int The batchsize
*/
int static get_batchsize();
// private:
vector<Layer*> layers; /**< All layers, in the order of insertion and running */
vector<Blob*> blobs; /**< All blobs, in the order of insertion */
vector<vector<Blob*> > lefts; /**< lefts for each layer */
vector<vector<Blob*> > rights; /**< rights for each layer */
MnistGenerator* dataGenerator;
static int batchsize;
/***
* @brief As its name.
*
* @param name Name of target blob.
*
* @return int The index in @Net::blobs.
*/
int get_blob_id_by_name(const char* name);
#ifdef TEST_ENABLED
FRIEND_TEST(SeqNetTest, add_layer_1layer_0in2out);
FRIEND_TEST(SeqNetTest, add_layer_3layers);
FRIEND_TEST(SeqNetTest, get_blob_id_by_name);
FRIEND_TEST(SeqNetTest, infer);
FRIEND_TEST(SeqNetTest, bp);
#endif
};
typedef SeqNet Net;
#endif |
DavyVan/MiniCaffe | minicaffe/layers/sigmoid_cross_entropy_loss.h | /***
* @file sigmoid_cross_entropy_loss.h
* @author <NAME>
* @brief
* @date 19/Mar/2019
*/
#ifndef _SIGMOID_CROSS_ENTROPY_LOSS_H_
#define _SIGMOID_CROSS_ENTROPY_LOSS_H_
#include "../layer.h"
#include "sigmoid.h"
class SigmoidCrossEntropyLoss : public Layer
{
public:
SigmoidCrossEntropyLoss(char* name);
void infer(std::vector<Blob*> lefts, std::vector<Blob*> rights);
void bp(std::vector<Blob*> lefts, std::vector<Blob*> rights);
void infer_gpu(std::vector<Blob*> lefts, std::vector<Blob*> rights);
void bp_gpu(std::vector<Blob*> lefts, std::vector<Blob*> rights);
void get_outputs_dimensions(int inputs_dims[], const int numInputs, int outputs_dims[], const int numOutputs);
bool check_dimensions();
int init();
private:
SigmoidLayer sigmoidLayer;
Blob* sigmoid_output;
};
#endif |
DavyVan/MiniCaffe | minicaffe/pooling.h | <gh_stars>1-10
#ifndef _PL_H_
#define _PL_H_
#include <cstdlib>
//#include "net.h"
#include "layer.h"
#include "errors.h"
#include "util.h"
class PoolingLayer : public Layer
{
public:
int mask_x;
int mask_y;
int stride;
coord_ptr tmp_space;
PoolingLayer();
PoolingLayer(char *name);
PoolingLayer(char *name, int mask_x_, int mask_y_, int stride_);
~PoolingLayer();
int init();
void infer(vector<Blob*> left_blobs, vector<Blob*> right_blobs);
void infer_gpu(vector<Blob*> left_blobs, vector<Blob*> right_blobs);
void bp(vector<Blob*> left_blobs, vector<Blob*> right_blobs);
void bp_gpu(vector<Blob*> left_blobs, vector<Blob*> right_blobs);
void get_outputs_dimensions(int inputs_dims[], const int numInputs, int outputs_dims[], const int numOutputs);
bool check_dimensions();
};
#endif
|
DavyVan/MiniCaffe | minicaffe/errors.h | <reponame>DavyVan/MiniCaffe<filename>minicaffe/errors.h
/***
* @file errors.h
* @author <NAME>
* @brief Definitions of error numbers and related functions.
* @date 01/Mar/2019
*/
/**
* Cannot use errno as variable name due to a confliction with errno.h
*/
#ifndef _ERRORS_H_
#define _ERRORS_H_
const int ZERO_DIM = 1; /**< Blobs with any dimension that equals to zero */
const int LEFT_NOT_MATCH = 2; /**< Expected left blobs don't match any existed blob. */
char* get_err_str(int _errno);
void print_err_str(int _errno);
#endif |
DavyVan/MiniCaffe | minicaffe/layers/relu_layer.h | //
// Created by mingchen on 3/2/19.
//
#ifndef MAIN_RELU_LAYER_H
#define MAIN_RELU_LAYER_H
#include "../layer.h"
#include "../blob.h"
#include <string>
class ReluLayer: public Layer {
public:
ReluLayer(char* name):Layer(name){};
void infer(vector<Blob*> lefts, vector<Blob*> rights);
void bp(vector<Blob*> lefts, vector<Blob*> rights);
void get_outputs_dimensions(int inputs_dims[], const int numInputs, int outputs_dims[], const int numOutputs);
bool check_dimensions();
int init();
void infer_gpu(vector<Blob*> lefts, vector<Blob*> rights);
void bp_gpu(vector<Blob*> lefts, vector<Blob*> rights);
};
#endif //MAIN_RELU_LAYER_H
|
DavyVan/MiniCaffe | minicaffe/normalization.h | <reponame>DavyVan/MiniCaffe
#ifndef _NL_H_
#define _NL_H_
#include <cstdlib>
//#include "net.h"
#include "layer.h"
#include "errors.h"
#include "util.h"
#include <string.h>
class NormalizationLayer : public Layer
{
public:
int nn;
float alpha;
float beta;
float kk;
NormalizationLayer();
NormalizationLayer(char *name);
NormalizationLayer(char *name, float alpha_, float beta_, float kk_, int nn_);
~NormalizationLayer();
int init();
void infer(vector<Blob*> left_blobs, vector<Blob*> right_blobs);
void bp(vector<Blob*> left_blobs, vector<Blob*> right_blobs);
void infer_gpu(vector<Blob*> left_blobs, vector<Blob*> right_blobs);
void bp_gpu(vector<Blob*> left_blobs, vector<Blob*> right_blobs);
void get_outputs_dimensions(int inputs_dims[], const int numInputs, int outputs_dims[], const int numOutputs);
bool check_dimensions();
};
#endif
|
DavyVan/MiniCaffe | minicaffe/generator.h | /***
* @file generator.h
* @author <NAME>
* @brief Generator
* @date 08/Mar/2019
*/
#ifndef _GENERATOR_H_
#define _GENERATOR_H_
#include "blob.h"
/***
* @brief This is the base class of generators
*
*/
class Generator
{
virtual Blob* next_batch()=0;
};
#endif |
DavyVan/MiniCaffe | minicaffe/util.h | <gh_stars>1-10
/***
* @file util.h
* @author <NAME>
* @brief Utilities functions.
* @date 01/Mar/2019
*/
#ifndef _UTIL_H_
#define _UTIL_H_
#include <cmath>
#include <iostream>
#include "blob.h"
void alloc_and_strcpy(char**dst, const char* src);
int print_matrix(float *A, int batch_size, int x, int y, int z);
int random_matrix(float *A, int eleNum, float scalar=1);
typedef struct coordinate
{
int row;
int col;
int z;
}coord, *coord_ptr;
int print_coord_matrix(coord_ptr A, int batch_size, int x, int y, int z);
/***
* @brief C[MxN] = alpha * A[MxK] * B[KxN] + beta * C[MxN]
* A or B cannot be C
*
*/
void simple_gemm(int M, int N, int K, float alpha, float* A, float* B, float beta, float* C);
/***
* @brief C = A + B, C can be A or B
*
*/
void vector_add(int L, float* A, float* B, float* C);
namespace helper{
inline bool float_eq(float a, float b){
if (std::abs(a-b)<0.0001) return 1;
return 0;
}
static void print_blob(Blob &blob){
using namespace std;
cout<<"print blob "<<blob.name<<endl;
for(int batch=0;batch<blob.batchSize;batch++){
cout<<"batch "<<batch<<endl;
for(int channel=0;channel<blob.z;channel++){
cout<<"channel "<<channel<<endl;
for(int y=0;y<blob.y;y++){
for(int x=0;x<blob.x;x++){
cout<<blob(batch,x,y,channel)<<" ";
}
cout<<endl;
}
}
}
cout<<endl;
}
}
#endif |
DavyVan/MiniCaffe | minicaffe/layers/sigmoid.h | /***
* @file sigmoid.h
* @author <NAME>
* @brief
* @date 19/Mar/2019
*/
#ifndef _SIGMOID_H_
#define _SIGMOID_H_
#include "../layer.h"
class SigmoidLayer : public Layer
{
public:
SigmoidLayer(char* name);
void infer(std::vector<Blob*> lefts, std::vector<Blob*> rights);
void bp(std::vector<Blob*> lefts, std::vector<Blob*> rights);
void get_outputs_dimensions(int inputs_dims[], const int numInputs, int outputs_dims[], const int numOutputs);
bool check_dimensions();
int init();
inline float sigmoid(float x);
};
#endif |
DavyVan/MiniCaffe | minicaffe/layers/mnist_generator.h | //
// Created by mingchen on 3/9/19.
//
#ifndef MAIN_MNIST_GENERATOR_H
#define MAIN_MNIST_GENERATOR_H
#include "../blob.h"
#include <string>
#include <fstream>
#include <vector>
class MnistGenerator {
public:
virtual std::vector<Blob> loadSample(int batchSize);
int reset();
MnistGenerator(std::string sampleFile,std::string labelFile);
private:
int offset;
int size;
int row_size,col_size;
std::ifstream sampleFS;
std::ifstream labelFS;
void loadToMemory();
std::vector<std::vector<float> > _images;
std::vector<int> _labels;
inline int to_int(char* buffer){
return ((buffer[0] & 0xff) << 24) | ((buffer[1] & 0xff) << 16) |
((buffer[2] & 0xff) << 8) | ((buffer[3] & 0xff) << 0);
}
};
#endif //MAIN_MNIST_GENERATOR_H
|
DavyVan/MiniCaffe | minicaffe/layers/fc_layer.h | <reponame>DavyVan/MiniCaffe
/***
* @file fc_layer.h
* @author <NAME>
* @brief Fully connected layer (inner product layer)
* @date 16/Mar/2019
*/
#ifndef _FC_LAYER_H_
#define _FC_LAYER_H_
#include "../layer.h"
#include "../blob.h"
class FCLayer : public Layer
{
public:
FCLayer(char* name, int num_output, bool bias_term, int flattened_dim=0);
void infer(std::vector<Blob*> lefts, std::vector<Blob*> rights);
void bp(std::vector<Blob*> lefts, std::vector<Blob*> rights);
void get_outputs_dimensions(int inputs_dims[], const int numInputs, int outputs_dims[], const int numOutputs);
bool check_dimensions();
int init(); // weights, bias
void infer_gpu(std::vector<Blob*> left_blobs, std::vector<Blob*> right_blobs);
void bp_gpu(std::vector<Blob*> left_blobs, std::vector<Blob*> right_blobs);
// private:
int N_; // output dim
int K_; // flattened dim
int M_; // batch size
bool bias_term;
float *weight = NULL;
float *bias = NULL;
// axis = 1;
// weight & bias are filled randomly [0, 1]
};
#endif |
Ridiculous-Innovations/WBANetworking | WBANetworking/WBANetworking.h | // WBANetworking.h
//
// Copyright (c) 2013 WBANetworking (http://WBANetworking.com/)
//
// 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.
@import Foundation;
#import <Availability.h>
#ifndef _WBANetworking_
#define _WBANetworking_
#import "WBAURLRequestSerialization.h"
#import "WBAURLResponseSerialization.h"
#import "WBASecurityPolicy.h"
#import "WBANetworkReachabilityManager.h"
#import "WBAURLConnectionOperation.h"
#import "WBAHTTPRequestOperation.h"
#import "WBAHTTPRequestOperationManager.h"
#if ( ( defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || \
( defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 ) )
#import "WBAURLSessionManager.h"
#import "WBAHTTPSessionManager.h"
#endif
#endif /* _WBANetworking_ */
|
Ridiculous-Innovations/WBANetworking | UIKit+WBANetworking/UIWebView+WBANetworking.h | <gh_stars>0
// UIWebView+WBANetworking.h
//
// Copyright (c) 2013-2015 WBANetworking (http://WBANetworking.com)
//
// 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.
@import Foundation;
#import <Availability.h>
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
@import UIKit;
@class WBAHTTPRequestSerializer, WBAHTTPResponseSerializer;
@protocol WBAURLRequestSerialization, WBAURLResponseSerialization;
/**
This category adds methods to the UIKit framework's `UIWebView` class. The methods in this category provide increased control over the request cycle, including progress monitoring and success / failure handling.
@discussion When using these category methods, make sure to assign `delegate` for the web view, which implements `–webView:shouldStartLoadWithRequest:navigationType:` appropriately. This allows for tapped links to be loaded through WBANetworking, and can ensure that `canGoBack` & `canGoForward` update their values correctly.
*/
@interface UIWebView (WBANetworking)
/**
The request serializer used to serialize requests made with the `-loadRequest:...` category methods. By default, this is an instance of `WBAHTTPRequestSerializer`.
*/
@property (nonatomic, strong) WBAHTTPRequestSerializer <WBAURLRequestSerialization> * requestSerializer;
/**
The response serializer used to serialize responses made with the `-loadRequest:...` category methods. By default, this is an instance of `WBAHTTPResponseSerializer`.
*/
@property (nonatomic, strong) WBAHTTPResponseSerializer <WBAURLResponseSerialization> * responseSerializer;
/**
Asynchronously loads the specified request.
@param request A URL request identifying the location of the content to load. This must not be `nil`.
@param progress A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread.
@param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred.
*/
- (void)loadRequest:(NSURLRequest *)request
progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress
success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
failure:(void (^)(NSError *error))failure;
/**
Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding.
@param request A URL request identifying the location of the content to load. This must not be `nil`.
@param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified.
@param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified.
@param progress A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread.
@param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred.
*/
- (void)loadRequest:(NSURLRequest *)request
MIMEType:(NSString *)MIMEType
textEncodingName:(NSString *)textEncodingName
progress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))progress
success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
failure:(void (^)(NSError *error))failure;
@end
#endif
|
henrythebuilder/nif_sample_cpp | src/nif_tool.h | #ifndef NIF_TOOL_INCLUDED
# define NIF_TOOL_INCLUDED
# include "erl_nif.h"
# include <string>
ERL_NIF_TERM extract_int_term(ErlNifEnv *env, ERL_NIF_TERM term);
ERL_NIF_TERM make_tuple_error(ErlNifEnv *env, const std::string text);
ERL_NIF_TERM make_tuple_error(ErlNifEnv *env, const std::string text, const int n);
#endif // NIF_TOOL_INCLUDED
// SPDX-License-Identifier: Apache-2.0
|
iunion/DJDatePicker | DJDatePicker/DJDatePicker/DJDatePicker.h | <gh_stars>0
//
// DJDatePicker.h
// DJDatePicker
//
// Created by DJ on 2017/8/24.
// Copyright © 2017年 DennisDeng. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, DJPickerStyle)
{
PickerStyle_YearMonthDayHourMinute = 0, // 年月日时分
PickerStyle_MonthDayHourMinute, // 月日时分
PickerStyle_YearMonthDay, // 年月日
PickerStyle_MonthDay, // 月日
PickerStyle_HourMinute // 时分(24)
};
typedef void(^DJDatePickerDoneBlock)(NSDate * _Nonnull date, BOOL isDone);
NS_ASSUME_NONNULL_BEGIN
@interface DJDatePicker : UIView
// 格式化
// 文本颜色
@property (nonatomic, strong) UIColor *formateColor;
// 显示时间格式
@property (nullable, nonatomic, strong) NSString *formate;
// 年份
// 文本颜色
@property (nonatomic, strong) UIColor *yearColor;
// 滚轮
// 年-月-日-时-分 分栏文字颜色
@property (nonatomic, strong) UIColor *pickerLabelColor;
// 滚轮日期颜色
@property (nonatomic, strong) UIColor *pickerItemColor;
// 确定按钮
@property (nonatomic, assign) BOOL showDoneBtn;
// 确定按钮背景颜色
@property (nonatomic, strong) UIColor *doneBtnBgColor;
// 确定按钮文本颜色
@property (nonatomic, strong) UIColor *doneBtnTextColor;
// 滚动最大时间限制(默认2099)
@property (nonatomic, strong) NSDate *maxLimitDate;
// 滚动最小时间限制(默认0)
@property (nonatomic, strong) NSDate *minLimitDate;
@property (nonatomic, strong, readonly) NSDate *pickerDate;
// 默认滚动到当前时间
- (nonnull instancetype)initWithPickerStyle:(DJPickerStyle)pickerStyle completeBlock:(nullable DJDatePickerDoneBlock)completeBlock;
// 滚动到指定的的日期
- (nonnull instancetype)initWithPickerStyle:(DJPickerStyle)pickerStyle scrollToDate:(nullable NSDate *)scrollToDate completeBlock:(nullable DJDatePickerDoneBlock)completeBlock;
// 滚动到指定的时间位置
- (void)scrollToDate:(nullable NSDate *)date animated:(BOOL)animated;
@end
NS_ASSUME_NONNULL_END
|
iunion/DJDatePicker | DJDatePicker/DJDatePicker/NSDate+Category.h | //
// NSDate+Category.h
// DJkit
//
// Created by DennisDeng on 13-12-18.
// Copyright (c) 2013年 DennisDeng. All rights reserved.
//
/*
<NAME>, http://ericasadun.com
iPhone Developer's Cookbook 3.x and beyond
BSD License, Use at your own risk
*/
#import <Foundation/Foundation.h>
//#define D_MINUTE 60
//#define D_HOUR 3600
//#define D_DAY 86400
//#define D_WEEK 604800
//#define D_YEAR 31556926
FOUNDATION_EXPORT const long long SECONDS_IN_YEAR;
FOUNDATION_EXPORT const long long SECONDS_IN_COMMONYEAR;
FOUNDATION_EXPORT const long long SECONDS_IN_LEAPYEAR;
FOUNDATION_EXPORT const NSInteger SECONDS_IN_MONTH_28;
FOUNDATION_EXPORT const NSInteger SECONDS_IN_MONTH_29;
FOUNDATION_EXPORT const NSInteger SECONDS_IN_MONTH_30;
FOUNDATION_EXPORT const NSInteger SECONDS_IN_MONTH_31;
FOUNDATION_EXPORT const NSInteger SECONDS_IN_WEEK;
FOUNDATION_EXPORT const NSInteger SECONDS_IN_DAY;
FOUNDATION_EXPORT const NSInteger SECONDS_IN_HOUR;
FOUNDATION_EXPORT const NSInteger SECONDS_IN_MINUTE;
FOUNDATION_EXPORT const NSInteger MILLISECONDS_IN_DAY;
NS_ASSUME_NONNULL_BEGIN
@interface NSDate (Category)
+ (NSString *)stringFromDate:(NSDate *)aDate;
+ (NSString *)stringFromDate:(NSDate *)aDate formatter:(NSString *)formatter;
+ (NSString *)stringFromTs:(NSTimeInterval)timestamp;
+ (NSString *)stringFromTs:(NSTimeInterval)timestamp formatter:(NSString *)formatter;
+ (NSString *)stringFromNow;
+ (NSTimeInterval)timeIntervalFromString:(NSString *)dateString;
+ (NSTimeInterval)timeIntervalFromString:(NSString *)dateString withFormat:(NSString *)format;
+ (NSDate *)dateFromString:(NSString *)dateString;
+ (NSDate *)dateFromString:(NSString *)dateString withFormat:(NSString *)format;
+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day;
+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day hour:(NSInteger)hour minute:(NSInteger)minute second:(NSInteger)second;
+ (NSCalendar *)currentCalendar;
+ (NSDate *)getCurrentDateWithSystemTimeZone;
+ (NSDate *)getCurrentDateWithTimeZone:(NSTimeZone *)timezone;
/**
* Returns the current date with the time set to midnight.
*/
+ (NSDate *)dateToday;
// Relative dates from the current date
+ (NSDate *)dateTomorrow;
+ (NSDate *)dateYesterday;
+ (NSDate *)dateWithDaysFromNow:(NSInteger)days;
+ (NSDate *)dateWithDaysBeforeNow:(NSInteger)days;
+ (NSDate *)dateWithHoursFromNow:(NSInteger)dHours;
+ (NSDate *)dateWithHoursBeforeNow:(NSInteger)dHours;
+ (NSDate *)dateWithMinutesFromNow:(NSInteger)dMinutes;
+ (NSDate *)dateWithMinutesBeforeNow:(NSInteger)dMinutes;
// Comparing dates
+ (BOOL)isSameDayfirst:(NSTimeInterval)firstDate second:(NSTimeInterval)secondDate;
+ (BOOL)isSameDay:(NSDate *)date asDate:(NSDate *)compareDate;
- (BOOL)isEqualToDateIgnoringTime:(NSDate *)aDate;
- (BOOL)isSameDayAsDate:(NSDate *)aDate;
- (BOOL)isToday;
- (BOOL)isTomorrow;
- (BOOL)isYesterday;
- (BOOL)isSameWeekAsDate:(NSDate *)aDate;
- (BOOL)isThisWeek;
- (BOOL)isNextWeek;
- (BOOL)isLastWeek;
- (BOOL)isSameMonthAsDate:(NSDate *)aDate;
- (BOOL)isThisMonth;
- (BOOL)isNextMonth;
- (BOOL)isLastMonth;
- (BOOL)isSameYearAsDate:(NSDate *)aDate;
- (BOOL)isThisYear;
- (BOOL)isNextYear;
- (BOOL)isLastYear;
- (BOOL)isEarlierThanDate:(NSDate *)aDate;
- (BOOL)isLaterThanDate:(NSDate *)aDate;
- (BOOL)isEarlierThanOrEqualTo:(NSDate *)aDate;
- (BOOL)isLaterThanOrEqualTo:(NSDate *)aDate;
- (BOOL)isInFuture;
- (BOOL)isInPast;
// Date roles
- (BOOL)isTypicallySunday;
- (BOOL)isTypicallyWorkday;
- (BOOL)isTypicallyWeekend;
- (BOOL)isLeapMonth;
// 闰年
- (BOOL)isInLeapYear;
// Date to String
- (NSString *)stringByFormatter:(NSString *)formatter;
- (NSString *)stringByDefaultFormatter;
// Adjusting dates
- (NSDate *)dateByAddingYears:(NSInteger)dYears;
- (NSDate *)dateBySubtractingYears:(NSInteger)dYears;
- (NSDate *)dateByAddingMonths:(NSInteger)dMonths;
- (NSDate *)dateBySubtractingMonths:(NSInteger)dMonths;
- (NSDate *)dateByAddingWeeks:(NSInteger)dweeks;
- (NSDate *)dateBySubtractingWeeks:(NSInteger)dweeks;
- (NSDate *)dateByAddingDays:(NSInteger)dDays;
- (NSDate *)dateBySubtractingDays:(NSInteger)dDays;
- (NSDate *)dateByAddingHours:(NSInteger)dHours;
- (NSDate *)dateBySubtractingHours:(NSInteger)dHours;
- (NSDate *)dateByAddingMinutes:(NSInteger)dMinutes;
- (NSDate *)dateBySubtractingMinutes:(NSInteger)dMinutes;
- (NSDate *)dateByAddingSeconds:(NSInteger)dSeconds;
- (NSDate *)dateBySubtractingSeconds:(NSInteger)dSeconds;
// Date extremes
/*
* Returns a copy of the date with the time set to 00:00:00 on the same day.
*/
- (NSDate *)dateAtStartOfDay;
/*
* Returns a copy of the date with the time set to 23:59:59 on the same day.
*/
- (NSDate *)dateAtEndOfDay;
// Retrieving intervals
- (NSInteger)minutesAfterDate:(NSDate *)aDate;
- (NSInteger)minutesBeforeDate:(NSDate *)aDate;
- (NSInteger)hoursAfterDate:(NSDate *)aDate;
- (NSInteger)hoursBeforeDate:(NSDate *)aDate;
- (NSInteger)daysAfterDate:(NSDate *)aDate;
- (NSInteger)daysBeforeDate:(NSDate *)aDate;
- (NSTimeInterval)secondsFromDate:(NSDate *)aDate;
- (NSInteger)minutesFromDate:(NSDate *)aDate;
- (NSInteger)hoursFromDate:(NSDate *)aDate;
- (NSInteger)daysFromDate:(NSDate *)aDate;
- (NSInteger)weeksFromDate:(NSDate *)aDate;
- (NSInteger)monthsFromDate:(NSDate *)aDate;
- (NSInteger)yearsFromDate:(NSDate *)aDate;
- (NSInteger)distanceInDaysToDate:(NSDate *)anotherDate;
// Decomposing dates
// 接近的小时
- (NSInteger)nearestHour;
// hour(小时)
- (NSInteger)hour;
// minute(分钟)
- (NSInteger)minute;
// second(秒)
- (NSInteger)seconds;
// day(日期)
- (NSInteger)day;
// month(月份)
- (NSInteger)month;
// quarter(季度)
- (NSInteger)quarter;
// year(年份)
- (NSInteger)year;
// era(年份)
- (NSInteger)era;
// dayOfYear(本年第几天)
- (NSInteger)dayOfYear;
// weekday(星期)
// Sunday:1, Monday:2, Tuesday:3, Wednesday:4, Friday:5, Saturday:6
- (NSInteger)weekday;
// weekOfMonth(本月第几周)
- (NSInteger)weekOfMonth;
// weekOfYear(本年第几周)
- (NSInteger)weekOfYear;
- (NSInteger)nthWeekday; // e.g. 2nd Tuesday of the month == 2
- (NSInteger)weekdayOrdinal; // same as nthWeekday
- (NSInteger)yearForWeekOfYear;
// 本月天数
- (NSInteger)daysInMonth;
// 本年天数
- (NSInteger)daysInYear;
// Date to String
- (NSString *)stringWithDefaultFormat;
- (NSString *)stringWithFormat:(NSString *)format;
- (NSString *)stringWithDateStyle:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle;
- (NSString *)mqString;
- (NSString *)shortString;
- (NSString *)shortDateString;
- (NSString *)shortTimeString;
- (NSString *)mediumString;
- (NSString *)mediumDateString;
- (NSString *)mediumTimeString;
- (NSString *)longString;
- (NSString *)longDateString;
- (NSString *)longTimeString;
@end
NS_ASSUME_NONNULL_END
|
iunion/DJDatePicker | DJDatePicker/DJDatePicker/UIView+Size.h | <reponame>iunion/DJDatePicker
//
// UIView+Size.h
// DJkit
//
// Created by DennisDeng on 14-5-5.
// Copyright (c) 2014年 DennisDeng. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIView (Size)
/**
* Shortcut for frame.origin
*/
@property (nonatomic, assign) CGPoint origin;
/**
* Shortcut for frame.size
*/
@property (nonatomic, assign) CGSize size;
/**
* Shortcut for frame.origin.x.
*
* Sets frame.origin.x = left
*/
@property (nonatomic, assign) CGFloat left;
/**
* Shortcut for frame.origin.x + frame.size.width
*
* Sets frame.origin.x = right - frame.size.width
*/
@property (nonatomic, assign) CGFloat right;
/**
* Shortcut for frame.origin.y
*
* Sets frame.origin.y = top
*/
@property (nonatomic, assign) CGFloat top;
/**
* Shortcut for frame.origin.y + frame.size.height
*
* Sets frame.origin.y = bottom - frame.size.height
*/
@property (nonatomic, assign) CGFloat bottom;
/** The x origin of the view's frame. */
@property (nonatomic, assign) CGFloat originX;
/** The max y origin of the view's frame. */
@property (nonatomic, assign) CGFloat originY;
/**
* Shortcut for center.x
*
* Sets center.x = centerX
*/
@property (nonatomic, assign) CGFloat centerX;
/**
* Shortcut for center.y
*
* Sets center.y = centerY
*/
@property (nonatomic, assign) CGFloat centerY;
/**
* Shortcut for frame.size.width
*
* Sets frame.size.width = width
*/
@property (nonatomic, assign) CGFloat width;
/**
* Shortcut for frame.size.height
*
* Sets frame.size.height = height
*/
@property (nonatomic, assign) CGFloat height;
// bounds accessors
@property (nonatomic, assign) CGSize boundsSize;
@property (nonatomic, assign) CGFloat boundsWidth;
@property (nonatomic, assign) CGFloat boundsHeight;
// content getters
@property (nonatomic, readonly) CGRect contentBounds;
@property (nonatomic, readonly) CGPoint contentCenter;
// additional frame setters
- (void)setLeft:(CGFloat)left right:(CGFloat)right;
- (void)setWidth:(CGFloat)width right:(CGFloat)right;
- (void)setTop:(CGFloat)top bottom:(CGFloat)bottom;
- (void)setHeight:(CGFloat)height bottom:(CGFloat)bottom;
@end
|
Mikescher/Serpilicum | src/AutoModifierStartEffect.h | <filename>src/AutoModifierStartEffect.h
#pragma once
#include "leveleffect.h"
class AutoModifierStartEffect :
public LevelEffect
{
private:
long startTime;
int x1;
int x2;
int y1;
int y2;
public:
AutoModifierStartEffect(int px, int py);
~AutoModifierStartEffect(void);
virtual void start(AbstractConsole *console);
virtual void run(AbstractConsole *console);
virtual void render(AbstractConsole *console);
};
|
Mikescher/Serpilicum | src/PathFindingAlgorithm.h | <gh_stars>0
#pragma once
#include <iostream>
#include <iomanip>
#include <queue>
#include <string>
#include <math.h>
#include <ctime>
#include "AbstractConsole.h"
#include "Dynamic2DArray.h"
using namespace std;
const int dir=4;
class PathFindingAlgorithm
{
private:
int m_w;
int m_h;
int *dx;
int *dy;
public:
int **map;
private:
int **closed_nodes_map;
int **open_nodes_map;
int **dir_map;
private:
string lastResult;
int lastResultTargetX;
int lastResultTargetY;
private:
string pathFind(const int & xStart, const int & yStart, const int & xFinish, const int & yFinish);
public:
PathFindingAlgorithm(int map_w, int map_h);
virtual ~PathFindingAlgorithm();
bool hasToRecalc(const int & xFinish, const int & yFinish, bool ignoreTargetChange);
int getWidth();
int getHeight();
int getNextDirection(const int & xStart, const int & yStart, const int & xFinish, const int & yFinish, bool ignoreTargetChange);
};
class node {
private:
int xPos;
int yPos;
int level;
int priority;
public:
node(int xp, int yp, int d, int p) {xPos=xp; yPos=yp; level=d; priority=p;}
int getxPos() const {return xPos;}
int getyPos() const {return yPos;}
int getLevel() const {return level;}
int getPriority() const {return priority;}
void updatePriority(const int & xDest, const int & yDest){ priority=level+estimate(xDest, yDest)*10; }
void nextLevel(const int & i) { level+=(dir==8?(i%2==0?10:14):10); }
const int & estimate(const int & xDest, const int & yDest) const
{
static int xd, yd, d;
xd=xDest-xPos;
yd=yDest-yPos;
d=static_cast<int>(sqrt(xd*xd+yd*yd));
return(d);
}
}; |
Mikescher/Serpilicum | src/PowerUp.h | #pragma once
enum PowerUpType {POWERUP_NULL, POWERUP_HEALTH, POWERUP_AUTO, POWERUP_ZOOM};
class PowerUp
{
private:
PowerUp * next;
int x;
int y;
public:
PowerUp(int px, int py);
~PowerUp(void);
virtual bool hasNextElement();
virtual PowerUp * getNextElement();
virtual void setNextElement(PowerUp * pnext);
//########
virtual int getX();
virtual int getY();
virtual char getSymbol() = 0;
virtual PowerUpType getType() = 0;
};
|
Mikescher/Serpilicum | src/LevelEffect.h | #pragma once
#include "AbstractConsole.h"
class LevelEffect
{
protected:
int x;
int y;
private:
bool is_alive;
public:
LevelEffect(int px, int py);
virtual ~LevelEffect(void);
virtual void start(AbstractConsole *console) = 0;
virtual void run(AbstractConsole *console) = 0;
virtual void render(AbstractConsole *console) = 0;
virtual void stop();
virtual void start();
virtual int getX();
virtual int getY();
virtual bool isAlive();
};
|
Mikescher/Serpilicum | src/ChooseGameModeMenu.h | <filename>src/ChooseGameModeMenu.h
#pragma once
#include "displayimagetextmenu.h"
#define GAMEMODECOUNT 6
class ChooseGameModeMenu :
public DisplayImageTextMenu
{
protected:
virtual void throwAction();
private:
long lastRun;
bool* traNext;
bool* traPrev;
int currmode;
AbstractConsole* console;
double transistion;
int transistionDirection;
std::string gamemode;
void update();
public:
ChooseGameModeMenu(int pid, AbstractConsole* console, ActionListener * quitListener);
virtual void run(AbstractConsole* pConsole);
virtual void render(AbstractConsole* pConsole);
virtual void onKeyDown(int keycode);
};
|
Mikescher/Serpilicum | src/OGLConsole.h | <reponame>Mikescher/Serpilicum<filename>src/OGLConsole.h<gh_stars>0
#pragma once
#include "DBConsole.h"
#include <Windows.h>
#include <WinBase.h>
#include <chrono>
#include "Keycodes.h"
#include "ListenerCollection.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <GL/glew.h>
#include <GL/glut.h>
class OGLConsole :
public DBConsole
{
private:
virtual unsigned char* loadBMPRaw(const unsigned char * image, unsigned int outWidth, unsigned int outHeight, bool flipY);
virtual GLuint LoadTextureRAW(int id, int w, int h);
protected:
GLuint chartextures;
virtual void loadTextures();
protected:
virtual void writeToConsole(int c, int x, int y);
virtual void showConsoleCursor(bool bShow);
virtual unsigned char getKeyState();
virtual void hideConsole();
virtual long getSystemCurrTimeMillis();
virtual void doSystemSleep(long duration);
virtual void setDimensions(short w, short h);
virtual void startRenderOGL();
virtual void renderOGL();
virtual void renderOGLPos(int x, int y, int chr);
public:
OGLConsole(void);
~OGLConsole(void);
virtual void initOGL();
virtual void clearBuffer();
virtual void swap();
virtual bool* getBoolImageResource(int id);
virtual void startLoop(ActionListener *looplistener, KeyEventListener *keyListener);
};
|
Mikescher/Serpilicum | src/AbstractConsole.h | <filename>src/AbstractConsole.h
#pragma once
#include <string>
#include "ListenerCollection.h"
const int BUFFER_W = 80;
const int BUFFER_H = 40;
class AbstractConsole
{
public:
virtual void init() = 0;
virtual void redraw() = 0;
virtual void write(int c, int x, int y) = 0;
virtual void write(std::string s, int x, int y) = 0;
virtual void clearBuffer() = 0;
virtual void swap() = 0;
virtual void zoomIn(int centerX, int centerY) = 0;
virtual unsigned char getCurrentKeyState() = 0;
virtual void setDimensions(short w, short h) = 0;
virtual long getCurrentTimeMillis() = 0;
virtual double getFPS() = 0;
virtual bool* getBoolImageResource(int id) = 0;
virtual void startLoop(ActionListener *looplistener, KeyEventListener *keyListener) = 0;
virtual void onLevelStart() = 0;
virtual void onLevelStop() = 0;
};
|
Mikescher/Serpilicum | src/Gamerules.h | <gh_stars>0
#pragma once
enum DisplayMethod {WINDOWS_CONSOLE, OGL_CONSOLE, CRAZY_CONSOLE};
const DisplayMethod DISPLAYMETHOD = CRAZY_CONSOLE;
const bool SHOWCONSOLE = false;
const int FPS_LIMITER = 60; // 0 == UNLIMITED
//#########################################
const bool GR_EnableCheats = false;
//########################################
class GAMERULES {
public:
int INITIAL_SPEED_SNAKE;
int INITIAL_SNAKE_LENGTH;
int INITIAL_LIFE_SHARDS;
int MAXIMAL_HP_PU_COUNT;
int choosen_gamemode;
bool InfiniteField;
bool DieOnSelfContact;
bool DecreaseShardsOnSelfContact;
bool BiteOnSelfContact;
bool expandOnHPCollection;
bool AddPointsOnHPCollect;
bool FactorialPointCalculation;
bool SpawnAspirinObstaclesOnHPCollect;
bool AlwaysUseAutoSnake;
bool InstantDeath;
bool EnableAutoPowerUp;
bool EnableZoomPowerUp;
public:
static GAMERULES &i() {static GAMERULES i; return i;}
private:
GAMERULES(){};
}; |
Mikescher/Serpilicum | src/HighscoreMenuHard.h | #pragma once
#include "highscoremenu.h"
class HighscoreMenuHard :
public HighscoreMenu
{
protected:
virtual std::string getName();
virtual int getHSID();
public:
HighscoreMenuHard(ActionListener* listener) : HighscoreMenu(listener){}
};
|
Mikescher/Serpilicum | src/DisplayImageTextMenu.h | <reponame>Mikescher/Serpilicum
#pragma once
#include "menu.h"
#include <math.h>
class DisplayImageTextMenu :
public Menu
{
protected:
int id;
ActionListener* listener;
bool* resourceArray;
long startTime;
int duration;
virtual void throwAction();
virtual void createMenu(ActionListener * quitListener);
public:
DisplayImageTextMenu(int pid, AbstractConsole* console, ActionListener * quitListener, int resourceID, int pduration);
virtual void render(AbstractConsole* pConsole);
virtual void run(AbstractConsole* pConsole);
virtual void onKeyDown(int keycode);
};
|
Mikescher/Serpilicum | src/SnakeElement.h | #pragma once
#include "AbstractConsole.h"
#include "Gamerules.h"
class SnakeElement
{
private:
SnakeElement *next;
int x,y;
public:
SnakeElement(int px, int py);
~SnakeElement(void);
virtual bool hasNextElement();
virtual SnakeElement* getNextElement();
virtual void setNextElement(SnakeElement* pnext);
virtual void setX(int x);
virtual void setY(int y);
virtual int getX();
virtual int getY();
virtual int moveX(int x);
virtual int moveY(int y);
virtual void set(int x, int y);
virtual void move(int x, int y);
virtual void moveRecursively(int tox, int toy);
virtual void extendRecursively(int tox, int toy);
virtual void removeNextElement();
}; |
Mikescher/Serpilicum | src/HealthPowerUp.h | <reponame>Mikescher/Serpilicum<filename>src/HealthPowerUp.h
#pragma once
#include "powerup.h"
class HealthPowerUp :
public PowerUp
{
public:
HealthPowerUp(int px, int py);
virtual ~HealthPowerUp(void);
virtual char getSymbol();
virtual PowerUpType getType();
};
|
Mikescher/Serpilicum | src/WindowsConsole.h | #pragma once
#include "DBConsole.h"
#include "Keycodes.h"
#include <Windows.h>
#include <WinBase.h>
#include <chrono>
#include "ListenerCollection.h"
class WindowsConsole :
public DBConsole
{
private:
HANDLE hConsole;
protected:
virtual void writeToConsole(int c, int x, int y);
virtual void showConsoleCursor(bool bShow);
virtual unsigned char getKeyState();
virtual void hideConsole();
virtual long getSystemCurrTimeMillis();
virtual void doSystemSleep(long duration);
virtual void setDimensions(short buffW, short buffH);
public:
WindowsConsole(void);
~WindowsConsole(void);
virtual bool* getBoolImageResource(int id);
virtual void startLoop(ActionListener *looplistener, KeyEventListener *keyListener);
};
|
Mikescher/Serpilicum | src/CrazyDouble.h | <filename>src/CrazyDouble.h<gh_stars>0
#pragma once
#include "AbstractConsole.h"
#include <GL/glut.h>
class CrazyDouble
{
private:
long lastRun;
protected:
double max_speed;
double max_value;
double min_value;
double initial_val;
double value;
double acceleration;
double speed;
double target;
bool running;
private:
virtual void newTarget();
public:
CrazyDouble(AbstractConsole* pConsole, double initial, double speedmax, double acc, double min, double max);
virtual GLfloat get() {return GLfloat(value);}
virtual void run(AbstractConsole* pConsole);
virtual void restart();
virtual void stop();
};
|
Mikescher/Serpilicum | src/HighscoreMenuNormal.h | #pragma once
#include "highscoremenu.h"
class HighscoreMenuNormal :
public HighscoreMenu
{
protected:
virtual std::string getName();
virtual int getHSID();
public:
HighscoreMenuNormal(ActionListener* listener) : HighscoreMenu(listener){}
};
|
Mikescher/Serpilicum | src/SnakeZoomModifier.h | <filename>src/SnakeZoomModifier.h<gh_stars>0
#pragma once
#include "snakemodifier.h"
class SnakeZoomModifier :
public SnakeModifier
{
private:
long startTime;
long runDelta;
public:
SnakeZoomModifier(Level* lvl, AbstractConsole *pConsole);
virtual void run(Level* lvl, AbstractConsole *pConsole);
virtual SnakeModifierType getType();
};
|
Mikescher/Serpilicum | src/SnakeAutoModifier.h | #pragma once
#include "snakemodifier.h"
#include "AbstractConsole.h"
class Level;
class SnakeAutoModifier :
public SnakeModifier
{
public:
long startTime;
long runDelta;
public:
SnakeAutoModifier(Level* lvl, AbstractConsole *pConsole);
virtual void run(Level* lvl, AbstractConsole *pConsole);
virtual SnakeModifierType getType();
};
|
Mikescher/Serpilicum | src/SnakeModifier.h | <filename>src/SnakeModifier.h
#pragma once
#include "AbstractConsole.h"
enum SnakeModifierType {SNAKEMODTYPE_NULL, SNAKEMODTYPE_PREAUTO, SNAKEMODTYPE_AUTO, SNAKEMODTYPE_ZOOM};
class Level;
class SnakeModifier
{
protected:
bool running;
public:
SnakeModifier(): running(true) {};
virtual bool isRunning() {return running;};
virtual void run(Level* lvl, AbstractConsole *pConsole) = 0;
virtual SnakeModifierType getType() = 0;
}; |
Mikescher/Serpilicum | src/MainMenu.h | <filename>src/MainMenu.h
#pragma once
#include "Menu.h"
#include "ListenerCollection.h"
class MainMenu :
public Menu
{
private:
virtual void createMenu(ActionListener * startGamelistener);
public:
MainMenu(ActionListener * startGamelistener);
virtual ~MainMenu(void);
};
|
Mikescher/Serpilicum | src/Menu.h | <reponame>Mikescher/Serpilicum
#pragma once
#include <vector>
#include "MenuElement.h"
#include "AbstractConsole.h"
class Menu {
private:
std::vector<MenuElement*> elements;
unsigned int focusIndex;
virtual void updateFocus();
public:
Menu(void);
virtual ~Menu(void);
virtual void onStart() {};
virtual void render(AbstractConsole* pConsole);
virtual void run(AbstractConsole* pConsole);
virtual void addElement(MenuElement* pElement);
virtual MenuElement* removeElement(MenuElement* pElement);
virtual MenuElement* getFocusedElement();
virtual bool isElementFocused();
virtual MenuElement* focusNextElement();
virtual MenuElement* focusPrevElement();
virtual bool focusElement(unsigned int el);
virtual void removeFocus();
virtual void onKeyDown(int keycode);
}; |
Mikescher/Serpilicum | src/Dynamic2DArray.h | <gh_stars>0
template <typename T> T **allocateDynamicArray( int nRows, int nCols) {
T **dynamicArray;
dynamicArray = new T*[nRows];
for( int i = 0 ; i < nRows ; i++ )
dynamicArray[i] = new T [nCols];
return dynamicArray;
}
template <typename T> void freeDynamicArray(T** dArray) {
delete [] *dArray;
delete [] dArray;
} |
Mikescher/Serpilicum | src/PowerUpSpawnEffect.h | <gh_stars>0
#pragma once
#include "leveleffect.h"
const int HPSE_EFFECT_DELAY = 125;
class PowerUpSpawnEffect :
public LevelEffect
{
private:
long startTime;
int mode;
virtual void renderMode0(AbstractConsole *console);
virtual void renderMode1(AbstractConsole *console);
virtual void renderMode2(AbstractConsole *console);
virtual void write(AbstractConsole* console, int cr, int x, int y);
public:
PowerUpSpawnEffect(int px, int py);
~PowerUpSpawnEffect(void);
virtual void start(AbstractConsole *console);
virtual void run(AbstractConsole *console);
virtual void render(AbstractConsole *console);
};
|
Mikescher/Serpilicum | src/Edit.h | #pragma once
#include "menuelement.h"
class Edit :
public MenuElement
{
private:
int id;
ActionListener * listener;
std::string text;
virtual void throwEvent();
public:
Edit(int id, std::string initval, int nx, int ny);
~Edit(void);
virtual void render(AbstractConsole* pConsole);
virtual std::string getText();
virtual bool isFocusable();
virtual void onKeyDown(int keycode);
virtual void setListener(ActionListener * lst);
virtual ActionListener *removeListener();
};
|
Mikescher/Serpilicum | src/SplashMenu.h | <gh_stars>0
#pragma once
#include "displayimagetextmenu.h"
class SplashMenu :
public DisplayImageTextMenu
{
private:
long startTime;
public:
SplashMenu(int pid, AbstractConsole* console, ActionListener * quitListener, int resourceID);
virtual void render(AbstractConsole* pConsole);
};
|
Mikescher/Serpilicum | src/Keycodes.h | #define KC_UP 0x26
#define KC_DOWN 0x28
#define KC_LEFT 0x25
#define KC_RIGHT 0x27
#define KC_SPACE 0x20
#define KC_ENTER 0x0D
#define KC_ESCAPE 0x1B
#define KC_BACKSPACE 0x08
#define KC_A 0x41
#define KC_B 0x42
#define KC_C 0x43
#define KC_D 0x44
#define KC_E 0x45
#define KC_F 0x46
#define KC_G 0x47
#define KC_H 0x48
#define KC_I 0x49
#define KC_J 0x4A
#define KC_K 0x4B
#define KC_L 0x4C
#define KC_M 0x4D
#define KC_N 0x4E
#define KC_O 0x4F
#define KC_P 0x50
#define KC_Q 0x51
#define KC_R 0x52
#define KC_S 0x53
#define KC_T 0x54
#define KC_U 0x55
#define KC_V 0x56
#define KC_W 0x57
#define KC_X 0x58
#define KC_Y 0x59
#define KC_Z 0x5A
#define KC_F1 0x70
#define KC_F2 0x71
#define KC_F3 0x72
#define KC_F4 0x73
#define KC_F5 0x74
#define KC_F6 0x75
#define KC_F7 0x76
#define KC_F8 0x77
#define KC_F9 0x78
#define KC_F10 0x79
#define KC_F11 0x7A
#define KC_F12 0x7B |
Mikescher/Serpilicum | src/PowerUpList.h | #pragma once
#include "PowerUp.h"
#include "AbstractConsole.h"
class PowerUpList
{
private:
PowerUp * first;
public:
PowerUpList(void);
~PowerUpList(void);
virtual int getLength();
virtual PowerUp * getFirst();
virtual PowerUp * getLast();
virtual bool isEmpty();
virtual void add(PowerUp * p);
virtual bool remove(PowerUp * p);
};
|
Mikescher/Serpilicum | src/Game.h | #pragma once
#include "AbstractConsole.h"
#include "Level.h"
#include "MenuDisplay.h"
#include "ListenerCollection.h"
class Game : public ActionListener
{
private:
AbstractConsole *console;
Level *level;
MenuDisplay *menu;
bool active;
std::string playerName;
virtual void render();
virtual void startNewLevel();
public:
Game(AbstractConsole *pconsole);
virtual ~Game(void);
virtual bool isActive();
virtual void onKeyDown (int keycode);
virtual void actionPerformed(int id, int param);
virtual void run(AbstractConsole *pConsole);
virtual std::string getPlayerName(void);
};
|
Mikescher/Serpilicum | src/ListenerCollection.h | #pragma once
class ActionListener {
public:
virtual void actionPerformed(int id, int param) = 0;
};
class KeyEventListener {
public:
virtual void keyEventPerformed(int key) = 0;
}; |
Mikescher/Serpilicum | src/Highscore.h | #pragma once
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include "Gamerules.h"
//const std::string FILENAME = "Highscore.txt";
struct HighscoreElement {
std::string name;
int point;
int gamemodeid;
};
class Highscore
{
private:
virtual std::string readScoreFile();
virtual std::vector<std::string> explode(const std::string& str, char delimiter);
virtual void sortHighscoreList(std::vector<HighscoreElement>& elements);
public:
Highscore(void);
~Highscore(void);
virtual void writeScore(std::string pname, int scoreValue);
virtual std::vector<HighscoreElement> readScore(int hsid);
};
|
Mikescher/Serpilicum | src/Label.h | #pragma once
#include "MenuElement.h"
#include "AbstractConsole.h"
class Label:public MenuElement
{
private:
std::string text;
public:
Label(void);
Label(std::string initval, int nx, int ny);
virtual ~Label(void);
virtual void render(AbstractConsole* pConsole);
virtual void onKeyDown(int keycode);
virtual bool isFocusable();
virtual void setText(std::string pText);
virtual std::string getText();
};
|
Mikescher/Serpilicum | src/AspirinObstacle.h | <filename>src/AspirinObstacle.h
#pragma once
#include "levelobstacle.h"
class Level;
class AspirinObstacle :
public LevelObstacle
{
private:
int dx;
int dy;
long lastMove;
public:
AspirinObstacle(int px, int py, int deltax, int deltay);
virtual bool isHorizontal();
virtual void init(AbstractConsole* pConsole);
virtual void run(AbstractConsole* pConsole);
virtual void render(AbstractConsole* pConsole);
virtual bool onSnakeHit(Level* level);
};
|
Mikescher/Serpilicum | src/AutoPowerUp.h | #pragma once
#include "powerup.h"
#include "AbstractConsole.h"
class AutoPowerUp :
public PowerUp
{
private:
long ctime;
AbstractConsole* console;
public:
AutoPowerUp(AbstractConsole* pCons, int px, int py);
~AutoPowerUp(void);
virtual char getSymbol();
virtual PowerUpType getType();
};
|
Mikescher/Serpilicum | src/HighscoreMenu.h | #pragma once
#include "menuelement.h"
#include "Highscore.h"
#include "menu.h"
#include "Label.h"
#include "Button.h"
#include "ListenerCollection.h"
#include "Game.h"
class HighscoreMenu :
public Menu
{
private:
ActionListener* listener;
virtual void createMenu(ActionListener* highMenuListener, Highscore* pHighscore);
protected:
virtual std::string getName() = 0;
virtual int getHSID() = 0;
public:
HighscoreMenu(ActionListener * highMenuListener);
~HighscoreMenu(void);
virtual void onStart();
};
|
Mikescher/Serpilicum | src/Button.h | #pragma once
#include "MenuElement.h"
#include "ListenerCollection.h"
class Button:
public MenuElement
{
private:
std::string text;
ActionListener * listener;
int id;
virtual void throwEvent();
public:
Button(void);
Button(int id);
Button(int id, std::string initval, int nx, int ny);
virtual ~Button(void);
virtual void render(AbstractConsole* pConsole);
virtual void onKeyDown(int keycode);
virtual bool isFocusable();
virtual void setText(std::string pText);
virtual std::string getText();
virtual void setListener(ActionListener * lst);
virtual ActionListener *removeListener();
};
|
Mikescher/Serpilicum | src/DBConsole.h | <reponame>Mikescher/Serpilicum<gh_stars>0
#pragma once
#include <string>
#include <algorithm>
#include "AbstractConsole.h"
class DBConsole :
public AbstractConsole
{
private:
long firstTimeMillis;
long lastRenderTime;
int fpsCount;
long fpsSum;
double fps;
bool showFPS;
protected:
int display[BUFFER_W][BUFFER_H];
int buffer[BUFFER_W][BUFFER_H];
bool currKeyStates[256];
protected:
virtual void writeToConsole(int c, int x, int y) = 0;
virtual void showConsoleCursor(bool bShow) = 0;
virtual void hideConsole() = 0;
virtual unsigned char getKeyState() = 0;
virtual long getSystemCurrTimeMillis() = 0;
virtual void doSystemSleep(long duration) = 0;
virtual void setDimensions(short w, short h) = 0;
public:
DBConsole(void);
virtual ~DBConsole(void);
virtual void init();
virtual void redraw();
virtual void write(int c, int x, int y);
virtual void write(std::string s, int x, int y);
virtual void clearBuffer();
virtual void swap();
virtual void zoomIn(int centerX, int centerY);
virtual unsigned char getCurrentKeyState();
virtual long getCurrentTimeMillis();
virtual double getFPS();
virtual void onLevelStart();
virtual void onLevelStop();
};
|
Mikescher/Serpilicum | src/DeathMenu.h | <reponame>Mikescher/Serpilicum<gh_stars>0
#pragma once
#include "menu.h"
#include "Label.h"
#include "Button.h"
#include "ListenerCollection.h"
#include "Highscore.h"
#include "Game.h"
#include "Gamerules.h"
class DeathMenu :
public Menu
{
private:
virtual void createMenu(ActionListener * restartListener,Highscore* pHighscore, int pscore);
public:
DeathMenu(ActionListener * restartListener, int pscore, Game* game);
};
|
Mikescher/Serpilicum | src/BiteEffect.h | <gh_stars>0
#pragma once
#include "leveleffect.h"
class BiteEffect :
public LevelEffect
{
private:
long startTime;
int delay;
long delta;
int mode;
int elementchar;
public:
BiteEffect(int px, int py, int delayID, int elchar);
~BiteEffect(void);
virtual void start(AbstractConsole *console);
virtual void run(AbstractConsole *console);
virtual void render(AbstractConsole *console);
};
|
Mikescher/Serpilicum | src/CrazyConsole.h | <reponame>Mikescher/Serpilicum
#pragma once
#pragma warning(disable: 4244)
#define _USE_MATH_DEFINES
#include "oglconsole.h"
#include <vector>
#include "CrazyDouble.h"
class CrazyConsole :
public OGLConsole
{
private:
GLfloat depth;
CrazyDouble* heightshift;
CrazyDouble* xangleShift;
CrazyDouble* yangleShift;
CrazyDouble* zangleShift;
CrazyDouble* rcolorShift;
CrazyDouble* gcolorShift;
CrazyDouble* bcolorShift;
CrazyDouble* xscaleShift;
CrazyDouble* yscaleShift;
protected:
virtual void startRenderOGL();
virtual void renderOGLPos(int x, int y, int chr);
public:
CrazyConsole();
virtual void initOGL();
virtual void restartCrazy();
virtual void stopCrazy();
virtual void onLevelStart();
virtual void onLevelStop();
};
|
Mikescher/Serpilicum | src/Snake.h | <gh_stars>0
#pragma once
#include "SnakeElement.h"
#include <cmath>
#include "SnakeModifier.h"
#include "PathFindingAlgorithm.h"
class Level;
const int SNAKEPARTCHARS[] = {186, 205, 186, 205, 200, 201, 187, 188, 'X'};
enum Direction {NORTH=0, EAST=1, SOUTH=2, WEST=3};
enum SnakeIntersecton {SIS_NULL=8, SIS_N=0, SIS_NE=4, SIS_E=1, SIS_ES=5, SIS_S=2, SIS_SW=6, SIS_W=3, SIS_NW=7};
class Snake
{
private: // PathFinding
Level *level;
PathFindingAlgorithm* algo;
bool lastSearchFailed;
bool doNotRecalc;
Direction calcDirection();
int getFieldIdent(int px, int py);
void getNearestPowerUp(int& px, int& py);
void getRandomPowerUp(int& px, int& py);
bool isDirectionFree(Direction d);
Direction getDirectionBetween(int x1, int y1, int x2, int y2);
private:
SnakeElement * head;
Direction direction;
public:
Snake(Level *lvl, int sx, int sy, Direction dir);
virtual ~Snake(void);
virtual void onBeforeMove(Level* lvl, AbstractConsole* pConsole);
virtual void onAfterMove(Level* lvl, AbstractConsole* pConsole);
virtual int getLength();
virtual SnakeElement * getHead();
virtual SnakeElement* getElementAt(int pos);
virtual Direction getDirection();
virtual SnakeIntersecton getIntersectionOrientation(int position);
virtual SnakeIntersecton getIntersectionOrientation(SnakeElement* prev, SnakeElement* cur, SnakeElement* next);
virtual int findElement(SnakeElement* el);
virtual void extendForward(int c);
virtual void moveForward();
virtual void extendForward();
virtual void autoMoveForward();
virtual void autoExtendForward();
virtual void setDirection(Direction dir);
};
|
Mikescher/Serpilicum | src/Level.h | #pragma once
#include "Snake.h"
#include "PowerUpList.h"
#include "AbstractConsole.h"
#include <vector>
#include "LevelEffect.h"
#include "LevelObstacle.h"
#include "PowerUpSpawnEffect.h"
#include "Gamerules.h"
#include <limits>
class Level
{
private:
std::vector<LevelEffect*> effects;
std::vector<LevelObstacle*> obstacles;
SnakeModifier* modifier;
bool tempcollsionmatrix[BUFFER_W][BUFFER_H];
AbstractConsole* console;
int lifes;
int snake_speed;
int score;
Snake * snake;
PowerUpList * powerupList;
bool running;
bool is_dead;
long lastRenderTime;
long lastHPPowerupAdd;
long lastSpecPowerupAdd;
long lastSpecPowerupAddTest;
virtual void renderPowerups(AbstractConsole *console);
virtual void renderSnake(AbstractConsole *console);
virtual void renderEffects(AbstractConsole *console);
virtual void renderObstacles(AbstractConsole *console);
virtual void renderShards(AbstractConsole *console);
virtual void renderPoints(AbstractConsole *console);
virtual void addMissingHealthPowerUps(AbstractConsole * pConsole);
virtual void addMissingSpecialPowerUps(AbstractConsole * pConsole);
virtual void addHealthPowerUps(AbstractConsole *pconsole, int count);
virtual void addHealthPowerUps(AbstractConsole *pconsole, int hpux, int hpuy);
virtual PowerUpType testForPowerUpCollision();
virtual void testForDeath(AbstractConsole* pConsole);
virtual void testForObstacleCollision(AbstractConsole* pConsole);
virtual void runEffects(AbstractConsole *console);
virtual void runObstacles(AbstractConsole *console);
virtual void runModifier(AbstractConsole *console);
virtual void onHPCollect(AbstractConsole* pConsole);
virtual void removeSnakePieceWithEffect(AbstractConsole* pConsole, SnakeElement* prevelement, int depth);
virtual void decreaseLifeShardsBy(int by);
virtual void spawnNewAspirinObstacle(AbstractConsole* pConsole);
virtual void addPoints();
public:
Level();
virtual ~Level(void);
virtual void render(AbstractConsole* pConsole);
virtual void onKeyDown(AbstractConsole* pConsole, int keycode);
virtual void run(AbstractConsole* pConsole);
virtual bool isPositionPowerUp(int xx, int yy);
virtual bool isPositionSnake(int xx, int yy);
virtual bool isPositionUsed(int xx, int yy);
virtual bool isSpecialPowerUpOnField();
virtual double getMinimalSnakeDistance(int px, int py);
virtual Snake * getSnake();
virtual PowerUpList * getPowerUpList();
virtual SnakeModifier* getModifier();
virtual SnakeModifierType getModifierType();
virtual int getLifeShards();
virtual void addEffect(AbstractConsole *console, LevelEffect * effect);
virtual void setModifier(SnakeModifier* mod);
virtual void addObstacle(AbstractConsole *console, LevelObstacle * obs);
virtual void start(AbstractConsole* pConsole);
virtual void stop();
virtual void onDie();
virtual bool isRunning();
virtual bool isDead();
virtual int getScore();
};
|
Subsets and Splits