repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
kouxichao/ncnn
examples/image_caption/image_caption.h
#pragma once //the size of input image #ifndef IMAGE_SIZE #define IMAGE_SIZE 384 #endif //max byte to save results #ifndef CAPTION_MAX_SIZE #define CAPTION_MAX_SIZE 1000 #endif //image_data path #ifndef RGB_PATH #define RGB_PATH "image.data" #endif //encoder's output dimmention #ifndef ENCODER_DIM #define ENCODER_DIM 2048 #endif //lstm h dimmention #ifndef DECODER_DIM #define DECODER_DIM 512 #endif //attention dimmention #ifndef ATTENTION_DIM #define ATTENTION_DIM 512 #endif //max caption length to generate(max decode times) #ifndef MAX_CAPTION_LENGTH #define MAX_CAPTION_LENGTH 50 #endif //vocabulary size #ifndef VOCABULARY_SIZE #define VOCABULARY_SIZE 11676 #endif //embedding dimmension #ifndef EMBEDDING_DIM #define EMBEDDING_DIM 512 #endif //number sequences to consider at each decode-step #ifndef BEAM_SIZE #define BEAM_SIZE 5 #endif //the size of decoder output image #ifndef ENCODER_IMAGE_SIZE #define ENCODER_IMAGE_SIZE 14 #endif //number sequences to consider at each decode-step #ifndef WEIGHT_BIN_FILEPATH #ifdef ARM_HISI #define WEIGHT_BIN_FILEPATH "./imagecaption_decoder.bin" #else #define WEIGHT_BIN_FILEPATH "../../../models/imagecaption/imagecaption_decoder.bin" #endif #endif #include "net.h" //nnie headers #include "hi_common.h" #include "hi_comm_sys.h" #include "hi_comm_svp.h" #include "sample_comm_nnie.h" /** *@args: * tensor : The data to be processed. * dim : 0 for c, 1 for h, 2 for w * k : The number of element to be selected. * dir : 1 for largest k element, 0 for smallest k element. */ //TODO dim,dir argument void topk(std::vector< std::pair<float, int> >& topK_re, ncnn::Mat& tensor, int k); /** * function: image caption decoder forward. * @args: * caption: store final result */ extern "C" { void SAMPLE_SVP_NNIE_Encode(HI_CHAR *pcSrcFile, HI_FLOAT *aps32PermuteResult[]); void SAMPLE_SVP_NNIE_ImaCap_init(); void SAMPLE_SVP_NNIE_ImaCap_End(); } //int imgcap_forward(ncnn::Mat& inputData, char* caption); int imgcap_forward(const char* image_path, char* caption);
kouxichao/ncnn
src/layer/dimop.h
#ifndef LAYER_DIMOP_H #define LAYER_DIMOP_H #include "layer.h" namespace ncnn { class DimOp : public Layer { public: DimOp(); virtual int load_param(const ParamDict& pd); virtual int forward(const std::vector<Mat>& bottom_blobs, std::vector<Mat>& top_blobs, const Option& opt) const; // virtual int forward_inplace(Mat& bottom_top_blob, const Option& opt) const; #if NCNN_VULKAN virtual int create_pipeline(); virtual int destroy_pipeline(); virtual int forward(const std::vector<VkMat>& bottom_blobs, std::vector<VkMat>& top_blobs, VkCompute& cmd, const Option& opt) const; virtual int forward_inplace(VkMat& bottom_top_blob, VkCompute& cmd, const Option& opt) const; #endif // NCNN_VULKAN enum { Operation_ADD = 0, Operation_SUB = 1, Operation_MUL = 2, Operation_DIV = 3, Operation_MAX = 4, Operation_MIN = 5, Operation_POW = 6, Operation_RSUB = 7, Operation_RDIV = 8 }; public: // param int op_type; int dim; #if NCNN_VULKAN Pipeline* pipeline_binaryop; Pipeline* pipeline_binaryop_pack4; #endif // NCNN_VULKAN }; } // namespace ncnn #endif // LAYER_BINARYOP_H
kouxichao/ncnn
examples/face_recognition/face_recognization.h
<filename>examples/face_recognition/face_recognization.h #ifndef FACE_RECOGNIZATION_h #define FACE_RECOGNIZATION_h //#include "net.h" #include<vector> #ifndef DKMAXBOXNUM #define DKMAXBOXNUM 30 // 最多可检测对象数目 #endif #ifndef FEATURE_DIM #define FEATURE_DIM 128 #endif #ifndef DKMINFACEREGISTERIMGNUM #define DKMINFACEREGISTERIMGNUM 5 // 人脸注册时最少需采集人脸数目 #endif typedef struct { // 顺时针排列 int x1; // 偏左上角横坐标 int y1; // 偏左上角纵坐标 int x2; // 偏右上角横坐标 int y2; // 偏右上角纵坐标 int x3; // 偏右下角横坐标 int y3; // 偏右下角纵坐标 int x4; // 偏左下角横坐标 int y4; // 偏左下角纵坐标 }DKSBox; typedef struct { int tag; // 标签,与宏定义对应 float confidence; // 置信度 DKSBox box; }DKSSingleDetectionRes; typedef struct { int num; // 当前检测出的物体总数目 DKSSingleDetectionRes boxes[DKMAXBOXNUM]; }DKSMultiDetectionRes; typedef struct { int index; //边界框索引 float threshold; // 相似度阈值,相似度超过该值认为不能认出该人脸 int k; }DKSFaceRecognizationParam; typedef struct { int index; //边界框索引 float threshold; // 相似度阈值,相似度超过该值认为不能认出该人脸 int flag; }DKSFaceRegisterParam; /* 工具函数 */ //计算向量内积 float dot(float* fc1, float* fc2); //规范化向量 int normalize(float* fc1); //knn最近邻实现 int knn(std::vector< std::pair<int, float> >& re, int k); /* 人脸注册识别相关函数 */ // 说明:录入人脸,在学习人脸阶段,获取至少DKMINFACEREGISTERIMGNUM张同一人脸图片 // 初始化,连接sqlite,准备写入人脸特征和语音,初始化学习图片次数为0 void DKFaceRegisterInit(); // 根据检测到的人脸结果计算特征 int DKFaceRegisterProcess(char * imgfilename, int iWidth, int iHeight, DKSMultiDetectionRes boxes, DKSFaceRegisterParam param); //参数1:将计算好的特征存入sqlite中(flag为1),或取消学习人脸(flag为0)关闭数据库。参数2:是否为新添加的人(增加记录数)。参数3:添加特征的行id(以1开始)注:当newPerson=true时,忽略参数rid。 void DKFaceRegisterEnd(int flag, bool newPerson, int rid); //参数1:将计算好的特征存入sqlite中(flag为1),或取消学习人脸(flag为0)关闭数据库。参数2:要存入的特征序数(为1时表示创建新的记录即有新人注册)。 void DKFaceRegisterEnd(const char* voiceFile); // 说明:从已注册的人脸中识别对应的人脸 // 初始化,连接sqlite,获取人脸库中各个人脸的特征 void DKFaceRecognizationInit(); int DKFaceRecognizationProcess(char* recvoicefile, const char * imgfilename, int iWidth, int iHeight, DKSMultiDetectionRes boxes, DKSFaceRecognizationParam param); // 释放人脸识别资源 void DKFaceRecognizationEnd(); #endif
kouxichao/ncnn
examples/image_caption/encoder_forward.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <signal.h> #include <pthread.h> #include <sys/prctl.h> #include <math.h> #include "hi_common.h" #include "hi_comm_sys.h" #include "hi_comm_svp.h" #include "sample_comm.h" #include "sample_comm_svp.h" #include "sample_comm_nnie.h" #include "sample_nnie_main.h" #include "sample_svp_nnie_software.h" #include "sample_comm_ive.h" /*ssd para*/ static SAMPLE_SVP_NNIE_MODEL_S s_stImgCapModel = {0}; static SAMPLE_SVP_NNIE_PARAM_S s_stImgCapNnieParam = {0}; static SAMPLE_SVP_NNIE_SSD_SOFTWARE_PARAM_S s_stImgCapSoftwareParam = {0}; /****************************************************************************** * function : NNIE Forward ******************************************************************************/ static HI_S32 IMGCAP_SVP_NNIE_Forward(SAMPLE_SVP_NNIE_PARAM_S *pstNnieParam, SAMPLE_SVP_NNIE_INPUT_DATA_INDEX_S* pstInputDataIdx, SAMPLE_SVP_NNIE_PROCESS_SEG_INDEX_S* pstProcSegIdx,HI_BOOL bInstant) { HI_S32 s32Ret = HI_SUCCESS; HI_U32 i = 0, j = 0; HI_BOOL bFinish = HI_FALSE; SVP_NNIE_HANDLE hSvpNnieHandle = 0; HI_U32 u32TotalStepNum = 0; SAMPLE_COMM_SVP_FlushCache(pstNnieParam->astForwardCtrl[pstProcSegIdx->u32SegIdx].stTskBuf.u64PhyAddr, (HI_VOID *) pstNnieParam->astForwardCtrl[pstProcSegIdx->u32SegIdx].stTskBuf.u64VirAddr, pstNnieParam->astForwardCtrl[pstProcSegIdx->u32SegIdx].stTskBuf.u32Size); /*set input blob according to node name*/ if(pstInputDataIdx->u32SegIdx != pstProcSegIdx->u32SegIdx) { for(i = 0; i < pstNnieParam->pstModel->astSeg[pstProcSegIdx->u32SegIdx].u16SrcNum; i++) { for(j = 0; j < pstNnieParam->pstModel->astSeg[pstInputDataIdx->u32SegIdx].u16DstNum; j++) { if(0 == strncmp(pstNnieParam->pstModel->astSeg[pstInputDataIdx->u32SegIdx].astDstNode[j].szName, pstNnieParam->pstModel->astSeg[pstProcSegIdx->u32SegIdx].astSrcNode[i].szName, SVP_NNIE_NODE_NAME_LEN)) { pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astSrc[i] = pstNnieParam->astSegData[pstInputDataIdx->u32SegIdx].astDst[j]; break; } } SAMPLE_SVP_CHECK_EXPR_RET((j == pstNnieParam->pstModel->astSeg[pstInputDataIdx->u32SegIdx].u16DstNum), HI_FAILURE,SAMPLE_SVP_ERR_LEVEL_ERROR,"Error,can't find %d-th seg's %d-th src blob!\n", pstProcSegIdx->u32SegIdx,i); } } /*NNIE_Forward*/ s32Ret = HI_MPI_SVP_NNIE_Forward(&hSvpNnieHandle, pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astSrc, pstNnieParam->pstModel, pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst, &pstNnieParam->astForwardCtrl[pstProcSegIdx->u32SegIdx], bInstant); SAMPLE_SVP_CHECK_EXPR_RET(HI_SUCCESS != s32Ret,s32Ret,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,HI_MPI_SVP_NNIE_Forward failed!\n"); if(bInstant) { /*Wait NNIE finish*/ while(HI_ERR_SVP_NNIE_QUERY_TIMEOUT == (s32Ret = HI_MPI_SVP_NNIE_Query(pstNnieParam->astForwardCtrl[pstProcSegIdx->u32SegIdx].enNnieId, hSvpNnieHandle, &bFinish, HI_TRUE))) { usleep(100); SAMPLE_SVP_TRACE(SAMPLE_SVP_ERR_LEVEL_INFO, "HI_MPI_SVP_NNIE_Query Query timeout!\n"); } } bFinish = HI_FALSE; for(i = 0; i < pstNnieParam->astForwardCtrl[pstProcSegIdx->u32SegIdx].u32DstNum; i++) { if(SVP_BLOB_TYPE_SEQ_S32 == pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].enType) { for(j = 0; j < pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u32Num; j++) { u32TotalStepNum += *((HI_U32*)(pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].unShape.stSeq.u64VirAddrStep)+j); } SAMPLE_COMM_SVP_FlushCache(pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u64PhyAddr, (HI_VOID *) pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u64VirAddr, u32TotalStepNum*pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u32Stride); } else { SAMPLE_COMM_SVP_FlushCache(pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u64PhyAddr, (HI_VOID *) pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u64VirAddr, pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u32Num* pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].unShape.stWhc.u32Chn* pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].unShape.stWhc.u32Height* pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u32Stride); } } return s32Ret; } /****************************************************************************** * function : Fill Src Data ******************************************************************************/ static HI_S32 IMGCAP_SVP_NNIE_FillSrcData(SAMPLE_SVP_NNIE_CFG_S* pstNnieCfg, SAMPLE_SVP_NNIE_PARAM_S *pstNnieParam, SAMPLE_SVP_NNIE_INPUT_DATA_INDEX_S* pstInputDataIdx) { FILE* fp = NULL; HI_U32 i =0, j = 0, n = 0,m = 0; HI_U32 number = 0; HI_U32 u32Height = 0, u32Width = 0, u32Chn = 0, u32Stride = 0, u32Dim = 0; HI_U32 u32VarSize = 0; HI_S32 s32Ret = HI_SUCCESS; HI_U8*pu8PicAddr = NULL; HI_U32*pu32StepAddr = NULL; HI_U32 u32SegIdx = pstInputDataIdx->u32SegIdx; HI_U32 u32NodeIdx = pstInputDataIdx->u32NodeIdx; HI_U32 u32TotalStepNum = 0; HI_U32 mean_val_rgb[3] = {0.485,0.456,0.406}; HI_U32 var_val_rgb[3] = {0.229,0.224,0.225}; /*open file*/ if (NULL != pstNnieCfg->pszPic) { fp = fopen(pstNnieCfg->pszPic,"rb"); SAMPLE_SVP_CHECK_EXPR_RET(NULL == fp,HI_INVALID_VALUE,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error, open file failed!\n"); } /*get data size*/ if(SVP_BLOB_TYPE_U8 <= pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].enType && SVP_BLOB_TYPE_YVU422SP >= pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].enType) { u32VarSize = sizeof(HI_U8); } else { u32VarSize = sizeof(HI_U32); } /*fill src data*/ if(SVP_BLOB_TYPE_SEQ_S32 == pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].enType) { u32Dim = pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].unShape.stSeq.u32Dim; number = u32Dim / 3; u32Stride = pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Stride; pu32StepAddr = (HI_U32*)(pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].unShape.stSeq.u64VirAddrStep); pu8PicAddr = (HI_U8*)(pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u64VirAddr); for(n = 0; n < pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Num; n++) { for(i = 0;i < *(pu32StepAddr+n); i++) { s32Ret = fread(pu8PicAddr,u32Dim*u32VarSize,1,fp); SAMPLE_SVP_CHECK_EXPR_GOTO(1 != s32Ret,FAIL,SAMPLE_SVP_ERR_LEVEL_ERROR,"Error,Read image file failed!\n"); for(m = 0;m < number; m++)//预处理 { pu8PicAddr[m] = (pu8PicAddr[m]/255 - mean_val_rgb[0])/var_val_rgb[0]; pu8PicAddr[m + number] = (pu8PicAddr[m + number]/255 - mean_val_rgb[1])/var_val_rgb[1]; pu8PicAddr[m + number * 2] = (pu8PicAddr[m + number * 2]/255 - mean_val_rgb[2])/var_val_rgb[2]; } pu8PicAddr += u32Stride; } u32TotalStepNum += *(pu32StepAddr+n); } SAMPLE_COMM_SVP_FlushCache(pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u64PhyAddr, (HI_VOID *) pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u64VirAddr, u32TotalStepNum*u32Stride); } else { u32Height = pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].unShape.stWhc.u32Height; u32Width = pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].unShape.stWhc.u32Width; u32Chn = pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].unShape.stWhc.u32Chn; u32Stride = pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Stride; pu8PicAddr = (HI_U8*)(pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u64VirAddr); if(SVP_BLOB_TYPE_YVU420SP== pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].enType) { for(n = 0; n < pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Num; n++) { for(i = 0; i < u32Chn*u32Height/2; i++) { s32Ret = fread(pu8PicAddr,u32Width*u32VarSize,1,fp); SAMPLE_SVP_CHECK_EXPR_GOTO(1 != s32Ret,FAIL,SAMPLE_SVP_ERR_LEVEL_ERROR,"Error,Read image file failed!\n"); pu8PicAddr += u32Stride; } } } else if(SVP_BLOB_TYPE_YVU422SP== pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].enType) { for(n = 0; n < pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Num; n++) { for(i = 0; i < u32Height*2; i++) { s32Ret = fread(pu8PicAddr,u32Width*u32VarSize,1,fp); SAMPLE_SVP_CHECK_EXPR_GOTO(1 != s32Ret,FAIL,SAMPLE_SVP_ERR_LEVEL_ERROR,"Error,Read image file failed!\n"); pu8PicAddr += u32Stride; } } } else { for(n = 0; n < pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Num; n++) { for(i = 0;i < u32Chn; i++) { for(j = 0; j < u32Height; j++) { s32Ret = fread(pu8PicAddr,u32Width*u32VarSize,1,fp); SAMPLE_SVP_CHECK_EXPR_GOTO(1 != s32Ret,FAIL,SAMPLE_SVP_ERR_LEVEL_ERROR,"Error,Read image file failed!\n"); pu8PicAddr += u32Stride; } } } } SAMPLE_COMM_SVP_FlushCache(pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u64PhyAddr, (HI_VOID *) pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u64VirAddr, pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Num*u32Chn*u32Height*u32Stride); } fclose(fp); return HI_SUCCESS; FAIL: fclose(fp); return HI_FAILURE; } /****************************************************************************** * function : IMGCAP Deinit ******************************************************************************/ static HI_S32 SAMPLE_SVP_NNIE_ImaCap_Deinit(SAMPLE_SVP_NNIE_PARAM_S *pstNnieParam, SAMPLE_SVP_NNIE_SSD_SOFTWARE_PARAM_S* pstSoftWareParam,SAMPLE_SVP_NNIE_MODEL_S *pstNnieModel) { HI_S32 s32Ret = HI_SUCCESS; /*hardware deinit*/ if(pstNnieParam!=NULL) { s32Ret = SAMPLE_COMM_SVP_NNIE_ParamDeinit(pstNnieParam); SAMPLE_SVP_CHECK_EXPR_TRACE(HI_SUCCESS != s32Ret,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,SAMPLE_COMM_SVP_NNIE_ParamDeinit failed!\n"); } /*model deinit*/ if(pstNnieModel!=NULL) { s32Ret = SAMPLE_COMM_SVP_NNIE_UnloadModel(pstNnieModel); SAMPLE_SVP_CHECK_EXPR_TRACE(HI_SUCCESS != s32Ret,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,SAMPLE_COMM_SVP_NNIE_UnloadModel failed!\n"); } return s32Ret; } /****************************************************************************** * function : IMGCAP init ******************************************************************************/ static HI_S32 SAMPLE_SVP_NNIE_ImgCap_ParamInit(SAMPLE_SVP_NNIE_CFG_S* pstCfg, SAMPLE_SVP_NNIE_PARAM_S *pstNnieParam, SAMPLE_SVP_NNIE_SSD_SOFTWARE_PARAM_S* pstSoftWareParam) { HI_S32 s32Ret = HI_SUCCESS; /*init hardware para*/ s32Ret = SAMPLE_COMM_SVP_NNIE_ParamInit(pstCfg,pstNnieParam); SAMPLE_SVP_CHECK_EXPR_GOTO(HI_SUCCESS != s32Ret,INIT_FAIL_0,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error(%#x),SAMPLE_COMM_SVP_NNIE_ParamInit failed!\n",s32Ret); return s32Ret; INIT_FAIL_0: s32Ret = SAMPLE_SVP_NNIE_ImaCap_Deinit(pstNnieParam,pstSoftWareParam,NULL); SAMPLE_SVP_CHECK_EXPR_RET(HI_SUCCESS != s32Ret,s32Ret,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error(%#x),SAMPLE_SVP_NNIE_ImaCap_Deinit failed!\n",s32Ret); return HI_FAILURE; } void SAMPLE_SVP_NNIE_ImaCap_init() { /*Sys init*/ //SAMPLE_COMM_SVP_CheckSysInit(); //系统初始化 system init HI_S32 s32Ret = HI_SUCCESS; //HI_S32就是 int s32Ret = 0 HI_CHAR *pcModelName = "./imagecaption_encoder.wk"; // 设置模型路径 SAMPLE_SVP_TRACE_INFO("Image caption encoder Load model!\n"); //输出模型的信息 s32Ret = SAMPLE_COMM_SVP_NNIE_LoadModel(pcModelName,&s_stImgCapModel); //载入模型 SAMPLE_SVP_CHECK_EXPR_GOTO(HI_SUCCESS != s32Ret,ENCODER_FAIL_0,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,SAMPLE_COMM_SVP_NNIE_LoadModel failed!\n"); //错误报告 return; ENCODER_FAIL_0: SAMPLE_SVP_NNIE_ImaCap_Deinit(&s_stImgCapNnieParam,&s_stImgCapSoftwareParam,&s_stImgCapModel); //SAMPLE_COMM_SVP_CheckSysExit(); } void SAMPLE_SVP_NNIE_ImaCap_End() { SAMPLE_SVP_NNIE_ImaCap_Deinit(&s_stImgCapNnieParam,&s_stImgCapSoftwareParam,&s_stImgCapModel); //SAMPLE_COMM_SVP_CheckSysExit(); } /****************************************************************************** * function : show IMGCAP sample(image 384x384 U8_C3) ******************************************************************************/ void SAMPLE_SVP_NNIE_Encode(HI_CHAR *pcSrcFile, HI_FLOAT *aps32PermuteResult[]) { HI_U32 u32PicNum = 1; HI_FLOAT f32PrintResultThresh = 0.0f; HI_S32 s32Ret = HI_SUCCESS; SAMPLE_SVP_NNIE_CFG_S stNnieCfg = {0}; SAMPLE_SVP_NNIE_INPUT_DATA_INDEX_S stInputDataIdx = {0}; SAMPLE_SVP_NNIE_PROCESS_SEG_INDEX_S stProcSegIdx = {0}; /*Set configuration parameter*/ stNnieCfg.pszPic= pcSrcFile; stNnieCfg.u32MaxInputNum = u32PicNum; //max input image num in each batch stNnieCfg.u32MaxRoiNum = 0; stNnieCfg.aenNnieCoreId[0] = SVP_NNIE_ID_0;//set NNIE core //clock_t finish = clock(); //printf("time cost %d ms:", (finish - start)/1000); /*Ssd parameter initialization*/ /*Ssd parameters are set in SAMPLE_SVP_NNIE_Ssd_SoftwareInit, if user has changed net struct, please make sure the parameter settings in SAMPLE_SVP_NNIE_Ssd_SoftwareInit function are correct*/ SAMPLE_SVP_TRACE_INFO("Image caption encoder parameter initialization!\n"); s_stImgCapNnieParam.pstModel = &s_stImgCapModel.stModel; s32Ret = SAMPLE_SVP_NNIE_ImgCap_ParamInit(&stNnieCfg,&s_stImgCapNnieParam,&s_stImgCapSoftwareParam); SAMPLE_SVP_CHECK_EXPR_GOTO(HI_SUCCESS != s32Ret,SSD_FAIL_0,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,SAMPLE_SVP_NNIE_ImgCap_ParamInit failed!\n"); /*Fill src data*/ SAMPLE_SVP_TRACE_INFO("Image caption encoder start!\n"); stInputDataIdx.u32SegIdx = 0; stInputDataIdx.u32NodeIdx = 0; s32Ret = IMGCAP_SVP_NNIE_FillSrcData(&stNnieCfg,&s_stImgCapNnieParam,&stInputDataIdx); SAMPLE_SVP_CHECK_EXPR_GOTO(HI_SUCCESS != s32Ret,SSD_FAIL_0,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,IMGCAP_SVP_NNIE_FillSrcData failed!\n"); /*NNIE process(process the 0-th segment)*/ stProcSegIdx.u32SegIdx = 0; s32Ret = IMGCAP_SVP_NNIE_Forward(&s_stImgCapNnieParam,&stInputDataIdx,&stProcSegIdx,HI_TRUE); SAMPLE_SVP_CHECK_EXPR_GOTO(HI_SUCCESS != s32Ret,SSD_FAIL_0,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,IMGCAP_SVP_NNIE_Forward failed!\n"); //printf("frame_num:%d(%d_%d_%d)\n", s_stImgCapNnieParam.astSegData[0].astDst[0].u32Num, \ s_stImgCapNnieParam.astSegData[0].astDst[0].unShape.stWhc.u32Chn,\ s_stImgCapNnieParam.astSegData[0].astDst[0].unShape.stWhc.u32Height,\ s_stImgCapNnieParam.astSegData[0].astDst[0].unShape.stWhc.u32Width); unsigned long size_out = s_stImgCapNnieParam.astSegData[0].astDst[0].unShape.stWhc.u32Width * \ s_stImgCapNnieParam.astSegData[0].astDst[0].unShape.stWhc.u32Height * \ s_stImgCapNnieParam.astSegData[0].astDst[0].unShape.stWhc.u32Chn; for(size_t i = 0; i < size_out; i++) { *((HI_FLOAT*)s_stImgCapNnieParam.astSegData[0].astDst[0].u64VirAddr + i) = (HI_FLOAT)(*((HI_S32*)s_stImgCapNnieParam.astSegData[0].astDst[0].u64VirAddr + i)); } memcpy(aps32PermuteResult[0], (HI_FLOAT*)s_stImgCapNnieParam.astSegData[0].astDst[0].u64VirAddr, sizeof(HI_FLOAT) * size_out); SSD_FAIL_0: SAMPLE_COMM_SVP_NNIE_ParamDeinit(&s_stImgCapNnieParam); return; }
kouxichao/ncnn
examples/test/resnet.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <signal.h> #include <pthread.h> #include <sys/prctl.h> #include <math.h> #include "hi_common.h" #include "hi_comm_sys.h" #include "hi_comm_svp.h" #include "sample_comm.h" #include "sample_comm_svp.h" #include "sample_comm_nnie.h" #include "sample_nnie_main.h" #include "sample_svp_nnie_software.h" #include "sample_comm_ive.h" /*ssd para*/ static SAMPLE_SVP_NNIE_MODEL_S s_stSsdModel = {0}; static SAMPLE_SVP_NNIE_PARAM_S s_stSsdNnieParam = {0}; static SAMPLE_SVP_NNIE_SSD_SOFTWARE_PARAM_S s_stSsdSoftwareParam = {0}; /****************************************************************************** * function : NNIE Forward ******************************************************************************/ static HI_S32 SAMPLE_SVP_NNIE_Forward(SAMPLE_SVP_NNIE_PARAM_S *pstNnieParam, SAMPLE_SVP_NNIE_INPUT_DATA_INDEX_S* pstInputDataIdx, SAMPLE_SVP_NNIE_PROCESS_SEG_INDEX_S* pstProcSegIdx,HI_BOOL bInstant) { HI_S32 s32Ret = HI_SUCCESS; HI_U32 i = 0, j = 0; HI_BOOL bFinish = HI_FALSE; SVP_NNIE_HANDLE hSvpNnieHandle = 0; HI_U32 u32TotalStepNum = 0; SAMPLE_COMM_SVP_FlushCache(pstNnieParam->astForwardCtrl[pstProcSegIdx->u32SegIdx].stTskBuf.u64PhyAddr, (HI_VOID *) pstNnieParam->astForwardCtrl[pstProcSegIdx->u32SegIdx].stTskBuf.u64VirAddr, pstNnieParam->astForwardCtrl[pstProcSegIdx->u32SegIdx].stTskBuf.u32Size); /*set input blob according to node name*/ if(pstInputDataIdx->u32SegIdx != pstProcSegIdx->u32SegIdx) { for(i = 0; i < pstNnieParam->pstModel->astSeg[pstProcSegIdx->u32SegIdx].u16SrcNum; i++) { for(j = 0; j < pstNnieParam->pstModel->astSeg[pstInputDataIdx->u32SegIdx].u16DstNum; j++) { if(0 == strncmp(pstNnieParam->pstModel->astSeg[pstInputDataIdx->u32SegIdx].astDstNode[j].szName, pstNnieParam->pstModel->astSeg[pstProcSegIdx->u32SegIdx].astSrcNode[i].szName, SVP_NNIE_NODE_NAME_LEN)) { pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astSrc[i] = pstNnieParam->astSegData[pstInputDataIdx->u32SegIdx].astDst[j]; break; } } SAMPLE_SVP_CHECK_EXPR_RET((j == pstNnieParam->pstModel->astSeg[pstInputDataIdx->u32SegIdx].u16DstNum), HI_FAILURE,SAMPLE_SVP_ERR_LEVEL_ERROR,"Error,can't find %d-th seg's %d-th src blob!\n", pstProcSegIdx->u32SegIdx,i); } } /*NNIE_Forward*/ s32Ret = HI_MPI_SVP_NNIE_Forward(&hSvpNnieHandle, pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astSrc, pstNnieParam->pstModel, pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst, &pstNnieParam->astForwardCtrl[pstProcSegIdx->u32SegIdx], bInstant); SAMPLE_SVP_CHECK_EXPR_RET(HI_SUCCESS != s32Ret,s32Ret,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,HI_MPI_SVP_NNIE_Forward failed!\n"); if(bInstant) { /*Wait NNIE finish*/ while(HI_ERR_SVP_NNIE_QUERY_TIMEOUT == (s32Ret = HI_MPI_SVP_NNIE_Query(pstNnieParam->astForwardCtrl[pstProcSegIdx->u32SegIdx].enNnieId, hSvpNnieHandle, &bFinish, HI_TRUE))) { usleep(100); SAMPLE_SVP_TRACE(SAMPLE_SVP_ERR_LEVEL_INFO, "HI_MPI_SVP_NNIE_Query Query timeout!\n"); } } bFinish = HI_FALSE; for(i = 0; i < pstNnieParam->astForwardCtrl[pstProcSegIdx->u32SegIdx].u32DstNum; i++) { if(SVP_BLOB_TYPE_SEQ_S32 == pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].enType) { for(j = 0; j < pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u32Num; j++) { u32TotalStepNum += *((HI_U32*)(pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].unShape.stSeq.u64VirAddrStep)+j); } SAMPLE_COMM_SVP_FlushCache(pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u64PhyAddr, (HI_VOID *) pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u64VirAddr, u32TotalStepNum*pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u32Stride); } else { SAMPLE_COMM_SVP_FlushCache(pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u64PhyAddr, (HI_VOID *) pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u64VirAddr, pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u32Num* pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].unShape.stWhc.u32Chn* pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].unShape.stWhc.u32Height* pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u32Stride); } } return s32Ret; } /****************************************************************************** * function : NNIE ForwardWithBbox ******************************************************************************/ static HI_S32 SAMPLE_SVP_NNIE_ForwardWithBbox(SAMPLE_SVP_NNIE_PARAM_S *pstNnieParam, SAMPLE_SVP_NNIE_INPUT_DATA_INDEX_S* pstInputDataIdx,SVP_SRC_BLOB_S astBbox[], SAMPLE_SVP_NNIE_PROCESS_SEG_INDEX_S* pstProcSegIdx,HI_BOOL bInstant) { HI_S32 s32Ret = HI_SUCCESS; HI_BOOL bFinish = HI_FALSE; SVP_NNIE_HANDLE hSvpNnieHandle = 0; HI_U32 u32TotalStepNum = 0; HI_U32 i, j; SAMPLE_COMM_SVP_FlushCache(pstNnieParam->astForwardWithBboxCtrl[pstProcSegIdx->u32SegIdx].stTskBuf.u64PhyAddr, (HI_VOID *) pstNnieParam->astForwardWithBboxCtrl[pstProcSegIdx->u32SegIdx].stTskBuf.u64VirAddr, pstNnieParam->astForwardWithBboxCtrl[pstProcSegIdx->u32SegIdx].stTskBuf.u32Size); /*set input blob according to node name*/ if(pstInputDataIdx->u32SegIdx != pstProcSegIdx->u32SegIdx) { for(i = 0; i < pstNnieParam->pstModel->astSeg[pstProcSegIdx->u32SegIdx].u16SrcNum; i++) { for(j = 0; j < pstNnieParam->pstModel->astSeg[pstInputDataIdx->u32SegIdx].u16DstNum; j++) { if(0 == strncmp(pstNnieParam->pstModel->astSeg[pstInputDataIdx->u32SegIdx].astDstNode[j].szName, pstNnieParam->pstModel->astSeg[pstProcSegIdx->u32SegIdx].astSrcNode[i].szName, SVP_NNIE_NODE_NAME_LEN)) { pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astSrc[i] = pstNnieParam->astSegData[pstInputDataIdx->u32SegIdx].astDst[j]; break; } } SAMPLE_SVP_CHECK_EXPR_RET((j == pstNnieParam->pstModel->astSeg[pstInputDataIdx->u32SegIdx].u16DstNum), HI_FAILURE,SAMPLE_SVP_ERR_LEVEL_ERROR,"Error,can't find %d-th seg's %d-th src blob!\n", pstProcSegIdx->u32SegIdx,i); } } /*NNIE_ForwardWithBbox*/ s32Ret = HI_MPI_SVP_NNIE_ForwardWithBbox(&hSvpNnieHandle, pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astSrc,astBbox, pstNnieParam->pstModel, pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst, &pstNnieParam->astForwardWithBboxCtrl[pstProcSegIdx->u32SegIdx], bInstant); SAMPLE_SVP_CHECK_EXPR_RET(HI_SUCCESS != s32Ret,s32Ret,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,HI_MPI_SVP_NNIE_ForwardWithBbox failed!\n"); if(bInstant) { /*Wait NNIE finish*/ while(HI_ERR_SVP_NNIE_QUERY_TIMEOUT == (s32Ret = HI_MPI_SVP_NNIE_Query(pstNnieParam->astForwardWithBboxCtrl[pstProcSegIdx->u32SegIdx].enNnieId, hSvpNnieHandle, &bFinish, HI_TRUE))) { usleep(100); SAMPLE_SVP_TRACE(SAMPLE_SVP_ERR_LEVEL_INFO, "HI_MPI_SVP_NNIE_Query Query timeout!\n"); } } bFinish = HI_FALSE; for(i = 0; i < pstNnieParam->astForwardCtrl[pstProcSegIdx->u32SegIdx].u32DstNum; i++) { if(SVP_BLOB_TYPE_SEQ_S32 == pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].enType) { for(j = 0; j < pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u32Num; j++) { u32TotalStepNum += *((HI_U32*)(pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].unShape.stSeq.u64VirAddrStep)+j); } SAMPLE_COMM_SVP_FlushCache(pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u64PhyAddr, (HI_VOID *) pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u64VirAddr, u32TotalStepNum*pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u32Stride); } else { SAMPLE_COMM_SVP_FlushCache(pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u64PhyAddr, (HI_VOID *) pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u64VirAddr, pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u32Num* pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].unShape.stWhc.u32Chn* pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].unShape.stWhc.u32Height* pstNnieParam->astSegData[pstProcSegIdx->u32SegIdx].astDst[i].u32Stride); } } return s32Ret; } /****************************************************************************** * function : Fill Src Data ******************************************************************************/ static HI_S32 SAMPLE_SVP_NNIE_FillSrcData(SAMPLE_SVP_NNIE_CFG_S* pstNnieCfg, SAMPLE_SVP_NNIE_PARAM_S *pstNnieParam, SAMPLE_SVP_NNIE_INPUT_DATA_INDEX_S* pstInputDataIdx) { FILE* fp = NULL; HI_U32 i =0, j = 0, n = 0,m = 0; HI_U32 number = 0; HI_U32 u32Height = 0, u32Width = 0, u32Chn = 0, u32Stride = 0, u32Dim = 0; HI_U32 u32VarSize = 0; HI_S32 s32Ret = HI_SUCCESS; HI_U8*pu8PicAddr = NULL; HI_U32*pu32StepAddr = NULL; HI_U32 u32SegIdx = pstInputDataIdx->u32SegIdx; HI_U32 u32NodeIdx = pstInputDataIdx->u32NodeIdx; HI_U32 u32TotalStepNum = 0; HI_U32 mean_val_rgb[3] = {0.485,0.456,0.406}; HI_U32 var_val_rgb[3] = {0.229,0.224,0.225}; /*open file*/ if (NULL != pstNnieCfg->pszPic) { fp = fopen(pstNnieCfg->pszPic,"rb"); SAMPLE_SVP_CHECK_EXPR_RET(NULL == fp,HI_INVALID_VALUE,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error, open file failed!\n"); } /*get data size*/ if(SVP_BLOB_TYPE_U8 <= pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].enType && SVP_BLOB_TYPE_YVU422SP >= pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].enType) { u32VarSize = sizeof(HI_U8); } else { u32VarSize = sizeof(HI_U32); } /*fill src data*/ if(SVP_BLOB_TYPE_SEQ_S32 == pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].enType) { u32Dim = pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].unShape.stSeq.u32Dim; number = u32Dim / 3; u32Stride = pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Stride; pu32StepAddr = (HI_U32*)(pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].unShape.stSeq.u64VirAddrStep); pu8PicAddr = (HI_U8*)(pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u64VirAddr); for(n = 0; n < pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Num; n++) { for(i = 0;i < *(pu32StepAddr+n); i++) { s32Ret = fread(pu8PicAddr,u32Dim*u32VarSize,1,fp); SAMPLE_SVP_CHECK_EXPR_GOTO(1 != s32Ret,FAIL,SAMPLE_SVP_ERR_LEVEL_ERROR,"Error,Read image file failed!\n"); for(m = 0;m < number; m++)//预处理 { pu8PicAddr[m] = (pu8PicAddr[m]/255 - mean_val_rgb[0])/var_val_rgb[0]; pu8PicAddr[m + number] = (pu8PicAddr[m + number]/255 - mean_val_rgb[1])/var_val_rgb[1]; pu8PicAddr[m + number * 2] = (pu8PicAddr[m + number * 2]/255 - mean_val_rgb[2])/var_val_rgb[2]; } pu8PicAddr += u32Stride; } u32TotalStepNum += *(pu32StepAddr+n); } SAMPLE_COMM_SVP_FlushCache(pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u64PhyAddr, (HI_VOID *) pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u64VirAddr, u32TotalStepNum*u32Stride); } else { u32Height = pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].unShape.stWhc.u32Height; u32Width = pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].unShape.stWhc.u32Width; u32Chn = pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].unShape.stWhc.u32Chn; u32Stride = pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Stride; pu8PicAddr = (HI_U8*)(pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u64VirAddr); if(SVP_BLOB_TYPE_YVU420SP== pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].enType) { for(n = 0; n < pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Num; n++) { for(i = 0; i < u32Chn*u32Height/2; i++) { s32Ret = fread(pu8PicAddr,u32Width*u32VarSize,1,fp); SAMPLE_SVP_CHECK_EXPR_GOTO(1 != s32Ret,FAIL,SAMPLE_SVP_ERR_LEVEL_ERROR,"Error,Read image file failed!\n"); pu8PicAddr += u32Stride; } } } else if(SVP_BLOB_TYPE_YVU422SP== pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].enType) { for(n = 0; n < pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Num; n++) { for(i = 0; i < u32Height*2; i++) { s32Ret = fread(pu8PicAddr,u32Width*u32VarSize,1,fp); SAMPLE_SVP_CHECK_EXPR_GOTO(1 != s32Ret,FAIL,SAMPLE_SVP_ERR_LEVEL_ERROR,"Error,Read image file failed!\n"); pu8PicAddr += u32Stride; } } } else { for(n = 0; n < pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Num; n++) { for(i = 0;i < u32Chn; i++) { for(j = 0; j < u32Height; j++) { s32Ret = fread(pu8PicAddr,u32Width*u32VarSize,1,fp); SAMPLE_SVP_CHECK_EXPR_GOTO(1 != s32Ret,FAIL,SAMPLE_SVP_ERR_LEVEL_ERROR,"Error,Read image file failed!\n"); pu8PicAddr += u32Stride; } } } } SAMPLE_COMM_SVP_FlushCache(pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u64PhyAddr, (HI_VOID *) pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u64VirAddr, pstNnieParam->astSegData[u32SegIdx].astSrc[u32NodeIdx].u32Num*u32Chn*u32Height*u32Stride); } fclose(fp); return HI_SUCCESS; FAIL: fclose(fp); return HI_FAILURE; } /****************************************************************************** * function : Ssd Deinit ******************************************************************************/ static HI_S32 SAMPLE_SVP_NNIE_Ssd_Deinit(SAMPLE_SVP_NNIE_PARAM_S *pstNnieParam, SAMPLE_SVP_NNIE_SSD_SOFTWARE_PARAM_S* pstSoftWareParam,SAMPLE_SVP_NNIE_MODEL_S *pstNnieModel) { HI_S32 s32Ret = HI_SUCCESS; /*hardware deinit*/ if(pstNnieParam!=NULL) { s32Ret = SAMPLE_COMM_SVP_NNIE_ParamDeinit(pstNnieParam); SAMPLE_SVP_CHECK_EXPR_TRACE(HI_SUCCESS != s32Ret,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,SAMPLE_COMM_SVP_NNIE_ParamDeinit failed!\n"); } /*model deinit*/ if(pstNnieModel!=NULL) { s32Ret = SAMPLE_COMM_SVP_NNIE_UnloadModel(pstNnieModel); SAMPLE_SVP_CHECK_EXPR_TRACE(HI_SUCCESS != s32Ret,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,SAMPLE_COMM_SVP_NNIE_UnloadModel failed!\n"); } return s32Ret; } /****************************************************************************** * function : Ssd software para init ******************************************************************************/ static HI_S32 SAMPLE_SVP_NNIE_Ssd_SoftwareInit(SAMPLE_SVP_NNIE_CFG_S* pstCfg, SAMPLE_SVP_NNIE_PARAM_S *pstNnieParam, SAMPLE_SVP_NNIE_SSD_SOFTWARE_PARAM_S* pstSoftWareParam) { HI_U32 i = 0; HI_S32 s32Ret = HI_SUCCESS; HI_U32 u32ClassNum = 0; HI_U32 u32TotalSize = 0; HI_U32 u32DstRoiSize = 0; HI_U32 u32DstScoreSize = 0; HI_U32 u32ClassRoiNumSize = 0; HI_U32 u32TmpBufTotalSize = 0; HI_U64 u64PhyAddr = 0; HI_U8* pu8VirAddr = NULL; /*Set Conv Parameters*/ /*the SSD sample report resule is after permute operation, conv result is (C, H, W), after permute, the report node's (C1, H1, W1) is (H, W, C), the stride of report result is aligned according to C dim*/ for(i = 0; i < 12; i++) { pstSoftWareParam->au32ConvHeight[i] = pstNnieParam->pstModel->astSeg[0].astDstNode[i].unShape.stWhc.u32Chn; pstSoftWareParam->au32ConvWidth[i] = pstNnieParam->pstModel->astSeg[0].astDstNode[i].unShape.stWhc.u32Height; pstSoftWareParam->au32ConvChannel[i] = pstNnieParam->pstModel->astSeg[0].astDstNode[i].unShape.stWhc.u32Width; if(i%2==1) { pstSoftWareParam->au32ConvStride[i/2] = SAMPLE_SVP_NNIE_ALIGN16(pstSoftWareParam->au32ConvChannel[i]*sizeof(HI_U32))/sizeof(HI_U32); } } /*Set PriorBox Parameters*/ pstSoftWareParam->au32PriorBoxWidth[0] = 38; pstSoftWareParam->au32PriorBoxWidth[1] = 19; pstSoftWareParam->au32PriorBoxWidth[2] = 10; pstSoftWareParam->au32PriorBoxWidth[3] = 5; pstSoftWareParam->au32PriorBoxWidth[4] = 3; pstSoftWareParam->au32PriorBoxWidth[5] = 1; pstSoftWareParam->au32PriorBoxHeight[0] = 38; pstSoftWareParam->au32PriorBoxHeight[1] = 19; pstSoftWareParam->au32PriorBoxHeight[2] = 10; pstSoftWareParam->au32PriorBoxHeight[3] = 5; pstSoftWareParam->au32PriorBoxHeight[4] = 3; pstSoftWareParam->au32PriorBoxHeight[5] = 1; pstSoftWareParam->u32OriImHeight = pstNnieParam->astSegData[0].astSrc[0].unShape.stWhc.u32Height; pstSoftWareParam->u32OriImWidth = pstNnieParam->astSegData[0].astSrc[0].unShape.stWhc.u32Width; pstSoftWareParam->af32PriorBoxMinSize[0][0] = 30.0f; pstSoftWareParam->af32PriorBoxMinSize[1][0] = 60.0f; pstSoftWareParam->af32PriorBoxMinSize[2][0] = 111.0f; pstSoftWareParam->af32PriorBoxMinSize[3][0] = 162.0f; pstSoftWareParam->af32PriorBoxMinSize[4][0] = 213.0f; pstSoftWareParam->af32PriorBoxMinSize[5][0] = 264.0f; pstSoftWareParam->af32PriorBoxMaxSize[0][0] = 60.0f; pstSoftWareParam->af32PriorBoxMaxSize[1][0] = 111.0f; pstSoftWareParam->af32PriorBoxMaxSize[2][0] = 162.0f; pstSoftWareParam->af32PriorBoxMaxSize[3][0] = 213.0f; pstSoftWareParam->af32PriorBoxMaxSize[4][0] = 264.0f; pstSoftWareParam->af32PriorBoxMaxSize[5][0] = 315.0f; pstSoftWareParam->u32MinSizeNum = 1; pstSoftWareParam->u32MaxSizeNum = 1; pstSoftWareParam->bFlip= HI_TRUE; pstSoftWareParam->bClip= HI_FALSE; pstSoftWareParam->au32InputAspectRatioNum[0] = 1; pstSoftWareParam->au32InputAspectRatioNum[1] = 2; pstSoftWareParam->au32InputAspectRatioNum[2] = 2; pstSoftWareParam->au32InputAspectRatioNum[3] = 2; pstSoftWareParam->au32InputAspectRatioNum[4] = 1; pstSoftWareParam->au32InputAspectRatioNum[5] = 1; pstSoftWareParam->af32PriorBoxAspectRatio[0][0] = 2; pstSoftWareParam->af32PriorBoxAspectRatio[0][1] = 0; pstSoftWareParam->af32PriorBoxAspectRatio[1][0] = 2; pstSoftWareParam->af32PriorBoxAspectRatio[1][1] = 3; pstSoftWareParam->af32PriorBoxAspectRatio[2][0] = 2; pstSoftWareParam->af32PriorBoxAspectRatio[2][1] = 3; pstSoftWareParam->af32PriorBoxAspectRatio[3][0] = 2; pstSoftWareParam->af32PriorBoxAspectRatio[3][1] = 3; pstSoftWareParam->af32PriorBoxAspectRatio[4][0] = 2; pstSoftWareParam->af32PriorBoxAspectRatio[4][1] = 0; pstSoftWareParam->af32PriorBoxAspectRatio[5][0] = 2; pstSoftWareParam->af32PriorBoxAspectRatio[5][1] = 0; pstSoftWareParam->af32PriorBoxStepWidth[0] = 8; pstSoftWareParam->af32PriorBoxStepWidth[1] = 16; pstSoftWareParam->af32PriorBoxStepWidth[2] = 32; pstSoftWareParam->af32PriorBoxStepWidth[3] = 64; pstSoftWareParam->af32PriorBoxStepWidth[4] = 100; pstSoftWareParam->af32PriorBoxStepWidth[5] = 300; pstSoftWareParam->af32PriorBoxStepHeight[0] = 8; pstSoftWareParam->af32PriorBoxStepHeight[1] = 16; pstSoftWareParam->af32PriorBoxStepHeight[2] = 32; pstSoftWareParam->af32PriorBoxStepHeight[3] = 64; pstSoftWareParam->af32PriorBoxStepHeight[4] = 100; pstSoftWareParam->af32PriorBoxStepHeight[5] = 300; pstSoftWareParam->f32Offset = 0.5f; //偏移量 pstSoftWareParam->as32PriorBoxVar[0] = (HI_S32)(0.1f*SAMPLE_SVP_NNIE_QUANT_BASE);//超参数设置 pstSoftWareParam->as32PriorBoxVar[1] = (HI_S32)(0.1f*SAMPLE_SVP_NNIE_QUANT_BASE); pstSoftWareParam->as32PriorBoxVar[2] = (HI_S32)(0.2f*SAMPLE_SVP_NNIE_QUANT_BASE); pstSoftWareParam->as32PriorBoxVar[3] = (HI_S32)(0.2f*SAMPLE_SVP_NNIE_QUANT_BASE); /*Set Softmax Parameters*/ pstSoftWareParam->u32SoftMaxInHeight = 21; pstSoftWareParam->au32SoftMaxInChn[0] = 121296; pstSoftWareParam->au32SoftMaxInChn[1] = 45486; pstSoftWareParam->au32SoftMaxInChn[2] = 12600; pstSoftWareParam->au32SoftMaxInChn[3] = 3150; pstSoftWareParam->au32SoftMaxInChn[4] = 756; pstSoftWareParam->au32SoftMaxInChn[5] = 84; pstSoftWareParam->u32ConcatNum = 6; pstSoftWareParam->u32SoftMaxOutWidth = 1; pstSoftWareParam->u32SoftMaxOutHeight = 21; pstSoftWareParam->u32SoftMaxOutChn = 8732; /*Set DetectionOut Parameters*/ pstSoftWareParam->u32ClassNum = 21; pstSoftWareParam->u32TopK = 400; pstSoftWareParam->u32KeepTopK = 200; pstSoftWareParam->u32NmsThresh = (HI_U16)(0.3f*SAMPLE_SVP_NNIE_QUANT_BASE); pstSoftWareParam->u32ConfThresh = 1; pstSoftWareParam->au32DetectInputChn[0] = 23104; pstSoftWareParam->au32DetectInputChn[1] = 8664; pstSoftWareParam->au32DetectInputChn[2] = 2400; pstSoftWareParam->au32DetectInputChn[3] = 600; pstSoftWareParam->au32DetectInputChn[4] = 144; pstSoftWareParam->au32DetectInputChn[5] = 16; /*Malloc assist buffer memory*/ u32ClassNum = pstSoftWareParam->u32ClassNum; u32TotalSize = SAMPLE_SVP_NNIE_Ssd_GetResultTmpBuf(pstNnieParam,pstSoftWareParam); u32DstRoiSize = SAMPLE_SVP_NNIE_ALIGN16(u32ClassNum*pstSoftWareParam->u32TopK*sizeof(HI_U32)*SAMPLE_SVP_NNIE_COORDI_NUM); u32DstScoreSize = SAMPLE_SVP_NNIE_ALIGN16(u32ClassNum*pstSoftWareParam->u32TopK*sizeof(HI_U32)); u32ClassRoiNumSize = SAMPLE_SVP_NNIE_ALIGN16(u32ClassNum*sizeof(HI_U32)); u32TotalSize = u32TotalSize+u32DstRoiSize+u32DstScoreSize+u32ClassRoiNumSize; s32Ret = SAMPLE_COMM_SVP_MallocCached("SAMPLE_SSD_INIT",NULL,(HI_U64*)&u64PhyAddr, (void**)&pu8VirAddr,u32TotalSize); SAMPLE_SVP_CHECK_EXPR_RET(HI_SUCCESS != s32Ret,s32Ret,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,Malloc memory failed!\n"); memset(pu8VirAddr,0, u32TotalSize); SAMPLE_COMM_SVP_FlushCache(u64PhyAddr,(void*)pu8VirAddr,u32TotalSize); /*set each tmp buffer addr*/ pstSoftWareParam->stPriorBoxTmpBuf.u64PhyAddr = u64PhyAddr; pstSoftWareParam->stPriorBoxTmpBuf.u64VirAddr = (HI_U64)(pu8VirAddr); pstSoftWareParam->stSoftMaxTmpBuf.u64PhyAddr = u64PhyAddr+ pstSoftWareParam->stPriorBoxTmpBuf.u32Size; pstSoftWareParam->stSoftMaxTmpBuf.u64VirAddr = (HI_U64)(pu8VirAddr+ pstSoftWareParam->stPriorBoxTmpBuf.u32Size); pstSoftWareParam->stGetResultTmpBuf.u64PhyAddr = u64PhyAddr+ pstSoftWareParam->stPriorBoxTmpBuf.u32Size+pstSoftWareParam->stSoftMaxTmpBuf.u32Size; pstSoftWareParam->stGetResultTmpBuf.u64VirAddr = (HI_U64)(pu8VirAddr+ pstSoftWareParam->stPriorBoxTmpBuf.u32Size+ pstSoftWareParam->stSoftMaxTmpBuf.u32Size); u32TmpBufTotalSize = pstSoftWareParam->stPriorBoxTmpBuf.u32Size+ pstSoftWareParam->stSoftMaxTmpBuf.u32Size + pstSoftWareParam->stGetResultTmpBuf.u32Size; /*set result blob*/ pstSoftWareParam->stDstRoi.enType = SVP_BLOB_TYPE_S32; pstSoftWareParam->stDstRoi.u64PhyAddr = u64PhyAddr+u32TmpBufTotalSize; pstSoftWareParam->stDstRoi.u64VirAddr = (HI_U64)(pu8VirAddr+u32TmpBufTotalSize); pstSoftWareParam->stDstRoi.u32Stride = SAMPLE_SVP_NNIE_ALIGN16(u32ClassNum* pstSoftWareParam->u32TopK*sizeof(HI_U32)*SAMPLE_SVP_NNIE_COORDI_NUM); pstSoftWareParam->stDstRoi.u32Num = 1; pstSoftWareParam->stDstRoi.unShape.stWhc.u32Chn = 1; pstSoftWareParam->stDstRoi.unShape.stWhc.u32Height = 1; pstSoftWareParam->stDstRoi.unShape.stWhc.u32Width = u32ClassNum* pstSoftWareParam->u32TopK*SAMPLE_SVP_NNIE_COORDI_NUM; pstSoftWareParam->stDstScore.enType = SVP_BLOB_TYPE_S32; pstSoftWareParam->stDstScore.u64PhyAddr = u64PhyAddr+u32TmpBufTotalSize+u32DstRoiSize; pstSoftWareParam->stDstScore.u64VirAddr = (HI_U64)(pu8VirAddr+u32TmpBufTotalSize+u32DstRoiSize); pstSoftWareParam->stDstScore.u32Stride = SAMPLE_SVP_NNIE_ALIGN16(u32ClassNum* pstSoftWareParam->u32TopK*sizeof(HI_U32)); pstSoftWareParam->stDstScore.u32Num = 1; pstSoftWareParam->stDstScore.unShape.stWhc.u32Chn = 1; pstSoftWareParam->stDstScore.unShape.stWhc.u32Height = 1; pstSoftWareParam->stDstScore.unShape.stWhc.u32Width = u32ClassNum* pstSoftWareParam->u32TopK; pstSoftWareParam->stClassRoiNum.enType = SVP_BLOB_TYPE_S32; pstSoftWareParam->stClassRoiNum.u64PhyAddr = u64PhyAddr+u32TmpBufTotalSize+ u32DstRoiSize+u32DstScoreSize; pstSoftWareParam->stClassRoiNum.u64VirAddr = (HI_U64)(pu8VirAddr+u32TmpBufTotalSize+ u32DstRoiSize+u32DstScoreSize); pstSoftWareParam->stClassRoiNum.u32Stride = SAMPLE_SVP_NNIE_ALIGN16(u32ClassNum*sizeof(HI_U32)); pstSoftWareParam->stClassRoiNum.u32Num = 1; pstSoftWareParam->stClassRoiNum.unShape.stWhc.u32Chn = 1; pstSoftWareParam->stClassRoiNum.unShape.stWhc.u32Height = 1; pstSoftWareParam->stClassRoiNum.unShape.stWhc.u32Width = u32ClassNum; return s32Ret; } /****************************************************************************** * function : Ssd init ******************************************************************************/ static HI_S32 SAMPLE_SVP_NNIE_Ssd_ParamInit(SAMPLE_SVP_NNIE_CFG_S* pstCfg, SAMPLE_SVP_NNIE_PARAM_S *pstNnieParam, SAMPLE_SVP_NNIE_SSD_SOFTWARE_PARAM_S* pstSoftWareParam) { HI_S32 s32Ret = HI_SUCCESS; /*init hardware para*/ s32Ret = SAMPLE_COMM_SVP_NNIE_ParamInit(pstCfg,pstNnieParam); SAMPLE_SVP_CHECK_EXPR_GOTO(HI_SUCCESS != s32Ret,INIT_FAIL_0,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error(%#x),SAMPLE_COMM_SVP_NNIE_ParamInit failed!\n",s32Ret); return s32Ret; INIT_FAIL_0: s32Ret = SAMPLE_SVP_NNIE_Ssd_Deinit(pstNnieParam,pstSoftWareParam,NULL); SAMPLE_SVP_CHECK_EXPR_RET(HI_SUCCESS != s32Ret,s32Ret,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error(%#x),SAMPLE_SVP_NNIE_Ssd_Deinit failed!\n",s32Ret); return HI_FAILURE; } /****************************************************************************** * function : show SSD sample(image 300x300 U8_C3) ******************************************************************************/ void SAMPLE_SVP_NNIE_Encode(HI_CHAR *pcSrcFile,HI_S32 *aps32PermuteResult) { //HI_CHAR *pcSrcFile = "./data/nnie_image/rgb_planar/dog_bike_car_300x300.bgr"; //HI_CHAR 就是 char类型的 这边是设置图片路径 HI_CHAR *pcModelName = "./resnet_0523.wk"; // 设置模型路径 HI_U32 u32PicNum = 1; //HI_U32 其实就是unsigned int 这个变量好像是输入图片的数量 HI_FLOAT f32PrintResultThresh = 0.0f; // HI_FLOAT 其实就是float 这个变量是输出结果的阈值 HI_S32 s32Ret = HI_SUCCESS; //HI_S32就是 int s32Ret = 0 SAMPLE_SVP_NNIE_CFG_S stNnieCfg = {0}; //结构体定义在sample_comm_nnie.h里面 SAMPLE_SVP_NNIE_INPUT_DATA_INDEX_S stInputDataIdx = {0}; SAMPLE_SVP_NNIE_PROCESS_SEG_INDEX_S stProcSegIdx = {0}; /*Set configuration parameter*/ //配置参数 f32PrintResultThresh = 0.8f; //打印输出结果的阈值设为0.8 stNnieCfg.pszPic= pcSrcFile; //输入图片的地址 stNnieCfg.u32MaxInputNum = u32PicNum; //max input image num in each batch 每一次运行时操作的最大图片数量 stNnieCfg.u32MaxRoiNum = 0; stNnieCfg.aenNnieCoreId[0] = SVP_NNIE_ID_0;//set NNIE core /*Sys init*/ SAMPLE_COMM_SVP_CheckSysInit(); //系统初始化 system init /*Ssd Load model*/ SAMPLE_SVP_TRACE_INFO("Ssd Load model!\n"); //输出模型的信息 s32Ret = SAMPLE_COMM_SVP_NNIE_LoadModel(pcModelName,&s_stSsdModel); //载入模型 SAMPLE_SVP_CHECK_EXPR_GOTO(HI_SUCCESS != s32Ret,SSD_FAIL_0,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,SAMPLE_COMM_SVP_NNIE_LoadModel failed!\n"); //错误报告 /*Ssd parameter initialization*/ /*Ssd parameters are set in SAMPLE_SVP_NNIE_Ssd_SoftwareInit, if user has changed net struct, please make sure the parameter settings in SAMPLE_SVP_NNIE_Ssd_SoftwareInit function are correct*/ SAMPLE_SVP_TRACE_INFO("Ssd parameter initialization!\n"); s_stSsdNnieParam.pstModel = &s_stSsdModel.stModel; s32Ret = SAMPLE_SVP_NNIE_Ssd_ParamInit(&stNnieCfg,&s_stSsdNnieParam,&s_stSsdSoftwareParam); SAMPLE_SVP_CHECK_EXPR_GOTO(HI_SUCCESS != s32Ret,SSD_FAIL_0,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,SAMPLE_SVP_NNIE_Ssd_ParamInit failed!\n"); /*Fill src data*/ SAMPLE_SVP_TRACE_INFO("Ssd start!\n"); stInputDataIdx.u32SegIdx = 0; stInputDataIdx.u32NodeIdx = 0; s32Ret = SAMPLE_SVP_NNIE_FillSrcData(&stNnieCfg,&s_stSsdNnieParam,&stInputDataIdx); SAMPLE_SVP_CHECK_EXPR_GOTO(HI_SUCCESS != s32Ret,SSD_FAIL_0,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,SAMPLE_SVP_NNIE_FillSrcData failed!\n"); /*NNIE process(process the 0-th segment)*/ stProcSegIdx.u32SegIdx = 0; s32Ret = SAMPLE_SVP_NNIE_Forward(&s_stSsdNnieParam,&stInputDataIdx,&stProcSegIdx,HI_TRUE); SAMPLE_SVP_CHECK_EXPR_GOTO(HI_SUCCESS != s32Ret,SSD_FAIL_0,SAMPLE_SVP_ERR_LEVEL_ERROR, "Error,SAMPLE_SVP_NNIE_Forward failed!\n"); for(int i = 0; i < SAMPLE_SVP_NNIE_SSD_REPORT_NODE_NUM; i++) { aps32PermuteResult[i] = (HI_S32*)s_stSsdNnieParam.astSegData[0].astDst[i].u64VirAddr; } SSD_FAIL_0: SAMPLE_SVP_NNIE_Ssd_Deinit(&s_stSsdNnieParam,&s_stSsdSoftwareParam,&s_stSsdModel); SAMPLE_COMM_SVP_CheckSysExit(); } /****************************************************************************** * function : SSD sample signal handle ******************************************************************************/ void SAMPLE_SVP_NNIE_Ssd_HandleSig(void) { SAMPLE_SVP_NNIE_Ssd_Deinit(&s_stSsdNnieParam,&s_stSsdSoftwareParam,&s_stSsdModel); memset(&s_stSsdNnieParam,0,sizeof(SAMPLE_SVP_NNIE_PARAM_S)); memset(&s_stSsdSoftwareParam,0,sizeof(SAMPLE_SVP_NNIE_SSD_SOFTWARE_PARAM_S)); memset(&s_stSsdModel,0,sizeof(SAMPLE_SVP_NNIE_MODEL_S)); SAMPLE_COMM_SVP_CheckSysExit(); }
smamczak/NibView
Example/NibView/NibView.h
<filename>Example/NibView/NibView.h // // NibView.h // NibView // // Created by Domas on 10/02/2017. // Copyright © 2017 Trafi. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for NibView. FOUNDATION_EXPORT double NibViewVersionNumber; //! Project version string for NibView. FOUNDATION_EXPORT const unsigned char NibViewVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <NibView/PublicHeader.h>
hfqf/SpeSqliteManager
SpeSqliteManager/SpeSqliteUpdateManager.h
// // Created by Points on 15-04-03. // Copyright (c) 2015年 Points. All rights reserved. // #import <Foundation/Foundation.h> #import <sqlite3.h> #define SINGLETON_FOR_HEADER(className) \ + (className *)sharedInstance; //单例实现的公用函数 #define SINGLETON_FOR_CLASS(className) \ + (className *)sharedInstance { \ static className *shared = nil; \ static dispatch_once_t onceToken; \ dispatch_once(&onceToken, ^{ \ shared = [[self alloc] init]; \ }); \ return shared; \ } @interface SpeSqliteUpdateManager : NSObject { sqlite3 *m_db; NSDictionary *m_sqlSettingDic;//在bundle中的数据库plist,即新plist NSDictionary *m_localSettingDic;//本地的数据库plist } SINGLETON_FOR_HEADER(SpeSqliteUpdateManager) //创建或升级本地数据库 +(void)createOrUpdateDB; //db名 + (NSString *)dbName; + (sqlite3 *)db; - (NSString *)pathLocalDB; @end
meego-tablet-ux/meego-app-fingerpaint
plugin/fingerpaint.h
<gh_stars>0 /* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ #ifndef FINGERPAINT_H #define FINGERPAINT_H #include <QGraphicsWidget> #include <QImage> class Fingerpaint : public QGraphicsWidget { Q_OBJECT public: Fingerpaint(QGraphicsItem *parent = 0); ~Fingerpaint(); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); void resizeEvent(QGraphicsSceneResizeEvent *event); bool sceneEvent(QEvent *event); public slots: void clear(); private: QImage image; QList<QColor> colors; Q_DISABLE_COPY(Fingerpaint) }; #endif // FINGERPAINT_H
hoheinzollern/FStar
examples/primitives/c/fstarlib.c
#include "fstarlib.h" // Rotate left and right for different sizes of integers uint8 FStar_UInt8_op_Less_Less_Less(uint8 x, int y){ return ((uint8)(x << y)) + (x >> (8 - y)); } uint8 FStar_UInt8_op_Greater_Greater_Greater(uint8 x, int y){ return (x >> y) + ((uint8)(x << (8 - y))); } uint8 FStar_UInt8_rotate_left(uint8 x, int y){ return ((uint8)(x << y)) + (x >> (8 - y)); } uint8 FStar_UInt8_rotate_right(uint8 x, int y){ return (x >> y) + ((uint8)(x << (8 - y))); } inline uint32 FStar_UInt32_op_Less_Less_Less(uint32 x, int y){ return ((uint32)(x << y)) + (x >> (32 - y)); } inline uint32 FStar_UInt32_op_Greater_Greater_Greater(uint32 x, int y){ return (x >> y) + ((uint32)(x << (32 - y))); } uint64 FStar_UInt63_op_Less_Less_Less(uint64 x, int y){ return ((uint64)(x << y)) + (x >> (64 - y)); } uint64 FStar_UInt63_op_Greater_Greater_Greater(uint64 x, int y){ return (x >> y) + ((uint64)(x << (64 - y))); } uint64 FStar_UInt64_op_Less_Less_Less(uint64 x, int y){ return ((uint64)(x << y)) + (x >> (64 - y)); } uint64 FStar_UInt64_op_Greater_Greater_Greater(uint64 x, int y){ return (x >> y) + ((uint64)(x << (64 - y))); } // Converts bytes to and from int32s. Should be integrated to the compiler void FStar_SBytes_sbytes_of_uint32s(uint8* res, uint32* b, int l){ unsigned int i; uint32* tmp = (uint32*)res; for(i = 0; i < l; i++){ tmp[i] = b[i]; } } void FStar_SBytes_xor_bytes(uint8* output, uint8* a, uint8* b, int l){ unsigned int i; for(i=0; i < l; i++){ output[i] = a[i] ^ b[i]; } } inline uint8 FStar_UInt8_gte(uint8 x, uint8 y){ return (uint8)~(((int16_t)x) - y >> 15); } inline uint8 FStar_UInt8_eq(uint8 a, uint8 b){ a = ~(a ^ b); a &= a << 4; a &= a << 2; a &= a << 1; return ((char)a) >> 7; } // Constant time comparisons uint32 FStar_UInt32_eq(uint32 a, uint32 b) { a = ~(a ^ b); a &= a << 16; a &= a << 8; a &= a << 4; a &= a << 2; a &= a << 1; return ((int32_t)a) >> 31; } uint32 FStar_UInt32_gte(uint32 a, uint32 b) { int64_t tmp; tmp = a - b; return ~(tmp >> 63); } uint64 FStar_UInt63_eq(uint64 a, uint64 b) { a = ~(a ^ b); a &= a << 32; a &= a << 16; a &= a << 8; a &= a << 4; a &= a << 2; a &= a << 1; return ((int64_t)a) >> 63; } uint64 FStar_UInt63_gte(uint64 a, uint64 b) { a -= - b; // Works because a and b are never negative return ~(a >> 63); } uint64 FStar_UInt64_eq(uint64 a, uint64 b) { a = ~(a ^ b); a &= a << 32; a &= a << 16; a &= a << 8; a &= a << 4; a &= a << 2; a &= a << 1; return ((int64_t)a) >> 63; } uint64 FStar_UInt64_gte(uint64 a, uint64 b) { return (uint64)~(((__int128_t)a) - b >> 127); } void print_bytes(uint8* b, int len){ int i; for (i = 0; i < len; i++){ if (b[i] < 0x10) {printf("0%x", 0xff & b[i]);} else {printf("%x", 0xff & b[i]);} } printf("\n"); }
hoheinzollern/FStar
examples/primitives/c/fstarlib.h
#include <stdint.h> #include <string.h> #include <stdio.h> // Integer constants #define FStar_UInt64_one_wide ((uint128_t)1) #define FStar_UInt64_zero_wide ((uint128_t)0) #define FStar_UInt64_one ((uint64)1) #define FStar_UInt64_zero ((uint64)0) #define FStar_UInt63_one ((uint64)1) #define FStar_UInt63_zero ((uint64)0) #define FStar_UInt32_one ((uint32)1) #define FStar_UInt32_zero ((uint32)0) #define FStar_UInt8_one ((uint8)1) #define FStar_UInt8_zero ((uint8)0) // Native FStar types (necessary while lemmas are not erased) typedef int FStar_Heap_heap; typedef unsigned uint128_t __attribute__((mode(TI))); #undef force_inline #define force_inline __attribute__((always_inline)) typedef uint128_t uint128; typedef uint64_t uint64; typedef uint64_t uint63; typedef uint32_t uint32; typedef uint8_t uint8; // Bignum types typedef uint64_t* Bigint_bigint; typedef uint8* Bignum_Bigint_bytes; typedef uint64_t* Bignum_Bigint_bigint; typedef uint128_t* Bignum_Bigint_bigint_wide; // Rotate left and right for different sizes of integers uint8 FStar_UInt8_op_Less_Less_Less(uint8 x, int y); uint8 FStar_UInt8_op_Greater_Greater_Greater(uint8 x, int y); uint8 FStar_UInt8_rotate_left(uint8 x, int y); uint8 FStar_UInt8_rotate_right(uint8 x, int y); uint32 FStar_UInt32_op_Less_Less_Less(uint32 x, int y); uint32 FStar_UInt32_op_Greater_Greater_Greater(uint32 x, int y); uint64 FStar_UInt63_op_Less_Less_Less(uint64 x, int y); uint64 FStar_UInt63_op_Greater_Greater_Greater(uint64 x, int y); uint64 FStar_UInt64_op_Less_Less_Less(uint64 x, int y); uint64 FStar_UInt64_op_Greater_Greater_Greater(uint64 x, int y); void FStar_SBytes_sbytes_of_uint32s(uint8* res, uint32* b, int l); void FStar_SBytes_xor_bytes(uint8* output, uint8* a, uint8* b, int l); // Constant time comparisons uint32 FStar_UInt32_eq(uint32 a, uint32 b); uint32 FStar_UInt32_gte(uint32 a, uint32 b); uint64 FStar_UInt63_eq(uint64 a, uint64 b); uint64 FStar_UInt63_gte(uint64 a, uint64 b); uint64 FStar_UInt64_eq(uint64 a, uint64 b); uint64 FStar_UInt64_gte(uint64 a, uint64 b); // Debugging functions void print_bytes(uint8* b, int len);
hoheinzollern/FStar
examples/primitives/c/test_curve.c
<gh_stars>1-10 #include <stdint.h> #include <stdio.h> #include "fstarlib.h" #define Bignum_Parameters_norm_length 5 #define Bignum_Parameters_a24_prime 121665 #define Bignum_Bigint_template int #define Bignum_Bigint_template_const Bignum_Bigint_template #define Bignum_Bigint_bigint uint64* #define Bignum_Bigint_bigint_wide uint128_t* #define Bignum_Bigint_bytes uint8* inline void force_inline multiply(uint128_t t[9], const uint64 in2[5], const uint64 in[5]) { uint64 r0,r1,r2,r3,r4,s0,s1,s2,s3,s4,c; r0 = in[0]; r1 = in[1]; r2 = in[2]; r3 = in[3]; r4 = in[4]; s0 = in2[0]; s1 = in2[1]; s2 = in2[2]; s3 = in2[3]; s4 = in2[4]; t[0] = ((uint128_t) r0) * s0; t[1] = ((uint128_t) r0) * s1 + ((uint128_t) r1) * s0; t[2] = ((uint128_t) r0) * s2 + ((uint128_t) r2) * s0 + ((uint128_t) r1) * s1; t[3] = ((uint128_t) r0) * s3 + ((uint128_t) r3) * s0 + ((uint128_t) r1) * s2 + ((uint128_t) r2) * s1; t[4] = ((uint128_t) r0) * s4 + ((uint128_t) r4) * s0 + ((uint128_t) r3) * s1 + ((uint128_t) r1) * s3 + ((uint128_t) r2) * s2; t[5] += ((uint128_t) r4) * s1 + ((uint128_t) r1) * s4 + ((uint128_t) r2) * s3 + ((uint128_t) r3) * s2; t[6] += ((uint128_t) r4) * s2 + ((uint128_t) r2) * s4 + ((uint128_t) r3) * s3; t[7] += ((uint128_t) r4) * s3 + ((uint128_t) r3) * s4; t[8] += ((uint128_t) r4) * s4; } typedef struct Curve_Point_point Curve_Point_point; struct Curve_Point_point{ Bignum_Bigint_bigint x; Bignum_Bigint_bigint y; Bignum_Bigint_bigint z; }; void decode_scalar(uint8 scalar[32]){ scalar[0] &= 248; scalar[31] &= 127; scalar[31] |= 64; } void decode_input(uint64 x[5], uint8 sc[32]){ uint64* s = (uint64*)sc; x[0] = s[0] & 0x7ffffffffffff; x[1] = ((s[0] >> 51) + (s[1] << 13)) & 0x7ffffffffffff; x[2] = ((s[1] >> 38) + (s[2] << 26)) & 0x7ffffffffffff; x[3] = ((s[2] >> 25) + (s[3] << 39)) & 0x7ffffffffffff; x[4] = (s[3] >> 12) & 0x7ffffffffffff; } void print_array(uint64* z, int len){ int i; for (i=0; i < len; i++){ printf("%lx ", z[i]); } printf("\n"); } void print_long_array(uint128_t* z, int len){ int i; for (i=0; i < len; i++){ printf("%lx%lx ", (uint64)(z[i]>>64), (uint64)z[i]); } printf("\n"); } void print_bigint(uint64 z[5]){ uint64 x[4] = {0}; int i, j; x[0] = z[0] + (z[1] << 51); x[1] = (z[1] >> 13) + (z[2] << 38); x[2] = (z[2] >> 26) + (z[3] << 25); x[3] = (z[3] >> 39) + (z[4] << 12); for (i=0; i < 4; i++){ for (j=0; j < 8; j++){ printf("%02lx", 0xff & (x[i] >> (8*j))); } } printf("\n"); } void test(){ uint64 output[9], rx[9] = {0}, ry[9] = {0}, rz[9] = {0}, qx[9] = {0}, qy[9] = {0}, qz[9] = {1}, zrecip[9] = {0}; uint64 axx[9] = {0}, ayy[9] = {0}, azz[9] = {0}, axxx[9] = {0}, ayyy[9] = {0}, azzz[9] = {0}; uint8 scalar[32] = {0xa5, 0x46, 0xe3, 0x6b, 0xf0, 0x52, 0x7c, 0x9d, 0x3b, 0x16, 0x15, 0x4b, 0x82, 0x46, 0x5e, 0xdd, 0x62, 0x14, 0x4c, 0x0a, 0xc1, 0xfc, 0x5a, 0x18, 0x50, 0x6a, 0x22, 0x44, 0xba, 0x44, 0x9a, 0xc4}; uint8 input[32] = {0xe6, 0xdb, 0x68, 0x67, 0x58, 0x30, 0x30, 0xdb, 0x35, 0x94, 0xc1, 0xa4, 0x24, 0xb1, 0x5f, 0x7c, 0x72, 0x66, 0x24, 0xec, 0x26, 0xb3, 0x35, 0x3b, 0x10, 0xa9, 0x03, 0xa6, 0xd0, 0xab, 0x1c, 0x4c}; char* expected = "c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552"; decode_scalar(scalar); decode_input(qx, input); Curve_Point_point basepoint = (Curve_Point_point) {qx, qy, qz}; Curve_Point_point res = (Curve_Point_point) {rx, ry, rz}; int i; printf(" Running 1000 computations of Curve25519 test vector ...\n"); for (i=0;i<1000;i++){ Curve_Ladder_montgomery_ladder(res, scalar, basepoint); } Bignum_Core_crecip_prime(zrecip, res.z); Bignum_Core_fmul(output, res.x, zrecip); printf("Expected:\n %s\nGot:\n ", expected); print_bigint(output); } int main(int argc, char** argv){ test(); return 0; }
hoheinzollern/FStar
examples/primitives/c/test_poly.c
#include <stdint.h> #include <stdio.h> #include "fstarlib.h" #define Parameters_platform_size 63 #define Parameters_platform_wide 63 #define Parameters_norm_length 5 #define Parameters_bytes_length 17 #define Parameters_ndiff_prime 26 #define Parameters_ndiff 28 void print_array(uint64* array, int len){ unsigned char i; for (i=0; i < len; i++){ printf("%lx ", array[i]); } printf("\n"); } void print_bytes2(char* bytes, int len){ unsigned char i; for (i=0; i < len; i++){ if (i < len - 1) printf("%02x:", bytes[i] & 0xff); else printf("%02x", bytes[i] & 0xff); } printf("\n"); } int main(int argc, char** argv){ uint8 key[32] = {0x85, 0xd6, 0xbe, 0x78, 0x57, 0x55, 0x6d, 0x33, 0x7f, 0x44, 0x52, 0xfe, 0x42, 0xd5, 0x06, 0xa8, 0x01, 0x03, 0x80, 0x8a, 0xfb, 0x0d, 0xb2, 0xfd, 0x4a, 0xbf, 0xf6, 0xaf, 0x41, 0x49, 0xf5, 0x1b}; uint8* msg = "Cryptographic Forum Research Group"; uint8* expected = "Tag: fdf8:f53e:61e4::18:c2:2b:8b:af:0c:01:27:a9"; uint8 hash[16] = {0}; /* uint64 a[9] = {2}, b[9] = {3}, c[9] = {10}, tmp[9] = {0}; Bignum_fsum_prime (a, b); print_array(a, 5); Bignum_multiplication(tmp,a, c); print_array(tmp, 9); Bignum_freduce_degree (tmp) ; print_array(tmp, 9); b [ Parameters_norm_length ] = FStar_UInt63_zero; print_array(tmp, 9); Bignum_carry (tmp, 0); print_array(tmp, 9); Bignum_carry2 (tmp); print_array(tmp, 9); Bignum_last_carry (tmp); print_array(tmp, 5); Poly_add_and_multiply(a, b, c); */ // print_bytes(key, 16); //uint64 acc[9] = {0}, r[5] = {0}; //Poly_clamp(key); //Poly_le_bytes_to_num(r, key); //Poly_poly1305_step(msg, acc, r, 2); //Poly_num_to_le_bytes(hash, acc); printf("Running 1.000.000 iterations of poly1305's test vector from RFC\n"); unsigned int i; for(i = 0; i < 1000000; i++){ Poly_poly1305_mac(hash, msg, 34, key); } Poly_poly1305_mac(hash, msg, 34, key); printf("%s\nGot: ", expected); print_bytes2(hash, 16); return 0; }
wavecomp/waveext
waveflow/kernel_lib/dfx_op_base.h
<gh_stars>1-10 /* * Copyright (c) 2010-2018 Wave Computing, Inc. and its applicable licensors. * All rights reserved; provided, that any files identified as open source shall * be governed by the specific open source license(s) applicable to such files. * * For any files associated with distributions under the Apache 2.0 license, * full attribution to The Apache Software Foundation is given via the license * below. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/common_shape_fns.h" #include "Eigen/Core" #include <stdlib.h> #include <string> #include <vector> #include "dyn_fx_pt.h" using namespace tensorflow; /* Base class for Dynamic Fixed Point operators. This will take care of parsing * any relevant attributes and keeping some appropriate binary point. * * This class is desined to make it easy for a custom operator to get the * Dynamic Fixed Point for a given I/O. I/O must be referenced by index, since the TF * C++ API isn't sophisticated enough to refer to I/O by name. * * Users must pass the name of the BP attributes through to the constructor. * The attributes given will be associated with a BP setting from some user- * declared BP generator operation. This base class handles the linkage between * this consumer operation and the BP generator operation. Any BP I/O without a * generator will return an fxbp of uninitialized, so the caller may handle this * however they decide. */ class WaveDynFxPointOp : public OpKernel { public: typedef std::vector<std::string> StringVec; typedef std::vector<DynFxPoint> DFXVector; typedef Eigen::Matrix<DynFxPoint, Eigen::Dynamic, Eigen::Dynamic> DFXMatrix2d; explicit WaveDynFxPointOp(OpKernelConstruction* ctx, const StringVec& attrs); protected: fxbp get_fxbp(bool isInput, int n) const; std::string get_vp_key(bool isInput, int n) const; void partial_in(fxbp& dest_bp, DFXVector& m_out, const float* flat_arr); void partial_out(fxbp& out_bp, float* conv_out, const DFXVector& m_out); void partial_in(fxbp& dest_bp, int32_t* m_out, const float* flat_arr, int n); void partial_out(fxbp& out_bp, float* conv_out, const int32_t* m_out, int32_t src_bp, int n); void partial_out(float* conv_out, const int32_t* m_out, int32_t src_bp, int n); int32_t stochastic_rounding(int32_t v, int32_t r); StringVec m_iLookup; StringVec m_oLookup; bool m_use_stochastic_round; private: bool get_iospec(const std::string& attr, bool& isInput, int& n); bool get_static_bp(const std::string& attr, fxbp& bp) const; bool get_dynamic_bp(const std::string& attr, fxbp& bp) const; };
wavecomp/waveext
waveflow/kernel_lib/gemm_fp.h
<reponame>wavecomp/waveext<filename>waveflow/kernel_lib/gemm_fp.h /* * Copyright (c) 2010-2018 Wave Computing, Inc. and its applicable licensors. * All rights reserved; provided, that any files identified as open source shall * be governed by the specific open source license(s) applicable to such files. * * For any files associated with distributions under the Apache 2.0 license, * full attribution to The Apache Software Foundation is given via the license * below. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "Eigen/Core" template<typename T> void fp_clear(T& m_out, int x, int y) { for (int j = 0; j < x; j++) { for (int k = 0; k < y; k++) { m_out(j, k) = 0.f; } } } template<typename Tin, typename Tout> static inline void mm_nn(bool zero, Tin& a_m, int a_x, int a_y, Tin& b_m, int b_x, int b_y, Tout& z_m) { // M[i] : A.dim[0] // N[j] : B.dim[1] // K[k] : A.dim[1] == B.dim[0] // output: (A.dim[0], B.dim[1]) for (int i = 0; i < a_x; i++) { for (int j = 0; j < b_y; j++) { // printf("generating out(%i, %i)\n", i, j); float val = 0.f; for (int k = 0; k < a_y; k++) { val += a_m(i, k) * b_m(k, j); } z_m(i, j) = zero ? val : z_m(i, j) + val; } } } template<typename Tin, typename Tout> static inline void mm_tn(bool zero, Tin& a_m, int a_x, int a_y, Tin& b_m, int b_x, int b_y, Tout& z_m) { // A (grad) is transposed (T,N) // M[i] : A.dim[1] // N[j] : B.dim[1] // K[k] : A.dim[0] == B.dim[0] // (k, i); (k, j) // output: (A.dim[1], B.dim[1]) // KS: there's probably an easier way to clear this tensor if (zero) { fp_clear(z_m, a_y, b_y); } for (int i = 0; i < a_y; i++) { for (int k = 0; k < a_x; k++) { for (int j = 0; j < b_y; j++) { z_m(i, j) += a_m(k, i) * b_m(k, j); } } } } template<typename Tin, typename Tout> static inline void mm_nt(bool zero, Tin& a_m, int a_x, int a_y, Tin& b_m, int b_x, int b_y, Tout& z_m) { // B (weights) is transposed (N,T) // M[i] : A.dim[0] // N[j] : B.dim[0] // K[k] : A.dim[1] == B.dim[1] // (i, k); (j, k) // output: (A.dim[0], B.dim[0]) for (int i = 0; i < a_x; i++) { for (int j = 0; j < b_x; j++) { float val = 0.f; for (int k = 0; k < a_y; k++) { val += a_m(i, k) * b_m(j, k); } z_m(i, j) = zero ? val : z_m(i, j) + val; } } } template<typename Tin, typename Tout> static inline void mm_tt(bool zero, Tin& a_m, int a_x, int a_y, Tin& b_m, int b_x, int b_y, Tout& z_m) { // A, B is transposed (T,T) // M[i] : A.dim[1] // N[j] : B.dim[0] // K[k] : A.dim[0] == B.dim[1] // (k, i); (j, k) // output: (A.dim[1], B.dim[0]) // KS: there's probably an easier way to clear this tensor if (zero) { fp_clear(z_m, a_y, b_x); } for (int i = 0; i < a_y; i++) { for (int k = 0; k < a_x; k++) { for (int j = 0; j < b_x; j++) { z_m(i, j) += a_m(k, i) * b_m(j, k); } } } }
wavecomp/waveext
waveflow/kernel_lib/softmax_lut_dfx.h
/* * Copyright (c) 2010-2018 Wave Computing, Inc. and its applicable licensors. * All rights reserved; provided, that any files identified as open source shall * be governed by the specific open source license(s) applicable to such files. * * For any files associated with distributions under the Apache 2.0 license, * full attribution to The Apache Software Foundation is given via the license * below. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(USE_VECTOR_INSTRUCTIONS) constexpr int32_t EXP_LUT_SIZE = 333; constexpr int32_t LUT(int32_t x, int32_t y) { return (x << 16) | (-y & 0xffff); } constexpr int32_t exp_lut[EXP_LUT_SIZE] = { LUT(16384, 15880), LUT(15880, 15391), LUT(15391, 14918), LUT(14918, 14459), LUT(14459, 14014), LUT(14014, 13583), LUT(13583, 13165), LUT(13165, 12760), LUT(12760, 12367), LUT(12367, 11987), LUT(11987, 11618), LUT(11618, 11261), LUT(11261, 10914), LUT(10914, 10578), LUT(10578, 10253), LUT(10253, 9937), LUT( 9937, 9632), LUT( 9632, 9335), LUT( 9335, 9048), LUT( 9048, 8770), LUT( 8770, 8500), LUT( 8500, 8238), LUT( 8238, 7985), LUT( 7985, 7739), LUT( 7739, 7501), LUT( 7501, 7270), LUT( 7270, 7047), LUT( 7047, 6830), LUT( 6830, 6620), LUT( 6620, 6416), LUT( 6416, 6219), LUT( 6219, 6027), LUT( 6027, 5842), LUT( 5842, 5662), LUT( 5662, 5488), LUT( 5488, 5319), LUT( 5319, 5155), LUT( 5155, 4997), LUT( 4997, 4843), LUT( 4843, 4694), LUT( 4694, 4550), LUT( 4550, 4410), LUT( 4410, 4274), LUT( 4274, 4143), LUT( 4143, 4015), LUT( 4015, 3892), LUT( 3892, 3772), LUT( 3772, 3656), LUT( 3656, 3543), LUT( 3543, 3434), LUT( 3434, 3329), LUT( 3329, 3226), LUT( 3226, 3127), LUT( 3127, 3031), LUT( 3031, 2937), LUT( 2937, 2847), LUT( 2847, 2760), LUT( 2760, 2675), LUT( 2675, 2592), LUT( 2592, 2513), LUT( 2513, 2435), LUT( 2435, 2360), LUT( 2360, 2288), LUT( 2288, 2217), LUT( 2217, 2149), LUT( 2149, 2083), LUT( 2083, 2019), LUT( 2019, 1957), LUT( 1957, 1897), LUT( 1897, 1838), LUT( 1838, 1782), LUT( 1782, 1727), LUT( 1727, 1674), LUT( 1674, 1622), LUT( 1622, 1572), LUT( 1572, 1524), LUT( 1524, 1477), LUT( 1477, 1432), LUT( 1432, 1388), LUT( 1388, 1345), LUT( 1345, 1304), LUT( 1304, 1263), LUT( 1263, 1225), LUT( 1225, 1187), LUT( 1187, 1150), LUT( 1150, 1115), LUT( 1115, 1081), LUT( 1081, 1047), LUT( 1047, 1015), LUT( 1015, 984), LUT( 984, 954), LUT( 954, 924), LUT( 924, 896), LUT( 896, 868), LUT( 868, 842), LUT( 842, 816), LUT( 816, 791), LUT( 791, 766), LUT( 766, 743), LUT( 743, 720), LUT( 720, 698), LUT( 698, 676), LUT( 676, 655), LUT( 655, 635), LUT( 635, 616), LUT( 616, 597), LUT( 597, 578), LUT( 578, 561), LUT( 561, 543), LUT( 543, 527), LUT( 527, 510), LUT( 510, 495), LUT( 495, 480), LUT( 480, 465), LUT( 465, 450), LUT( 450, 437), LUT( 437, 423), LUT( 423, 410), LUT( 410, 398), LUT( 398, 385), LUT( 385, 373), LUT( 373, 362), LUT( 362, 351), LUT( 351, 340), LUT( 340, 330), LUT( 330, 319), LUT( 319, 310), LUT( 310, 300), LUT( 300, 291), LUT( 291, 282), LUT( 282, 273), LUT( 273, 265), LUT( 265, 257), LUT( 257, 249), LUT( 249, 241), LUT( 241, 234), LUT( 234, 227), LUT( 227, 220), LUT( 220, 213), LUT( 213, 206), LUT( 206, 200), LUT( 200, 194), LUT( 194, 188), LUT( 188, 182), LUT( 182, 176), LUT( 176, 171), LUT( 171, 166), LUT( 166, 161), LUT( 161, 156), LUT( 156, 151), LUT( 151, 146), LUT( 146, 142), LUT( 142, 137), LUT( 137, 133), LUT( 133, 129), LUT( 129, 125), LUT( 125, 121), LUT( 121, 118), LUT( 118, 114), LUT( 114, 110), LUT( 110, 107), LUT( 107, 104), LUT( 104, 101), LUT( 101, 97), LUT( 97, 94), LUT( 94, 92), LUT( 92, 89), LUT( 89, 86), LUT( 86, 83), LUT( 83, 81), LUT( 81, 78), LUT( 78, 76), LUT( 76, 74), LUT( 74, 71), LUT( 71, 69), LUT( 69, 67), LUT( 67, 65), LUT( 65, 63), LUT( 63, 61), LUT( 61, 59), LUT( 59, 57), LUT( 57, 56), LUT( 56, 54), LUT( 54, 52), LUT( 52, 51), LUT( 51, 49), LUT( 49, 47), LUT( 47, 46), LUT( 46, 45), LUT( 45, 43), LUT( 43, 42), LUT( 42, 41), LUT( 41, 39), LUT( 39, 38), LUT( 38, 37), LUT( 37, 36), LUT( 36, 35), LUT( 35, 34), LUT( 34, 33), LUT( 33, 32), LUT( 32, 31), LUT( 31, 30), LUT( 30, 29), LUT( 29, 28), LUT( 28, 27), LUT( 27, 26), LUT( 26, 25), LUT( 25, 25), LUT( 25, 24), LUT( 24, 23), LUT( 23, 22), LUT( 22, 22), LUT( 22, 21), LUT( 21, 20), LUT( 20, 20), LUT( 20, 19), LUT( 19, 19), LUT( 19, 18), LUT( 18, 17), LUT( 17, 17), LUT( 17, 16), LUT( 16, 16), LUT( 16, 15), LUT( 15, 15), LUT( 15, 14), LUT( 14, 14), LUT( 14, 14), LUT( 14, 13), LUT( 13, 13), LUT( 13, 12), LUT( 12, 12), LUT( 12, 12), LUT( 12, 11), LUT( 11, 11), LUT( 11, 11), LUT( 11, 10), LUT( 10, 10), LUT( 10, 10), LUT( 10, 9), LUT( 9, 9), LUT( 9, 9), LUT( 9, 9), LUT( 9, 8), LUT( 8, 8), LUT( 8, 8), LUT( 8, 8), LUT( 8, 7), LUT( 7, 7), LUT( 7, 7), LUT( 7, 7), LUT( 7, 6), LUT( 6, 6), LUT( 6, 6), LUT( 6, 6), LUT( 6, 6), LUT( 6, 5), LUT( 5, 5), LUT( 5, 5), LUT( 5, 5), LUT( 5, 5), LUT( 5, 5), LUT( 5, 5), LUT( 5, 4), LUT( 4, 4), LUT( 4, 4), LUT( 4, 4), LUT( 4, 4), LUT( 4, 4), LUT( 4, 4), LUT( 4, 4), LUT( 4, 3), LUT( 3, 3), LUT( 3, 3), LUT( 3, 3), LUT( 3, 3), LUT( 3, 3), LUT( 3, 3), LUT( 3, 3), LUT( 3, 3), LUT( 3, 3), LUT( 3, 3), LUT( 3, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 2), LUT( 2, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 1), LUT( 1, 0) }; #else constexpr int32_t EXP_LUT_SIZE = 334; constexpr int32_t exp_lut[EXP_LUT_SIZE] = { 16384, 15880, 15391, 14918, 14459, 14014, 13583, 13165, 12760, 12367, 11987, 11618, 11261, 10914, 10578, 10253, 9937, 9632, 9335, 9048, 8770, 8500, 8238, 7985, 7739, 7501, 7270, 7047, 6830, 6620, 6416, 6219, 6027, 5842, 5662, 5488, 5319, 5155, 4997, 4843, 4694, 4550, 4410, 4274, 4143, 4015, 3892, 3772, 3656, 3543, 3434, 3329, 3226, 3127, 3031, 2937, 2847, 2760, 2675, 2592, 2513, 2435, 2360, 2288, 2217, 2149, 2083, 2019, 1957, 1897, 1838, 1782, 1727, 1674, 1622, 1572, 1524, 1477, 1432, 1388, 1345, 1304, 1263, 1225, 1187, 1150, 1115, 1081, 1047, 1015, 984, 954, 924, 896, 868, 842, 816, 791, 766, 743, 720, 698, 676, 655, 635, 616, 597, 578, 561, 543, 527, 510, 495, 480, 465, 450, 437, 423, 410, 398, 385, 373, 362, 351, 340, 330, 319, 310, 300, 291, 282, 273, 265, 257, 249, 241, 234, 227, 220, 213, 206, 200, 194, 188, 182, 176, 171, 166, 161, 156, 151, 146, 142, 137, 133, 129, 125, 121, 118, 114, 110, 107, 104, 101, 97, 94, 92, 89, 86, 83, 81, 78, 76, 74, 71, 69, 67, 65, 63, 61, 59, 57, 56, 54, 52, 51, 49, 47, 46, 45, 43, 42, 41, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 25, 24, 23, 22, 22, 21, 20, 20, 19, 19, 18, 17, 17, 16, 16, 15, 15, 14, 14, 14, 13, 13, 12, 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 }; #endif constexpr int32_t RECIP_LUT_SIZE = 128; constexpr int32_t recip_lut[RECIP_LUT_SIZE] = { 16384, 16257, 16132, 16009, 15888, 15768, 15650, 15534, 15420, 15308, 15197, 15087, 14980, 14873, 14769, 14665, 14564, 14463, 14364, 14266, 14170, 14075, 13981, 13888, 13797, 13707, 13618, 13530, 13443, 13358, 13273, 13190, 13107, 13026, 12945, 12866, 12788, 12710, 12633, 12558, 12483, 12409, 12336, 12264, 12193, 12122, 12053, 11984, 11916, 11848, 11782, 11716, 11651, 11586, 11523, 11460, 11398, 11336, 11275, 11215, 11155, 11096, 11038, 10980, 10923, 10866, 10810, 10755, 10700, 10645, 10592, 10538, 10486, 10434, 10382, 10331, 10280, 10230, 10180, 10131, 10082, 10034, 9986, 9939, 9892, 9846, 9800, 9754, 9709, 9664, 9620, 9576, 9533, 9489, 9447, 9404, 9362, 9321, 9279, 9239, 9198, 9158, 9118, 9079, 9039, 9001, 8962, 8924, 8886, 8849, 8812, 8775, 8738, 8702, 8666, 8630, 8595, 8560, 8525, 8490, 8456, 8422, 8389, 8355, 8322, 8289, 8257, 8224 }; constexpr int32_t LOG_LUT_SIZE = 129; constexpr int32_t log_lut[LOG_LUT_SIZE] = { 22713, 22458, 22205, 21954, 21705, 21457, 21212, 20968, 20726, 20486, 20248, 20012, 19777, 19543, 19312, 19082, 18854, 18627, 18402, 18178, 17956, 17735, 17516, 17298, 17082, 16867, 16654, 16441, 16231, 16021, 15813, 15607, 15401, 15197, 14994, 14792, 14592, 14393, 14195, 13998, 13802, 13608, 13415, 13222, 13031, 12841, 12652, 12465, 12278, 12092, 11908, 11724, 11542, 11360, 11179, 11000, 10821, 10644, 10467, 10291, 10117, 9943, 9770, 9598, 9427, 9257, 9087, 8919, 8751, 8584, 8418, 8253, 8089, 7926, 7763, 7601, 7440, 7280, 7121, 6962, 6804, 6647, 6490, 6335, 6180, 6026, 5872, 5719, 5567, 5416, 5265, 5115, 4966, 4817, 4669, 4522, 4376, 4230, 4084, 3940, 3796, 3652, 3509, 3367, 3226, 3085, 2944, 2805, 2666, 2527, 2389, 2252, 2115, 1979, 1843, 1708, 1573, 1439, 1306, 1173, 1040, 908, 777, 646, 516, 386, 257, 128, 0 };
wavecomp/waveext
waveflow/kernel_lib/config.h
<reponame>wavecomp/waveext /* * Copyright (c) 2010-2018 Wave Computing, Inc. and its applicable licensors. * All rights reserved; provided, that any files identified as open source shall * be governed by the specific open source license(s) applicable to such files. * * For any files associated with distributions under the Apache 2.0 license, * full attribution to The Apache Software Foundation is given via the license * below. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once using namespace std; class WaveConfigOp { public: static string m_rounding_mode; static string m_config2; static string m_config3; };
wavecomp/waveext
waveflow/kernel_lib/binop_dfx.h
/* * Copyright (c) 2010-2018 Wave Computing, Inc. and its applicable licensors. * All rights reserved; provided, that any files identified as open source shall * be governed by the specific open source license(s) applicable to such files. * * For any files associated with distributions under the Apache 2.0 license, * full attribution to The Apache Software Foundation is given via the license * below. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/util/bcast.h" #include <stdlib.h> #include "dyn_fx_pt.h" using namespace tensorflow; class WaveBinDfxOp : public OpKernel { public: typedef std::vector<DynFxPoint> DFXVector; explicit WaveBinDfxOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} void Compute(OpKernelContext* context) override { DCHECK_EQ(2, context->num_inputs()); const Tensor& tensor_a = context->input(0); const Tensor& tensor_b = context->input(1); // check shapes of input and weights const TensorShape& a_shape = tensor_a.shape(); const TensorShape& b_shape = tensor_b.shape(); // Broadcast preparation BCast bcast(BCast::FromShape(a_shape), BCast::FromShape(b_shape)); if (!bcast.IsValid()) { context->SetStatus(errors::InvalidArgument("Incompatible shapes: ", a_shape.DebugString(), " vs. ", b_shape.DebugString())); return; } const TensorShape output_shape = BCast::ToShape(bcast.output_shape()); #if 0 printf("Got shapes: a: [%d](%d, %d), b: [%d](%d)\n", a_shape.dims(), a_shape.dim_size(0), a_shape.dim_size(1), b_shape.dims(), b_shape.dim_size(0)); printf("shape z: [%d](%d, %d)\n", out_shape.dims(), out_shape.dim_size(0), out_shape.dim_size(1)); #endif // create output tensor Tensor* output = NULL; OP_REQUIRES_OK(context, context->forward_input_or_allocate_output( {0, 1}, 0, output_shape, &output)); ndims = static_cast<int>(bcast.x_reshape().size()); auto a_flat = tensor_a.flat<float>(); auto b_flat = tensor_b.flat<float>(); auto z_flat = output->flat<float>(); m_a_shape = BCast::ToShape(bcast.x_reshape()); m_b_shape = BCast::ToShape(bcast.y_reshape()); m_z_shape = BCast::ToShape(bcast.result_shape()); if (ndims <= 1) { DFXVector a_vp_vec, b_vp_vec, z_vp_vec; a_vp_vec.resize(a_flat.size()); b_vp_vec.resize(b_flat.size()); z_vp_vec.resize(z_flat.size()); partial_in(a_vp_vec, a_flat.data()); partial_in(b_vp_vec, b_flat.data()); for (int i = 0; i < z_flat.size(); i++) { int j = (tensor_a.NumElements() == 1) ? 0 : i; int k = (tensor_b.NumElements() == 1) ? 0 : i; binop(z_vp_vec[i], a_vp_vec[j], b_vp_vec[k]); } partial_out(z_flat.data(), z_vp_vec); } else if (ndims == 2) { op_2d(z_flat.data(), a_flat.data(), b_flat.data(), z_flat.size(), bcast.x_reshape()[0], bcast.x_reshape()[1], bcast.y_reshape()[0], bcast.y_reshape()[1]); } else if (ndims < 6) { op_nd(z_flat.data(), a_flat.data(), b_flat.data(), ndims); } else { context->SetStatus(errors::Unimplemented("Broadcast between ", context->input(0).shape().DebugString(), " and ", context->input(1).shape().DebugString(), " is not supported yet.")); } } private: TensorShape m_a_shape; TensorShape m_b_shape; TensorShape m_z_shape; int ndims; void partial_in(DFXVector& m_out, const float* flat_arr) { fxbp dest_bp(0, 16); dest_bp.set_range_fp(flat_arr, flat_arr + m_out.size()); for (int i = 0; i < m_out.size(); i++) { m_out[i].set_fxbp(dest_bp); m_out[i] = flat_arr[i]; } } void partial_out(float* conv_out, const DFXVector& m_out) { fxbp out_bp(0, 16); out_bp.set_range_dfx(m_out.data(), m_out.data()+m_out.size()); for (int i = 0; i < m_out.size(); i++) { DynFxPoint v(out_bp); v = m_out[i]; conv_out[i] = v.to_fp(); } } void op_2d(float* z_data, const float* a_data, const float* b_data, int z_offset, int a_rows, int a_cols, int b_rows, int b_cols) { DFXVector a_vp_vec, b_vp_vec, z_vp_vec; a_vp_vec.resize(a_rows*a_cols); b_vp_vec.resize(b_rows*b_cols); z_vp_vec.resize(z_offset); partial_in(a_vp_vec, a_data); partial_in(b_vp_vec, b_data); for (int i = 0; i < z_offset; i++) { int j, k; if (a_rows == 1) { j = i % (a_rows * a_cols); if (b_cols == 1) { k = i / (a_rows * a_cols); } else { k = i; } } else if(b_rows == 1) { if (a_cols == 1) { j = i / (b_rows * b_cols); } else { j = i; } k = i % (b_rows * b_cols); } else if (a_cols == 1) { j = i / b_cols; k = i; } else if (b_cols == 1) { j = i; k = i / a_cols; } binop(z_vp_vec[i], a_vp_vec[j], b_vp_vec[k]); } partial_out(z_data, z_vp_vec); } void op_nd(float* z_data, const float* a_data, const float* b_data, int curr_num_dims) { int a_offset = 1; int b_offset = 1; int z_offset = 1; int top_dim = ndims-curr_num_dims; for (int i=ndims-1; i>top_dim; i--) { a_offset *= m_a_shape.dim_size(i); b_offset *= m_b_shape.dim_size(i); z_offset *= m_z_shape.dim_size(i); } for (int i = 0; i < m_z_shape.dim_size(top_dim); i++) { int j = (m_a_shape.dim_size(top_dim) == 1) ? 0 : i; int k = (m_b_shape.dim_size(top_dim) == 1) ? 0 : i; const float* a_in = a_data + j*a_offset; const float* b_in = b_data + k*b_offset; float* z_out = z_data + i*z_offset; if (curr_num_dims > 3) { op_nd(z_out, a_in, b_in, curr_num_dims-1); } else { op_2d(z_out, a_in, b_in, m_z_shape.dim_size(ndims-1)*m_z_shape.dim_size(ndims-2), m_a_shape.dim_size(ndims-2), m_a_shape.dim_size(ndims-1), m_b_shape.dim_size(ndims-2), m_b_shape.dim_size(ndims-1)); } } } // Overrride this function virtual void binop(DynFxPoint& c, const DynFxPoint& a, const DynFxPoint& b) = 0; };
wavecomp/waveext
waveflow/kernel_lib/dfx_registry.h
/* * Copyright (c) 2010-2018 Wave Computing, Inc. and its applicable licensors. * All rights reserved; provided, that any files identified as open source shall * be governed by the specific open source license(s) applicable to such files. * * For any files associated with distributions under the Apache 2.0 license, * full attribution to The Apache Software Foundation is given via the license * below. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor.h" #include <string> #include <unordered_map> #include "dyn_fx_pt.h" class DynFxPointRegistry; /* This class implemented a key/Tensor registry for ops to use. It's designed * to connect ops in a Tensorflow graph together by key name. Technically, it * can be used for any Tensor/Name binding. In practice, it's used to associate * graph ops which generate a BP based on some criteria, with downstream * consumer ops. */ class DynFxPointRegistry { public: void register_dfx(const std::string& n, tensorflow::Tensor* bp); tensorflow::Tensor* find_dfx(const std::string& n) const; // Singleton constructor static DynFxPointRegistry* get_registry(); private: typedef std::unordered_map<const std::string, tensorflow::Tensor*, std::hash<std::string>> TensorBPMap; explicit DynFxPointRegistry() {} TensorBPMap m_tensor_bp_map; };
wavecomp/waveext
waveflow/kernel_lib/gemm_dfx.h
<filename>waveflow/kernel_lib/gemm_dfx.h /* * Copyright (c) 2010-2018 Wave Computing, Inc. and its applicable licensors. * All rights reserved; provided, that any files identified as open source shall * be governed by the specific open source license(s) applicable to such files. * * For any files associated with distributions under the Apache 2.0 license, * full attribution to The Apache Software Foundation is given via the license * below. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "Eigen/Core" #include "dyn_fx_pt.h" template<typename T> void dfx_clear(const fxbp& bp_set, T& m_out, int rows, int cols) { for (int j = 0; j < rows; j++) { for (int k = 0; k < cols; k++) { m_out(j, k).set_fxbp(bp_set); m_out(j, k) = 0; } } } template<typename Tin, typename Tout> static inline void mm_nn(bool zero, const fxbp& bp, Tin& a_m, int a_x, int a_y, Tin& b_m, int b_x, int b_y, Tout& z_m) { // M[i] : A.dim[0] // N[j] : B.dim[1] // K[k] : A.dim[1] == B.dim[0] // output: (A.dim[0], B.dim[1]) for (int i = 0; i < a_x; i++) { for (int j = 0; j < b_y; j++) { DynFxPoint v(bp); for (int k = 0; k < a_y; k++) { v += a_m(i, k) * b_m(k, j); } z_m(i, j) = zero ? v : z_m(i, j) + v; } } } template<typename Tin, typename Tout> static inline void mm_tn(bool zero, const fxbp& bp, Tin& a_m, int a_x, int a_y, Tin& b_m, int b_x, int b_y, Tout& z_m) { // A (grad) is transposed (T,N) // M[i] : A.dim[1] // N[j] : B.dim[1] // K[k] : A.dim[0] == B.dim[0] // (k, i); (k, j) // output: (A.dim[1], B.dim[1]) // KS: there's probably an easier way to clear this tensor if (zero) { dfx_clear(bp, z_m, a_y, b_y); } for (int i = 0; i < a_y; i++) { for (int k = 0; k < a_x; k++) { for (int j = 0; j < b_y; j++) { z_m(i, j) += a_m(k, i) * b_m(k, j); } } } } template<typename Tin, typename Tout> static inline void mm_nt(bool zero, const fxbp& bp, Tin& a_m, int a_x, int a_y, Tin& b_m, int b_x, int b_y, Tout& z_m) { // B (weights) is transposed (N,T) // M[i] : A.dim[0] // N[j] : B.dim[0] // K[k] : A.dim[1] == B.dim[1] // (i, k); (j, k) // output: (A.dim[0], B.dim[0]) for (int i = 0; i < a_x; i++) { for (int j = 0; j < b_x; j++) { DynFxPoint v(bp); for (int k = 0; k < a_y; k++) { v += a_m(i, k) * b_m(j, k); } z_m(i, j) = zero ? v : z_m(i, j) + v; } } } template<typename Tin, typename Tout> static inline void mm_tt(bool zero, const fxbp& bp, Tin& a_m, int a_x, int a_y, Tin& b_m, int b_x, int b_y, Tout& z_m) { // A, B is transposed (T,T) // M[i] : A.dim[1] // N[j] : B.dim[0] // K[k] : A.dim[0] == B.dim[1] // (k, i); (j, k) // output: (A.dim[1], B.dim[0]) // KS: there's probably an easier way to clear this tensor if (zero) { dfx_clear(bp, z_m, a_y, b_x); } for (int i = 0; i < a_y; i++) { for (int k = 0; k < a_x; k++) { for (int j = 0; j < b_x; j++) { z_m(i, j) += a_m(k, i) * b_m(j, k); } } } } // Helper functions // These functions are commonly used to copy in FP arrays and prepare // BP matrixes for compute. template<typename Tout> void fp2dfx(fxbp& dest_bp, Tout& m_out, const float* flat_arr) { // Destination binary point will be reset to whatever best represents // the array to copy. if (dest_bp.m_bp == -1 || !dest_bp.m_initialized) { dest_bp.set_range_fp(flat_arr, flat_arr + m_out.size()); } for (int i = 0; i < m_out.rows(); i++) { for (int j = 0; j < m_out.cols(); j++) { m_out(i, j).set_fxbp(dest_bp); m_out(i, j) = flat_arr[i*m_out.cols() + j]; } } } template<typename Tout> void fp2dfx(int dest_wl, Tout& m_out, const float* flat_arr) { fxbp dest_bp(-1, dest_wl); fp2dfx(dest_bp, m_out, flat_arr); } template<typename Tin> void dfx2fp(fxbp& out_bp, float* conv_out, const Tin& m_out) { // Destination binary point will be reset to whatever best represents // the array to copy. if (out_bp.m_bp == -1 || !out_bp.m_initialized) { out_bp.set_range_dfx(m_out.data(), m_out.data()+m_out.size()); } for (int i = 0; i < m_out.rows(); i++) { for (int j = 0; j < m_out.cols(); j++) { // Individual matrix values are quantized as they are converted // out to FP. DynFxPoint v(out_bp); v = m_out(i, j); conv_out[i*m_out.cols() + j] = v.to_fp(); } } } template<typename Tin> void dfx2fp(int out_wl, float* conv_out, const Tin& m_out) { fxbp out_bp(-1, out_wl); dfx2fp(out_bp, conv_out, m_out); }
wavecomp/waveext
waveflow/kernel_lib/tanh_lut_dfx.h
<filename>waveflow/kernel_lib/tanh_lut_dfx.h<gh_stars>1-10 /* * Copyright (c) 2010-2018 Wave Computing, Inc. and its applicable licensors. * All rights reserved; provided, that any files identified as open source shall * be governed by the specific open source license(s) applicable to such files. * * For any files associated with distributions under the Apache 2.0 license, * full attribution to The Apache Software Foundation is given via the license * below. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(USE_VECTOR_INSTRUCTIONS) constexpr int32_t TANH_LUT_SIZE = 178; constexpr int32_t LUT(int32_t x, int32_t y) { return (x << 16) | (-y & 0xffff); } constexpr int32_t tanh_lut[TANH_LUT_SIZE] = { LUT( 0, 512), LUT( 512, 1023), LUT( 1023, 1532), LUT( 1532, 2037), LUT( 2037, 2539), LUT( 2539, 3036), LUT( 3036, 3528), LUT( 3528, 4013), LUT( 4013, 4490), LUT( 4490, 4960), LUT( 4960, 5420), LUT( 5420, 5871), LUT( 5871, 6312), LUT( 6312, 6743), LUT( 6743, 7163), LUT( 7163, 7571), LUT( 7571, 7968), LUT( 7968, 8353), LUT( 8353, 8726), LUT( 8726, 9087), LUT( 9087, 9435), LUT( 9435, 9771), LUT( 9771, 10095), LUT(10095, 10406), LUT(10406, 10706), LUT(10706, 10993), LUT(10993, 11269), LUT(11269, 11533), LUT(11533, 11785), LUT(11785, 12027), LUT(12027, 12258), LUT(12258, 12478), LUT(12478, 12688), LUT(12688, 12888), LUT(12888, 13078), LUT(13078, 13260), LUT(13260, 13432), LUT(13432, 13595), LUT(13595, 13751), LUT(13751, 13898), LUT(13898, 14038), LUT(14038, 14171), LUT(14171, 14296), LUT(14296, 14415), LUT(14415, 14528), LUT(14528, 14634), LUT(14634, 14735), LUT(14735, 14830), LUT(14830, 14920), LUT(14920, 15005), LUT(15005, 15085), LUT(15085, 15161), LUT(15161, 15232), LUT(15232, 15300), LUT(15300, 15363), LUT(15363, 15423), LUT(15423, 15480), LUT(15480, 15533), LUT(15533, 15584), LUT(15584, 15631), LUT(15631, 15676), LUT(15676, 15718), LUT(15718, 15757), LUT(15757, 15795), LUT(15795, 15830), LUT(15830, 15863), LUT(15863, 15894), LUT(15894, 15923), LUT(15923, 15951), LUT(15951, 15977), LUT(15977, 16001), LUT(16001, 16024), LUT(16024, 16046), LUT(16046, 16066), LUT(16066, 16085), LUT(16085, 16103), LUT(16103, 16120), LUT(16120, 16136), LUT(16136, 16151), LUT(16151, 16165), LUT(16165, 16178), LUT(16178, 16190), LUT(16190, 16202), LUT(16202, 16213), LUT(16213, 16223), LUT(16223, 16233), LUT(16233, 16242), LUT(16242, 16251), LUT(16251, 16259), LUT(16259, 16266), LUT(16266, 16273), LUT(16273, 16280), LUT(16280, 16286), LUT(16286, 16292), LUT(16292, 16298), LUT(16298, 16303), LUT(16303, 16308), LUT(16308, 16312), LUT(16312, 16317), LUT(16317, 16321), LUT(16321, 16325), LUT(16325, 16328), LUT(16328, 16332), LUT(16332, 16335), LUT(16335, 16338), LUT(16338, 16341), LUT(16341, 16343), LUT(16343, 16346), LUT(16346, 16348), LUT(16348, 16350), LUT(16350, 16352), LUT(16352, 16354), LUT(16354, 16356), LUT(16356, 16358), LUT(16358, 16359), LUT(16359, 16361), LUT(16361, 16362), LUT(16362, 16363), LUT(16363, 16365), LUT(16365, 16366), LUT(16366, 16367), LUT(16367, 16368), LUT(16368, 16369), LUT(16369, 16370), LUT(16370, 16371), LUT(16371, 16372), LUT(16372, 16372), LUT(16372, 16373), LUT(16373, 16374), LUT(16374, 16374), LUT(16374, 16375), LUT(16375, 16375), LUT(16375, 16376), LUT(16376, 16376), LUT(16376, 16377), LUT(16377, 16377), LUT(16377, 16378), LUT(16378, 16378), LUT(16378, 16378), LUT(16378, 16379), LUT(16379, 16379), LUT(16379, 16379), LUT(16379, 16380), LUT(16380, 16380), LUT(16380, 16380), LUT(16380, 16380), LUT(16380, 16381), LUT(16381, 16381), LUT(16381, 16381), LUT(16381, 16381), LUT(16381, 16381), LUT(16381, 16382), LUT(16382, 16382), LUT(16382, 16382), LUT(16382, 16382), LUT(16382, 16382), LUT(16382, 16382), LUT(16382, 16382), LUT(16382, 16382), LUT(16382, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16384) }; #else constexpr int32_t TANH_LUT_SIZE = 179; constexpr int tanh_lut[TANH_LUT_SIZE] = { 0, 512, 1023, 1532, 2037, 2539, 3036, 3528, 4013, 4490, 4960, 5420, 5871, 6312, 6743, 7163, 7571, 7968, 8353, 8726, 9087, 9435, 9771, 10095, 10406, 10706, 10993, 11269, 11533, 11785, 12027, 12258, 12478, 12688, 12888, 13078, 13260, 13432, 13595, 13751, 13898, 14038, 14171, 14296, 14415, 14528, 14634, 14735, 14830, 14920, 15005, 15085, 15161, 15232, 15300, 15363, 15423, 15480, 15533, 15584, 15631, 15676, 15718, 15757, 15795, 15830, 15863, 15894, 15923, 15951, 15977, 16001, 16024, 16046, 16066, 16085, 16103, 16120, 16136, 16151, 16165, 16178, 16190, 16202, 16213, 16223, 16233, 16242, 16251, 16259, 16266, 16273, 16280, 16286, 16292, 16298, 16303, 16308, 16312, 16317, 16321, 16325, 16328, 16332, 16335, 16338, 16341, 16343, 16346, 16348, 16350, 16352, 16354, 16356, 16358, 16359, 16361, 16362, 16363, 16365, 16366, 16367, 16368, 16369, 16370, 16371, 16372, 16372, 16373, 16374, 16374, 16375, 16375, 16376, 16376, 16377, 16377, 16378, 16378, 16378, 16379, 16379, 16379, 16380, 16380, 16380, 16380, 16381, 16381, 16381, 16381, 16381, 16382, 16382, 16382, 16382, 16382, 16382, 16382, 16382, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16384 }; #endif
wavecomp/waveext
waveflow/kernel_lib/sigmoid_lut_dfx.h
/* * Copyright (c) 2010-2018 Wave Computing, Inc. and its applicable licensors. * All rights reserved; provided, that any files identified as open source shall * be governed by the specific open source license(s) applicable to such files. * * For any files associated with distributions under the Apache 2.0 license, * full attribution to The Apache Software Foundation is given via the license * below. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if defined(USE_VECTOR_INSTRUCTIONS) constexpr int32_t SIGMOID_LUT_SIZE = 167; constexpr int32_t LUT(int32_t x, int32_t y) { return (x << 16) | (-y & 0xffff); } constexpr int32_t sigmoid_lut[SIGMOID_LUT_SIZE] = { LUT( 8192, 8448), LUT( 8448, 8703), LUT( 8703, 8958), LUT( 8958, 9211), LUT( 9211, 9462), LUT( 9462, 9710), LUT( 9710, 9956), LUT( 9956, 10198), LUT(10198, 10437), LUT(10437, 10672), LUT(10672, 10902), LUT(10902, 11128), LUT(11128, 11348), LUT(11348, 11564), LUT(11564, 11773), LUT(11773, 11978), LUT(11978, 12176), LUT(12176, 12369), LUT(12369, 12555), LUT(12555, 12735), LUT(12735, 12909), LUT(12909, 13077), LUT(13077, 13239), LUT(13239, 13395), LUT(13395, 13545), LUT(13545, 13689), LUT(13689, 13826), LUT(13826, 13958), LUT(13958, 14085), LUT(14085, 14206), LUT(14206, 14321), LUT(14321, 14431), LUT(14431, 14536), LUT(14536, 14636), LUT(14636, 14731), LUT(14731, 14822), LUT(14822, 14908), LUT(14908, 14990), LUT(14990, 15067), LUT(15067, 15141), LUT(15141, 15211), LUT(15211, 15277), LUT(15277, 15340), LUT(15340, 15400), LUT(15400, 15456), LUT(15456, 15509), LUT(15509, 15559), LUT(15559, 15607), LUT(15607, 15652), LUT(15652, 15694), LUT(15694, 15735), LUT(15735, 15772), LUT(15772, 15808), LUT(15808, 15842), LUT(15842, 15874), LUT(15874, 15904), LUT(15904, 15932), LUT(15932, 15959), LUT(15959, 15984), LUT(15984, 16008), LUT(16008, 16030), LUT(16030, 16051), LUT(16051, 16071), LUT(16071, 16089), LUT(16089, 16107), LUT(16107, 16123), LUT(16123, 16139), LUT(16139, 16154), LUT(16154, 16167), LUT(16167, 16180), LUT(16180, 16193), LUT(16193, 16204), LUT(16204, 16215), LUT(16215, 16225), LUT(16225, 16234), LUT(16234, 16243), LUT(16243, 16252), LUT(16252, 16260), LUT(16260, 16267), LUT(16267, 16274), LUT(16274, 16281), LUT(16281, 16287), LUT(16287, 16293), LUT(16293, 16298), LUT(16298, 16304), LUT(16304, 16308), LUT(16308, 16313), LUT(16313, 16317), LUT(16317, 16321), LUT(16321, 16325), LUT(16325, 16329), LUT(16329, 16332), LUT(16332, 16335), LUT(16335, 16338), LUT(16338, 16341), LUT(16341, 16343), LUT(16343, 16346), LUT(16346, 16348), LUT(16348, 16350), LUT(16350, 16352), LUT(16352, 16354), LUT(16354, 16356), LUT(16356, 16358), LUT(16358, 16359), LUT(16359, 16361), LUT(16361, 16362), LUT(16362, 16364), LUT(16364, 16365), LUT(16365, 16366), LUT(16366, 16367), LUT(16367, 16368), LUT(16368, 16369), LUT(16369, 16370), LUT(16370, 16371), LUT(16371, 16372), LUT(16372, 16372), LUT(16372, 16373), LUT(16373, 16374), LUT(16374, 16374), LUT(16374, 16375), LUT(16375, 16375), LUT(16375, 16376), LUT(16376, 16376), LUT(16376, 16377), LUT(16377, 16377), LUT(16377, 16378), LUT(16378, 16378), LUT(16378, 16379), LUT(16379, 16379), LUT(16379, 16379), LUT(16379, 16379), LUT(16379, 16380), LUT(16380, 16380), LUT(16380, 16380), LUT(16380, 16380), LUT(16380, 16381), LUT(16381, 16381), LUT(16381, 16381), LUT(16381, 16381), LUT(16381, 16381), LUT(16381, 16382), LUT(16382, 16382), LUT(16382, 16382), LUT(16382, 16382), LUT(16382, 16382), LUT(16382, 16382), LUT(16382, 16382), LUT(16382, 16382), LUT(16382, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16383), LUT(16383, 16384) }; #else constexpr int32_t SIGMOID_LUT_SIZE = 168; constexpr int32_t sigmoid_lut[SIGMOID_LUT_SIZE] = { 8192, 8448, 8703, 8958, 9211, 9462, 9710, 9956, 10198, 10437, 10672, 10902, 11128, 11348, 11564, 11773, 11978, 12176, 12369, 12555, 12735, 12909, 13077, 13239, 13395, 13545, 13689, 13826, 13958, 14085, 14206, 14321, 14431, 14536, 14636, 14731, 14822, 14908, 14990, 15067, 15141, 15211, 15277, 15340, 15400, 15456, 15509, 15559, 15607, 15652, 15694, 15735, 15772, 15808, 15842, 15874, 15904, 15932, 15959, 15984, 16008, 16030, 16051, 16071, 16089, 16107, 16123, 16139, 16154, 16167, 16180, 16193, 16204, 16215, 16225, 16234, 16243, 16252, 16260, 16267, 16274, 16281, 16287, 16293, 16298, 16304, 16308, 16313, 16317, 16321, 16325, 16329, 16332, 16335, 16338, 16341, 16343, 16346, 16348, 16350, 16352, 16354, 16356, 16358, 16359, 16361, 16362, 16364, 16365, 16366, 16367, 16368, 16369, 16370, 16371, 16372, 16372, 16373, 16374, 16374, 16375, 16375, 16376, 16376, 16377, 16377, 16378, 16378, 16379, 16379, 16379, 16379, 16380, 16380, 16380, 16380, 16381, 16381, 16381, 16381, 16381, 16382, 16382, 16382, 16382, 16382, 16382, 16382, 16382, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16383, 16384 }; #endif
wavecomp/waveext
waveflow/kernel_lib/dyn_fx_pt.h
<filename>waveflow/kernel_lib/dyn_fx_pt.h /* * Copyright (c) 2010-2018 Wave Computing, Inc. and its applicable licensors. * All rights reserved; provided, that any files identified as open source shall * be governed by the specific open source license(s) applicable to such files. * * For any files associated with distributions under the Apache 2.0 license, * full attribution to The Apache Software Foundation is given via the license * below. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <assert.h> #include <math.h> #include <memory> #include <iostream> #include <x86intrin.h> // Forward declarations class fxbp; class DynFxPoint; /* Subclass to represent a shared binary point. */ class fxbp { public: fxbp() {m_bp = 0; m_wl = 16; m_initialized = false;} fxbp(int32_t b) {initialize(b, 16);} fxbp(int32_t b, int32_t w) {assert(w <= 32); initialize(b, w);} fxbp(float f) { int32_t w = 16; initialize(w - get_int_bits(f) - 2, w); } fxbp(float f, int32_t w){ assert(w <= 32); initialize(w - get_int_bits(f) - 2, w); } void initialize(int32_t b, int32_t w) { m_bp = b; m_wl = w; m_initialized = true; } template <typename Ti> void set_range_fp(Ti start, Ti end); template <typename Ti> void set_range_dfx(Ti start, Ti end); void set_range_int32(const int32_t* start, const int32_t* end, int32_t src_bp); float epsilon() const {return (float)((uint32_t)1 << m_bp);} static int32_t get_int_bits(float v); int32_t m_bp; int32_t m_wl; bool m_initialized; }; /* Dynamic Fixed Point type, multi-precision. */ class DynFxPoint { public: DynFxPoint() {m_v = 0;} DynFxPoint(fxbp bp) {m_fxbp = bp; m_v = 0;} // Direct initialization ctors DynFxPoint(const int& i) { operator=(i); } DynFxPoint(const float& f) { operator=(f); } // explicit cast operators explicit operator float() const { return to_fp(); } explicit operator int() const { return get_value() >> m_fxbp.m_bp; } void set_fxbp(fxbp); void set_fxbp(uint32_t b, uint32_t w); fxbp get_fxbp() const {return m_fxbp;} DynFxPoint& operator=(const float &f); DynFxPoint& operator=(const DynFxPoint &v); DynFxPoint& operator=(const int &v); int32_t& operator()() {return m_v;} DynFxPoint operator+(const DynFxPoint &y) const; DynFxPoint operator-(const DynFxPoint &y) const; DynFxPoint operator-() const; DynFxPoint operator*(const DynFxPoint &y) const; DynFxPoint operator/(const DynFxPoint &y) const; //DynFxPoint operator%(const DynFxPoint &y) const; bool operator>(const DynFxPoint &y) const; bool operator>=(const DynFxPoint &y) const; bool operator<(const DynFxPoint &y) const; bool operator<=(const DynFxPoint &y) const; bool operator==(const DynFxPoint &y) const; bool operator!=(const DynFxPoint &y) const; DynFxPoint& operator+=(const DynFxPoint &y); DynFxPoint& operator-=(const DynFxPoint &y); DynFxPoint& operator*=(const DynFxPoint &y); DynFxPoint& operator/=(const DynFxPoint &y); DynFxPoint& operator++(); DynFxPoint operator++(int unused); DynFxPoint& operator--(); DynFxPoint operator--(int unused); int32_t get_value() const; float to_fp() const; void set_bits(const int32_t& v) {m_v = v;} void adjust_bp(int bp); // public globals static void quantize(DynFxPoint* v); friend std::ostream &operator<<(std::ostream& strm, const DynFxPoint& obj) { strm << obj.to_fp(); return strm; } private: int32_t with_params(unsigned p, unsigned bp, bool round=true) const; int64_t with_params(int64_t v, unsigned p, unsigned bp, bool round=true) const; int32_t round_adjustment(int32_t v, unsigned r) const; void adjust_precision(unsigned p); int32_t sat_eval(int64_t v) const; int32_t sat_eval(int p, int64_t v) const; int32_t m_v; fxbp m_fxbp; }; template <typename Ti> void fxbp::set_range_fp(Ti start, Ti end) { m_initialized = true; // Reset the BP based on the range of all tensor values. The goal is to set // the BP to allow the highest/lowest valued elements to be below/above the // saturation threshold of the integer field. float vmax = 1e-10; for (auto it = start; it != end; ++it) { float v = fabs(*it); vmax = fmax(vmax, v); } int32_t int_bits = get_int_bits(vmax); // Int can be no larger than WL - 1. If so, we will saturate some values in // the tensor in order to constrain the precision. int32_t fx_int_max = m_wl - 1; // Float32 base type can only represent 23 bits of fraction no matter what. fx_int_max = fx_int_max > 23 ? 23 : fx_int_max; // An int field of -16 yields a BP of 31, which is the max value before // some functions begin to return invalid results (max word size == 32). const int32_t fx_int_min = -16; int_bits = int_bits > fx_int_max ? fx_int_max : int_bits; int_bits = int_bits < fx_int_min ? fx_int_min : int_bits; // FX word format: |signed integer | fraction | // BP is the fraction bits m_bp = m_wl - 1 - int_bits; assert(m_bp < 32); assert(m_bp >= 0); } template <typename Ti> void fxbp::set_range_dfx(Ti start, Ti end) { m_initialized = true; // We need to set based on the min BP (max number of int bits). int32_t fx_int_max = 0; int32_t fx_lzc = 1000; for (auto it = start; it != end; ++it) { const fxbp& src_bp = it->get_fxbp(); int32_t int_bits = 32 - src_bp.m_bp - 1; fx_int_max = int_bits > fx_int_max ? int_bits : fx_int_max; int32_t v = it->get_value(); v = v >= 0 ? v : -v; int32_t int_lz = __builtin_clz(v) - 1; fx_lzc = int_lz < fx_lzc ? int_lz : fx_lzc; } m_bp = m_wl - (fx_int_max - fx_lzc) - 1; }
briandl2000/reactphysics3d
include/reactphysics3d/components/RigidBodyComponents.h
/******************************************************************************** * ReactPhysics3D physics library, http://www.reactphysics3d.com * * Copyright (c) 2010-2020 <NAME> * ********************************************************************************* * * * This software is provided 'as-is', without any express or implied warranty. * * In no event will the authors be held liable for any damages arising from the * * use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not claim * * that you wrote the original software. If you use this software in a * * product, an acknowledgment in the product documentation would be * * appreciated but is not required. * * * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * * * 3. This notice may not be removed or altered from any source distribution. * * * ********************************************************************************/ #ifndef REACTPHYSICS3D_RIGID_BODY_COMPONENTS_H #define REACTPHYSICS3D_RIGID_BODY_COMPONENTS_H // Libraries #include <reactphysics3d/mathematics/Transform.h> #include <reactphysics3d/mathematics/Matrix3x3.h> #include <reactphysics3d/engine/Entity.h> #include <reactphysics3d/components/Components.h> #include <reactphysics3d/containers/Map.h> // ReactPhysics3D namespace namespace reactphysics3d { // Class declarations class MemoryAllocator; class EntityManager; class RigidBody; enum class BodyType; /// Enumeration for the type of a body /// STATIC : A static body has infinite mass, zero velocity but the position can be /// changed manually. A static body does not collide with other static or kinematic bodies. /// KINEMATIC : A kinematic body has infinite mass, the velocity can be changed manually and its /// position is computed by the physics engine. A kinematic body does not collide with /// other static or kinematic bodies. /// DYNAMIC : A dynamic body has non-zero mass, non-zero velocity determined by forces and its /// position is determined by the physics engine. A dynamic body can collide with other /// dynamic, static or kinematic bodies. enum class BodyType {STATIC, KINEMATIC, DYNAMIC}; // Class RigidBodyComponents /** * This class represent the component of the ECS that contains data about a rigid body. * The components of the sleeping entities (bodies) are always stored at the end of the array. */ class RigidBodyComponents : public Components { private: // -------------------- Attributes -------------------- // /// Array of body entities of each component Entity* mBodiesEntities; /// Array of pointers to the corresponding rigid bodies RigidBody** mRigidBodies; /// Array of boolean values to know if the body is allowed to go to sleep bool* mIsAllowedToSleep; /// Array of boolean values to know if the body is sleeping bool* mIsSleeping; /// Array with values for elapsed time since the body velocity was below the sleep velocity decimal* mSleepTimes; /// Array with the type of bodies (static, kinematic or dynamic) BodyType* mBodyTypes; /// Array with the linear velocity of each component Vector3* mLinearVelocities; Vector3* mLinearVelocitiesFactors; /// Array with the angular velocity of each component Vector3* mAngularVelocities; Vector3* mAngularVelocitiesFactors; /// Array with the external force of each component Vector3* mExternalForces; /// Array with the external torque of each component Vector3* mExternalTorques; /// Array with the linear damping factor of each component decimal* mLinearDampings; /// Array with the angular damping factor of each component decimal* mAngularDampings; /// Array with the mass of each component decimal* mMasses; /// Array with the inverse mass of each component decimal* mInverseMasses; /// Array with the inertia tensor of each component Vector3* mLocalInertiaTensors; /// Array with the inverse of the inertia tensor of each component Vector3* mInverseInertiaTensorsLocal; /// Array with the constrained linear velocity of each component Vector3* mConstrainedLinearVelocities; /// Array with the constrained angular velocity of each component Vector3* mConstrainedAngularVelocities; /// Array with the split linear velocity of each component Vector3* mSplitLinearVelocities; /// Array with the split angular velocity of each component Vector3* mSplitAngularVelocities; /// Array with the constrained position of each component (for position error correction) Vector3* mConstrainedPositions; /// Array of constrained orientation for each component (for position error correction) Quaternion* mConstrainedOrientations; /// Array of center of mass of each component (in local-space coordinates) Vector3* mCentersOfMassLocal; /// Array of center of mass of each component (in world-space coordinates) Vector3* mCentersOfMassWorld; /// True if the gravity needs to be applied to this component bool* mIsGravityEnabled; /// Array with the boolean value to know if the body has already been added into an island bool* mIsAlreadyInIsland; /// For each body, the list of joints entities the body is part of List<Entity>* mJoints; // -------------------- Methods -------------------- // /// Allocate memory for a given number of components virtual void allocate(uint32 nbComponentsToAllocate) override; /// Destroy a component at a given index virtual void destroyComponent(uint32 index) override; /// Move a component from a source to a destination index in the components array virtual void moveComponentToIndex(uint32 srcIndex, uint32 destIndex) override; /// Swap two components in the array virtual void swapComponents(uint32 index1, uint32 index2) override; public: /// Structure for the data of a rigid body component struct RigidBodyComponent { RigidBody* body; BodyType bodyType; const Vector3& worldPosition; /// Constructor RigidBodyComponent(RigidBody* body, BodyType bodyType, const Vector3& worldPosition) : body(body), bodyType(bodyType), worldPosition(worldPosition) { } }; // -------------------- Methods -------------------- // /// Constructor RigidBodyComponents(MemoryAllocator& allocator); /// Destructor virtual ~RigidBodyComponents() override = default; /// Add a component void addComponent(Entity bodyEntity, bool isSleeping, const RigidBodyComponent& component); /// Return a pointer to a rigid body RigidBody* getRigidBody(Entity bodyEntity); /// Return true if the body is allowed to sleep bool getIsAllowedToSleep(Entity bodyEntity) const; /// Set the value to know if the body is allowed to sleep void setIsAllowedToSleep(Entity bodyEntity, bool isAllowedToSleep) const; /// Return true if the body is sleeping bool getIsSleeping(Entity bodyEntity) const; /// Set the value to know if the body is sleeping void setIsSleeping(Entity bodyEntity, bool isSleeping) const; /// Return the sleep time decimal getSleepTime(Entity bodyEntity) const; /// Set the sleep time void setSleepTime(Entity bodyEntity, decimal sleepTime) const; /// Return the body type of a body BodyType getBodyType(Entity bodyEntity); /// Set the body type of a body void setBodyType(Entity bodyEntity, BodyType bodyType); /// Return the linear velocity of an entity const Vector3& getLinearVelocity(Entity bodyEntity) const; /// Set the linear velocity of an entity void setLinearVelocity(Entity bodyEntity, const Vector3& linearVelocity); void setLinearVelocityFactor(Entity bodyEntity, const Vector3& setLinearVelocityFactor); /// Return the angular velocity of an entity const Vector3& getAngularVelocity(Entity bodyEntity) const; /// Set the angular velocity of an entity void setAngularVelocity(Entity bodyEntity, const Vector3& angularVelocity); void setAngularVelocityFactor(Entity bodyEntity, const Vector3& setAngularVelocityFactor); /// Return the external force of an entity const Vector3& getExternalForce(Entity bodyEntity) const; /// Return the external torque of an entity const Vector3& getExternalTorque(Entity bodyEntity) const; /// Return the linear damping factor of an entity decimal getLinearDamping(Entity bodyEntity) const; /// Return the angular damping factor of an entity decimal getAngularDamping(Entity bodyEntity) const; /// Return the mass of an entity decimal getMass(Entity bodyEntity) const; /// Set the mass of an entity void setMass(Entity bodyEntity, decimal mass); /// Return the mass inverse of an entity decimal getMassInverse(Entity bodyEntity) const; /// Set the inverse mass of an entity void setMassInverse(Entity bodyEntity, decimal inverseMass); /// Return the local inertia tensor of an entity const Vector3& getLocalInertiaTensor(Entity bodyEntity); /// Set the local inertia tensor of an entity void setLocalInertiaTensor(Entity bodyEntity, const Vector3& inertiaTensorLocal); /// Return the inverse local inertia tensor of an entity const Vector3& getInertiaTensorLocalInverse(Entity bodyEntity); /// Set the external force of an entity void setExternalForce(Entity bodyEntity, const Vector3& externalForce); /// Set the external force of an entity void setExternalTorque(Entity bodyEntity, const Vector3& externalTorque); /// Set the linear damping factor of an entity void setLinearDamping(Entity bodyEntity, decimal linearDamping); /// Set the angular damping factor of an entity void setAngularDamping(Entity bodyEntity, decimal angularDamping); /// Set the inverse local inertia tensor of an entity void setInverseInertiaTensorLocal(Entity bodyEntity, const Vector3& inertiaTensorLocalInverse); /// Return the constrained linear velocity of an entity const Vector3& getConstrainedLinearVelocity(Entity bodyEntity) const; /// Return the constrained angular velocity of an entity const Vector3& getConstrainedAngularVelocity(Entity bodyEntity) const; /// Return the split linear velocity of an entity const Vector3& getSplitLinearVelocity(Entity bodyEntity) const; /// Return the split angular velocity of an entity const Vector3& getSplitAngularVelocity(Entity bodyEntity) const; /// Return the constrained position of an entity Vector3& getConstrainedPosition(Entity bodyEntity); /// Return the constrained orientation of an entity Quaternion& getConstrainedOrientation(Entity bodyEntity); /// Return the local center of mass of an entity const Vector3& getCenterOfMassLocal(Entity bodyEntity); /// Return the world center of mass of an entity const Vector3& getCenterOfMassWorld(Entity bodyEntity); /// Return true if gravity is enabled for this entity bool getIsGravityEnabled(Entity bodyEntity) const; /// Return true if the entity is already in an island bool getIsAlreadyInIsland(Entity bodyEntity) const; /// Set the constrained linear velocity of an entity void setConstrainedLinearVelocity(Entity bodyEntity, const Vector3& constrainedLinearVelocity); /// Set the constrained angular velocity of an entity void setConstrainedAngularVelocity(Entity bodyEntity, const Vector3& constrainedAngularVelocity); /// Set the split linear velocity of an entity void setSplitLinearVelocity(Entity bodyEntity, const Vector3& splitLinearVelocity); /// Set the split angular velocity of an entity void setSplitAngularVelocity(Entity bodyEntity, const Vector3& splitAngularVelocity); /// Set the constrained position of an entity void setConstrainedPosition(Entity bodyEntity, const Vector3& constrainedPosition); /// Set the constrained orientation of an entity void setConstrainedOrientation(Entity bodyEntity, const Quaternion& constrainedOrientation); /// Set the local center of mass of an entity void setCenterOfMassLocal(Entity bodyEntity, const Vector3& centerOfMassLocal); /// Set the world center of mass of an entity void setCenterOfMassWorld(Entity bodyEntity, const Vector3& centerOfMassWorld); /// Set the value to know if the gravity is enabled for this entity void setIsGravityEnabled(Entity bodyEntity, bool isGravityEnabled); /// Set the value to know if the entity is already in an island void setIsAlreadyInIsland(Entity bodyEntity, bool isAlreadyInIsland); /// Return the list of joints of a body const List<Entity>& getJoints(Entity bodyEntity) const; /// Add a joint to a body component void addJointToBody(Entity bodyEntity, Entity jointEntity); /// Remove a joint from a body component void removeJointFromBody(Entity bodyEntity, Entity jointEntity); // -------------------- Friendship -------------------- // friend class PhysicsWorld; friend class ContactSolverSystem; friend class SolveBallAndSocketJointSystem; friend class SolveFixedJointSystem; friend class SolveHingeJointSystem; friend class SolveSliderJointSystem; friend class DynamicsSystem; friend class BallAndSocketJoint; friend class FixedJoint; friend class HingeJoint; friend class SliderJoint; }; // Return a pointer to a body rigid inline RigidBody* RigidBodyComponents::getRigidBody(Entity bodyEntity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mRigidBodies[mMapEntityToComponentIndex[bodyEntity]]; } // Return true if the body is allowed to sleep inline bool RigidBodyComponents::getIsAllowedToSleep(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mIsAllowedToSleep[mMapEntityToComponentIndex[bodyEntity]]; } // Set the value to know if the body is allowed to sleep inline void RigidBodyComponents::setIsAllowedToSleep(Entity bodyEntity, bool isAllowedToSleep) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mIsAllowedToSleep[mMapEntityToComponentIndex[bodyEntity]] = isAllowedToSleep; } // Return true if the body is sleeping inline bool RigidBodyComponents::getIsSleeping(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mIsSleeping[mMapEntityToComponentIndex[bodyEntity]]; } // Set the value to know if the body is sleeping inline void RigidBodyComponents::setIsSleeping(Entity bodyEntity, bool isSleeping) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mIsSleeping[mMapEntityToComponentIndex[bodyEntity]] = isSleeping; } // Return the sleep time inline decimal RigidBodyComponents::getSleepTime(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mSleepTimes[mMapEntityToComponentIndex[bodyEntity]]; } // Set the sleep time inline void RigidBodyComponents::setSleepTime(Entity bodyEntity, decimal sleepTime) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mSleepTimes[mMapEntityToComponentIndex[bodyEntity]] = sleepTime; } // Return the body type of a body inline BodyType RigidBodyComponents::getBodyType(Entity bodyEntity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mBodyTypes[mMapEntityToComponentIndex[bodyEntity]]; } // Set the body type of a body inline void RigidBodyComponents::setBodyType(Entity bodyEntity, BodyType bodyType) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mBodyTypes[mMapEntityToComponentIndex[bodyEntity]] = bodyType; } // Return the linear velocity of an entity inline const Vector3& RigidBodyComponents::getLinearVelocity(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mLinearVelocities[mMapEntityToComponentIndex[bodyEntity]]; } // Return the angular velocity of an entity inline const Vector3& RigidBodyComponents::getAngularVelocity(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mAngularVelocities[mMapEntityToComponentIndex[bodyEntity]]; } // Set the linear velocity of an entity inline void RigidBodyComponents::setLinearVelocity(Entity bodyEntity, const Vector3& linearVelocity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mLinearVelocities[mMapEntityToComponentIndex[bodyEntity]] = linearVelocity; } inline void RigidBodyComponents::setLinearVelocityFactor(Entity bodyEntity, const Vector3& linearVelocityFactor) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mLinearVelocitiesFactors[mMapEntityToComponentIndex[bodyEntity]] = linearVelocityFactor; } // Set the angular velocity of an entity inline void RigidBodyComponents::setAngularVelocity(Entity bodyEntity, const Vector3& angularVelocity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mAngularVelocities[mMapEntityToComponentIndex[bodyEntity]] = angularVelocity; } inline void RigidBodyComponents::setAngularVelocityFactor(Entity bodyEntity, const Vector3& angularVelocityFactor) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mAngularVelocitiesFactors[mMapEntityToComponentIndex[bodyEntity]] = angularVelocityFactor; } // Return the external force of an entity inline const Vector3& RigidBodyComponents::getExternalForce(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mExternalForces[mMapEntityToComponentIndex[bodyEntity]]; } // Return the external torque of an entity inline const Vector3& RigidBodyComponents::getExternalTorque(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mExternalTorques[mMapEntityToComponentIndex[bodyEntity]]; } // Return the linear damping factor of an entity inline decimal RigidBodyComponents::getLinearDamping(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mLinearDampings[mMapEntityToComponentIndex[bodyEntity]]; } // Return the angular damping factor of an entity inline decimal RigidBodyComponents::getAngularDamping(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mAngularDampings[mMapEntityToComponentIndex[bodyEntity]]; } // Return the mass of an entity inline decimal RigidBodyComponents::getMass(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mMasses[mMapEntityToComponentIndex[bodyEntity]]; } // Return the inverse mass of an entity inline decimal RigidBodyComponents::getMassInverse(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mInverseMasses[mMapEntityToComponentIndex[bodyEntity]]; } // Return the inverse local inertia tensor of an entity inline const Vector3& RigidBodyComponents::getInertiaTensorLocalInverse(Entity bodyEntity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mInverseInertiaTensorsLocal[mMapEntityToComponentIndex[bodyEntity]]; } // Set the external force of an entity inline void RigidBodyComponents::setExternalForce(Entity bodyEntity, const Vector3& externalForce) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mExternalForces[mMapEntityToComponentIndex[bodyEntity]] = externalForce; } // Set the external force of an entity inline void RigidBodyComponents::setExternalTorque(Entity bodyEntity, const Vector3& externalTorque) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mExternalTorques[mMapEntityToComponentIndex[bodyEntity]] = externalTorque; } // Set the linear damping factor of an entity inline void RigidBodyComponents::setLinearDamping(Entity bodyEntity, decimal linearDamping) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mLinearDampings[mMapEntityToComponentIndex[bodyEntity]] = linearDamping; } // Set the angular damping factor of an entity inline void RigidBodyComponents::setAngularDamping(Entity bodyEntity, decimal angularDamping) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mAngularDampings[mMapEntityToComponentIndex[bodyEntity]] = angularDamping; } // Set the mass of an entity inline void RigidBodyComponents::setMass(Entity bodyEntity, decimal mass) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mMasses[mMapEntityToComponentIndex[bodyEntity]] = mass; } // Set the mass inverse of an entity inline void RigidBodyComponents::setMassInverse(Entity bodyEntity, decimal inverseMass) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mInverseMasses[mMapEntityToComponentIndex[bodyEntity]] = inverseMass; } // Return the local inertia tensor of an entity inline const Vector3& RigidBodyComponents::getLocalInertiaTensor(Entity bodyEntity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mLocalInertiaTensors[mMapEntityToComponentIndex[bodyEntity]]; } // Set the local inertia tensor of an entity inline void RigidBodyComponents::setLocalInertiaTensor(Entity bodyEntity, const Vector3& inertiaTensorLocal) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mLocalInertiaTensors[mMapEntityToComponentIndex[bodyEntity]] = inertiaTensorLocal; } // Set the inverse local inertia tensor of an entity inline void RigidBodyComponents::setInverseInertiaTensorLocal(Entity bodyEntity, const Vector3& inertiaTensorLocalInverse) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mInverseInertiaTensorsLocal[mMapEntityToComponentIndex[bodyEntity]] = inertiaTensorLocalInverse; } // Return the constrained linear velocity of an entity inline const Vector3& RigidBodyComponents::getConstrainedLinearVelocity(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mConstrainedLinearVelocities[mMapEntityToComponentIndex[bodyEntity]]; } // Return the constrained angular velocity of an entity inline const Vector3& RigidBodyComponents::getConstrainedAngularVelocity(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mConstrainedAngularVelocities[mMapEntityToComponentIndex[bodyEntity]]; } // Return the split linear velocity of an entity inline const Vector3& RigidBodyComponents::getSplitLinearVelocity(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mSplitLinearVelocities[mMapEntityToComponentIndex[bodyEntity]]; } // Return the split angular velocity of an entity inline const Vector3& RigidBodyComponents::getSplitAngularVelocity(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mSplitAngularVelocities[mMapEntityToComponentIndex[bodyEntity]]; } // Return the constrained position of an entity inline Vector3& RigidBodyComponents::getConstrainedPosition(Entity bodyEntity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mConstrainedPositions[mMapEntityToComponentIndex[bodyEntity]]; } // Return the constrained orientation of an entity inline Quaternion& RigidBodyComponents::getConstrainedOrientation(Entity bodyEntity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mConstrainedOrientations[mMapEntityToComponentIndex[bodyEntity]]; } // Return the local center of mass of an entity inline const Vector3& RigidBodyComponents::getCenterOfMassLocal(Entity bodyEntity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mCentersOfMassLocal[mMapEntityToComponentIndex[bodyEntity]]; } // Return the world center of mass of an entity inline const Vector3& RigidBodyComponents::getCenterOfMassWorld(Entity bodyEntity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mCentersOfMassWorld[mMapEntityToComponentIndex[bodyEntity]]; } // Set the constrained linear velocity of an entity inline void RigidBodyComponents::setConstrainedLinearVelocity(Entity bodyEntity, const Vector3& constrainedLinearVelocity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mConstrainedLinearVelocities[mMapEntityToComponentIndex[bodyEntity]] = constrainedLinearVelocity; } // Set the constrained angular velocity of an entity inline void RigidBodyComponents::setConstrainedAngularVelocity(Entity bodyEntity, const Vector3& constrainedAngularVelocity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mConstrainedAngularVelocities[mMapEntityToComponentIndex[bodyEntity]] = constrainedAngularVelocity; } // Set the split linear velocity of an entity inline void RigidBodyComponents::setSplitLinearVelocity(Entity bodyEntity, const Vector3& splitLinearVelocity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mSplitLinearVelocities[mMapEntityToComponentIndex[bodyEntity]] = splitLinearVelocity; } // Set the split angular velocity of an entity inline void RigidBodyComponents::setSplitAngularVelocity(Entity bodyEntity, const Vector3& splitAngularVelocity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mSplitAngularVelocities[mMapEntityToComponentIndex[bodyEntity]] = splitAngularVelocity; } // Set the constrained position of an entity inline void RigidBodyComponents::setConstrainedPosition(Entity bodyEntity, const Vector3& constrainedPosition) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mConstrainedPositions[mMapEntityToComponentIndex[bodyEntity]] = constrainedPosition; } // Set the constrained orientation of an entity inline void RigidBodyComponents::setConstrainedOrientation(Entity bodyEntity, const Quaternion& constrainedOrientation) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mConstrainedOrientations[mMapEntityToComponentIndex[bodyEntity]] = constrainedOrientation; } // Set the local center of mass of an entity inline void RigidBodyComponents::setCenterOfMassLocal(Entity bodyEntity, const Vector3& centerOfMassLocal) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mCentersOfMassLocal[mMapEntityToComponentIndex[bodyEntity]] = centerOfMassLocal; } // Set the world center of mass of an entity inline void RigidBodyComponents::setCenterOfMassWorld(Entity bodyEntity, const Vector3& centerOfMassWorld) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mCentersOfMassWorld[mMapEntityToComponentIndex[bodyEntity]] = centerOfMassWorld; } // Return true if gravity is enabled for this entity inline bool RigidBodyComponents::getIsGravityEnabled(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mIsGravityEnabled[mMapEntityToComponentIndex[bodyEntity]]; } // Return true if the entity is already in an island inline bool RigidBodyComponents::getIsAlreadyInIsland(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mIsAlreadyInIsland[mMapEntityToComponentIndex[bodyEntity]]; } // Set the value to know if the gravity is enabled for this entity inline void RigidBodyComponents::setIsGravityEnabled(Entity bodyEntity, bool isGravityEnabled) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mIsGravityEnabled[mMapEntityToComponentIndex[bodyEntity]] = isGravityEnabled; } // Set the value to know if the entity is already in an island inline void RigidBodyComponents::setIsAlreadyInIsland(Entity bodyEntity, bool isAlreadyInIsland) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mIsAlreadyInIsland[mMapEntityToComponentIndex[bodyEntity]] = isAlreadyInIsland; } // Return the list of joints of a body inline const List<Entity>& RigidBodyComponents::getJoints(Entity bodyEntity) const { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); return mJoints[mMapEntityToComponentIndex[bodyEntity]]; } // Add a joint to a body component inline void RigidBodyComponents::addJointToBody(Entity bodyEntity, Entity jointEntity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mJoints[mMapEntityToComponentIndex[bodyEntity]].add(jointEntity); } // Remove a joint from a body component inline void RigidBodyComponents::removeJointFromBody(Entity bodyEntity, Entity jointEntity) { assert(mMapEntityToComponentIndex.containsKey(bodyEntity)); mJoints[mMapEntityToComponentIndex[bodyEntity]].remove(jointEntity); } } #endif
furkankaplan/fk-firebase-kit-ios
fk-firebase-kit-ios/Resource/fk_firebase_kit_ios.h
// // fk_firebase_kit_ios.h // fk-firebase-kit-ios // // Created by <NAME> on 29.09.2020. // #import <Foundation/Foundation.h> //! Project version number for fk_firebase_kit_ios. FOUNDATION_EXPORT double fk_firebase_kit_iosVersionNumber; //! Project version string for fk_firebase_kit_ios. FOUNDATION_EXPORT const unsigned char fk_firebase_kit_iosVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <fk_firebase_kit_ios/PublicHeader.h>
krenzlin/teensy-synth
src/filter.h
#pragma once #include <stdint.h> namespace filter { struct LP { int32_t sample {}; int32_t process(int32_t input); }; }
krenzlin/teensy-synth
src/buffer.h
<filename>src/buffer.h<gh_stars>0 #include <stddef.h> #include <array> template<typename T, size_t N> struct Buffer { size_t read_ix {0}; size_t write_ix {0}; std::array<T, N+1> values {}; T default_value {}; inline bool empty() { return write_ix == read_ix; } inline bool full() { return advance(write_ix) == read_ix; } inline size_t capacity() { return N; } inline size_t advance(const size_t ix) { return (ix + 1) % (capacity() + 1); } bool write(const T value) { if (full()) { return false; } values[write_ix] = value; write_ix = advance(write_ix); return true; } T read() { if (empty()) { return default_value; } T value = values[read_ix]; read_ix = advance(read_ix); return value; } };
krenzlin/teensy-synth
src/voices.h
#pragma once #include <stdint.h> #include <math.h> #include "misc.h" #include "ADSR.h" namespace osc { constexpr uint8_t n_voices {16}; template<typename T> struct VoiceManager { std::array<T, n_voices> voices {}; std::array<T*, 127> notes {}; int32_t process() { int32_t sample = 0; for (auto &voice : voices) { if (voice.is_active()) { sample += voice.process() / n_voices; } } return sample; } void note_on(const int note, const int velocity=127) { for (auto &voice : voices) { if (!voice.is_active()) { voice.note_on(note, velocity); notes[note] = &voice; break; } } } void note_off(const int note, const int velocity=127) { if (notes[note]) { notes[note]->note_off(velocity, note); notes[note] = nullptr; } } void set_env(float value) { for (auto &voice: voices) { voice.set_env(value); } } }; template<typename T> class Env : public T { ADSR env; public: bool is_active() { return env.getState(); } void note_on(const int note, const int velocity=127) { env.reset(); env.gate(true); T::note_on(note, velocity); } void note_off(uint8_t note, uint8_t velocity=127) { env.gate(false); T::note_off(note, velocity); } void set_ADSR(float attack, float decay, float sustain, float release) { env.setAttackRate(attack * misc::samplerate); env.setDecayRate(decay * misc::samplerate); env.setSustainLevel(sustain); env.setReleaseRate(release * misc::samplerate); } int32_t process() { if (!is_active()) { return 0; } return T::process() * env.process(); } // one-knob ADSR void set_env(float value) { if (value < 0.5) { float decay = powf(10, 1.5f * value); float release = value; set_ADSR(0.f, decay, 0.f, release); } else if(value >= 0.5) { value = (value - 0.5f) * 2.f; float ar = powf(10, 2.f * value); set_ADSR(ar, 0, 1.0, ar); } } }; using PolySaw = VoiceManager<Env<PolyBLEPSaw>>; }
krenzlin/teensy-synth
src/osc.h
<gh_stars>0 #pragma once #include <stdint.h> #include "delay.h" #include "filter.h" namespace osc { class Saw { uint32_t phase {(uint32_t) INT32_MIN}; uint32_t p_incr {0}; int32_t sample{0}; uint8_t note_ {0}; public: void note_on(uint8_t note, uint8_t velocity=127); void note_off(uint8_t note, uint8_t velocity=127); int32_t process(); }; class PolyBLEPSaw { uint32_t phase {(uint32_t) INT32_MIN}; uint32_t p_incr {0}; int32_t sample{0}; uint8_t note_ {0}; public: void note_on(uint8_t note, uint8_t velocity=127); void note_off(uint8_t note, uint8_t velocity=127); int32_t process(); }; class KarplusStrong { Delay<int32_t, 110> forward; filter::LP lp; public: void note_on(uint8_t note, uint8_t velocity=127); void note_off(uint8_t note, uint8_t velocity=127); int32_t process(); }; }
krenzlin/teensy-synth
tests/mocks/core_pins.h
#include <stdint.h> uint32_t analogWriteResolution(uint32_t bits); void analogWriteDAC0(int val);
krenzlin/teensy-synth
src/misc.h
<gh_stars>0 #pragma once #include <stdint.h> namespace misc { constexpr float tuning {440.f}; #ifdef AUDIO_SAMPLE_RATE_EXACT constexpr uint16_t samplerate {(uint16_t) AUDIO_SAMPLE_RATE_EXACT}; #else constexpr uint16_t samplerate {48000U}; #endif constexpr uint32_t random_seed {42U}; // must be non-zero!! float m_to_f(const uint8_t note, const float tuning=tuning); uint32_t m_to_incr(const uint8_t note); uint32_t f_to_incr(const float freq); uint16_t sr_to_us(const uint16_t sr=samplerate); inline int32_t u32_to_s32(const uint32_t x) { return x + INT32_MIN; } inline uint32_t s32_to_u32(const int32_t x) { return (uint32_t) x - (uint32_t) INT32_MIN; } inline uint16_t s32_to_u12(const int32_t x) { return misc::s32_to_u32(x) >> (32 - 12); // (x - INT32_MIN) >> 20 === (x >> 20) + 0x800 } inline int16_t s32_to_s16(const int32_t x) { return x >> (32 - 16); } inline float s32_to_float(const int32_t x) { return (float) x / (float) INT32_MAX; } uint32_t fast_rand(); float fast_float_rand(); uint8_t random_note(uint8_t min=0, uint8_t max=127); /* PolyBLEP is normally calculated for phases going from 0 to 1 * This is an unsigned int version so it will work for phases from 0..UINT32_MAX * and return a *signed* int */ inline int32_t polyblep(uint32_t p, uint32_t dp) { static float pf {0.f}; if (p < dp) { pf = (float) p / (float) dp; return (-pf*pf/2 + pf - .5f) * INT32_MAX; } else if (UINT32_MAX - p < dp) { /* used to be p -= UINT32_MAX & p /= dp * BUT this would be negative (as nothing is bigger than UINT32_MAX) * which cannot be repesented in uint32_t * so instead calculate the positive (or abs) of it * and use -p in the following calculations * ALSO introduce a float version (pf) as the new p will be between 0..1 */ pf = (UINT32_MAX - p) / (float) dp; // was (max*pf*pf)/2 + (max*pf) + max/2; // using -pf -> pf^2 stays positiv but max*pf is negated // update: factoring out max return (pf*pf/2 - pf + .5f) * INT32_MAX; } return 0; } }
krenzlin/teensy-synth
src/AudioObjects.h
<filename>src/AudioObjects.h #include "Audio.h" #include "osc.h" #include "voices.h" #include "misc.h" #define AUDIO_BLOCK_SAMPLES 128 template<typename T> class AudioObject : public AudioStream, public T { public: AudioObject() : AudioStream(0, NULL) {}; void update(void) { auto block = allocate(); if (block == NULL) return; for (auto i = 0; i < AUDIO_BLOCK_SAMPLES; i++) { block->data[i] = misc::s32_to_s16(T::process()); } transmit(block); release(block); } }; using AudioPolySaw = AudioObject<osc::PolySaw>;
krenzlin/teensy-synth
src/delay.h
<gh_stars>0 #include <stddef.h> #include <array> template<size_t N> inline size_t advance(const size_t ix) { return (ix + 1) % (N); } template<typename T, size_t N> struct Delay { size_t ix {0}; std::array<T, N> values {}; inline size_t length() { return N; } T read() { return values[ix]; } void clear() { values.fill(0); } void write(const T value) { values[ix] = value; ix = advance<N>(ix); } T update(const T value) { T out = read(); write(value); return out; } T update() { return update(0); } };
krenzlin/teensy-synth
src/luts.h
#pragma once #include <stdint.h> #include <array> #include "misc.h" namespace luts { const auto m_to_incr = []() { std::array<uint32_t, 128> lut; for (auto i=0; i<=127; i++) { auto f = misc::m_to_f(i); lut[i] = misc::f_to_incr(f); } return lut; }(); }
nacker/menuItem
menuItem/ViewController.h
// // ViewController.h // menuItem // // Created by nacker <EMAIL> on 15/9/29. // Copyright © 2015年 Shanghai Minlan Information & Technology Co ., Ltd. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
WCTP/Apriori_Production
Apriori/Apriori/SubList.h
<gh_stars>0 /* Author: <NAME> & <NAME> * Class : CSI-281-01 * Assignment : Final Project * Date Assigned : November 30, 2017 * Due Date : November 5, 2017 * * Description : * An implementation of the Apriori algorithm. * * Certification of Authenticity : * I certify that this is entirely my own work, except where I have given fully * documented references to the work of others. I understand the definition and * consequences of plagiarism and acknowledge that the assessor of this assignment * may, for the purpose of assessing this assignment : * - Reproduce this assignment and provide a copy to another member of * academic staff; and / or * - Communicate a copy of this assignment to a plagiarism checking service * (which may then retain a copy of this assignment on its database for * the purpose of future plagiarism checking) * ***********************************************************************************************/ #ifndef SUB_LIST_H #define SUB_LIST_H #include <iostream> #include <fstream> using namespace std; class SubList { private: struct Node { int *mItemSubset; int mSupport; Node *mNext; /* Pre: none * Post: initialize object * Purpose: to initialize the data in the object ********************************************************************/ Node() { mItemSubset = NULL; mSupport = 0; mNext = NULL; } /* Pre: int dynamic array, int * Post: initialize object * Purpose: to initialize the data in the object ********************************************************************/ Node(int* itemSubset, int subsetLength) { mItemSubset = new int[subsetLength]; for (int i = 0; i < subsetLength; i++) { mItemSubset[i] = itemSubset[i]; } mSupport = 0; mNext = NULL; } /* Pre: int dynamic array, int * Post: initialize object * Purpose: to initialize the data in the object ********************************************************************/ ~Node() { delete[] mItemSubset; mSupport = 0; mNext = NULL; } }; Node *mHead; Node *mTail; int mLength; public: /* Constructors */ SubList(); /* Destructor */ ~SubList(); /* Accessors */ int getItem(int listIndex, int subsetIndex); int getLength(); int* getSubset(int listIndex); int getSupport(int listIndex); /* Mutators */ void setItem(int listIndex, int subsetIndex, int item); void setItemSubset(int listIndex, int* subset); void setSupport(int listIndex, int support); /* Functions */ void clear(); bool display(int subsetLength); void incrementSupport(int listIndex); bool insert(int* itemSubset, int subsetLength); bool isEmpty(); bool isExist(int* itemSubset); void outputToFile(int subsetLength, ofstream& out, int* itemTranslation); int* removeAt(int listIndex); /* Operator Overloading */ int* operator[](int listIndex); }; #endif
WCTP/Apriori_Production
Apriori/Apriori/ItemsList.h
<gh_stars>0 /* Author: <NAME> & <NAME> * Class : CSI-281-01 * Assignment : Final Project * Date Assigned : November 30, 2017 * Due Date : November 5, 2017 * * Description : * An implementation of the Apriori algorithm. * * Certification of Authenticity : * I certify that this is entirely my own work, except where I have given fully * documented references to the work of others. I understand the definition and * consequences of plagiarism and acknowledge that the assessor of this assignment * may, for the purpose of assessing this assignment : * - Reproduce this assignment and provide a copy to another member of * academic staff; and / or * - Communicate a copy of this assignment to a plagiarism checking service * (which may then retain a copy of this assignment on its database for * the purpose of future plagiarism checking) * ***********************************************************************************************/ #ifndef ITEMS_LIST_H #define ITEMS_LIST_H #include <iostream> using namespace std; class ItemsList { private: struct Node { int mItemNumber; Node *mNext; Node() { mItemNumber = -1; mNext = NULL; } Node(int itemNumber) { mItemNumber = mItemNumber; mNext = NULL; } }; Node *mHead; Node *mTail; int mLength; public: ItemsList(); ~ItemsList(); int getItem(int index); int getLength(); void setItem(int index, int item); void clear(); void display(); bool insert(int item); bool isEmpty(); bool isExist(int item); bool remove(int item); int removeAt(int index); int operator[] (int index); }; #endif
WCTP/Apriori_Production
Apriori/Apriori/functions.h
<gh_stars>0 #ifndef FUNCTIONS_H #define FUNCTIONS_H #include <iostream> #include <string> #include <sstream> #include <fstream> #include "ItemsList.h" #include "SubList.h" using namespace std; /* functions */ void calculateSupport(SubList& sub1, SubList& sub2, bool flipper, bool **transaction, int fileLength, int subsetLength); string getFileName(); int getItemList(string filename, ItemsList& item); void generateSubSet1(SubList& sub1, int itemCount); void generateSubSet2(SubList& sub1, SubList& sub2, int itemCount); bool generateSubSet(SubList& sub1, SubList& sub2, int itemCount, int subSetNumber, bool subFlipper); void initializeTransactions(bool **transaction, int* itemTranslation, int itemCount, string filename); void outputSupport(SubList& sub1, SubList& sub2, bool flipper, ofstream &fout, int subLength, int *itemTranslation); void pruneSubSet(SubList& sub1, SubList& sub2, bool subFlipper, int subsetLength, int supportMinimum); int searchItem(int* itemTranslation, int item, int itemCount); void transferItems(ItemsList& items, int* itemTranslation); #endif
constantine97a/nginx-1.0.14_comment
src/os/unix/ngx_shmem.h
<reponame>constantine97a/nginx-1.0.14_comment<filename>src/os/unix/ngx_shmem.h /* * Copyright (C) <NAME> * Copyright (C) Nginx, Inc. */ #ifndef _NGX_SHMEM_H_INCLUDED_ #define _NGX_SHMEM_H_INCLUDED_ #include <ngx_config.h> #include <ngx_core.h> /** * 进程间的互斥锁基本上实现方式是两种,、 * #1 进程间的共享内存 * #2 使用文件锁的方式进程 */ typedef struct { u_char *addr; size_t size; ngx_str_t name; ngx_log_t *log; ngx_uint_t exists; /* unsigned exists:1; */ } ngx_shm_t; /** * 创建共享内存 * @param shm * @return */ ngx_int_t ngx_shm_alloc(ngx_shm_t *shm); /** * 释放共享内存 * @param shm */ void ngx_shm_free(ngx_shm_t *shm); #endif /* _NGX_SHMEM_H_INCLUDED_ */
constantine97a/nginx-1.0.14_comment
src/http/ngx_http_request_body.c
/* * Copyright (C) <NAME> * Copyright (C) Nginx, Inc. */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> static void ngx_http_read_client_request_body_handler(ngx_http_request_t *r); static ngx_int_t ngx_http_do_read_client_request_body(ngx_http_request_t *r); static ngx_int_t ngx_http_write_request_body(ngx_http_request_t *r, ngx_chain_t *body); static ngx_int_t ngx_http_read_discarded_request_body(ngx_http_request_t *r); static ngx_int_t ngx_http_test_expect(ngx_http_request_t *r); /* * on completion ngx_http_read_client_request_body() adds to * r->request_body->bufs one or two bufs: * *) one memory buf that was preread in r->header_in; * *) one memory or file buf that contains the rest of the body */ //异步接收包体?哪里异步? ngx_int_t ngx_http_read_client_request_body(ngx_http_request_t *r, ngx_http_client_body_handler_pt post_handler) { size_t preread; ssize_t size; ngx_buf_t *b; ngx_chain_t *cl, **next; ngx_temp_file_t *tf; ngx_http_request_body_t *rb; ngx_http_core_loc_conf_t *clcf; //首先把该请求对应的原始请求的引用计数加1,这同时是在要求每一个HTTP模块在传入的post_handler方法被回调时, // 务必调用类似ngx_http_finalize_request的方法去结束请求,否则引用计数会始终无法清零,从而导致请求无法释放 r->main->count++; //如果request_body不为null,已经读过了, // 如果discard_body为1,则证明曾经执行过丢弃包体的方法,现在包体正在被丢弃中,仍然跳到第2步执行 if (r->request_body || r->discard_body) { post_handler(r); return NGX_OK; } if (ngx_http_test_expect(r) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } rb = ngx_pcalloc(r->pool, sizeof(ngx_http_request_body_t)); if (rb == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } r->request_body = rb; //判断content_lengt>0 只有>0继续执行读取,否则执行post_handler if (r->headers_in.content_length_n < 0) { post_handler(r); return NGX_OK; } clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); //如果请求content_length长度为0 if (r->headers_in.content_length_n == 0) { if (r->request_body_in_file_only) { tf = ngx_pcalloc(r->pool, sizeof(ngx_temp_file_t)); if (tf == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } tf->file.fd = NGX_INVALID_FILE; tf->file.log = r->connection->log; tf->path = clcf->client_body_temp_path; tf->pool = r->pool; tf->warn = "a client request body is buffered to a temporary file"; tf->log_level = r->request_body_file_log_level; tf->persistent = r->request_body_in_persistent_file; tf->clean = r->request_body_in_clean_file; if (r->request_body_file_group_access) { tf->access = 0660; } rb->temp_file = tf; if (ngx_create_temp_file(&tf->file, tf->path, tf->pool, tf->persistent, tf->clean, tf->access) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } } post_handler(r); return NGX_OK; } rb->post_handler = post_handler; /* * set by ngx_pcalloc(): * * rb->bufs = NULL; * rb->buf = NULL; * rb->rest = 0; */ //有可能提前先读取到了http header ,所以检查header_in 缓冲区是否由未被解析成header的内容 //如果有的话 preread = r->header_in->last - r->header_in->pos; if (preread) { /* there is the pre-read part of the request body */ ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http client request body preread %uz", preread); b = ngx_calloc_buf(r->pool); if (b == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } b->temporary = 1; b->start = r->header_in->pos; b->pos = r->header_in->pos; b->last = r->header_in->last; b->end = r->header_in->end; rb->bufs = ngx_alloc_chain_link(r->pool); if (rb->bufs == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } rb->bufs->buf = b; rb->bufs->next = NULL; rb->buf = b; if ((off_t) preread >= r->headers_in.content_length_n) { /* the whole request body was pre-read */ r->header_in->pos += (size_t) r->headers_in.content_length_n; r->request_length += r->headers_in.content_length_n; b->last = r->header_in->pos; if (r->request_body_in_file_only) { if (ngx_http_write_request_body(r, rb->bufs) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } } post_handler(r); return NGX_OK; } /* * to not consider the body as pipelined request in * ngx_http_set_keepalive() */ r->header_in->pos = r->header_in->last; r->request_length += preread; rb->rest = r->headers_in.content_length_n - preread; if (rb->rest <= (off_t) (b->end - b->last)) { /* the whole request body may be placed in r->header_in */ rb->to_write = rb->bufs; r->read_event_handler = ngx_http_read_client_request_body_handler; return ngx_http_do_read_client_request_body(r); } next = &rb->bufs->next; } else { b = NULL; rb->rest = r->headers_in.content_length_n; next = &rb->bufs; } size = clcf->client_body_buffer_size; size += size >> 2; if (rb->rest < size) { size = (ssize_t) rb->rest; if (r->request_body_in_single_buf) { size += preread; } } else { size = clcf->client_body_buffer_size; /* disable copying buffer for r->request_body_in_single_buf */ b = NULL; } rb->buf = ngx_create_temp_buf(r->pool, size); if (rb->buf == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } cl = ngx_alloc_chain_link(r->pool); if (cl == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } cl->buf = rb->buf; cl->next = NULL; if (b && r->request_body_in_single_buf) { size = b->last - b->pos; ngx_memcpy(rb->buf->pos, b->pos, size); rb->buf->last += size; next = &rb->bufs; } *next = cl; if (r->request_body_in_file_only || r->request_body_in_single_buf) { rb->to_write = rb->bufs; } else { rb->to_write = rb->bufs->next ? rb->bufs->next : rb->bufs; } r->read_event_handler = ngx_http_read_client_request_body_handler; return ngx_http_do_read_client_request_body(r); } static void ngx_http_read_client_request_body_handler(ngx_http_request_t *r) { ngx_int_t rc; if (r->connection->read->timedout) { r->connection->timedout = 1; ngx_http_finalize_request(r, NGX_HTTP_REQUEST_TIME_OUT); return; } rc = ngx_http_do_read_client_request_body(r); if (rc >= NGX_HTTP_SPECIAL_RESPONSE) { ngx_http_finalize_request(r, rc); } } static ngx_int_t ngx_http_do_read_client_request_body(ngx_http_request_t *r) { size_t size; ssize_t n; ngx_buf_t *b; ngx_connection_t *c; ngx_http_request_body_t *rb; ngx_http_core_loc_conf_t *clcf; c = r->connection; rb = r->request_body; ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0, "http read client request body"); for ( ;; ) { for ( ;; ) { if (rb->buf->last == rb->buf->end) { if (ngx_http_write_request_body(r, rb->to_write) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } rb->to_write = rb->bufs->next ? rb->bufs->next : rb->bufs; rb->buf->last = rb->buf->start; } size = rb->buf->end - rb->buf->last; if ((off_t) size > rb->rest) { size = (size_t) rb->rest; } n = c->recv(c, rb->buf->last, size); ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0, "http client request body recv %z", n); if (n == NGX_AGAIN) { break; } if (n == 0) { ngx_log_error(NGX_LOG_INFO, c->log, 0, "client closed prematurely connection"); } if (n == 0 || n == NGX_ERROR) { c->error = 1; return NGX_HTTP_BAD_REQUEST; } rb->buf->last += n; rb->rest -= n; r->request_length += n; if (rb->rest == 0) { break; } if (rb->buf->last < rb->buf->end) { break; } } ngx_log_debug1(NGX_LOG_DEBUG_HTTP, c->log, 0, "http client request body rest %O", rb->rest); if (rb->rest == 0) { break; } if (!c->read->ready) { clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); ngx_add_timer(c->read, clcf->client_body_timeout); if (ngx_handle_read_event(c->read, 0) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } return NGX_AGAIN; } } if (c->read->timer_set) { ngx_del_timer(c->read); } if (rb->temp_file || r->request_body_in_file_only) { /* save the last part */ if (ngx_http_write_request_body(r, rb->to_write) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } b = ngx_calloc_buf(r->pool); if (b == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } b->in_file = 1; b->file_pos = 0; b->file_last = rb->temp_file->file.offset; b->file = &rb->temp_file->file; if (rb->bufs->next) { rb->bufs->next->buf = b; } else { rb->bufs->buf = b; } } if (rb->bufs->next && (r->request_body_in_file_only || r->request_body_in_single_buf)) { rb->bufs = rb->bufs->next; } r->read_event_handler = ngx_http_block_reading; rb->post_handler(r); return NGX_OK; } static ngx_int_t ngx_http_write_request_body(ngx_http_request_t *r, ngx_chain_t *body) { ssize_t n; ngx_temp_file_t *tf; ngx_http_request_body_t *rb; ngx_http_core_loc_conf_t *clcf; rb = r->request_body; if (rb->temp_file == NULL) { tf = ngx_pcalloc(r->pool, sizeof(ngx_temp_file_t)); if (tf == NULL) { return NGX_ERROR; } clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); tf->file.fd = NGX_INVALID_FILE; tf->file.log = r->connection->log; tf->path = clcf->client_body_temp_path; tf->pool = r->pool; tf->warn = "a client request body is buffered to a temporary file"; tf->log_level = r->request_body_file_log_level; tf->persistent = r->request_body_in_persistent_file; tf->clean = r->request_body_in_clean_file; if (r->request_body_file_group_access) { tf->access = 0660; } rb->temp_file = tf; } n = ngx_write_chain_to_temp_file(rb->temp_file, body); /* TODO: n == 0 or not complete and level event */ if (n == NGX_ERROR) { return NGX_ERROR; } rb->temp_file->offset += n; return NGX_OK; } ngx_int_t ngx_http_discard_request_body(ngx_http_request_t *r) { ssize_t size; ngx_event_t *rev; if (r != r->main || r->discard_body) { return NGX_OK; } if (ngx_http_test_expect(r) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } rev = r->connection->read; ngx_log_debug0(NGX_LOG_DEBUG_HTTP, rev->log, 0, "http set discard body"); if (rev->timer_set) { ngx_del_timer(rev); } if (r->headers_in.content_length_n <= 0 || r->request_body) { return NGX_OK; } size = r->header_in->last - r->header_in->pos; if (size) { if (r->headers_in.content_length_n > size) { r->header_in->pos += size; r->headers_in.content_length_n -= size; } else { r->header_in->pos += (size_t) r->headers_in.content_length_n; r->headers_in.content_length_n = 0; return NGX_OK; } } r->read_event_handler = ngx_http_discarded_request_body_handler; if (ngx_handle_read_event(rev, 0) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } if (ngx_http_read_discarded_request_body(r) == NGX_OK) { r->lingering_close = 0; } else { r->count++; r->discard_body = 1; } return NGX_OK; } void ngx_http_discarded_request_body_handler(ngx_http_request_t *r) { ngx_int_t rc; ngx_msec_t timer; ngx_event_t *rev; ngx_connection_t *c; ngx_http_core_loc_conf_t *clcf; c = r->connection; rev = c->read; if (rev->timedout) { c->timedout = 1; c->error = 1; ngx_http_finalize_request(r, NGX_ERROR); return; } if (r->lingering_time) { timer = (ngx_msec_t) (r->lingering_time - ngx_time()); if (timer <= 0) { r->discard_body = 0; r->lingering_close = 0; ngx_http_finalize_request(r, NGX_ERROR); return; } } else { timer = 0; } rc = ngx_http_read_discarded_request_body(r); if (rc == NGX_OK) { r->discard_body = 0; r->lingering_close = 0; ngx_http_finalize_request(r, NGX_DONE); return; } /* rc == NGX_AGAIN */ if (ngx_handle_read_event(rev, 0) != NGX_OK) { c->error = 1; ngx_http_finalize_request(r, NGX_ERROR); return; } if (timer) { clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); timer *= 1000; if (timer > clcf->lingering_timeout) { timer = clcf->lingering_timeout; } ngx_add_timer(rev, timer); } } static ngx_int_t ngx_http_read_discarded_request_body(ngx_http_request_t *r) { size_t size; ssize_t n; u_char buffer[NGX_HTTP_DISCARD_BUFFER_SIZE]; ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http read discarded body"); for ( ;; ) { if (r->headers_in.content_length_n == 0) { r->read_event_handler = ngx_http_block_reading; return NGX_OK; } if (!r->connection->read->ready) { return NGX_AGAIN; } size = (r->headers_in.content_length_n > NGX_HTTP_DISCARD_BUFFER_SIZE) ? NGX_HTTP_DISCARD_BUFFER_SIZE: (size_t) r->headers_in.content_length_n; n = r->connection->recv(r->connection, buffer, size); if (n == NGX_ERROR) { r->connection->error = 1; return NGX_OK; } if (n == NGX_AGAIN) { return NGX_AGAIN; } if (n == 0) { return NGX_OK; } r->headers_in.content_length_n -= n; } } static ngx_int_t ngx_http_test_expect(ngx_http_request_t *r) { ngx_int_t n; ngx_str_t *expect; if (r->expect_tested || r->headers_in.expect == NULL || r->http_version < NGX_HTTP_VERSION_11) { return NGX_OK; } r->expect_tested = 1; expect = &r->headers_in.expect->value; if (expect->len != sizeof("100-continue") - 1 || ngx_strncasecmp(expect->data, (u_char *) "100-continue", sizeof("100-continue") - 1) != 0) { return NGX_OK; } ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "send 100 Continue"); n = r->connection->send(r->connection, (u_char *) "HTTP/1.1 100 Continue" CRLF CRLF, sizeof("HTTP/1.1 100 Continue" CRLF CRLF) - 1); if (n == sizeof("HTTP/1.1 100 Continue" CRLF CRLF) - 1) { return NGX_OK; } /* we assume that such small packet should be send successfully */ return NGX_ERROR; }
constantine97a/nginx-1.0.14_comment
objs/autotest.c
#include <sys/types.h> #include <unistd.h> #include <sched.h> int main() { sched_yield(); return 0; }
MoltenCoffee/aoc-2021
day03/src/main.c
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include "../../lib/common.h" #define LINES 1000 static char getMostPrevalentChar(char **array, int lines, int pos) { int oneCount = 0; int totalCount = 0; for (int i = 0; i < lines; i++) { if (array[i][0] == 'n') continue; totalCount++; if (array[i][pos] == '1') oneCount++; } // Cast to float is critical! Otherwise result will be int as well, causing truncation if (oneCount == totalCount / (float)2) return '1'; return oneCount > (totalCount / (float)2) ? '1' : '0'; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Exactly one argument expected: path to input\n"); return EXIT_FAILURE; } char *file = readFile(argv[1]); char *line = readLine(file); typedef char storedLine[13]; char **lines = calloc(LINES, sizeof(storedLine)); if (lines == NULL) { fprintf(stderr, "Couldn't allocate memory!\n"); exit(EXIT_FAILURE); } // ++++++++ // Part one // ++++++++ int count[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int totalLines = 0; while (line != NULL) { for (int i = 0; i < 12; i++) { if (line[i] == '1') count[i]++; } lines[totalLines] = line; totalLines++; line = readLine(NULL); } int threshold = totalLines / 2; char mostPrevalent[13]; char leastPrevalent[13]; for (int i = 0; i < 12; i++) { mostPrevalent[i] = (count[i] > threshold) ? '1' : '0'; leastPrevalent[i] = (count[i] > threshold) ? '0' : '1'; } mostPrevalent[12] = '\0'; char *ptr; printf("Answer part 1: %ld\n", strtol(mostPrevalent, &ptr, 2) * strtol(leastPrevalent, &ptr, 2)); // ++++++++ // Part two // ++++++++ char **oxy = calloc(totalLines, sizeof(char *)); char **co2 = calloc(totalLines, sizeof(char *)); if (oxy == NULL || co2 == NULL) { fprintf(stderr, "Couldn't allocate memory!\n"); exit(EXIT_FAILURE); } int oxyCount = 0; int co2Count = 0; // Move relevant lines to correct array and count them for (int i = 0; i < totalLines; i++) { if (lines[i][0] == mostPrevalent[0]) { oxy[oxyCount] = lines[i]; oxyCount++; } else { co2[co2Count] = lines[i]; co2Count++; } } int oxyRemaining = oxyCount; int co2Remaining = co2Count; // Loop over oxygen for (int i = 1; i < 12; i++) { if (oxyRemaining == 1) break; char mostPrevalentChar = getMostPrevalentChar(oxy, oxyCount, i); for (int j = 0; j < oxyCount; j++) { if (oxyRemaining == 1) break; if (oxy[j][0] == 'n') continue; if (oxy[j][i] != mostPrevalentChar) { oxy[j] = "nnnnnnnnnnnn"; oxyRemaining--; } } } // Loop over CO2 for (int i = 1; i < 12; i++) { if (co2Remaining == 1) break; char mostPrevalentChar = getMostPrevalentChar(co2, co2Count, i); for (int j = 0; j < co2Count; j++) { if (co2Remaining == 1) break; if (co2[j][0] == 'n') continue; if (co2[j][i] == mostPrevalentChar) { co2[j] = "nnnnnnnnnnnn"; co2Remaining--; } } } long oxyRating; long co2Rating; // Find the remaining values for (int i = 0; i < oxyCount; i++) { if (oxy[i][0] == 'n') continue; oxyRating = strtol(oxy[i], &ptr, 2); break; } for (int i = 0; i < co2Count; i++) { if (co2[i][0] == 'n') continue; co2Rating = strtol(co2[i], &ptr, 2); break; } printf("Answer part 2: %ld\n", oxyRating * co2Rating); free(oxy); free(co2); free(lines); return EXIT_SUCCESS; }
MoltenCoffee/aoc-2021
day02/src/main.c
<gh_stars>0 #include <stdlib.h> #include <ctype.h> #include <stdbool.h> #include <string.h> #include <stdio.h> #define INPUT_SIZE 1000 typedef enum { UP, DOWN, FORWARD } Direction; typedef struct { Direction direction; int amount; } Instruction; int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Only one argument expected: path to input"); return EXIT_FAILURE; } FILE *file = fopen(argv[1], "r"); if (file == NULL) { fprintf(stderr, "File %s could not be opened", argv[1]); return EXIT_FAILURE; } Instruction *input = (Instruction *)calloc(INPUT_SIZE, sizeof(Instruction)); int inputCount = 0; for (;;) { if (feof(file)) break; char c = fgetc(file); if (isspace(c)) continue; Direction currDir; switch (c) { case 'u': currDir = UP; break; case 'd': currDir = DOWN; break; case 'f': currDir = FORWARD; break; } for (;;) { if (feof(file)) break; c = fgetc(file); if (isspace(c)) continue; if (isdigit(c)) { char numString[2] = {c, '\0'}; int amount = atoi(numString); Instruction newInstr; newInstr.direction = currDir; newInstr.amount = amount; input[inputCount] = newInstr; inputCount++; break; } } } // ++++++++ // Part one // ++++++++ int horz1 = 0; int depth1 = 0; for (int i = 0; i < inputCount; i++) { switch (input[i].direction) { case UP: depth1 -= input[i].amount; break; case DOWN: depth1 += input[i].amount; break; case FORWARD: horz1 += input[i].amount; break; } } printf("Part 1:\n"); printf("Horizontal distance: %d\n", horz1); printf("Depth: %d\n", depth1); printf("Multiplied: %d\n", horz1 * depth1); // ++++++++ // Part two // ++++++++ int aim = 0; int horz2 = 0; int depth2 = 0; for (int i = 0; i < inputCount; i++) { switch (input[i].direction) { case UP: aim -= input[i].amount; break; case DOWN: aim += input[i].amount; break; case FORWARD: horz2 += input[i].amount; depth2 += aim * input[i].amount; break; } } printf("\n\nPart 2:\n"); printf("Horizontal distance: %d\n", horz2); printf("Depth: %d\n", depth2); printf("Multiplied: %d\n", horz2 * depth2); free(input); return EXIT_SUCCESS; }
MoltenCoffee/aoc-2021
day04/src/main.c
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <stdbool.h> #include "../../lib/common.h" #define LIST_SIZE 100 #define BOARD_ROWS 5 #define BOARD_COLS 5 typedef struct Field { int val; bool checked; } Field; typedef Field Row[BOARD_COLS]; typedef Row Board[BOARD_ROWS]; static int calcRemaining(Board board) { int sum = 0; for (int i = 0; i < BOARD_ROWS; i++) { for (int j = 0; j < BOARD_COLS; j++) { if (!board[i][j].checked) { sum += board[i][j].val; } } } return sum; } static bool crossFields(Board board, int draw) { // 5 rows, 5 cols int checkCounts[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for (int i = 0; i < BOARD_ROWS; i++) { for (int j = 0; j < BOARD_COLS; j++) { if (board[i][j].checked) { checkCounts[i]++; checkCounts[j + BOARD_ROWS]++; continue; } if (board[i][j].val == draw) { board[i][j].checked = true; checkCounts[i]++; checkCounts[j + BOARD_ROWS]++; } } } for (int i = 0; i < 10; i++) { if (checkCounts[i] == 5) { return true; } } return false; } static void printBoard(Board board) { for (int i = 0; i < BOARD_ROWS; i++) { printf("%d, %d, %d, %d, %d\n", board[i][0].checked, board[i][1].checked, board[i][2].checked, board[i][3].checked, board[i][4].checked); } printf("\n"); } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Exactly one argument expected: path to input\n"); return EXIT_FAILURE; } char *file = readFile(argv[1]); // Loop utils char buffer[3]; int bufferCount = 0; // Read draw numbers from input int draw[LIST_SIZE]; int drawCount = 0; int charCount = 0; for (;;) { char c = file[charCount]; charCount++; if (isdigit(c)) { buffer[bufferCount] = c; bufferCount++; } else if (c == ',' || c == '\n') { buffer[bufferCount] = '\0'; draw[drawCount] = atoi(buffer); buffer[0] = '\0'; bufferCount = 0; drawCount++; } if (c == '\n') break; } // Read boards from input Board boards[LIST_SIZE]; int boardCount = 0; int currentRow = 0; int currentCol = 0; for (;;) { char c = file[charCount]; charCount++; if (isdigit(c)) { buffer[bufferCount] = c; bufferCount++; } else if (c == ' ' || c == '\n' || ((c == '\0' && buffer[0] != '\0'))) { if (buffer[0] == '\0') continue; buffer[bufferCount] = '\0'; boards[boardCount][currentRow][currentCol].val = atoi(buffer); boards[boardCount][currentRow][currentCol].checked = false; buffer[0] = '\0'; bufferCount = 0; if (c == '\0') { boardCount++; break; } if (currentCol == BOARD_COLS - 1 && currentRow == BOARD_ROWS - 1) { boardCount++; currentCol = 0; currentRow = 0; } else if (currentCol >= BOARD_COLS - 1) { currentRow++; currentCol = 0; } else { currentCol++; } } } // Loop over draw numbers, loop over boards inside to mark int ammountWon = 0; bool wonArray[LIST_SIZE]; for (int i = 0; i < drawCount; i++) { for (int j = 0; j < boardCount; j++) { if (wonArray[j] == true) continue; bool won = crossFields(boards[j], draw[i]); if (won) { ammountWon++; wonArray[j] = true; if (ammountWon == 1) { printf("\nPart one:\n\nBoard %d wins first, in round %d!\n", j, i); printBoard(boards[j]); int score = calcRemaining(boards[j]) * draw[i]; printf("Score: %d\n", score); } else if (ammountWon == boardCount) { printf("\nPart two:\n\nBoard %d wins last, in round %d!\n", j, i); printBoard(boards[j]); int score = calcRemaining(boards[j]) * draw[i]; printf("Score: %d\n", score); } } } } return EXIT_SUCCESS; }
MoltenCoffee/aoc-2021
day10/src/main.c
<reponame>MoltenCoffee/aoc-2021 #include <ctype.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "../../lib/common.h" static int compare(const void* a, const void* b) { uint64_t int_a = *((uint64_t*)a); uint64_t int_b = *((uint64_t*)b); if (int_a == int_b) return 0; else if (int_a < int_b) return -1; else return 1; } int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "\033[1;31mExactly one argument expected: path to input\n"); return EXIT_FAILURE; } char* file = readFile(argv[1]); // Count lines and linelength int maxLineLength = 0; int currLineLength = 0; int lineCount = 0; int charCount = 0; char prev; for (;;) { char c = file[charCount]; charCount++; if (c == '\0') { if (prev != '\n') { lineCount++; if (currLineLength > maxLineLength) maxLineLength = currLineLength; currLineLength = 0; } break; } else if (c == '\n') { lineCount++; if (currLineLength > maxLineLength) maxLineLength = currLineLength; currLineLength = 0; continue; } currLineLength++; prev = c; } // Allocate memory for lines char** lines = calloc(lineCount, sizeof(char*)); if (lines == NULL) fprintf(stderr, "\033[1;31mCould not allocate memory!"); for (int i = 0; i < lineCount; i++) { lines[i] = calloc(maxLineLength + 1, sizeof(char)); if (lines[i] == NULL) fprintf(stderr, "\033[1;31mCould not allocate memory!"); } // Store data into lines lineCount = 0; int lineCharCount = 0; for (int i = 0; i < charCount; i++) { char c = file[i]; if (c == '\n' || c == '\0') { lines[lineCount][lineCharCount] = '\0'; lineCount++; lineCharCount = 0; if (c == '\0') break; } else { lines[lineCount][lineCharCount] = c; lineCharCount++; } } free(file); // Create stack for syntax cheking char* charStack = calloc(maxLineLength + 1, sizeof(char)); if (charStack == NULL) fprintf(stderr, "\033[1;31mCould not allocate memory!"); int stackPos = 0; // Create array for line scores uint64_t* completionScores = calloc(lineCount, sizeof(uint64_t)); if (completionScores == NULL) fprintf(stderr, "\033[1;31mCould not allocate memory!"); int completionScoreCount = 0; uint32_t errorScore = 0; for (int i = 0; i < lineCount; i++) { bool hadError = false; for (int j = 0; j < maxLineLength; j++) { char c = lines[i][j]; if (c == '\0') break; switch (c) { case '(': case '[': case '{': case '<': charStack[stackPos] = c; stackPos++; break; case ')': if (charStack[stackPos - 1] == '(') { stackPos--; } else { hadError = true; errorScore += 3; } break; case ']': if (charStack[stackPos - 1] == '[') { stackPos--; } else { hadError = true; errorScore += 57; } break; case '}': if (charStack[stackPos - 1] == '{') { stackPos--; } else { hadError = true; errorScore += 1197; } break; case '>': if (charStack[stackPos - 1] == '<') { stackPos--; } else { hadError = true; errorScore += 25137; } break; } if (hadError) break; } if (hadError) { stackPos = 0; continue; } uint64_t completionScore = 0; for (int k = stackPos - 1; k >= 0; k--) { switch (charStack[k]) { case '(': completionScore *= 5; completionScore += 1; break; case '[': completionScore *= 5; completionScore += 2; break; case '{': completionScore *= 5; completionScore += 3; break; case '<': completionScore *= 5; completionScore += 4; break; } } completionScores[completionScoreCount] = completionScore; completionScoreCount++; stackPos = 0; } // Sort autocomplete scores qsort(completionScores, completionScoreCount, sizeof(uint64_t), compare); printf("Part 1: Error score: %d\n", errorScore); printf("Part 2: Autocomplete score: %ld\n", completionScores[(completionScoreCount - 1) / 2]); // Cleanup free(charStack); for (int i = 0; i < lineCount; i++) { free(lines[i]); } free(lines); return EXIT_SUCCESS; }
MoltenCoffee/aoc-2021
day11/src/main.c
#include <ctype.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "../../lib/common.h" #define ROW_COUNT 10 #define COL_COUNT 10 typedef uint8_t Grid[ROW_COUNT][COL_COUNT]; static void propagateFlash(Grid rows, Grid flashed) { // Flash all octopuses with 9 or higher bool loopAgain = false; for (int i = 0; i < ROW_COUNT; i++) { for (int j = 0; j < COL_COUNT; j++) { if (rows[i][j] > 9 && flashed[i][j] != 1) { flashed[i][j] = 1; loopAgain = true; // And increase all surrounding // above if (i > 0) rows[i - 1][j]++; // below if (i < ROW_COUNT - 1) rows[i + 1][j]++; // left if (j > 0) rows[i][j - 1]++; // right if (j < COL_COUNT - 1) rows[i][j + 1]++; // above left if (i > 0 && j > 0) rows[i - 1][j - 1]++; // above right if (i > 0 && j < COL_COUNT - 1) rows[i - 1][j + 1]++; // below left if (i < ROW_COUNT - 1 && j > 0) rows[i + 1][j - 1]++; // below right if (i < ROW_COUNT - 1 && j < COL_COUNT - 1) rows[i + 1][j + 1]++; } } } if (loopAgain) propagateFlash(rows, flashed); } static uint8_t step(Grid rows) { Grid flashed = {0}; // Increase all by one for (int i = 0; i < ROW_COUNT; i++) { for (int j = 0; j < COL_COUNT; j++) { rows[i][j]++; } } propagateFlash(rows, flashed); // Reset all that flashed, count flashed uint8_t flashCount = 0; for (int i = 0; i < ROW_COUNT; i++) { for (int j = 0; j < COL_COUNT; j++) { if (flashed[i][j] == 1) { rows[i][j] = 0; flashCount++; } } } return flashCount; } int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "\033[1;31mExactly one argument expected: path to input\n"); return EXIT_FAILURE; } char* file = readFile(argv[1]); Grid rows = {0}; uint8_t charCount = 0; uint8_t lineCount = 0; uint8_t colCount = 0; char prev; for (;;) { char c = file[charCount]; charCount++; if (isdigit(c)) { rows[lineCount][colCount] = (uint8_t)(c - 48); colCount++; } else if (c == '\n') { if (prev == '\n') continue; lineCount++; colCount = 0; } else if (c == '\0') { break; } prev = c; } free(file); // Model steps uint16_t flashCount = 0; uint16_t allFlashedInStep; for (int i = 0;; i++) { uint8_t flashesInStep = step(rows); if (i < 100) flashCount += flashesInStep; if (flashesInStep == 100) { allFlashedInStep = i + 1; if (i >= 100) break; } } printf("Part 1: Total flashed after 100 steps: %d\n", flashCount); printf("Part 2: All flash in step: %d\n", allFlashedInStep); return EXIT_SUCCESS; }
MoltenCoffee/aoc-2021
day06/src/main.c
<reponame>MoltenCoffee/aoc-2021 #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <ctype.h> #include "../../lib/common.h" #define DAYS 256 #define NEW_FISH_VALUE 8 #define RESET_FISH_VALUE 6 int main(int argc, char *argv[]) { printf("\n"); if (argc != 2) { fprintf(stderr, "Exactly one argument expected: path to input\n"); return EXIT_FAILURE; } char *file = readFile(argv[1]); uint64_t stages[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; // Insert input data into array int charCount = 0; for (;;) { char c = file[charCount]; if (c == '\0') break; if (isdigit(c)) { switch (c) { case '1': stages[1]++; break; case '2': stages[2]++; break; case '3': stages[3]++; break; case '4': stages[4]++; break; case '5': stages[5]++; break; } } charCount++; } for (int i = 0; i < DAYS; i++) { uint64_t newStages[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; // Build new array for (int i = 0; i < 9; i++) { if (i == 0) { newStages[RESET_FISH_VALUE] += stages[0]; newStages[NEW_FISH_VALUE] += stages[0]; } else { newStages[i - 1] += stages[i]; } } // update old array for (int i = 0; i < 9; i++) { stages[i] = newStages[i]; } } uint64_t totalFish = stages[0] + stages[1] + stages[2] + stages[3] + stages[4] + stages[5] + stages[6] + stages[7] + stages[8]; printf("Total fish after %d days: %ld\n\n", DAYS, totalFish); return EXIT_SUCCESS; }
MoltenCoffee/aoc-2021
day07/src/main.c
<filename>day07/src/main.c<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <ctype.h> #include "../../lib/common.h" #define INPUT_SIZE 1000 static int compare(const void *a, const void *b) { uint16_t int_a = *((uint16_t *)a); uint16_t int_b = *((uint16_t *)b); if (int_a == int_b) return 0; else if (int_a < int_b) return -1; else return 1; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Exactly one argument expected: path to input\n"); return EXIT_FAILURE; } char *file = readFile(argv[1]); uint16_t input[INPUT_SIZE]; int inputCount = 0; int charCount = 0; char buffer[5]; int bufferCount = 0; for (;;) { char c = file[charCount]; charCount++; if (isdigit(c)) { buffer[bufferCount] = c; bufferCount++; } else { if (buffer[0] == '\0') continue; buffer[bufferCount] = '\0'; input[inputCount] = atoi(buffer); inputCount++; buffer[0] = '\0'; bufferCount = 0; if (c == '\0') break; } } free(file); // Not the fastest, but it works qsort(input, inputCount, sizeof(uint16_t), compare); // ====== // Part 1 // ====== uint32_t fuelUsed = 0; uint16_t median = input[INPUT_SIZE / 2]; for (int i = 0; i < inputCount; i++) { fuelUsed += abs(input[i] - median); } printf("Part 1: %d units of fuel used.\n", fuelUsed); // ====== // Part 2 // ====== uint64_t fuelUsed2 = 0; uint64_t temp = 0; uint16_t max = input[inputCount - 1]; for (uint16_t i = 0; i < max; i++) { temp = 0; for (int j = 0; j < inputCount; j++) { uint64_t delta = abs(i - input[j]); temp += delta * (delta + 1) / 2; } if (i == 0 || temp < fuelUsed2) fuelUsed2 = temp; } printf("Part 2: %ld units of fuel used.\n", fuelUsed2); return EXIT_SUCCESS; }
MoltenCoffee/aoc-2021
day13/src/main.c
#include <ctype.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "../../lib/common.h" #define INITIAL_ARRAY_SIZE 1020 #define GROW_FACTOR 2 typedef struct Coord { uint16_t X; uint16_t Y; } Coord; static Coord foldCoords(Coord* coords, int coordCount, char foldDir, uint16_t foldLine) { Coord max = {0, 0}; for (int i = 0; i < coordCount; i++) { if (foldDir == 'x') { // Fold to left if (coords[i].X < foldLine) continue; uint16_t newX = foldLine - (coords[i].X - foldLine); coords[i].X = newX; if (newX > max.X) max.X = newX; } else if (foldDir == 'y') { // Fold to top if (coords[i].Y < foldLine) continue; uint16_t newY = foldLine - (coords[i].Y - foldLine); coords[i].Y = newY; if (newY > max.Y) max.Y = newY; } } return max; } static uint8_t** createGrid(Coord* coords, Coord max) { uint8_t** rows = calloc(max.Y + 1, sizeof(uint8_t*)); if (rows == NULL) fprintf(stderr, "\033[1;31mCould not allocate memory!\n"); for (int i = 0; i <= max.Y; i++) { rows[i] = calloc(max.X + 1, sizeof(uint8_t)); if (rows[i] == NULL) fprintf(stderr, "\033[1;31mCould not allocate memory!\n"); } return rows; } static uint16_t countDots(Coord* coords, Coord max, int coordCount) { uint8_t** rows = createGrid(coords, max); uint16_t count = 0; for (int i = 0; i < coordCount; i++) { if (rows[coords[i].Y][coords[i].X] != 1) { rows[coords[i].Y][coords[i].X] = 1; count++; } } for (int i = 0; i <= max.Y; i++) { free(rows[i]); } free(rows); return count; } int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "\033[1;31mExactly one argument expected: path to input\n"); return EXIT_FAILURE; } char* file = readFile(argv[1]); // Count coords and instructions int charCount = 0; int lineCount = 0; char prev; char buffer[5]; int buffCount = 0; int maxCoords = INITIAL_ARRAY_SIZE; Coord* coords = calloc(maxCoords, sizeof(Coord)); if (coords == NULL) fprintf(stderr, "\033[1;31mCould not allocate memory!\n"); Coord max = {0, 0}; // Parse coords for (;;) { char c = file[charCount]; charCount++; if (isdigit(c)) { buffer[buffCount] = c; buffCount++; } else if (c == '\n' || c == ',') { buffer[buffCount] = '\0'; if (lineCount + 1 > maxCoords) { maxCoords = maxCoords * GROW_FACTOR * sizeof(Coord); coords = realloc(coords, maxCoords); if (coords == NULL) fprintf(stderr, "\033[1;31mCould not grow memory!\n"); } uint16_t parsed = (uint16_t)atoi(buffer); if (c == ',') { if (parsed > max.X) max.X = parsed; coords[lineCount].X = parsed; } else { if (parsed > max.Y) max.Y = parsed; coords[lineCount].Y = parsed; } buffCount = 0; buffer[buffCount] = '\0'; if (c == '\n') { if (prev == '\n') break; lineCount++; } } prev = c; } // Parse instructions int lineCharCount = 0; char foldDir; uint16_t foldLine; int foldCount = 0; uint16_t dotCountFirstFold; for (;;) { char c = file[charCount]; charCount++; if (c == '\n' || c == '\0') { buffer[buffCount] = '\0'; foldLine = (uint16_t)atoi(buffer); buffCount = 0; buffer[buffCount] = '\0'; lineCharCount = 0; Coord localMax = foldCoords(coords, lineCount, foldDir, foldLine); foldCount++; if (foldDir == 'x') { max.X = localMax.X; } else { max.Y = localMax.Y; } if (foldCount == 1) dotCountFirstFold = countDots(coords, max, lineCount); if (c == '\0') break; continue; } if (lineCharCount == 11) { foldDir = c; } else if (lineCharCount > 12 && isdigit(c)) { buffer[buffCount] = c; buffCount++; } lineCharCount++; } free(file); printf("Part 1: dots after 1 fold: %d\n", dotCountFirstFold); uint8_t** rows = createGrid(coords, max); for (int i = 0; i < lineCount; i++) { if (rows[coords[i].Y][coords[i].X] != 1) { rows[coords[i].Y][coords[i].X] = 1; } } printf("Part 2: code:\n"); for (uint16_t i = 0; i <= max.Y; i++) { for (uint16_t j = 0; j <= max.X; j++) { printf(rows[i][j] == 1 ? "█" : " "); } printf("\n"); } // Cleanup for (int i = 0; i <= max.Y; i++) { free(rows[i]); } free(rows); free(coords); return EXIT_SUCCESS; }
MoltenCoffee/aoc-2021
lib/common.h
#ifndef aoc_files_h #define aoc_files_h #include <stdio.h> #include <stdlib.h> #include <string.h> char* readFile(const char* path); char* readLine(char* buffer); #endif
MoltenCoffee/aoc-2021
day09/src/main.c
#include <ctype.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "../../lib/common.h" typedef struct Point { int value; bool visited; } Point; static bool isLowPoint(Point** rows, int r, int c, int maxRow, int maxCol) { int current = rows[r][c].value; if (r != 0 && current >= rows[r - 1][c].value) return false; if (c != 0 && current >= rows[r][c - 1].value) return false; if (r != maxRow && current >= rows[r + 1][c].value) return false; if (c != maxCol && current >= rows[r][c + 1].value) return false; return true; } // This cannot handle multiple low points in same basin. Problem? static int findBasinSize(Point** rows, int r, int c, int maxRow, int maxCol) { int size = 0; if (!rows[r][c].visited) { rows[r][c].visited = true; size++; } if (r != 0 && rows[r - 1][c].value < 9 && !rows[r - 1][c].visited) { size += findBasinSize(rows, r - 1, c, maxRow, maxCol); } if (c != 0 && rows[r][c - 1].value < 9 && !rows[r][c - 1].visited) { size += findBasinSize(rows, r, c - 1, maxRow, maxCol); } if (r != maxRow && rows[r + 1][c].value < 9 && !rows[r + 1][c].visited) { size += findBasinSize(rows, r + 1, c, maxRow, maxCol); } if (c != maxCol && rows[r][c + 1].value < 9 && !rows[r][c + 1].visited) { size += findBasinSize(rows, r, c + 1, maxRow, maxCol); } return size; } int main(int argc, char* argv[]) { if (argc != 2) { fprintf(stderr, "\033[1;31mExactly one argument expected: path to input\n"); return EXIT_FAILURE; } char* file = readFile(argv[1]); int rowCount = 0; int columnCount = 0; // Count columns and rows int charCount = 0; char prev; for (;;) { char c = file[charCount]; if (c == '\0') { if (prev == '\n') { printf("yes"); rowCount--; } else if (isdigit(prev)) { rowCount++; } break; } else if (c == '\n') { rowCount++; } else if (rowCount == 0 && isdigit(c)) { columnCount++; } prev = c; charCount++; } // Allocate memory Point** rows = calloc(sizeof(Point**), rowCount); if (rows == NULL) fprintf(stderr, "\033[1;31mCould not allocate memory!\n"); for (int i = 0; i < rowCount; i++) { rows[i] = calloc(sizeof(Point), columnCount); if (rows[i] == NULL) if (rows == NULL) fprintf(stderr, "\033[1;31mCould not allocate memory!\n"); } // Add data to memory int matrixRow = 0; int matrixColumn = 0; for (int i = 0; i < charCount; i++) { char c = file[i]; if (c == '\n') { matrixRow++; matrixColumn = 0; continue; } else if (isdigit(c)) { rows[matrixRow][matrixColumn].value = (int)(c - 48); rows[matrixRow][matrixColumn].visited = false; matrixColumn++; } } free(file); int maxRow = rowCount - 1; int maxCol = columnCount - 1; int totalRisk = 0; int largestBasins[3] = {0, 0, 0}; int smallestBigBasin = 0; for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { if (isLowPoint(rows, i, j, maxRow, maxCol)) { totalRisk += (1 + rows[i][j].value); int basinSize = findBasinSize(rows, i, j, maxRow, maxCol); if (basinSize > largestBasins[smallestBigBasin]) { largestBasins[smallestBigBasin] = basinSize; for (int k = 0; k < 3; k++) { if (largestBasins[k] < largestBasins[smallestBigBasin]) { smallestBigBasin = k; } } } } } } uint32_t answer2 = 1; for (int i = 0; i < 3; i++) { answer2 *= largestBasins[i]; } printf("Part 1: total risk level of lowpoints is: %d\n", totalRisk); printf("Part 2: multiplied basin sizes is: %d\n", answer2); // Cleanup for (int i = 0; i < rowCount; i++) { free(rows[i]); } free(rows); return EXIT_SUCCESS; }
MoltenCoffee/aoc-2021
day01/src/main.c
#include <stdlib.h> #include <ctype.h> #include <stdio.h> #define ARRAY_SIZE 2000 static inline void emptyBuffer(char *buffer) { buffer[0] = '\0'; } static inline void addValue(char *buffer, long *values, int i) { values[i] = atol(buffer); } static void readValues(FILE *file, long *values) { char buffer[10]; int curr = 0; int total = 0; for (;;) { if (feof(file)) return; char c = fgetc(file); if (isdigit(c)) { buffer[curr] = c; curr++; } else if (c == '\n') { buffer[curr] = '\0'; addValue(buffer, values, total); total++; emptyBuffer(buffer); curr = 0; } } } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Only one argument expected: path to input"); return EXIT_FAILURE; } FILE *file = fopen(argv[1], "r"); if (file == NULL) { fprintf(stderr, "File %s could not be opened", argv[1]); return EXIT_FAILURE; } long *values = (long *)calloc(ARRAY_SIZE, sizeof(long)); readValues(file, values); fclose(file); // ++++++++ // Part one // ++++++++ int increasedValuesCount = 0; for (int i = 1; i < ARRAY_SIZE; i++) { if (values[i] > values[i - 1]) { increasedValuesCount++; } } printf("Increased values compared to last value: %d\n", increasedValuesCount); // ++++++++ // Part two // ++++++++ int increasedWindowSumCount = 0; long prevSum = 0; // Not terribly efficient, but it works for (int i = 2; i < ARRAY_SIZE; i++) { long newSum = values[i] + values[i-1] + values[i-2]; if (i > 2 && newSum > prevSum) { increasedWindowSumCount++; } prevSum = newSum; } printf("Increased window sum compared to last window: %d\n", increasedWindowSumCount); // Cleanup free(values); return EXIT_SUCCESS; }
MoltenCoffee/aoc-2021
lib/common.c
#include "common.h" static size_t getFilesize(FILE* file) { fseek(file, 0L, SEEK_END); size_t fileSize = ftell(file); rewind(file); return fileSize; } char* readFile(const char* path) { FILE* file = fopen(path, "r"); if (file == NULL) fprintf(stderr, "\033[1;31mCould not open provided file. Check spelling or " "permissions for %s\n", path); size_t fileSize = getFilesize(file); // Allocate memory for file contents char* buffer = (char*)malloc(fileSize + 1); if (buffer == NULL) fprintf(stderr, "\033[1;31mCould not allocate memory to read file %s\n", path); // Read file into memory size_t bytesRead = fread(buffer, sizeof(char), fileSize, file); if (bytesRead < fileSize) fprintf(stderr, "\033[1;31mCould not read file %s into memory\n", path); // Add null byte buffer[bytesRead] = '\0'; fclose(file); return buffer; } char* readLine(char* buffer) { return strtok(buffer, "\n"); }
MoltenCoffee/aoc-2021
day08/src/main.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <ctype.h> #include <stdbool.h> #include "../../lib/common.h" #define TOTAL_LINES 200 typedef char segment[8]; typedef segment row[14]; typedef int keyRow[10]; typedef int outputRow[4]; typedef char mapRow[7]; static int findIndex(int *array, int length, int value) { for (int i = 0; i < length; i++) { if (array[i] == value) return i; } } static int segmentsInCommon(keyRow translation, row currentRow, int currentPos, int b) { int index = findIndex(translation, 10, b); int found = 0; int currentLength = strlen(currentRow[currentPos]); int compareLength = strlen(currentRow[index]); for (int k = 0; k < compareLength; k++) { char c = currentRow[index][k]; for (int m = 0; m < currentLength; m++) { if (currentRow[currentPos][m] == c) { found++; break; } } } return found; } static void sortCharsAlphabetically(char *string) { int i, j; char temp; int length = strlen(string); for (i = 0; i < length - 1; i++) { for (j = i + 1; j < length; j++) { if (string[i] > string[j]) { temp = string[i]; string[i] = string[j]; string[j] = temp; } } } } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Exactly one argument expected: path to input\n"); return EXIT_FAILURE; } char *file = readFile(argv[1]); row rows[TOTAL_LINES]; int rowCount = 0; char *fileLine = readLine(file); while (fileLine != NULL) { int charCount = 0, bufferCount = 0, itemCount = 0; char prev; for (;;) { char c = fileLine[charCount]; charCount++; if ((c == ' ' && prev != '|') || c == '\0') { // End string in buffer rows[rowCount][itemCount][bufferCount] = '\0'; sortCharsAlphabetically(rows[rowCount][itemCount]); itemCount++; bufferCount = 0; if (c == '\0') break; } else if (isalpha(c)) { // Add character to buffer rows[rowCount][itemCount][bufferCount] = c; bufferCount++; } prev = c; } rowCount++; fileLine = readLine(NULL); } free(file); keyRow translations[TOTAL_LINES]; outputRow outputs[TOTAL_LINES]; uint16_t count1478 = 0; uint32_t answer = 0; for (int i = 0; i < TOTAL_LINES; i++) { // Find 1, 4, 7, 8 for (int j = 0; j < 14; j++) { int length = strlen(rows[i][j]); int translated = 0; switch (length) { case 2: translated = 1; break; case 3: translated = 7; break; case 4: translated = 4; break; case 7: translated = 8; break; default: translated = 0; break; } if (j > 9) { outputs[i][j - 10] = translated; } else { translations[i][j] = translated; } } for (int j = 0; j < 10; j++) { int length = strlen(rows[i][j]); // Find 9, 6 0 if (length == 6) { int inCommon = segmentsInCommon(translations[i], rows[i], j, 4); if (inCommon == 4) { translations[i][j] = 9; } else { int inCommon = segmentsInCommon(translations[i], rows[i], j, 7); if (inCommon == 2) { translations[i][j] = 6; } // else 0 } } // Find 2, 3, 5 else if (length == 5) { int inCommon = segmentsInCommon(translations[i], rows[i], j, 1); if (inCommon == 2) { translations[i][j] = 3; } else { int inCommon = segmentsInCommon(translations[i], rows[i], j, 4); if (inCommon == 3) { translations[i][j] = 5; } else { translations[i][j] = 2; } } } } // ====== // Part 1 // ====== for (int j = 0; j < 4; j++) { if (outputs[i][j] != 0) count1478++; } // ====== // Part 2 // ====== char buffer[5]; int bufferCount = 0; for (int j = 0; j < 4; j++) { if (outputs[i][j] != 0) { // Convert int to ASCII char ('0' = 48) buffer[bufferCount] = (char)(outputs[i][j] + 48); bufferCount++; } else { for (int k = 0; k < 10; k++) { if (strcmp(rows[i][k], rows[i][j + 10]) == 0) { outputs[i][j] = translations[i][k]; break; } } // Convert int to ASCII char ('0' = 48) buffer[bufferCount] = (char)(outputs[i][j] + 48); bufferCount++; } if (j == 3) { buffer[bufferCount] = '\0'; answer += atoi(buffer); bufferCount = 0; buffer[bufferCount] = '\0'; } } } printf("Part 1: %d\n", count1478); printf("Part 2: %d\n", answer); return EXIT_SUCCESS; }
MoltenCoffee/aoc-2021
day05/src/main.c
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <stdbool.h> #include "../../lib/common.h" #define TOTAL_LINES 500 typedef struct Line { int x1; int y1; int x2; int y2; } Line; int main(int argc, char *argv[]) { printf("\n"); if (argc != 2) { fprintf(stderr, "Exactly one argument expected: path to input\n"); return EXIT_FAILURE; } char *file = readFile(argv[1]); // Read lines Line lines[TOTAL_LINES]; int lineCount = 0; int maxX = 0; int maxY = 0; char *fileLine = readLine(file); while (fileLine != NULL) { if (lineCount == TOTAL_LINES) break; char buffer[4]; int bufferCount = 0; int charCount = 0; int coords[4]; int coordCount = 0; // Loop over characters in line, store coords, find max coords for (;;) { char c = fileLine[charCount]; charCount++; if (isdigit(c)) { buffer[bufferCount] = c; bufferCount++; } else if (c == ',' || c == ' ' || c == '\n' || c == '\0') { if (buffer[0] == '\0') continue; buffer[bufferCount] = '\0'; bufferCount = 0; int coord = atoi(buffer); if ((coordCount == 0 || coordCount == 2) && coord > maxX) { maxX = coord; } else if ((coordCount == 1 || coordCount == 3) && coord > maxY) { maxY = coord; } coords[coordCount] = coord; coordCount++; buffer[0] = '\0'; if (c == '\n' || c == '\0') { coordCount = 0; break; } } } lines[lineCount].x1 = coords[0]; lines[lineCount].y1 = coords[1]; lines[lineCount].x2 = coords[2]; lines[lineCount].y2 = coords[3]; lineCount++; fileLine = readLine(NULL); } // Allocate memory for grid int **grid = calloc(maxX + 1, sizeof(int *)); if (grid == NULL) fprintf(stderr, "Could not allocate memory!\n"); for (int i = 0; i < maxX + 1; i++) { grid[i] = calloc(maxY + 1, sizeof(int)); if (grid[i] == NULL) fprintf(stderr, "Could not allocate memory!\n"); } // Fill grid with horizontal and vertical lines for (int i = 0; i < lineCount; i++) { int x1 = lines[i].x1, x2 = lines[i].x2, y1 = lines[i].y1, y2 = lines[i].y2; int low, high, current; if (x1 == x2) { // Handle vertical if (y1 > y2) { high = y1; low = y2; } else { high = y2; low = y1; } current = low; while (current <= high) { grid[x1][current]++; current++; } } else if (y1 == y2) { // Handle horizontal if (x1 > x2) { high = x1; low = x2; } else { high = x2; low = x1; } current = low; while (current <= high) { grid[current][y1]++; current++; } } else { // Handle diagonal (always 45 degrees) int lowX, highX, lowY, highY, currentX, currentY; if (x1 > x2) { lowX = x2; lowY = y2; highX = x1; highY = y1; } else { lowX = x1; lowY = y1; highX = x2; highY = y2; } currentX = lowX; currentY = lowY; bool increaseY = lowY < highY; while (currentX <= highX) { grid[currentX][currentY]++; currentX++; if (increaseY) { currentY++; } else { currentY--; } } } } int dangerCount = 0; for (int x = 0; x < maxX + 1; x++) { for (int y = 0; y < maxY + 1; y++) { if (grid[x][y] >= 2) { dangerCount++; } } } printf("Dangerous tiles: %d\n\n", dangerCount); // cleanup for (int i = 0; i < maxX + 1; i++) { free(grid[i]); } free(grid); return EXIT_SUCCESS; }
ScaleFT/libxjwt
src/keyset.c
<reponame>ScaleFT/libxjwt /** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include "xjwt/xjwt_keyset.h" #include "xjwt/xjwt_error.h" #include "internal/xjwt_key.h" #include "internal/xjwt_keyset.h" #include <jansson.h> #include <string.h> XJWT_API(xjwt_error_t*) xjwt_keyset_create_from_memory(const char* buffer, size_t buflen, xjwt_keyset_t** out) { xjwt_keyset_t* ks = NULL; size_t ikeys = 0; xjwt_error_t* err = NULL; json_error_t jerror; json_t* doc = NULL; json_t* keylist = NULL; doc = json_loadb(buffer, buflen, 0, &jerror); if (doc == NULL) { /* TODO(pquerna): make generic error handle for json documents */ return xjwt_error_createf( XJWT_EINVAL, "xjwt_keyset: invalid keyset document: %s @ %d:%d", jerror.text, jerror.line, jerror.column); } keylist = json_object_get(doc, "keys"); if (!json_is_array(keylist)) { json_decref(doc); return xjwt_error_create( XJWT_EINVAL, "xjwt_keyset: invalid keyset document: missing .keys"); } ks = calloc(1, sizeof(xjwt_keyset_t)); for (ikeys = 0; ikeys < json_array_size(keylist); ikeys++) { xjwt_key_t* nextkey = NULL; json_t* key = json_array_get(keylist, ikeys); err = xjwt_key_create_from_json(key, &nextkey); if (err != XJWT_SUCCESS) { json_decref(doc); xjwt_keyset_destroy(ks); return err; } nextkey->next = ks->keys; ks->keys = nextkey; } json_decref(doc); *out = ks; return XJWT_SUCCESS; } XJWT_API(xjwt_key_t*) xjwt_keyset__get_by_keyid(xjwt_keyset_t* ks, const char* keyid) { xjwt_key_t* key = ks->keys; if (keyid == NULL) { return NULL; } while (key != NULL) { if (key->key_id != NULL && strcmp(keyid, key->key_id) == 0) { return key; } key = key->next; } return NULL; } XJWT_API(void) xjwt_keyset_destroy(xjwt_keyset_t* ks) { if (ks != NULL) { if (ks->keys != NULL) { xjwt_key_destroy(ks->keys); } free(ks); } }
ScaleFT/libxjwt
tests/test_split.c
/** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "xjwt/xjwt.h" #include "internal/xjwt_parse.h" #include "xjwt_tests.h" #include <string.h> static void split_jwt_parts(void **state) { char *buf = NULL; size_t len = 0; xjwt_parsed_t *parsed = NULL; xjwt_load_fixture("e1_af.jwt", &buf, &len); XJWT_NO_ERROR(xjwt__parse_untrusted(buf, len, &parsed)); XJWT_ASSERT(parsed != NULL); XJWT_ASSERT(strcmp(parsed->header, "<KEY>" "<KEY>" "9") == 0); XJWT_ASSERT(strcmp(parsed->payload, "<KEY>" "<KEY>" "<KEY>" "zdWVyLmV4YW1wbGUuY29tIiwibmJmIjoxLjUxMDYyMTExM2UrMDksInN1" "YiI6ImFiMGVkYWYxLTRlZDEtNDBjMC1hZmNiLTE4ZGNmNzU3MTJlNyJ" "9") == 0); XJWT_ASSERT(strcmp(parsed->signature, "DOQpYvNU6VGg5Pp8fjQr6y8Ksa5H2v9mNe25dv" "KKXTzAuOzeXIPKX0GuapiAs1aptCd5Gt8Gwqfu" "KrPnGupfGQ") == 0); xjwt__parsed_destroy(parsed); free(buf); } static void split_too_many(void **state) { const char *buf = "hello.world.there.1.f"; size_t len = strlen(buf); xjwt_parsed_t *parsed = NULL; XJWT_FAIL(xjwt__parse_untrusted(buf, len, &parsed)); XJWT_ASSERT(parsed == NULL); } static void split_too_few(void **state) { const char *buf = "hello.world"; size_t len = strlen(buf); xjwt_parsed_t *parsed = NULL; XJWT_FAIL(xjwt__parse_untrusted(buf, len, &parsed)); XJWT_ASSERT(parsed == NULL); } XJWT_TESTS_START(split) XJWT_TESTS_ENTRY(split_jwt_parts) XJWT_TESTS_ENTRY(split_too_many) XJWT_TESTS_ENTRY(split_too_few) XJWT_TESTS_END()
ScaleFT/libxjwt
tests/utils.c
<reponame>ScaleFT/libxjwt /** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "xjwt_tests.h" #include <sys/stat.h> #include <string.h> #include <stdlib.h> #include <stdio.h> char executable_path[PATHMAX] = {'\0'}; char testdir_path[PATHMAX] = {'\0'}; #ifdef __APPLE__ #include <mach-o/dyld.h> /* _NSGetExecutablePath */ #endif static void get_executable_path() { #if defined(__APPLE__) uint32_t bufsize = sizeof(executable_path); _NSGetExecutablePath(executable_path, &bufsize); #elif defined(__linux__) readlink("/proc/self/exe", executable_path, PATHMAX - 1); #elif defined(__FreeBSD__) size_t cb = sizeof(executable_path); int mib[4]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PATHNAME; mib[3] = -1; sysctl(mib, 4, executable_path, &cb, NULL, 0); #else #error port get_executable_path() #endif } void xjwt_tests_setup() { char *p; get_executable_path(); p = strrchr(executable_path, '/'); memcpy(testdir_path, executable_path, p - executable_path); } void xjwt_load_fixture(const char *fname, char **outbuf, size_t *outlen) { char p[PATHMAX]; FILE *fp; struct stat s; char *buf; snprintf(p, sizeof(p), "%s/../tests/fixtures/%s", testdir_path, fname); /* fprintf(stderr, "xjwt_load_fixture path: %s\n", p); */ fp = fopen(p, "r"); XJWT_ASSERT(fp != NULL); stat(p, &s); buf = malloc(s.st_size + 1); fread(buf, s.st_size, 1, fp); buf[s.st_size] = '\0'; fclose(fp); *outbuf = buf; *outlen = s.st_size; }
ScaleFT/libxjwt
src/key.c
/** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include "xjwt/xjwt_keyset.h" #include "xjwt/xjwt_error.h" #include "internal/xjwt_key.h" #include "internal/xjwt_json.h" #include <jansson.h> #include <string.h> XJWT_API(xjwt_error_t*) xjwt_key_create_from_json(json_t* doc, xjwt_key_t** out) { xjwt_error_t* err = NULL; /** * doc is json with the following shape (EC key): * { * "use": "sig", * "kty": "EC", * "kid": "9872c4bc33d6903c", * "crv": "P-256", * "alg": "ES256", * "x": "<KEY>", * "y": "<KEY>" * } * */ xjwt_key_t* key = NULL; key = calloc(1, sizeof(xjwt_key_t)); key->key_type = xjwt_json_strdup(doc, "kty"); key->key_id = xjwt_json_strdup(doc, "kid"); key->algorithm = xjwt_json_strdup(doc, "alg"); key->use = xjwt_json_strdup(doc, "use"); if (key->key_type == NULL) { xjwt_key_destroy(key); return xjwt_error_create(XJWT_EINVAL, "xjwt_key: invalid key document: .kty invalid"); } if (strcmp(key->key_type, "EC") == 0) { err = xjwt_key__parse_ec(doc, key); if (err != XJWT_SUCCESS) { xjwt_key_destroy(key); return err; } } else { err = xjwt_error_createf( XJWT_EINVAL, "xjwt_key: invalid key document: unsupported key type: '%s'", key->key_type); xjwt_key_destroy(key); return err; } *out = key; return XJWT_SUCCESS; } XJWT_API(void) xjwt_key_destroy(xjwt_key_t* ks) { if (ks != NULL) { if (ks->next != NULL) { xjwt_key_destroy(ks->next); ks->next = NULL; } if (ks->key_type != NULL) { free((void*)ks->key_type); } if (ks->key_id != NULL) { free((void*)ks->key_id); } if (ks->algorithm != NULL) { free((void*)ks->algorithm); } if (ks->use != NULL) { free((void*)ks->use); } if (ks->evp != NULL) { EVP_PKEY_free(ks->evp); } free(ks); } }
ScaleFT/libxjwt
src/internal/xjwt_key.h
<reponame>ScaleFT/libxjwt<filename>src/internal/xjwt_key.h /** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _xjwt_internal_key_h_ #define _xjwt_internal_key_h_ #include <stddef.h> #include "xjwt/xjwt_error.h" #include "xjwt/xjwt_visibility.h" #include <jansson.h> #include <openssl/evp.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ typedef struct xjwt_key_t { struct xjwt_key_t* next; const char* key_type; const char* key_id; const char* algorithm; const char* use; EVP_PKEY* evp; } xjwt_key_t; XJWT_API(xjwt_error_t*) xjwt_key_create_from_json(json_t* doc, xjwt_key_t** out); XJWT_API(void) xjwt_key_destroy(xjwt_key_t* ks); XJWT_API(xjwt_error_t*) xjwt_key__parse_ec(json_t* doc, xjwt_key_t* key); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _xjwt_internal_key_h_ */
ScaleFT/libxjwt
tests/test_verify.c
<reponame>ScaleFT/libxjwt<filename>tests/test_verify.c /** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "xjwt/xjwt.h" #include "internal/xjwt_keyset.h" #include "xjwt_tests.h" #include <string.h> typedef struct tcb_baton_t { uint64_t now; } tcb_baton_t; static uint64_t tcb(void *baton) { return ((tcb_baton_t *)baton)->now; } static void verify_no_validators(void **state) { char *buf = NULL; size_t len = 0; xjwt_verify_options_t opts = {0}; xjwt_verify_failure_t *failed = NULL; xjwt_verify_success_t *success = NULL; tcb_baton_t baton = {0}; xjwt_load_fixture("jwk_none.json", &buf, &len); XJWT_NO_ERROR(xjwt_keyset_create_from_memory(buf, len, &opts.keyset)); free(buf); xjwt_load_fixture("e1_af.jwt", &buf, &len); opts.expected_issuer = "https://issuer.example.com"; opts.expected_subject = "ab0edaf1-4ed1-40c0-afcb-18dcf75712e7"; opts.expected_audience = "https://audience.example.com"; opts.now = tcb; baton.now = 1510621410; opts.baton = &baton; xjwt_verify(&opts, buf, len, &success, &failed); XJWT_ASSERT(success == NULL); XJWT_ASSERT(failed != NULL); XJWT_ASSERT(failed->err != NULL); XJWT_ASSERT(failed->err->err == XJWT_EINVAL); XJWT_ASSERT(strstr(failed->err->msg, "unknown key id") != NULL); XJWT_ASSERT( strstr(failed->err->msg, "65289b19-e0c6-4918-8933-7961781adb0d") != NULL); xjwt_verify_failure_destroy(failed); } static void verify_e1(void **state) { char *buf = NULL; size_t len = 0; xjwt_verify_options_t opts = {0}; xjwt_verify_failure_t *failed = NULL; xjwt_verify_success_t *success = NULL; tcb_baton_t baton = {0}; xjwt_load_fixture("e1_jwk.json", &buf, &len); XJWT_NO_ERROR(xjwt_keyset_create_from_memory(buf, len, &opts.keyset)); free(buf); xjwt_load_fixture("e1_af.jwt", &buf, &len); opts.expected_issuer = "https://issuer.example.com"; opts.expected_subject = "ab0edaf1-4ed1-40c0-afcb-18dcf75712e7"; opts.expected_audience = "https://audience.example.com"; opts.now = tcb; baton.now = 1510621410; opts.baton = &baton; xjwt_verify(&opts, buf, len, &success, &failed); if (failed != NULL) XJWT_NO_ERROR(failed->err); XJWT_ASSERT(success != NULL); XJWT_ASSERT(failed == NULL); xjwt_verify_success_destroy(success); /* expire it */ baton.now = 1510621414; xjwt_verify(&opts, buf, len, &success, &failed); XJWT_ASSERT(failed != NULL); XJWT_ASSERT(success == NULL); xjwt_verify_failure_destroy(failed); /* not before it... */ baton.now = 1510621110; xjwt_verify(&opts, buf, len, &success, &failed); XJWT_ASSERT(failed != NULL); XJWT_ASSERT(success == NULL); xjwt_verify_failure_destroy(failed); free(buf); xjwt_keyset_destroy(opts.keyset); } XJWT_TESTS_START(verify) XJWT_TESTS_ENTRY(verify_e1) XJWT_TESTS_ENTRY(verify_no_validators) XJWT_TESTS_END()
ScaleFT/libxjwt
tests/xjwt_tests.h
<filename>tests/xjwt_tests.h /** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _xjwt_tests_h_ #define _xjwt_tests_h_ #include <stdarg.h> #include <stddef.h> #include <setjmp.h> #include <stdio.h> #include "cmockery.h" #ifdef XJWT_TEST_ALL #define XJWT_TESTS_START(module) \ int xjwt_tests_##module() { \ int rv = 0; \ const UnitTest tests[] = { #define XJWT_TESTS_ENTRY(entry) unit_test(entry), #define XJWT_TESTS_END() \ } \ ; \ rv = run_tests(tests); \ return rv; \ } #else #define XJWT_TESTS_START(module) \ int main(int argc, char *argv[]) { \ const UnitTest tests[] = { #define XJWT_TESTS_ENTRY(entry) unit_test(entry), #define XJWT_TESTS_END() \ } \ ; \ xjwt_tests_setup(); \ return run_tests(tests); \ } #endif #undef XJWT_ASSERT #define XJWT_ASSERT(expression) \ mock_assert((int)(expression), #expression, __FILE__, __LINE__); #define XJWT_NO_ERROR(expression) \ do { \ xjwt_error_t *xjwt__xx__err = NULL; \ xjwt__xx__err = (expression); \ if (xjwt__xx__err != XJWT_SUCCESS) { \ fprintf(stderr, "xjwt_error: %s\n", xjwt__xx__err->msg); \ } \ mock_assert(xjwt__xx__err == XJWT_SUCCESS, #expression, __FILE__, \ __LINE__); \ } while (0) #define XJWT_FAIL(expression) \ do { \ xjwt_error_t *xjwt__xx__err = NULL; \ xjwt__xx__err = (expression); \ if (xjwt__xx__err == XJWT_SUCCESS) { \ fprintf(stderr, "xjwt_error: %s\n", xjwt__xx__err->msg); \ } \ mock_assert(xjwt__xx__err != XJWT_SUCCESS, #expression, __FILE__, \ __LINE__); \ xjwt_error_destroy(xjwt__xx__err); \ } while (0) #define XJWT_TEST_MODULE(name) int xjwt_tests_##name(); XJWT_TEST_MODULE(keyset) XJWT_TEST_MODULE(split) XJWT_TEST_MODULE(verify) #define PATHMAX 1024 extern char executable_path[PATHMAX]; extern char testdir_path[PATHMAX]; void xjwt_tests_setup(); void xjwt_load_fixture(const char *fname, char **outbuf, size_t *outlen); #endif
ScaleFT/libxjwt
src/validator.c
<reponame>ScaleFT/libxjwt<gh_stars>1-10 /** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "xjwt/xjwt_validator.h" #include "internal/xjwt_parse.h" #include "internal/xjwt_key.h" #include "internal/xjwt_keyset.h" #include <stdlib.h> #include <jansson.h> #include <string.h> #include <openssl/evp.h> #define XJWT_MIN_JWT_SIZE (16) #define XJWT_MAX_JWT_SIZE (16000) static const EVP_MD *alg_to_evp_md(const char *alg, int *keysize) { if (alg == NULL) { return NULL; } if (strcmp("ES256", alg) == 0) { *keysize = 32; return EVP_sha256(); } else if (strcmp("ES384", alg) == 0) { *keysize = 48; return EVP_sha384(); } else if (strcmp("ES521", alg) == 0) { *keysize = 66; return EVP_sha512(); } else { return NULL; } } static xjwt_error_t *xjwt__get_tv(json_t *payload, const char *key, uint64_t *t) { double v; json_t *num = json_object_get(payload, key); if (!json_is_number(num)) { return xjwt_error_createf(XJWT_EINVAL, "xjwt_verify: JWT .%s is not number", key); } v = json_number_value(num); if (v < 946684800.0) { /* old old date, not reasonable. */ return xjwt_error_createf( XJWT_EINVAL, "xjwt_verify: JWT .%s contains outlandish date", key); } *t = (uint64_t)v; return XJWT_SUCCESS; } static xjwt_error_t *xjwt__verify_payload_claims(xjwt_verify_options_t *opts, json_t *payload, int *reason) { uint64_t now = 0; uint64_t nbf = 0; uint64_t expires = 0; xjwt_error_t *err = XJWT_SUCCESS; if (opts->now != NULL) { now = opts->now(opts->baton); } else { /* TODO(pquerna): use gettimeofday? */ now = (uint64_t)time(NULL); } err = xjwt__get_tv(payload, "exp", &expires); if (err != XJWT_SUCCESS) { *reason = XJWT_VERIFY_MALFORMED; return err; } if (now > expires) { *reason = XJWT_VERIFY_EXPIRED; return xjwt_error_createf( XJWT_EINVAL, "xjwt_verify: JWT expired: now:'%d' is after exp:'%d'", now, expires); } err = xjwt__get_tv(payload, "nbf", &nbf); if (err != XJWT_SUCCESS) { *reason = XJWT_VERIFY_MALFORMED; return err; } if (now < nbf) { *reason = XJWT_VERIFY_EXPIRED; return xjwt_error_createf( XJWT_EINVAL, "xjwt_verify: JWT nbf is before now: now:'%d' is after nbf:'%d'", now, nbf); } if (opts->expected_issuer != NULL) { const char *issuer = json_string_value(json_object_get(payload, "iss")); if (issuer == NULL || strcmp(opts->expected_issuer, issuer) != 0) { *reason = XJWT_VERIFY_EXPECT_MISMATCH; return xjwt_error_createf(XJWT_EINVAL, "xjwt_verify: Issuer mismatch. '%s' != '%s'", opts->expected_issuer, issuer); } } if (opts->expected_subject != NULL) { const char *subject = json_string_value(json_object_get(payload, "sub")); if (subject == NULL || strcmp(opts->expected_subject, subject) != 0) { *reason = XJWT_VERIFY_EXPECT_MISMATCH; return xjwt_error_createf(XJWT_EINVAL, "xjwt_verify: Subject mismatch. '%s' != '%s'", opts->expected_subject, subject); } } if (opts->expected_audience != NULL) { int success = 0; size_t index; json_t *value; json_t *aud = json_object_get(payload, "aud"); if (!json_is_array(aud)) { *reason = XJWT_VERIFY_MALFORMED; return xjwt_error_createf(XJWT_EINVAL, "xjwt_verify: Audience is not an array", opts->expected_audience); } json_array_foreach(aud, index, value) { const char *audname = json_string_value(value); if (audname != NULL && strcmp(opts->expected_audience, audname) == 0) { success = 1; } } if (success != 1) { *reason = XJWT_VERIFY_EXPECT_MISMATCH; return xjwt_error_createf(XJWT_EINVAL, "xjwt_verify: Audience mismatch. Expected '%s'", opts->expected_audience); } } return XJWT_SUCCESS; } XJWT_API(void) xjwt_verify(xjwt_verify_options_t *opts, const char *data, size_t len, xjwt_verify_success_t **outsuccess, xjwt_verify_failure_t **outfailure) { int reason = -1; xjwt_error_t *err = XJWT_SUCCESS; int keysize = 0; xjwt_parsed_t *parsed = NULL; json_error_t jerror; json_t *jheader = NULL; json_t *jpayload = NULL; EVP_MD_CTX *md_ctx = NULL; const char *ec_sig = NULL; size_t ec_sig_len = 0; /* ref_ prefixed is memory managed by jansson, life time of owning doc is all * the matters */ json_t *ref_v = NULL; const char *ref_hdr_alg = NULL; const char *ref_hdr_kid = NULL; xjwt_key_t *ref_pubkey; const EVP_MD *ref_md; /* static ref from openssl */ if (len > XJWT_MAX_JWT_SIZE) { reason = XJWT_VERIFY_MALFORMED; err = xjwt_error_createf( XJWT_EINVAL, "xjwt_verify: invalid JWT: JWT is too large: %zd bytes", len); goto failed; } if (len <= XJWT_MIN_JWT_SIZE) { reason = XJWT_VERIFY_MALFORMED; err = xjwt_error_createf( XJWT_EINVAL, "xjwt_verify: invalid JWT: JWT is too small: %zd bytes", len); goto failed; } err = xjwt__parse_untrusted(data, len, &parsed); if (err != XJWT_SUCCESS) { reason = XJWT_VERIFY_MALFORMED; goto failed; } jheader = json_loads(parsed->header_decoded, 0, &jerror); if (jheader == NULL) { reason = XJWT_VERIFY_MALFORMED; err = xjwt_error_createf(XJWT_EINVAL, "xjwt_verify: invalid JWT Header: %s @ %d:%d", jerror.text, jerror.line, jerror.column); goto failed; } ref_v = json_object_get(jheader, "alg"); if (!json_is_string(ref_v)) { reason = XJWT_VERIFY_MALFORMED; err = xjwt_error_create( XJWT_EINVAL, "xjwt_verify: invalid JWT Header: expected .alg field"); goto failed; } ref_hdr_alg = json_string_value(ref_v); /* TODO(pquerna): factoring for EC vs Ed25519 */ ref_md = alg_to_evp_md(ref_hdr_alg, &keysize); if (ref_md == NULL) { reason = XJWT_VERIFY_MALFORMED; err = xjwt_error_create( XJWT_EINVAL, "xjwt_verify: invalid JWT Header: .alg type is unsupported"); goto failed; } ref_v = json_object_get(jheader, "kid"); if (!json_is_string(ref_v)) { reason = XJWT_VERIFY_MALFORMED; err = xjwt_error_create( XJWT_EINVAL, "xjwt_verify: invalid JWT Header: expected .kid field"); goto failed; } ref_hdr_kid = json_string_value(ref_v); ref_pubkey = xjwt_keyset__get_by_keyid(opts->keyset, ref_hdr_kid); if (ref_pubkey == NULL) { reason = XJWT_VERIFY_NO_VALIDATORS; err = xjwt_error_createf( XJWT_EINVAL, "xjwt_verify: invalid JWT Header: unknown key id (.kid): \"%s\"", ref_hdr_kid); goto failed; } err = xjwt__parse_ec_signature(parsed, &ec_sig, &ec_sig_len); if (err != XJWT_SUCCESS) { reason = XJWT_VERIFY_MALFORMED; goto failed; } md_ctx = EVP_MD_CTX_create(); if (md_ctx == NULL) { reason = XJWT_VERIFY_UNKNOWN; err = xjwt_error_create(XJWT_ENOMEM, "xjwt_verify: failed to create md_ctx"); goto failed; } if (EVP_DigestVerifyInit(md_ctx, NULL, ref_md, NULL, ref_pubkey->evp) != 1) { reason = XJWT_VERIFY_UNKNOWN; err = xjwt_error_create(XJWT_ENOMEM, "xjwt_verify: failed to init digest"); goto failed; } if (EVP_DigestVerifyUpdate(md_ctx, parsed->signed_data, parsed->signed_data_l) != 1) { reason = XJWT_VERIFY_UNKNOWN; err = xjwt_error_create(XJWT_ENOMEM, "xjwt_verify: failed to update digest"); goto failed; } if (EVP_DigestVerifyFinal(md_ctx, (const unsigned char *)ec_sig, ec_sig_len) != 1) { reason = XJWT_VERIFY_INVALID_SIGNATURE; err = xjwt_error_create(XJWT_EINVAL, "xjwt_verify: failed to verify signature"); goto failed; } /** * At this point, we have a basic validation of the JWT's signer; Let's parse * the claims and keep rolling. */ err = xjwt__parse_payload(parsed, &jpayload); if (err != XJWT_SUCCESS) { reason = XJWT_VERIFY_MALFORMED; goto failed; } err = xjwt__verify_payload_claims(opts, jpayload, &reason); if (err != XJWT_SUCCESS) { goto failed; } goto success; failed: if (reason == -1) { reason = XJWT_VERIFY_UNKNOWN; } *outsuccess = NULL; *outfailure = calloc(1, sizeof(xjwt_verify_failure_t)); (*outfailure)->reason = reason; (*outfailure)->err = err; goto cleanup; success: *outfailure = NULL; *outsuccess = calloc(1, sizeof(xjwt_verify_success_t)); json_incref(jpayload); (*outsuccess)->payload = jpayload; goto cleanup; cleanup: if (md_ctx != NULL) { EVP_MD_CTX_destroy(md_ctx); } if (jpayload != NULL) { json_decref(jpayload); } if (jheader != NULL) { json_decref(jheader); } if (parsed != NULL) { xjwt__parsed_destroy(parsed); } if (ec_sig != NULL) { free((void *)ec_sig); } return; } XJWT_API(void) xjwt_verify_success_destroy(xjwt_verify_success_t *p) { if (p != NULL) { if (p->payload != NULL) { json_decref(p->payload); } free(p); } } XJWT_API(void) xjwt_verify_failure_destroy(xjwt_verify_failure_t *p) { if (p != NULL) { if (p->err != NULL) { xjwt_error_destroy(p->err); } free(p); } }
ScaleFT/libxjwt
src/key_ec.c
/** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "xjwt/xjwt_error.h" #include "internal/xjwt_key.h" #include "internal/xjwt_json.h" #include "internal/xjwt_b64.h" #include <string.h> #include <openssl/ec.h> #include <openssl/bn.h> #include <openssl/err.h> static int curve_to_nid(const char *type) { if (strcmp("P-256", type) == 0) { return NID_X9_62_prime256v1; } else if (strcmp("P-384", type) == 0) { return NID_secp384r1; } else if (strcmp("P-521", type) == 0) { return NID_secp521r1; } else { return -1; } } XJWT_API(xjwt_error_t *) xjwt_key__parse_ec(json_t *doc, xjwt_key_t *key) { xjwt_error_t *err = NULL; int nid; EC_KEY *pubkey = NULL; json_t *jcrv; json_t *jnum; size_t lbuf; char *buf; BIGNUM *bx; BIGNUM *by; jcrv = json_object_get(doc, "crv"); if (!json_is_string(jcrv)) { return xjwt_error_create(XJWT_EINVAL, "xjwt_key: invalid key document: .crv invalid"); } nid = curve_to_nid(json_string_value(jcrv)); if (nid == -1) { return xjwt_error_createf( XJWT_EINVAL, "xjwt_key: invalid key document: .crv unknown curve: '%s'", json_string_value(jcrv)); } jnum = json_object_get(doc, "x"); if (!json_is_string(jnum)) { return xjwt_error_create(XJWT_EINVAL, "xjwt_key: invalid key document: .x invalid"); } err = xjwt__url_base64_decode(json_string_value(jnum), &buf, &lbuf); if (err != XJWT_SUCCESS) { return xjwt_error_createf( XJWT_EINVAL, "xjwt_key: invalid key document: .x invalid: (%d) %s", err->err, err->msg); } bx = BN_bin2bn((const unsigned char *)buf, lbuf, NULL); free(buf); jnum = json_object_get(doc, "y"); if (!json_is_string(jnum)) { BN_free(bx); return xjwt_error_create(XJWT_EINVAL, "xjwt_key: invalid key document: .y invalid"); } err = xjwt__url_base64_decode(json_string_value(jnum), &buf, &lbuf); if (err != XJWT_SUCCESS) { BN_free(bx); return xjwt_error_createf( XJWT_EINVAL, "xjwt_key: invalid key document: .y invalid: (%d) %s", err->err, err->msg); } by = BN_bin2bn((const unsigned char *)buf, lbuf, NULL); free(buf); pubkey = EC_KEY_new_by_curve_name(nid); if (pubkey == NULL) { BN_free(bx); BN_free(by); return xjwt_error_createf( XJWT_EINVAL, "xjwt_key: invalid key document: .crv unsupported curve: '%s'", json_string_value(jcrv)); } if (EC_KEY_set_public_key_affine_coordinates(pubkey, bx, by) != 1) { /* ERR_print_errors_fp(stderr); BN_print_fp(stderr, bx); fprintf(stderr, "\n"); BN_print_fp(stderr, by); fprintf(stderr, "\n"); */ BN_free(bx); BN_free(by); EC_KEY_free(pubkey); /* TODO(pquerna): openssl error conversion */ return xjwt_error_create(XJWT_EINVAL, "xjwt_key: invalid key document: EC " "set_public_key_affine_coordinates failed"); } BN_free(bx); BN_free(by); key->evp = EVP_PKEY_new(); if (EVP_PKEY_assign_EC_KEY(key->evp, pubkey) != 1) { /* TODO(pquerna): openssl error conversion */ EC_KEY_free(pubkey); return xjwt_error_create( XJWT_EINVAL, "xjwt_key: invalid key document: EVP set1 EC_KEY failed"); } return XJWT_SUCCESS; }
ScaleFT/libxjwt
tests/test_keyset.c
<gh_stars>1-10 /** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "xjwt/xjwt.h" #include "internal/xjwt_keyset.h" #include "xjwt_tests.h" #include <string.h> static void keyset_parse_memory(void **state) { xjwt_keyset_t *ks; char *buf = NULL; size_t len = 0; xjwt_key_t *key; xjwt_load_fixture("jwk_af.json", &buf, &len); XJWT_NO_ERROR(xjwt_keyset_create_from_memory(buf, len, &ks)); key = xjwt_keyset__get_by_keyid(ks, "65289b19-e0c6-4918-8933-7961781adb0d"); XJWT_ASSERT(strcmp("65289b19-e0c6-4918-8933-7961781adb0d", key->key_id) == 0); XJWT_ASSERT(strcmp("ES256", key->algorithm) == 0); XJWT_ASSERT(strcmp("sig", key->use) == 0); XJWT_ASSERT(strcmp("EC", key->key_type) == 0); xjwt_keyset_destroy(ks); free(buf); } XJWT_TESTS_START(keyset) XJWT_TESTS_ENTRY(keyset_parse_memory) XJWT_TESTS_END()
ScaleFT/libxjwt
src/b64.c
<reponame>ScaleFT/libxjwt /** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "internal/xjwt_b64.h" #include <string.h> #include <openssl/bio.h> #include <openssl/evp.h> #include <openssl/buffer.h> static char *b64_mutate_url_to_normal(const char *input) { size_t i = 0; size_t inlen = strlen(input); size_t outlen = inlen + ((4 - inlen % 4) % 4); char *output = calloc(1, outlen + 1); for (; input[i] != 0; i++) { char c = input[i]; switch (c) { case '-': output[i] = '+'; break; case '_': output[i] = '/'; break; default: output[i] = c; break; } } for (; i < outlen; i++) { output[i] = '='; } return output; } static size_t b64_decode_len(const char *src, size_t len) { size_t p = 0; if (len < 4) { /* invalid base64 src. prob empty string */ return 0; } if (src[len - 1] == '=' && src[len - 2] == '=') { p = 2; } else if (src[len - 1] == '=') { p = 1; } return (len * 3) / 4 - p; } XJWT_API(xjwt_error_t *) xjwt__url_base64_decode(const char *xsrc, char **out, size_t *len) { BIO *b64; BIO *bio; size_t outlen; char *outbuf; /** * TODO(pquerna): implement URL safe natively using a table * (using a BIO requires a bunch of allocs and i'm are doing this * in an ultra terrible way) */ char *src = b64_mutate_url_to_normal(xsrc); size_t slen = strlen(src); outlen = b64_decode_len(src, slen); if (outlen == 0) { free(src); return xjwt_error_create( XJWT_EINVAL, "xjwt_b64: invalid base64 data: less than 4 bytes"); } outbuf = calloc(1, outlen + 1); bio = BIO_new_mem_buf(src, slen); b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bio = BIO_push(b64, bio); /* NOTE: not sure if we should assert outlen === expected outlen. */ outlen = BIO_read(bio, outbuf, outlen); BIO_free_all(bio); if (outlen <= 0) { free(src); free(outbuf); return xjwt_error_create(XJWT_EINVAL, "xjwt: failed to decode base64"); } free(src); *out = outbuf; if (len != NULL) { *len = outlen; } return XJWT_SUCCESS; }
ScaleFT/libxjwt
src/error.c
<reponame>ScaleFT/libxjwt /** * Copyright 2017, ScaleFT Inc * Copyright 2007-2010 <NAME>. * Copyright 2006 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef __linux__ #define _GNU_SOURCE #endif #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "xjwt/xjwt_error.h" xjwt_error_t* xjwt_error_create_impl(xjwt_status_t err, const char* msg, uint32_t line, const char* file) { xjwt_error_t* e; e = malloc(sizeof(*e)); e->err = err; e->msg = strdup(msg); e->line = line; e->file = strdup(file); return e; } xjwt_error_t* xjwt_error_createf_impl(xjwt_status_t err, uint32_t line, const char* file, const char* fmt, ...) { int rv; xjwt_error_t* e; va_list ap; e = malloc(sizeof(*e)); e->err = err; va_start(ap, fmt); rv = vasprintf((char**)&e->msg, fmt, ap); va_end(ap); if (rv == -1) { e->msg = strdup( "vasprintf inside xjwt_error_createf_impl returned -1, you likely " "have larger problems here"); } e->line = line; e->file = strdup(file); return e; } xjwt_error_t* xjwt_error_dup(xjwt_error_t* err) { xjwt_error_t* e; e = malloc(sizeof(*e)); e->err = err->err; e->msg = strdup(err->msg); e->line = err->line; e->file = strdup(err->file); return e; } void xjwt_error_destroy(xjwt_error_t* err) { if (err) { free((void*)err->msg); free((void*)err->file); free(err); } }
ScaleFT/libxjwt
include/xjwt/xjwt_error.h
/** * Copyright 2017, ScaleFT Inc * Copyright 2007-2010 <NAME>. * Copyright 2006 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Based off of ETL's error types (which is based off of Subversion's) */ /** * @file xjwt_error.h */ #include <stdint.h> #include "xjwt_visibility.h" #ifndef _xjwt_error_h_ #define _xjwt_error_h_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * Check if the @c xjwt_error_t returned by @a expression is equal to * @c XJWT_SUCCESS. If it is, do nothing, if not, then return it. */ #define XJWT_ERR(expression) \ do { \ xjwt_error_t* xjwt__xx__err = (expression); \ if (xjwt__xx__err) return xjwt__xx__err; \ } while (0) /** A low level error code. */ typedef int xjwt_status_t; /** Successful return value for a function that returns @c xjwt_error_t. */ #define XJWT_SUCCESS NULL /** The available buffer space was exhausted. */ #define XJWT_ENOSPACE -1 /** The input was invalid. */ #define XJWT_EINVAL -2 /** The requested functionality has not been implemented. */ #define XJWT_ENOTIMPL -3 /** The I/O operation in question failed. */ #define XJWT_EIO -4 /* Unable to allocate memory */ #define XJWT_ENOMEM -5 /** An exception object. */ typedef struct { /** The underlying status code. */ xjwt_status_t err; /** A human readable error message. */ const char* msg; /** The line on which the error occurred. */ uint32_t line; /** The file in which the error occurred. */ const char* file; } xjwt_error_t; /** * Return a new @c xjwt_error_t with underlying @c xjwt_status_t @a err * and message @a msg. */ #define xjwt_error_create(err, msg) \ xjwt_error_create_impl(err, msg, __LINE__, __FILE__) /** * The underlying function that implements @c xjwt_error_t_error_create. * * This is an implementation detail, and should not be directly called * by users. */ XJWT_API(xjwt_error_t*) xjwt_error_create_impl(xjwt_status_t err, const char* msg, uint32_t line, const char* file); /** * Return a new @c xjwt_error_t with underlying @c xjwt_status_t @a err * and message created @c printf style with @a fmt and varargs. */ #define xjwt_error_createf(err, fmt, ...) \ xjwt_error_createf_impl(err, __LINE__, __FILE__, fmt, __VA_ARGS__) /** * The underlying function that implements @c xjwt_error_createf. * * This is an implementation detail, and should not be directly called * by users. */ XJWT_API(xjwt_error_t*) xjwt_error_createf_impl(xjwt_status_t err, uint32_t line, const char* file, const char* fmt, ...); /** Destroy @a err. */ XJWT_API(void) xjwt_error_destroy(xjwt_error_t* err); /** Duplicates an error object */ XJWT_API(xjwt_error_t*) xjwt_error_dup(xjwt_error_t* err); #ifdef __cplusplus } #endif /* __cplusplus */ #endif
ScaleFT/libxjwt
include/xjwt/xjwt_validator.h
/** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _xjwt_validator_h_ #define _xjwt_validator_h_ #include <time.h> #include <jansson.h> #include "xjwt_error.h" #include "xjwt_keyset.h" #include "xjwt_visibility.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** * JWT Validation Functions */ typedef struct xjwt_validator_t xjwt_validator_t; typedef uint64_t(xjwt_time_cb)(void* baton); typedef struct xjwt_verify_options_t { /* Baton passed into all callbacks */ void* baton; xjwt_time_cb* now; xjwt_keyset_t* keyset; const char* expected_issuer; const char* expected_subject; const char* expected_audience; } xjwt_verify_options_t; typedef struct xjwt_verify_success_t { json_t* payload; } xjwt_verify_success_t; typedef enum XJWT_VERIFY_FAILURES { XJWT_VERIFY_UNKNOWN = 0, XJWT_VERIFY_NOT_PRESENT = 1, XJWT_VERIFY_EXPIRED = 2, XJWT_VERIFY_INVALID_SIGNATURE = 3, XJWT_VERIFY_NO_VALIDATORS = 4, XJWT_VERIFY_MALFORMED = 5, XJWT_VERIFY_EXPECT_MISMATCH = 6 } XJWT_VERIFY_FAILURES; /** * Contains an enum of possible reasons valilcation failed for a JWT. * * *err may be empty, but reason will always contain a reason. * **/ typedef struct xjwt_verify_failure_t { XJWT_VERIFY_FAILURES reason; xjwt_error_t* err; } xjwt_verify_failure_t; /** * Verifies a JWT according to a strict sub-set of the JWT standards meant to * intersect with real world use cases. * * On Success, *outsucess is set to non-NULL. * On Failure, *outfailure is set to non-NULL and explains why verification * failed. */ XJWT_API(void) xjwt_verify(xjwt_verify_options_t* opts, const char* data, size_t len, xjwt_verify_success_t** outsuccess, xjwt_verify_failure_t** outfailure); XJWT_API(void) xjwt_verify_success_destroy(xjwt_verify_success_t* success); XJWT_API(void) xjwt_verify_failure_destroy(xjwt_verify_failure_t* fail); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _xjwt_validator_h_ */
ScaleFT/libxjwt
src/parse.c
/** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "internal/xjwt_parse.h" #include "internal/xjwt_b64.h" #include <openssl/ecdsa.h> #include <openssl/opensslv.h> #include <stdlib.h> #include <string.h> #include <stdio.h> /* OpenSSL compat shim - see: * https://wiki.openssl.org/index.php/OpenSSL_1.1.0_Changes#Compatibility_Layer */ #if OPENSSL_VERSION_NUMBER < 0x10100000L static int ECDSA_SIG_set0(ECDSA_SIG *sig, BIGNUM *r, BIGNUM *s) { if (r == NULL || s == NULL) return 0; BN_clear_free(sig->r); BN_clear_free(sig->s); sig->r = r; sig->s = s; return 1; } #endif XJWT_API(xjwt_error_t *) xjwt__parse_untrusted(const char *input, size_t len, xjwt_parsed_t **out) { xjwt_error_t *err = XJWT_SUCCESS; size_t i = 0; int count = 0; xjwt_parsed_t *rv = NULL; char *header = NULL; char *payload = NULL; char *signature = NULL; char *header_decoded = NULL; size_t header_decoded_l = 0; char *signature_decoded = NULL; size_t signature_decoded_l = 0; char *buf = calloc(1, len + 1); header = buf; for (; i < len; i++) { char c = input[i]; switch (c) { case '.': buf[i] = 0; switch (count) { case 0: payload = buf + i + 1; break; case 1: signature = buf + i + 1; break; default: free(buf); return xjwt_error_create( XJWT_EINVAL, "xjwt_verify: invalid JWT: too many periods"); } count++; break; default: buf[i] = c; break; } } if (count != 2) { free(buf); return xjwt_error_create(XJWT_EINVAL, "xjwt_verify: invalid JWT: missing periods"); } err = xjwt__url_base64_decode(header, &header_decoded, &header_decoded_l); if (err != XJWT_SUCCESS) { free(buf); return err; } err = xjwt__url_base64_decode(signature, &signature_decoded, &signature_decoded_l); if (err != XJWT_SUCCESS) { free(buf); free(header_decoded); return err; } rv = calloc(1, sizeof(xjwt_parsed_t)); rv->header_decoded = header_decoded; rv->header_decoded_l = header_decoded_l; rv->signature_decoded = signature_decoded; rv->signature_decoded_l = signature_decoded_l; rv->header = strdup(header); rv->payload = strdup(payload); rv->signature = strdup(signature); rv->signed_data_l = strlen(header) + strlen(payload) + 1; rv->signed_data = calloc(1, rv->signed_data_l + 1); /* TODO(pquenra): this is stupid / lazy */ snprintf((char *)rv->signed_data, rv->signed_data_l + 1, "%s.%s", header, payload); *out = rv; free(buf); return XJWT_SUCCESS; } XJWT_API(void) xjwt__parsed_destroy(xjwt_parsed_t *p) { if (p != NULL) { if (p->header != NULL) { free((void *)p->header); } if (p->header_decoded != NULL) { free((void *)p->header_decoded); } if (p->payload != NULL) { free((void *)p->payload); } if (p->signature != NULL) { free((void *)p->signature); } if (p->signature_decoded != NULL) { free((void *)p->signature_decoded); } if (p->signed_data != NULL) { free((void *)p->signed_data); } free(p); } } XJWT_API(xjwt_error_t *) xjwt__parse_payload(xjwt_parsed_t *jwt, json_t **doc) { xjwt_error_t *err = XJWT_SUCCESS; json_error_t jerror; char *decoded = NULL; json_t *payload; size_t dlen = 0; err = xjwt__url_base64_decode(jwt->payload, &decoded, &dlen); if (err != XJWT_SUCCESS) { return err; } payload = json_loadb(decoded, dlen, 0, &jerror); if (payload == NULL) { free(decoded); return xjwt_error_createf( XJWT_EINVAL, "xjwt_verify: payload failed to parse: %s @ %d:%d", jerror.text, jerror.line, jerror.column); } free(decoded); *doc = payload; return XJWT_SUCCESS; } XJWT_API(xjwt_error_t *) xjwt__parse_ec_signature(xjwt_parsed_t *jwt, const char **outecsig, size_t *outlen) { unsigned char *p = NULL; size_t len; size_t offset = jwt->signature_decoded_l / 2; ECDSA_SIG *sig = ECDSA_SIG_new(); BIGNUM *r, *s; /* TODO(pquerna): assert signature size constraints here? */ r = BN_bin2bn((const unsigned char *)jwt->signature_decoded, jwt->signature_decoded_l / 2, NULL); s = BN_bin2bn((const unsigned char *)jwt->signature_decoded + offset, jwt->signature_decoded_l / 2, NULL); /* NOTE(morgabra) Calling this function transfers the memory management of the * values to the ECDSA_SIG object, and therefore the values that have been * passed in should not be freed directly after this function has been called. */ if (!ECDSA_SIG_set0(sig, r, s)) { ECDSA_SIG_free(sig); BN_free(r); BN_free(s); return xjwt_error_create(XJWT_ENOMEM, "xjwt_verify: ECDSA_SIG_set0 failed"); } len = i2d_ECDSA_SIG(sig, &p); if (len <= 0) { ECDSA_SIG_free(sig); return xjwt_error_create(XJWT_ENOMEM, "xjwt_verify: i2d_ECDSA_SIG failed"); } *outecsig = calloc(1, len + 1); memcpy((void *)*outecsig, p, len); *outlen = len; ECDSA_SIG_free(sig); if (p) { OPENSSL_free(p); } return XJWT_SUCCESS; }
ScaleFT/libxjwt
src/internal/xjwt_parse.h
<gh_stars>1-10 /** * Copyright 2017, ScaleFT Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef _xjwt_internal_parse_h_ #define _xjwt_internal_parse_h_ #include "xjwt/xjwt_error.h" #include "xjwt/xjwt_visibility.h" #include <stddef.h> #include <jansson.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ typedef struct xjwt_parsed_t { /* fields that are split into untrusted parts */ const char *header; size_t header_decoded_l; const char *header_decoded; const char *payload; const char *signature; size_t signature_decoded_l; const char *signature_decoded; size_t signed_data_l; const char *signed_data; } xjwt_parsed_t; XJWT_API(xjwt_error_t *) xjwt__parse_untrusted(const char *input, size_t len, xjwt_parsed_t **out); XJWT_API(void) xjwt__parsed_destroy(xjwt_parsed_t *p); XJWT_API(xjwt_error_t *) xjwt__parse_ec_signature(xjwt_parsed_t *jwt, const char **outecsig, size_t *outlen); XJWT_API(xjwt_error_t *) xjwt__parse_payload(xjwt_parsed_t *jwt, json_t **doc); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _xjwt_internal_parse_h_ */
maximbilan/UISegmentedControl_IconAndText
UISegmentedControl_IconAndText/UIImage+UISegmentedControlIconAndText.h
<reponame>maximbilan/UISegmentedControl_IconAndText<gh_stars>1-10 // // UIImage+UISegmentedControlIconAndText.h // UISegmentedControl_IconAndText // // Created by <NAME> on 6/8/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface UIImage (UISegmentedControlIconAndText) + (id)imageFromImage:(UIImage *)image string:(NSString *)string font:(UIFont *)font color:(UIColor *)color; @end
n-t-roff/ex-3.6
mapmalloc.c
<reponame>n-t-roff/ex-3.6 /* * AT&T Unix 7th Edition memory allocation routines. * * Modified by <NAME>, Freiburg i. Br., Germany, February 2005. * * Copyright(C) Caldera International Inc. 2001-2002. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * Redistributions of source code and documentation must retain the * above copyright notice, this list of conditions and the following * disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed or owned by Caldera * International, Inc. * Neither the name of Caldera International, Inc. nor the names of * other contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA * INTERNATIONAL, INC. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL CALDERA INTERNATIONAL, INC. BE * LIABLE FOR ANY DIRECT, INDIRECT INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Sccsid @(#)mapmalloc.c 1.7 (gritter) 8/18/05 */ #ifdef VMUNIX #include <sys/types.h> #include <unistd.h> #include <errno.h> #include <sys/mman.h> #include <inttypes.h> #ifndef MAP_FAILED #define MAP_FAILED ((void *)-1) #endif /* !MAP_FAILED */ #ifndef MAP_ANON #ifdef MAP_ANONYMOUS #define MAP_ANON MAP_ANONYMOUS #else /* !MAP_ANONYMOUS */ #include <sys/stat.h> #include <fcntl.h> #endif /* !MAP_ANONYMOUS */ #endif /* !MAP_ANON */ /* * Since ex makes use of sbrk(), the C library's version of malloc() * must be avoided. */ /* #define debug #define longdebug */ #ifdef debug #define ASSERT(p) if(!(p))botch("p");else #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int botch(char *s) { const char msg[] = "assertion botched\n"; write(2, msg, sizeof msg - 1); /*printf("assertion botched: %s\n",s);*/ abort(); } static int allock(void *); #ifdef debugprint void dump(const char *msg, uintptr_t t) { const char hex[] = "0123456789ABCDEF"; int i; write(2, msg, strlen(msg)); write(2, ": ", 2); for (i = sizeof t - 1; i >= 0; i--) { write(2, &hex[(t & (0x0f << 8*i+4)) >> 8*i+4], 1); write(2, &hex[(t & (0x0f << 8*i)) >> 8*i], 1); } write(2, "\n", 1); } #else #define dump(a, b) #endif #else #define ASSERT(p) #define dump(a, b) #endif #ifdef valgrind #include <valgrind.h> #else /* !valgrind */ #define VALGRIND_MALLOCLIKE_BLOCK(a, b, c, d) #define VALGRIND_FREELIKE_BLOCK(a, b) #endif /* !valgrind */ /* avoid break bug */ #ifdef pdp11 #define GRANULE 64 #else #define GRANULE 0 #endif /* C storage allocator * circular first-fit strategy * works with noncontiguous, but monotonically linked, arena * each block is preceded by a ptr to the (pointer of) * the next following block * blocks are exact number of words long * aligned to the data type requirements of ALIGN * pointers to blocks must have BUSY bit 0 * bit in ptr is 1 for busy, 0 for idle * gaps in arena are merely noted as busy blocks * last block of arena (pointed to by alloct) is empty and * has a pointer to first * idle blocks are coalesced during space search * * this variant uses mmap() instead of sbrk() * mmap() is used to allocate pools of increasing size * memory is then allocated from the first possible pool * * a different implementation may need to redefine * ALIGN, NALIGN, BLOCK, BUSY, INT * where INT is integer type to which a pointer can be cast */ #define INT intptr_t #define ALIGN intptr_t #define NALIGN 1 #define WORD sizeof (union store) #define BLOCK 1024 /* a multiple of WORD*/ #define BUSY ((intptr_t)1) #ifdef NULL #undef NULL #endif #define NULL 0 #define testbusy(p) ((INT)(p)&BUSY) #define setbusy(p) (union store *)((INT)(p)|BUSY) #define clearbusy(p) (union store *)((INT)(p)&~BUSY) static struct pool *pool0; union store { union store *ptr; struct pool *pool; ALIGN dummy[NALIGN]; INT callocsp; /*calloc clears an array of integers*/ }; struct pool { struct pool *Next; union store Allocs[2]; /*initial arena*/ union store *Allocp; /*search ptr*/ union store *Alloct; /*arena top*/ union store *Allocx; /*for benefit of realloc*/ char *Brk; char *End; ALIGN Dummy[NALIGN]; }; #define allocs (o->Allocs) #define allocp (o->Allocp) #define alloct (o->Alloct) #define allocx (o->Allocx) static void * map(void *addr, size_t len) { #ifndef MAP_ANON int flags = 0; static int fd = -1; if (fd==-1 && ((fd=open("/dev/zero",O_RDWR))<0 || fcntl(fd,F_SETFD,FD_CLOEXEC)<0)) return(MAP_FAILED); #else /* MAP_ANON */ int flags = MAP_ANON; int fd = -1; #endif /* MAP_ANON */ flags |= MAP_PRIVATE; if (addr) flags |= MAP_FIXED; return(mmap(addr,len,PROT_READ|PROT_WRITE,flags,fd,0)); } static void * mallock(size_t nbytes, union store *start, union store *end) { union store *p, *q; struct pool *o; size_t nw; static size_t temp; /*coroutines assume no auto*/ static size_t poolblock = 0100000; if (nbytes == 0) nbytes = 1; if(pool0==0 || pool0==MAP_FAILED) { /*first time*/ if((pool0=map(NULL, poolblock))==MAP_FAILED) { errno = ENOMEM; return(NULL); } pool0->Brk = (char *)pool0->Dummy; pool0->End = (char *)pool0+poolblock; } o = pool0; first: if(allocs[0].ptr==0) { /*first time for this pool*/ allocs[0].ptr = setbusy(&allocs[1]); allocs[1].ptr = setbusy(&allocs[0]); alloct = &allocs[1]; allocp = &allocs[0]; } nw = (nbytes+2*WORD+WORD-1)/WORD; ASSERT(allocp>=allocs && allocp<=alloct); ASSERT(allock(o)); for(p=allocp; ; ) { for(temp=0; ; ) { if(!testbusy(p->ptr)) { while(!testbusy((q=p->ptr)->ptr)) { int ua = p->ptr==allocp; ASSERT(q>p&&q<alloct); p->ptr = q->ptr; if (ua) allocp = p->ptr; } if(q>=p+nw && p+nw>=p && (start==NULL || p+nw<start || p>end || p+2==start)) goto found; } q = p; p = clearbusy(p->ptr); if(p>q) ASSERT(p<=alloct); else if(q!=alloct || p!=allocs) { ASSERT(q==alloct&&p==allocs); errno = ENOMEM; return(NULL); } else if(++temp>1) break; } temp = ((nw+BLOCK/WORD)/(BLOCK/WORD))*(BLOCK/WORD); q = (void *)o->Brk; if(q+temp+GRANULE < q) { errno = ENOMEM; return(NULL); } if(o->Brk+temp*WORD>=o->End) { size_t new; if(o->Next!=0&&o->Next!=MAP_FAILED) { o = o->Next; goto first; } poolblock += poolblock/(poolblock&(poolblock-1) ? 3:2); new = (((nw*WORD)+poolblock)/poolblock)*poolblock; if ((o->Next=map(0,new))==MAP_FAILED) { poolblock /= 4; new=(((nw*WORD)+poolblock)/poolblock)*poolblock; if ((o->Next=map(0,new))==MAP_FAILED) { errno = ENOMEM; return(NULL); } } o = o->Next; o->Brk = (char *)o->Dummy; o->End = (char *)o + new; goto first; } o->Brk += temp*WORD; ASSERT(q>alloct); alloct->ptr = q; if(q!=alloct+1) alloct->ptr = setbusy(alloct->ptr); alloct = q->ptr = q+temp-1; alloct->ptr = setbusy(allocs); } found: allocp = p + nw; ASSERT(allocp<=alloct); if(q>allocp) { allocx = allocp->ptr; allocp->ptr = p->ptr; } p->ptr = setbusy(allocp); p[1].pool = o; dump("malloc", (uintptr_t)(p + 2)); VALGRIND_MALLOCLIKE_BLOCK(p+2,nbytes,0,0); return(p+2); } void * malloc(size_t nbytes) { return mallock(nbytes, NULL, NULL); } /* freeing strategy tuned for LIFO allocation */ void free(register void *ap) { union store *p = ap; struct pool *o; dump(" free", (uintptr_t)ap); if (ap == NULL) return; o = p[-1].pool; ASSERT(p>clearbusy(allocs[1].ptr)&&p<=alloct); ASSERT(allock(o)); allocp = p -= 2; ASSERT(testbusy(p->ptr)); p->ptr = clearbusy(p->ptr); ASSERT(p->ptr > allocp && p->ptr <= alloct); VALGRIND_FREELIKE_BLOCK(ap,0); } /* realloc(p, nbytes) reallocates a block obtained from malloc() * and freed since last call of malloc() * to have new size nbytes, and old content * returns new location, or 0 on failure */ void * realloc(void *ap, size_t nbytes) { union store *p = ap; union store *q; struct pool *o; union store *s, *t; size_t nw; size_t onw; if (p==NULL) return(malloc(nbytes)); if (nbytes==0) { free(p); return NULL; } if(testbusy(p[-2].ptr)) free(p); onw = p[-2].ptr - p; o = p[-1].pool; q = mallock(nbytes, p, &p[onw]); if(q==NULL || q==p) return(q); s = p; t = q; nw = (nbytes+WORD-1)/WORD; if(nw<onw) onw = nw; while (onw) { onw--; *t++ = *s++; } if(q<p && q+nw>=p && p[-1].pool==q[-1].pool) (q+(q+nw-p))->ptr = allocx; return(q); } #ifdef debug int allock(void *ao) { #ifdef longdebug struct pool *o = ao; union store *p; int x; x = 0; for(p= &allocs[0]; clearbusy(p->ptr) > p; p=clearbusy(p->ptr)) { if(p==allocp) x++; } ASSERT(p==alloct); ASSERT(x==1|p==allocp); #endif return(1); } #endif /* calloc - allocate and clear memory block */ #define CHARPERINT (sizeof(INT)/sizeof(char)) void * calloc(size_t num, size_t size) { char *mp; INT *q; size_t m; num *= size; mp = malloc(num); if(mp==NULL) return(NULL); q = (INT *) mp; m = (num+CHARPERINT-1)/CHARPERINT; while(m) { m--; *q++ = 0; } return(mp); } #ifdef notdef /*ARGSUSED*/ void cfree(char *p, size_t num, size_t size) { free(p); } /* * Just in case ... */ char * memalign(size_t alignment, size_t size) { return NULL; } char * valloc(size_t size) { return NULL; } char * mallinfo(void) { return NULL; } int mallopt(void) { return -1; } #endif /* notdef */ char * poolsbrk(intptr_t val) { (void)val; return NULL; } #endif /* VMUNIX */
n-t-roff/ex-3.6
ex_vars.h
<filename>ex_vars.h /* sccs id @(#) ex_vars.h @(#)makeoptions 6.1 10/18/80 */ #define AUTOINDENT 0 #define AUTOPRINT 1 #define AUTOWRITE 2 #define BEAUTIFY 3 #define DIRECTORY 4 #define EDCOMPATIBLE 5 #define ERRORBELLS 6 #define HARDTABS 7 #define IGNORECASE 8 #define LISP 9 #define LIST 10 #define MAGIC 11 #define MESG 12 #define NUMBER 13 #define OPEN 14 #define OPTIMIZE 15 #define PARAGRAPHS 16 #define PROMPT 17 #define READONLY 18 #define REDRAW 19 #define REMAP 20 #define REPORT 21 #define SCROLL 22 #define SECTIONS 23 #define SHELL 24 #define SHIFTWIDTH 25 #define SHOWMATCH 26 #define SLOWOPEN 27 #define TABSTOP 28 #define TAGLENGTH 29 #define TAGS 30 #define TERM 31 #define TERSE 32 #define TIMEOUT 33 #define TTYTYPE 34 #define WARN 35 #define WINDOW 36 #define WRAPSCAN 37 #define WRAPMARGIN 38 #define WRITEANY 39 #define NOPTS 40
n-t-roff/ex-3.6
ex_put.c
/* Copyright (c) 1980 Regents of the University of California */ /* static char *sccsid = "@(#)ex_put.c 6.3 11/3/80"; */ #include "ex.h" #include "ex_tty.h" #include "ex_vis.h" /* * Terminal driving and line formatting routines. * Basic motion optimizations are done here as well * as formatting of lines (printing of control characters, * line numbering and the like). */ /* * The routines outchar, putchar and pline are actually * variables, and these variables point at the current definitions * of the routines. See the routine setflav. * We sometimes make outchar be routines which catch the characters * to be printed, e.g. if we want to see how long a line is. * During open/visual, outchar and putchar will be set to * routines in the file ex_vput.c (vputchar, vinschar, etc.). */ static void normchar(int); static void slobber(int); static void flush2(void); static int plodput(int); static int plod(int); static void ttcharoff(void); static void normal(ttymode); static void sTTY(int); void (*Outchar)() = termchar; void (*Putchar)() = normchar; void (*Pline)() = normline; void (* setlist(bool t))() { void (*P)(); listf = t; P = Putchar; Putchar = t ? listchar : normchar; return (P); } void (* setnumb(bool t))() { void (*P)(); numberf = t; P = Pline; Pline = t ? (void (*)())numbline : normline; return (P); } /* * Format c for list mode; leave things in common * with normal print mode to be done by normchar. */ void listchar(int c) { c &= (TRIM|QUOTE); switch (c) { case '\t': case '\b': outchar('^'); c = ctlof(c); break; case '\n': break; case '\n' | QUOTE: outchar('$'); break; default: if (c & QUOTE) break; if ((c < ' ' && c != '\n') || c == DELETE) outchar('^'), c = ctlof(c); break; } normchar(c); } /* * Format c for printing. Handle funnies of upper case terminals * and crocky hazeltines which don't have ~. */ static void normchar(int c) { register char *colp; c &= (TRIM|QUOTE); if (c == '~' && HZ) { normchar('\\'); c = '^'; } if (c & QUOTE) switch (c) { case ' ' | QUOTE: case '\b' | QUOTE: break; case QUOTE: return; default: c &= TRIM; #ifdef BIT8 if ((c < ' ' && (c != '\b' || !OS) && c != '\n' && c != '\t') || c == DELETE) ex_putchar('^'), c = ctlof(c); #endif } else if ((c < ' ' && (c != '\b' || !OS) && c != '\n' && c != '\t') || c == DELETE) ex_putchar('^'), c = ctlof(c); else if (UPPERCASE) { if (isupper(c)) { outchar('\\'); c = tolower(c); } else { colp = "({)}!|^~'`"; while (*colp++) if (c == *colp++) { outchar('\\'); c = colp[-2]; break; } } } outchar(c); } /* * Print a line with a number. */ void numbline(int i) { if (shudclob) slobber(' '); ex_printf("%6d ", i); normline(); } /* * Normal line output, no numbering. */ void normline(void) { register char *cp; if (shudclob) slobber(linebuf[0]); /* pdp-11 doprnt is not reentrant so can't use "printf" here in case we are tracing */ for (cp = linebuf; *cp;) ex_putchar(*cp++); if (!inopen) ex_putchar('\n' | QUOTE); } /* * Given c at the beginning of a line, determine whether * the printing of the line will erase or otherwise obliterate * the prompt which was printed before. If it won't, do it now. */ static void slobber(int c) { shudclob = 0; switch (c) { case '\t': if (Putchar == listchar) return; break; default: return; case ' ': case 0: break; } if (OS) return; flush(); putch(' '); if (BC) tputs(BC, 0, putch); else putch('\b'); } /* * The output buffer is initialized with a useful error * message so we don't have to keep it in data space. */ static char linb[66]; static char *linp = linb; /* * Phadnl records when we have already had a complete line ending with \n. * If another line starts without a flush, and the terminal suggests it, * we switch into -nl mode so that we can send lineffeeds to avoid * a lot of spacing. */ static bool phadnl; /* * Indirect to current definition of putchar. */ void ex_putchar(int c) { (*Putchar)(c); } /* * Termchar routine for command mode. * Watch for possible switching to -nl mode. * Otherwise flush into next level of buffering when * small buffer fills or at a newline. */ void termchar(int c) { if (pfast == 0 && phadnl) pstart(); if (c == '\n') phadnl = 1; else if (linp >= &linb[63]) flush1(); *linp++ = c; if (linp >= &linb[63]) { fgoto(); flush1(); } } void flush(void) { flush1(); flush2(); } /* * Flush from small line buffer into output buffer. * Work here is destroying motion into positions, and then * letting fgoto do the optimized motion. */ void flush1(void) { register char *lp; int c; *linp = 0; lp = linb; while (*lp) switch (c = *lp++) { case '\r': destline += destcol / COLUMNS; destcol = 0; continue; case '\b': if (destcol) destcol--; continue; case ' ': destcol++; continue; case '\t': destcol += value(TABSTOP) - destcol % value(TABSTOP); continue; case '\n': destline += destcol / COLUMNS + 1; if (destcol != 0 && destcol % COLUMNS == 0) destline--; destcol = 0; continue; default: fgoto(); for (;;) { if (AM == 0 && outcol == COLUMNS) fgoto(); c &= TRIM; putch(c); if (c == '\b') { outcol--; destcol--; } else if (c >= ' ' && c != DELETE) { outcol++; destcol++; if (XN && outcol % COLUMNS == 0) putch('\n'); } c = *lp++; if (c <= ' ') break; } --lp; continue; } linp = linb; } static void flush2(void) { fgoto(); flusho(); pstop(); } /* * Sync the position of the output cursor. * Most work here is rounding for terminal boundaries getting the * column position implied by wraparound or the lack thereof and * rolling up the screen to get destline on the screen. */ void fgoto(void) { register int l, c; if (destcol > COLUMNS - 1) { destline += destcol / COLUMNS; destcol %= COLUMNS; } if (outcol > COLUMNS - 1) { l = (outcol + 1) / COLUMNS; outline += l; outcol %= COLUMNS; if (AM == 0) { while (l > 0) { if (pfast) { if (xCR) tputs(xCR, 0, putch); else putch('\r'); } if (xNL) tputs(xNL, 0, putch); else putch('\n'); l--; } outcol = 0; } if (outline > EX_LINES - 1) { destline -= outline - (EX_LINES - 1); outline = EX_LINES - 1; } } if (destline > EX_LINES - 1) { l = destline; destline = EX_LINES - 1; if (outline < EX_LINES - 1) { c = destcol; if (pfast == 0 && (!CA || holdcm)) destcol = 0; fgoto(); destcol = c; } while (l > EX_LINES - 1) { /* * The following linefeed (or simulation thereof) * is supposed to scroll up the screen, since we * are on the bottom line. We make the assumption * that linefeed will scroll. If ns is in the * capability list this won't work. We should * probably have an sc capability but sf will * generally take the place if it works. * * Superbee glitch: in the middle of the screen we * have to use esc B (down) because linefeed screws up * in "Efficient Paging" (what a joke) mode (which is * essential in some SB's because CRLF mode puts garbage * in at end of memory), but you must use linefeed to * scroll since down arrow won't go past memory end. * I turned this off after recieving <NAME>'s * Superbee description which wins better. */ if (xNL /* && !XB */ && pfast) tputs(xNL, 0, putch); else putch('\n'); l--; if (pfast == 0) outcol = 0; } } if (destline < outline && !((CA && !holdcm) || UP != NOSTR)) destline = outline; if (CA && !holdcm) if (plod(costCM) > 0) plod(0); else tputs(tgoto(CM, destcol, destline), 0, putch); else plod(0); outline = destline; outcol = destcol; } /* * Tab to column col by flushing and then setting destcol. * Used by "set all". */ void ex_tab(int col) { flush1(); destcol = col; } /* * Move (slowly) to destination. * Hard thing here is using home cursor on really deficient terminals. * Otherwise just use cursor motions, hacking use of tabs and overtabbing * and backspace. */ static int plodcnt, plodflg; static int plodput(int c) { if (plodflg) { plodcnt--; return c; } else return putch(c); } static int plod(int cnt) { register int i, j, k; register int soutcol, soutline; plodcnt = plodflg = cnt; soutcol = outcol; soutline = outline; /* * Consider homing and moving down/right from there, vs moving * directly with local motions to the right spot. */ if (HO) { /* * i is the cost to home and tab/space to the right to * get to the proper column. This assumes ND space costs * 1 char. So i+destcol is cost of motion with home. */ if (GT) i = (destcol / value(HARDTABS)) + (destcol % value(HARDTABS)); else i = destcol; /* * j is cost to move locally without homing */ if (destcol >= outcol) { /* if motion is to the right */ j = destcol / value(HARDTABS) - outcol / value(HARDTABS); if (GT && j) j += destcol % value(HARDTABS); else j = destcol - outcol; } else /* leftward motion only works if we can backspace. */ if (outcol - destcol <= i && (BS || BC)) i = j = outcol - destcol; /* cheaper to backspace */ else j = i + 1; /* impossibly expensive */ /* k is the absolute value of vertical distance */ k = outline - destline; if (k < 0) k = -k; j += k; /* * Decision. We may not have a choice if no UP. */ if (i + destline < j || (!UP && destline < outline)) { /* * Cheaper to home. Do it now and pretend it's a * regular local motion. */ tputs(HO, 0, plodput); outcol = outline = 0; } else if (LL) { /* * Quickly consider homing down and moving from there. * Assume cost of LL is 2. */ k = (EX_LINES - 1) - destline; if (i + k + 2 < j && (k<=0 || UP)) { tputs(LL, 0, plodput); outcol = 0; outline = EX_LINES - 1; } } } else /* * No home and no up means it's impossible, so we return an * incredibly big number to make cursor motion win out. */ if (!UP && destline < outline) return (500); if (GT) i = destcol % value(HARDTABS) + destcol / value(HARDTABS); else i = destcol; /* if (BT && outcol > destcol && (j = (((outcol+7) & ~7) - destcol - 1) >> 3)) { j *= (k = strlen(BT)); if ((k += (destcol&7)) > 4) j += 8 - (destcol&7); else j += k; } else */ j = outcol - destcol; /* * If we will later need a \n which will turn into a \r\n by * the system or the terminal, then don't bother to try to \r. */ if ((NONL || !pfast) && outline < destline) goto dontcr; /* * If the terminal will do a \r\n and there isn't room for it, * then we can't afford a \r. */ if (NC && outline >= destline) goto dontcr; /* * If it will be cheaper, or if we can't back up, then send * a return preliminarily. */ if (j > i + 1 || (outcol > destcol && !BS && !BC)) { /* * BUG: this doesn't take the (possibly long) length * of xCR into account. */ if (xCR) tputs(xCR, 0, plodput); else plodput('\r'); if (NC) { if (xNL) tputs(xNL, 0, plodput); else plodput('\n'); outline++; } outcol = 0; } dontcr: while (outline < destline) { outline++; if (xNL && pfast) tputs(xNL, 0, plodput); else plodput('\n'); if (plodcnt < 0) goto out; if (NONL || pfast == 0) outcol = 0; } if (BT) k = strlen(BT); while (outcol > destcol) { if (plodcnt < 0) goto out; /* if (BT && !insmode && outcol - destcol > 4+k) { tputs(BT, 0, plodput); outcol--; outcol &= ~7; continue; } */ outcol--; if (BC) tputs(BC, 0, plodput); else plodput('\b'); } while (outline > destline) { outline--; tputs(UP, 0, plodput); if (plodcnt < 0) goto out; } if (GT && !insmode && destcol - outcol > 1) { for (;;) { i = tabcol(outcol, value(HARDTABS)); if (i > destcol) break; if (TA) tputs(TA, 0, plodput); else plodput('\t'); outcol = i; } if (destcol - outcol > 4 && i < COLUMNS && (BC || BS)) { if (TA) tputs(TA, 0, plodput); else plodput('\t'); outcol = i; while (outcol > destcol) { outcol--; if (BC) tputs(BC, 0, plodput); else plodput('\b'); } } } while (outcol < destcol) { /* * move one char to the right. We don't use ND space * because it's better to just print the char we are * moving over. There are various exceptions, however. * If !inopen, vtube contains garbage. If the char is * a null or a tab we want to print a space. Other random * chars we use space for instead, too. */ if (!inopen || vtube[outline]==NULL || (i=vtube[outline][outcol]) < ' ') i = ' '; if (insmode && ND) tputs(ND, 0, plodput); else plodput(i); outcol++; if (plodcnt < 0) goto out; } out: if (plodflg) { outcol = soutcol; outline = soutline; } return(plodcnt); } /* * An input line arrived. * Calculate new (approximate) screen line position. * Approximate because kill character echoes newline with * no feedback and also because of long input lines. */ void noteinp(void) { outline++; if (outline > EX_LINES - 1) outline = EX_LINES - 1; destline = outline; destcol = outcol = 0; } /* * Something weird just happened and we * lost track of whats happening out there. * Since we cant, in general, read where we are * we just reset to some known state. * On cursor addressible terminals setting to unknown * will force a cursor address soon. */ void termreset(void) { endim(); if (TI) /* otherwise it flushes anyway, and 'set tty=dumb' vomits */ putpad(TI); /*adb change -- emit terminal initial sequence */ destcol = 0; destline = EX_LINES - 1; if (CA) { outcol = UKCOL; outline = UKCOL; } else { outcol = destcol; outline = destline; } } /* * Low level buffering, with the ability to drain * buffered output without printing it. */ char *obp = obuf; void draino(void) { obp = obuf; } void flusho(void) { if (obp != obuf) { write(1, obuf, obp - obuf); obp = obuf; } } void putnl(void) { ex_putchar('\n'); } #if 0 putS(cp) char *cp; { if (cp == NULL) return; while (*cp) putch(*cp++); } #endif int putch(int c) { c &= TRIM; *obp++ = c; if (obp >= &obuf[sizeof obuf]) flusho(); return c; } /* * Miscellaneous routines related to output. */ /* * Put with padding */ void putpad(char *cp) { flush(); tputs(cp, 0, putch); } /* * Set output through normal command mode routine. */ void setoutt(void) { Outchar = termchar; } /* * Printf (temporarily) in list mode. */ void lprintf(char *cp, char *dp) { void (*P)(); P = setlist(1); ex_printf(cp, dp); Putchar = P; } /* * Newline + flush. */ void putNFL(void) { putnl(); flush(); } /* * Try to start -nl mode. */ void pstart(void) { if (NONL) return; if (!value(OPTIMIZE)) return; if (ruptible == 0 || pfast) return; fgoto(); flusho(); pfast = 1; normtty++; #ifndef USG3TTY tty.sg_flags = normf & ~(ECHO|XTABS|CRMOD); #else tty = normf; tty.c_oflag &= ~(ONLCR # ifdef TAB3 |TAB3 # endif ); tty.c_lflag &= ~ECHO; #endif sTTY(1); } /* * Stop -nl mode. */ void pstop(void) { if (inopen) return; phadnl = 0; linp = linb; draino(); normal(normf); pfast &= ~1; } /* * Prep tty for open mode. */ ttymode ostart(void) { ttymode f; if (!intty) error("Open and visual must be used interactively"); gTTY(1); normtty++; #ifndef USG3TTY f = tty.sg_flags; tty.sg_flags = (normf &~ (ECHO|XTABS|CRMOD)) | # ifdef CBREAK CBREAK; # else RAW; # endif # ifdef TIOCGETC ttcharoff(); # endif #else f = tty; tty = normf; tty.c_iflag &= ~ICRNL; tty.c_lflag &= ~(ECHO|ICANON); # ifdef TAB3 tty.c_oflag &= ~TAB3; # endif tty.c_cc[VMIN] = 1; tty.c_cc[VTIME] = 1; ttcharoff(); #endif sTTY(1); tostart(); pfast |= 2; return (f); } /* actions associated with putting the terminal in open mode */ void tostart(void) { putpad(VS); putpad(KS); if (!value(MESG)) { if (ttynbuf[0] == 0) { register char *tn; if ((tn=ttyname(2)) == NULL && (tn=ttyname(1)) == NULL && (tn=ttyname(0)) == NULL) ttynbuf[0] = 1; else strcpy(ttynbuf, tn); } if (ttynbuf[0] != 1) { struct stat sbuf; stat(ttynbuf, &sbuf); ttymesg = sbuf.st_mode & 0777; chmod(ttynbuf, #ifdef UCBV7 /* * This applies to the UCB V7 Pdp-11 system with the * -u write option only. */ 0611 /* 11 = urgent only allowed */ #else 0600 #endif ); } } } /* * Turn off start/stop chars if they aren't the default ^S/^Q. * This is so idiots who make esc their start/stop don't lose. * We always turn off quit since datamedias send ^\ for their * right arrow key. */ #if defined(TIOCGETC) && !defined(USG3TTY) ttcharoff() { nttyc.t_quitc = '\377'; if (nttyc.t_startc != CTRL('q')) nttyc.t_startc = '\377'; if (nttyc.t_stopc != CTRL('s')) nttyc.t_stopc = '\377'; # ifdef TIOCLGET nlttyc.t_suspc = '\377'; /* ^Z */ nlttyc.t_dsuspc = '\377'; /* ^Y */ nlttyc.t_flushc = '\377'; /* ^O */ nlttyc.t_lnextc = '\377'; /* ^V */ # endif } #endif #ifdef USG3TTY static void ttcharoff(void) { long vdisable; if ((vdisable = fpathconf(STDIN_FILENO, _PC_VDISABLE)) == -1) vdisable = '\377'; tty.c_cc[VQUIT] = vdisable; #ifdef VSUSP tty.c_cc[VSUSP] = vdisable; #endif #ifdef VDSUSP tty.c_cc[VDSUSP] = vdisable; #endif /* * The following is sample code if USG ever lets people change * their start/stop chars. As long as they can't we can't get * into trouble so we just leave them alone. */ # ifdef VSTART if (tty.c_cc[VSTART] != CTRL('q')) tty.c_cc[VSTART] = vdisable; # endif # ifdef VSTOP if (tty.c_cc[VSTOP] != CTRL('s')) tty.c_cc[VSTOP] = vdisable; # endif } #endif /* * Stop open, restoring tty modes. */ void ostop(ttymode f) { #ifndef USG3TTY pfast = (f & CRMOD) == 0; #else pfast = (f.c_oflag & OCRNL) == 0; #endif termreset(), fgoto(), flusho(); normal(f); tostop(); } /* Actions associated with putting the terminal in the right mode. */ void tostop(void) { putpad(VE); putpad(KE); if (!value(MESG)) chmod(ttynbuf, ttymesg); } #ifndef CBREAK /* * Into cooked mode for interruptibility. */ vcook() { tty.sg_flags &= ~RAW; sTTY(1); } /* * Back into raw mode. */ vraw() { tty.sg_flags |= RAW; sTTY(1); } #endif /* * Restore flags to normal state f. */ static void normal(ttymode f) { if (normtty > 0) { setty(f); normtty--; } } /* * Straight set of flags to state f. */ ttymode setty(ttymode f) { #ifndef USG3TTY register int ot = tty.sg_flags; #else ttymode ot; ot = tty; #endif #ifndef USG3TTY if (f == normf) { nttyc = ottyc; # ifdef TIOCLGET nlttyc = olttyc; # endif } else ttcharoff(); tty.sg_flags = f; #else if (tty.c_lflag & ICANON) ttcharoff(); tty = f; #endif sTTY(1); return (ot); } void gTTY(int i) { #ifndef USG3TTY ignore(gtty(i, &tty)); # ifdef TIOCGETC ioctl(i, TIOCGETC, &ottyc); nttyc = ottyc; # endif # ifdef TIOCGLTC ioctl(i, TIOCGLTC, &olttyc); nlttyc = olttyc; # endif #else tcgetattr(i, &tty); #endif } /* * sTTY: set the tty modes on file descriptor i to be what's * currently in global "tty". (Also use nttyc if needed.) */ static void sTTY(int i) { #ifndef USG3TTY # ifdef USG /* Bug in USG tty driver, put out a DEL as a patch. */ if (tty.sg_ospeed >= B1200) write(1, "\377", 1); # endif # ifdef TIOCSETN /* Don't flush typeahead if we don't have to */ ioctl(i, TIOCSETN, &tty); # else /* We have to. Too bad. */ stty(i, &tty); # endif # ifdef TIOCGETC /* Update the other random chars while we're at it. */ ioctl(i, TIOCSETC, &nttyc); # endif # ifdef TIOCSLTC ioctl(i, TIOCSLTC, &nlttyc); # endif #else /* USG 3 very simple: just set everything */ tcsetattr(i, TCSAFLUSH, &tty); #endif } /* * Print newline, or blank if in open/visual */ void noonl(void) { ex_putchar(Outchar != termchar ? ' ' : '\n'); } #ifdef SIGTSTP /* * We have just gotten a susp. Suspend and prepare to resume. */ void onsusp(int i) { ttymode f; (void)i; f = setty(normf); vnfl(); putpad(TE); flush(); signal(SIGTSTP, SIG_DFL); kill(0, SIGTSTP); /* the pc stops here */ signal(SIGTSTP, onsusp); vcontin(0); setty(f); if (!inopen) error(0); else { if (vcnt < 0) { vcnt = -vcnt; if (state == VISUAL) vclear(); else if (state == CRTOPEN) vcnt = 0; } vdirty(0, EX_LINES); vrepaint(cursor); } } #endif
MichaelQuell/PSNM
GrayScott/Programs/OpenCL/gs_functions.c
// // // //This file contains only functions for main_gs.c // // #include <CL/cl.h> #include <sys/time.h> #include <string.h> //read the INPUTFILE void parainit(int * Nx, int * Ny, int * Tmax, int * plotgap, double * Lx, double * Ly, double * dt, double * Du, double * Dv, double * A, double *B ){ int intcomm[4]; double dpcomm[7]; char InputFileName[]="./INPUTFILE"; FILE*fp; fp=fopen(InputFileName,"r"); if(!fp) {fprintf(stderr, "Failed to load IPUTFILE.\n");exit(1);} int ierr=fscanf(fp, "%d %d %d %d %lf %lf %lf %lf %lf %lf %lf", &intcomm[0],&intcomm[1],&intcomm[2],&intcomm[3],&dpcomm[0],&dpcomm[1],&dpcomm[2],&dpcomm[3],&dpcomm[4],&dpcomm[5],&dpcomm[6]); if(ierr!=11){fprintf(stderr, "INPUTFILE corrupted:%d\n",ierr);exit(1);} fclose(fp); printf("NX %d\nNY %d\nTmax %d\nplotgap %d\n",intcomm[0],intcomm[1],intcomm[2],intcomm[3]); printf("Lx %lf\nLy %lf\ndt %lf\nDu %lf\nDv %lf\nF %lf\nk %lf\n",dpcomm[0],dpcomm[1],dpcomm[2],dpcomm[3],dpcomm[4],dpcomm[5],dpcomm[6]); *Nx=intcomm[0]; *Ny=intcomm[1]; *Tmax=intcomm[2]; *plotgap=intcomm[3]; *Lx=dpcomm[0]; *Ly=dpcomm[1]; *dt=dpcomm[2]; *Du=dpcomm[3]; *Dv=dpcomm[4]; *A=dpcomm[5]; *B=dpcomm[5]+dpcomm[6]; printf("Read Inputfile\n"); }; //loads a kernel from a file #define MAX_SOURCE_SIZE 8192 void loadKernel(cl_kernel *kernel,cl_context *context, cl_device_id *device_id, char*name){ cl_program p_kernel; cl_int ret=0; size_t source_size; char *source_str; char nameconfig[100]; int i=0; source_str = (char *)malloc(MAX_SOURCE_SIZE*sizeof(char)); for(i=0;i<MAX_SOURCE_SIZE;i++){source_str[i]='\0';} FILE* fp; strcpy(nameconfig,"./"); strcat(nameconfig,name); strcat(nameconfig,".cl"); fp = fopen(nameconfig, "r"); if (!fp) {fprintf(stderr, "Failed to load kernel.\n"); exit(1); } source_size = fread( source_str, sizeof(char), MAX_SOURCE_SIZE, fp ); fclose( fp ); p_kernel = clCreateProgramWithSource(*context, 1, (const char **)&source_str, (const size_t *)&source_size, &ret); if(ret!=CL_SUCCESS){printf("createProgram ret:%d\n",ret);exit(1); } ret = clBuildProgram(p_kernel, 1, &*device_id, NULL, NULL, NULL); if(ret!=CL_SUCCESS){printf("buildProgram ret:%d\n",ret); exit(1); } *kernel = clCreateKernel(p_kernel, name, &ret); if(ret!=CL_SUCCESS){printf("createKernel ret:%d\n",ret);exit(1); } ret = clReleaseProgram(p_kernel); if(ret!=CL_SUCCESS){printf("releaseProgram ret:%d\n",ret);exit(1); } printf("got kernel %s\n",name); free(source_str); }; //displays an array on gpu memory (debug) void printCL(cl_mem* cl_u,cl_command_queue* command_queue, int Nx,int Ny){ double* u; int i=0; int j=0; cl_int ret=0; u=(double*)malloc(Nx*Ny*sizeof(double)); ret = clEnqueueReadBuffer(*command_queue, *cl_u, CL_TRUE, 0, Nx*Ny*sizeof(double), u, 0, NULL, NULL); ret = clFinish(*command_queue); if(ret!=CL_SUCCESS){printf("failed");} for(i=0;i<Nx;i++){ for(j=0;j<Ny;j++){ printf("%f ",u[i+Nx*j]); } printf("\n"); } printf("\n"); free(u); }; //displays an real part of complex array on gpu memory (debug) void printCL_C(cl_mem* cl_u,cl_command_queue* command_queue, int Nx,int Ny){ double* u; int i=0; int j=0; cl_int ret=0; u=(double*)malloc(2*Nx*Ny*sizeof(double)); ret = clEnqueueReadBuffer(*command_queue, *cl_u, CL_TRUE, 0, 2*Nx*Ny*sizeof(double), u, 0, NULL, NULL); ret = clFinish(*command_queue); if(ret!=CL_SUCCESS){printf("failed");} for(i=0;i<Nx;i++){ for(j=0;j<Ny;j++){ printf("%f ",u[2*i+Nx*2*j]); } printf("\n"); } printf("\n"); free(u); }; //make plans for FFT void fftinit(clfftPlanHandle *planHandle, cl_context* context, cl_command_queue* command_queue, cl_mem* tmpBuffer, int Nx,int Ny){ clfftDim dim = CLFFT_2D; size_t clLength[2] = {Nx,Ny}; cl_int ret=0; // Setup clFFT. clfftSetupData fftSetup; ret = clfftInitSetupData(&fftSetup); if(ret!=CL_SUCCESS){printf("clFFT init ret:%d\n",ret);exit(1); } ret = clfftSetup(&fftSetup); if(ret!=CL_SUCCESS){printf("clFFT Setup ret:%d\n",ret);exit(1); } // Create a default plan for a complex FFT. ret = clfftCreateDefaultPlan(&*planHandle, *context, dim, clLength); if(ret!=CL_SUCCESS){printf("clFFT Plan ret:%d\n",ret);exit(1); } // Set plan parameters. ret = clfftSetPlanPrecision(*planHandle, CLFFT_DOUBLE); if(ret!=CL_SUCCESS){printf("clFFT Precision ret:%d\n",ret);exit(1); } //ret = clfftSetPlanBatchSize(*planHandle, (size_t) Ny ); //if(ret!=CL_SUCCESS){printf("clFFT Batch ret:%d\n",ret);exit(1); } ret = clfftSetLayout(*planHandle, CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED); if(ret!=CL_SUCCESS){printf("clFFT Layout ret:%d\n",ret);exit(1); } ret = clfftSetResultLocation(*planHandle, CLFFT_OUTOFPLACE); if(ret!=CL_SUCCESS){printf("clFFT Place ret:%d\n",ret);exit(1); } // Bake the plan. ret = clfftBakePlan(*planHandle, 1, &*command_queue, NULL, NULL); if(ret!=CL_SUCCESS){printf("clFFT Bake ret:%d\n",ret);exit(1); } // Create temporary buffer. // Size of temp buffer. size_t tmpBufferSize = 0; ret = clfftGetTmpBufSize(*planHandle, &tmpBufferSize); if ((ret == CL_SUCCESS) && (tmpBufferSize > 0)) { *tmpBuffer = clCreateBuffer(*context, CL_MEM_READ_WRITE, tmpBufferSize, NULL, &ret); if (ret != CL_SUCCESS){printf("Error with tmpBuffer clCreateBuffer\n");exit(1);} } }; //destroy plans void fftdestroy(clfftPlanHandle *planHandle,cl_mem* tmpBuffer){ cl_int ret=0; clReleaseMemObject(*tmpBuffer); ret = clfftDestroyPlan(&*planHandle); if(ret!=0){printf("Error while destroying fft");exit(1);} clfftTeardown(); }; //fft2dfoward void fft2dfor(cl_mem *cl_u, cl_mem *cl_uhat, clfftPlanHandle *planHandle, cl_command_queue* command_queue, cl_mem* tmpBuffer){ int ret=0; ret = clfftEnqueueTransform(*planHandle, CLFFT_FORWARD, 1, command_queue, 0, NULL, NULL,&*cl_u, &*cl_uhat, *tmpBuffer); if (ret != CL_SUCCESS){printf("FFT failedA%d",ret);} ret = clFinish(*command_queue); if (ret != CL_SUCCESS){printf("FFT failedB%d",ret);} }; //fft2dback void fft2dback(cl_mem *cl_u, cl_mem *cl_uhat, clfftPlanHandle *planHandle, cl_command_queue* command_queue, cl_mem* tmpBuffer){ int ret=0; ret = clfftEnqueueTransform(*planHandle, CLFFT_BACKWARD, 1, command_queue, 0, NULL, NULL,&*cl_uhat, &*cl_u, *tmpBuffer); if (ret != CL_SUCCESS){printf("FFT failedC%d",ret);} ret = clFinish(*command_queue); if (ret != CL_SUCCESS){printf("FFT failedD%d",ret);} }; //writes an image to disk and returns the maximum of cl_u double writeimage(cl_mem* cl_u, cl_command_queue *command_queue, int Nx,int Ny, int plotnum, char* prefix){ int i=0; cl_int ret=0; int header=54; double* u; u=(double*)malloc(2*Nx*Ny*sizeof(double)); ret = clEnqueueReadBuffer(*command_queue, *cl_u, CL_TRUE, 0, 2*Nx*Ny * sizeof(double), u, 0, NULL, NULL); ret = clFinish(*command_queue); if(ret!=0){printf("Error hahah");} double max=0.0; for(i=0;i<Nx*Ny;i++){ if(u[2*i]>max){max=u[2*i];} } unsigned char*picture=(unsigned char*)malloc((3*Nx*Ny+header)*sizeof(unsigned char)); for(i=0;i<Nx*Ny;i++){ picture[3*i+header+0]=(unsigned char)(255*u[2*i]/max); picture[3*i+header+1]=(unsigned char)(255*u[2*i]/max); picture[3*i+header+2]=(unsigned char)(255*u[2*i]/max); } //header for bmp file int w=Ny; int h=Nx; int padSize=(4-w%4)%4; int filesize=header + 3*h*w+h*padSize; unsigned char bmppad[3] = {0,0,0}; //padding picture[ 0]='B'; picture[ 1]='M'; picture[ 2] = (unsigned char)(filesize ); picture[ 3] = (unsigned char)(filesize>> 8); picture[ 4] = (unsigned char)(filesize>>16); picture[ 5] = (unsigned char)(filesize>>24); picture[ 6] = 0; picture[ 7] = 0; picture[ 8] = 0; picture[ 9] = 0; picture[10] = 54; picture[11] = 0; picture[12] = 0; picture[13] = 0; picture[14] = 40; picture[15] = 0; picture[16] = 0; picture[17] = 0;//3 picture[18] = (unsigned char)( w ); picture[19] = (unsigned char)( w>> 8); picture[20] = (unsigned char)( w>>16); picture[21] = (unsigned char)( w>>24); picture[22] = (unsigned char)( h ); picture[23] = (unsigned char)( h>> 8); picture[24] = (unsigned char)( h>>16); picture[25] = (unsigned char)( h>>24); picture[26] = 1; picture[27] = 0; picture[28] = 24; picture[29] = 0; for(i=30;i<54;i++){ picture[i]=0; } FILE*fp; //file name char tmp_str[10]; char nameconfig[100]; strcpy(nameconfig,"./data/"); strcat(nameconfig,prefix); sprintf(tmp_str,"%d",10000000+plotnum); strcat(nameconfig,tmp_str); strcat(nameconfig,".bmp"); fp=fopen(nameconfig,"wb"); if (!fp) {fprintf(stderr, "Failed to write data.\n"); exit(1); } for(i=0;i<header;i++){fwrite(&picture[i], sizeof(unsigned char), 1, fp);} for(i=0;i<h;i++){ fwrite(picture+(w*(h-i-1)*3)+header,3* sizeof(unsigned char), w, fp); fwrite(bmppad,sizeof(unsigned char),(4-(w*3)%4)%4,fp); } fclose( fp ); free(picture); free(u); return max; }; //writes the array to disk (debug) void writedata(cl_mem* cl_u, cl_command_queue *command_queue, int Nx,int Ny, int plotnum,char* prefix){ int i=0; cl_int ret=0; double* u; u=(double*)malloc(Nx*Ny*sizeof(double)); ret = clEnqueueReadBuffer(*command_queue, *cl_u, CL_TRUE, 0, Nx*Ny * sizeof(double), u, 0, NULL, NULL); ret = clFinish(*command_queue); if(ret!=0){printf("Error hahah");} FILE*fp; //file name char tmp_str[10]; char nameconfig[100]; strcpy(nameconfig,"./data/"); strcat(nameconfig,prefix); sprintf(tmp_str,"%d",10000000+plotnum); strcat(nameconfig,tmp_str); strcat(nameconfig,".datbin"); fp=fopen(nameconfig,"wb"); if (!fp) {fprintf(stderr, "Failed to write data.\n"); exit(1); } for(i=0;i<Nx;i++){fwrite(u+i*Ny, sizeof(double), Ny, fp);} fclose( fp ); free(u); }; //writes the real part of complex array to disk void writedata_C(cl_mem* cl_u, cl_command_queue *command_queue, int Nx,int Ny, int plotnum,char* prefix){ int i=0; cl_int ret=0; double* u; u=(double*)malloc(2*Nx*Ny*sizeof(double)); ret = clEnqueueReadBuffer(*command_queue, *cl_u, CL_TRUE, 0, 2*Nx*Ny * sizeof(double), u, 0, NULL, NULL); ret = clFinish(*command_queue); if(ret!=0){printf("Error hahah");} for(i=0;i<Nx*Ny;i++){u[i]=u[2*i];} FILE*fp; //file name char tmp_str[10]; char nameconfig[100]; strcpy(nameconfig,"./data/"); strcat(nameconfig,prefix); sprintf(tmp_str,"%d",10000000+plotnum); strcat(nameconfig,tmp_str); strcat(nameconfig,".datbin"); fp=fopen(nameconfig,"wb"); if (!fp) {fprintf(stderr, "Failed to write data.\n"); exit(1); } for(i=0;i<Nx;i++){fwrite(u+i*Ny, sizeof(double), Ny, fp);} fclose( fp ); free(u); }; //loades the data from disk (debug) void loaddata(cl_mem* cl_u, cl_command_queue *command_queue, int Nx,int Ny, char*name){ int i=0; int numread=0; cl_int ret=0; double* u; u=(double*)malloc(Nx*Ny*sizeof(double)); FILE*fp; fp=fopen(name,"rb"); if (!fp) {fprintf(stderr, "Failed to open file.\n"); exit(1); } for(i=0;i<Nx;i++){ numread=fread(u+i*Ny, sizeof(double), Ny, fp); if (numread!=Ny) {fprintf(stderr, "Failed to read file.\n"); exit(1); } } fclose( fp ); ret = clEnqueueWriteBuffer(*command_queue, *cl_u, CL_TRUE, 0, Nx*Ny * sizeof(double), u, 0, NULL, NULL); ret = clFinish(*command_queue); if(ret!=0){printf("Error hahah");} free(u); }; //writes an array to disc ASCII void writearray(double*u,int lenght,char* prefix){ int i=0; char nameconfig[100]; strcpy(nameconfig,"./data/"); strcat(nameconfig,prefix); FILE*fp; fp=fopen(nameconfig,"w"); if (!fp) {fprintf(stderr, "Failed to write data.\n"); exit(1); } for(i=0;i<lenght;i++){ fprintf(fp,"%.17g\n",u[i]); } }; //start measuring time void mtime_s(struct timeval* tvs){ gettimeofday(&*tvs, NULL); }; //end measuring time+ printing void mtime_e(struct timeval* tvs, char* printme){ struct timeval tve; double elapsedTime; gettimeofday(&tve, NULL); elapsedTime = (tve.tv_sec - (*tvs).tv_sec) * 1000.0; // sec to ms elapsedTime += (tve.tv_usec - (*tvs).tv_usec) / 1000.0; // us to ms printf("%s%lfms\n",printme,elapsedTime); };
MichaelQuell/PSNM
GrayScott/Programs/OpenCL/main_gs.c
<filename>GrayScott/Programs/OpenCL/main_gs.c<gh_stars>10-100 #include "clFFT.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <sys/time.h> #include "gs_functions.c" #if defined(cl_amd_fp64) || defined(cl_khr_fp64) #if defined(cl_amd_fp64) #pragma OPENCL EXTENSION cl_amd_fp64 : enable #elif defined(cl_khr_fp64) #pragma OPENCL EXTENSION cl_khr_fp64 : enable #endif // function declarations/definitions using double precision floating-point arithmetic #endif int main(void) { //time meassuring struct timeval tvs; //variables int Nx=1024; int Ny=1024; int plotnum=0; int Tmax=2; int plottime=0; int plotgap=1; double Lx=1.0; double Ly=1.0; double dt=0.0; double A=0.0; double B=0.0; double Du=0.0; double Dv=0.0; //splitting coefficients double a=0.5; double b=0.5; double c=1.0; //loop counters int i=0; int j=0; int n=0; double*umax=NULL; double*vmax=NULL; parainit(&Nx,&Ny,&Tmax,&plotgap,&Lx,&Ly,&dt,&Du,&Dv,&A,&B); plottime=plotgap; vmax=(double*)malloc((Tmax/plotgap+1)*sizeof(double)); umax=(double*)malloc((Tmax/plotgap+1)*sizeof(double)); //openCL variables cl_platform_id *platform_id = NULL; cl_kernel frequencies = NULL, initialdata = NULL, linearpart=NULL; cl_kernel nonlinearpart_a=NULL, nonlinearpart_b=NULL; cl_int ret; cl_uint num_platforms; // Detect how many platforms there are. ret = clGetPlatformIDs(0, NULL, &num_platforms); // Allocate enough space for the number of platforms. platform_id = (cl_platform_id*) malloc(num_platforms*sizeof(cl_platform_id)); // Store the platforms ret = clGetPlatformIDs(num_platforms, platform_id, NULL); printf("Found %d platform(s)!\n",num_platforms); cl_uint *num_devices; num_devices=(cl_uint*) malloc(num_platforms*sizeof(cl_uint)); cl_device_id **device_id = NULL; device_id =(cl_device_id**) malloc(num_platforms*sizeof(cl_device_id*)); // Detect number of devices in the platforms for(i=0;i<num_platforms;i++){ char buf[65536]; size_t size; ret = clGetPlatformInfo(platform_id[i],CL_PLATFORM_VERSION,sizeof(buf),buf,&size); printf("%s\n",buf); ret = clGetDeviceIDs(platform_id[i],CL_DEVICE_TYPE_ALL,0,NULL,num_devices); printf("Found %d device(s) on platform %d!\n", num_devices[i],i); ret = clGetPlatformInfo(platform_id[i],CL_PLATFORM_NAME,sizeof(buf),buf,&size); printf("%s ",buf); // Store numDevices from platform device_id[i]=(cl_device_id*) malloc(num_devices[i]*sizeof(device_id)); ret = clGetDeviceIDs(platform_id[i],CL_DEVICE_TYPE_ALL,num_devices[i],device_id[i],NULL); for(j=0;j<num_devices[i];j++){ ret = clGetDeviceInfo(device_id[i][j],CL_DEVICE_NAME,sizeof(buf),buf,&size); printf("%s (%d,%d)\n",buf,i,j); } } //create context and command_queue cl_context context = NULL; cl_command_queue command_queue = NULL; //Which platform and device do i choose? int chooseplatform=0; int choosedevice=0; printf("Choose platform %d and device %d!\n",chooseplatform,choosedevice); context = clCreateContext( NULL, num_devices[chooseplatform], device_id[chooseplatform], NULL, NULL, &ret); if(ret!=CL_SUCCESS){printf("createContext ret:%d\n",ret); exit(1); } command_queue = clCreateCommandQueue(context, device_id[chooseplatform][choosedevice], 0, &ret); if(ret!=CL_SUCCESS){printf("createCommandQueue ret:%d\n",ret); exit(1); } //OpenCL arrays cl_mem cl_u = NULL,cl_v = NULL; cl_mem cl_uhat = NULL, cl_vhat = NULL; cl_mem cl_kx = NULL, cl_ky = NULL; //FFT clfftPlanHandle planHandle; cl_mem tmpBuffer = NULL; fftinit(&planHandle,&context, &command_queue, &tmpBuffer, Nx, Ny); //allocate gpu memory/ cl_u=clCreateBuffer(context, CL_MEM_READ_WRITE, 2*Nx* Ny* sizeof(double), NULL, &ret); cl_v=clCreateBuffer(context, CL_MEM_READ_WRITE, 2*Nx* Ny* sizeof(double), NULL, &ret); cl_uhat=clCreateBuffer(context, CL_MEM_READ_WRITE, 2*Nx * Ny* sizeof(double), NULL, &ret); cl_vhat=clCreateBuffer(context, CL_MEM_READ_WRITE, 2*Nx * Ny* sizeof(double), NULL, &ret); cl_kx = clCreateBuffer(context, CL_MEM_READ_WRITE, Nx * sizeof(double), NULL, &ret); cl_ky = clCreateBuffer(context, CL_MEM_READ_WRITE, Ny * sizeof(double), NULL, &ret); printf("allocated space\n"); //load the kernels loadKernel(&frequencies,&context,&device_id[chooseplatform][choosedevice],"frequencies"); loadKernel(&initialdata,&context,&device_id[chooseplatform][choosedevice],"initialdata"); loadKernel(&linearpart,&context,&device_id[chooseplatform][choosedevice],"linearpart"); loadKernel(&nonlinearpart_a,&context,&device_id[chooseplatform][choosedevice],"nonlinearpart_a"); loadKernel(&nonlinearpart_b,&context,&device_id[chooseplatform][choosedevice],"nonlinearpart_b"); size_t global_work_size[1] = {Nx*Ny}; size_t global_work_size_X[1] = {Nx}; size_t global_work_size_Y[1] = {Ny}; //frequencies ret = clSetKernelArg(frequencies, 0, sizeof(cl_mem),(void *)&cl_kx); ret = clSetKernelArg(frequencies, 1, sizeof(double),(void* )&Lx); ret = clSetKernelArg(frequencies, 2, sizeof(int),(void* )&Nx); ret = clEnqueueNDRangeKernel(command_queue, frequencies, 1, NULL, global_work_size_X, NULL, 0, NULL, NULL); ret = clFinish(command_queue); ret = clSetKernelArg(frequencies, 0, sizeof(cl_mem),(void *)&cl_ky); ret = clSetKernelArg(frequencies, 1, sizeof(double),(void* )&Ly); ret = clSetKernelArg(frequencies, 2, sizeof(int),(void* )&Ny); ret = clEnqueueNDRangeKernel(command_queue, frequencies, 1, NULL, global_work_size_Y, NULL, 0, NULL, NULL); ret = clFinish(command_queue); //printCL(&cl_kx,&command_queue,Nx,1); //printCL(&cl_ky,&command_queue,1,Ny); //inintial data ret = clSetKernelArg(initialdata, 0, sizeof(cl_mem),(void *)&cl_u); ret = clSetKernelArg(initialdata, 1, sizeof(cl_mem),(void* )&cl_v); ret = clSetKernelArg(initialdata, 2, sizeof(int),(void* )&Nx); ret = clSetKernelArg(initialdata, 3, sizeof(int),(void* )&Ny); ret = clSetKernelArg(initialdata, 4, sizeof(double),(void* )&Lx); ret = clSetKernelArg(initialdata, 5, sizeof(double),(void* )&Ly); ret = clEnqueueNDRangeKernel(command_queue, initialdata, 1, NULL, global_work_size, NULL, 0, NULL, NULL); ret = clFinish(command_queue); //make output writedata_C(&cl_u, &command_queue,Nx,Ny,plotnum,"u"); writedata_C(&cl_v, &command_queue,Nx,Ny,plotnum,"v"); umax[plotnum]=writeimage(&cl_u, &command_queue,Nx,Ny,plotnum,"u"); vmax[plotnum]=writeimage(&cl_v, &command_queue,Nx,Ny,plotnum,"v"); printf("Got initial data, starting timestepping\n"); mtime_s(&tvs); for(n=0;n<=Tmax;n++){ //nonlinearpart_a ret = clSetKernelArg(nonlinearpart_a, 0, sizeof(cl_mem),(void *)&cl_u); ret = clSetKernelArg(nonlinearpart_a, 1, sizeof(cl_mem),(void* )&cl_v); ret = clSetKernelArg(nonlinearpart_a, 2, sizeof(double),(void* )&A); ret = clSetKernelArg(nonlinearpart_a, 3, sizeof(double),(void* )&dt); ret = clSetKernelArg(nonlinearpart_a, 4, sizeof(double),(void* )&a); ret = clEnqueueNDRangeKernel(command_queue, nonlinearpart_a, 1, NULL, global_work_size, NULL, 0, NULL, NULL); ret = clFinish(command_queue); //nonlinearpart_b ret = clSetKernelArg(nonlinearpart_b, 0, sizeof(cl_mem),(void *)&cl_u); ret = clSetKernelArg(nonlinearpart_b, 1, sizeof(cl_mem),(void* )&cl_v); ret = clSetKernelArg(nonlinearpart_b, 2, sizeof(double),(void* )&A); ret = clSetKernelArg(nonlinearpart_b, 3, sizeof(double),(void* )&dt); ret = clSetKernelArg(nonlinearpart_b, 4, sizeof(double),(void* )&b); ret = clEnqueueNDRangeKernel(command_queue, nonlinearpart_b, 1, NULL, global_work_size, NULL, 0, NULL, NULL); ret = clFinish(command_queue); //linear fft2dfor(&cl_u, &cl_uhat,&planHandle,&command_queue,&tmpBuffer); fft2dfor(&cl_v, &cl_vhat,&planHandle,&command_queue,&tmpBuffer); //printf("A%f,B%f\n",A,B); ret = clSetKernelArg(linearpart, 0, sizeof(cl_mem),(void *)&cl_uhat); ret = clSetKernelArg(linearpart, 1, sizeof(cl_mem),(void *)&cl_vhat); ret = clSetKernelArg(linearpart, 2, sizeof(cl_mem),(void* )&cl_kx); ret = clSetKernelArg(linearpart, 3, sizeof(cl_mem),(void* )&cl_ky); ret = clSetKernelArg(linearpart, 4, sizeof(double),(void* )&Du); ret = clSetKernelArg(linearpart, 5, sizeof(double),(void* )&Dv); ret = clSetKernelArg(linearpart, 6, sizeof(double),(void* )&A); ret = clSetKernelArg(linearpart, 7, sizeof(double),(void* )&B); ret = clSetKernelArg(linearpart, 8, sizeof(double),(void* )&dt); ret = clSetKernelArg(linearpart, 9, sizeof(double),(void* )&c); ret = clSetKernelArg(linearpart, 10, sizeof(int),(void* )&Nx); ret = clSetKernelArg(linearpart, 11, sizeof(int),(void* )&Ny); ret = clEnqueueNDRangeKernel(command_queue, linearpart, 1, NULL, global_work_size, NULL, 0, NULL, NULL); ret = clFinish(command_queue); fft2dback(&cl_u, &cl_uhat,&planHandle,&command_queue,&tmpBuffer); fft2dback(&cl_v, &cl_vhat,&planHandle,&command_queue,&tmpBuffer); //nonlinearpart_b ret = clSetKernelArg(nonlinearpart_b, 0, sizeof(cl_mem),(void *)&cl_u); ret = clSetKernelArg(nonlinearpart_b, 1, sizeof(cl_mem),(void* )&cl_v); ret = clSetKernelArg(nonlinearpart_b, 2, sizeof(double),(void* )&A); ret = clSetKernelArg(nonlinearpart_b, 3, sizeof(double),(void* )&dt); ret = clSetKernelArg(nonlinearpart_b, 4, sizeof(double),(void* )&b); ret = clEnqueueNDRangeKernel(command_queue, nonlinearpart_b, 1, NULL, global_work_size, NULL, 0, NULL, NULL); ret = clFinish(command_queue); //nonlinearpart_a ret = clSetKernelArg(nonlinearpart_a, 0, sizeof(cl_mem),(void *)&cl_u); ret = clSetKernelArg(nonlinearpart_a, 1, sizeof(cl_mem),(void* )&cl_v); ret = clSetKernelArg(nonlinearpart_a, 2, sizeof(double),(void* )&A); ret = clSetKernelArg(nonlinearpart_a, 3, sizeof(double),(void* )&dt); ret = clSetKernelArg(nonlinearpart_a, 4, sizeof(double),(void* )&a); ret = clEnqueueNDRangeKernel(command_queue, nonlinearpart_a, 1, NULL, global_work_size, NULL, 0, NULL, NULL); ret = clFinish(command_queue); // done if(n==plottime){ printf("time:%f, step:%d,%d,umax:%f,vmax:%f\n",n*dt,n,plotnum,umax[plotnum],vmax[plotnum]); plottime=plottime+plotgap; plotnum=plotnum+1; writedata_C(&cl_u, &command_queue,Nx,Ny,plotnum,"u"); writedata_C(&cl_v, &command_queue,Nx,Ny,plotnum,"v"); umax[plotnum]=writeimage(&cl_u, &command_queue,Nx,Ny,plotnum,"u"); vmax[plotnum]=writeimage(&cl_v, &command_queue,Nx,Ny,plotnum,"v"); } }//end timestepping printf("Finished time stepping\n"); mtime_e(&tvs,"Programm took:"); writearray(umax,(Tmax/plotgap)+1,"u"); writearray(vmax,(Tmax/plotgap)+1,"v"); free(umax); free(vmax); clReleaseMemObject(cl_u); clReleaseMemObject(cl_v); clReleaseMemObject(cl_uhat); clReleaseMemObject(cl_vhat); clReleaseMemObject(cl_kx); clReleaseMemObject(cl_ky); ret = clReleaseKernel(initialdata); ret = clReleaseKernel(frequencies); ret = clReleaseKernel(linearpart); ret = clReleaseKernel(nonlinearpart_a); ret = clReleaseKernel(nonlinearpart_b); fftdestroy(&planHandle, &tmpBuffer); ret = clReleaseCommandQueue(command_queue); ret = clReleaseContext(context); for(i=0;i<num_platforms;i++){free(device_id[i]);} free(device_id); free(platform_id); free(num_devices); printf("Program execution complete\n"); return 0; }
kelvin943/ZQFoundation
ZQCommon/Category/Other/UIImage+ZQAdd.h
// // UIImage+ZQAdd.h // ZQFoundation // // Created by macro on 2019/9/10. // #import <UIKit/UIKit.h> /* e.g: get image from defaul iconfont: ImageWithDefaultIconfont(_iconStr_,_size_,_color_) get image from costom iconfont: ImageWithDefaultIconfont(_fontName_,_iconStr_,_size_,_color_) */ #define ImageWithIconfont(_fontName_,_iconStr_,_size_,_color_) \ [UIImage imageFromIconfontWihtFontName:_fontName_ iconStr:_iconStr_ size:_size_ color:_color_] #define ImageWithDefaultIconfont(_iconStr_,_size_,_color_) \ [UIImage imageFromIconfontWihtFontName:@"iconfont" iconStr:_iconStr_ size:_size_ color:_color_] NS_ASSUME_NONNULL_BEGIN @interface UIImage (IconFont) //使用默认的 iconfont 获取等宽高的图片 + (UIImage *)imageFromIconfontWithIconStr:(NSString *)iconStr size:(NSUInteger)size color:(UIColor *)color; //使用指定 iconfont 获取等宽高的图片 + (UIImage *)imageFromIconfontWihtFontName:(NSString *)fontName iconStr:(NSString*)iconStr size:(NSUInteger)size color:(UIColor *)color; //使用默认的iconfont 获取指定 frame 大小的图片 + (UIImage *)imageFrame:(CGRect)frame iconStr:(NSString*)iconStr fontSize:(CGFloat)size color:(UIColor *)color; //使用指定的iconfont 获取指定 frame 大小的图片 + (UIImage *)imageFrame:(CGRect)frame iconStr:(NSString*)iconStr fontName:(NSString*)fontName fontSize:(CGFloat)size color:(UIColor *)color; @end @interface UIImage (Scale) + (UIImage *)imageWithColor:(UIColor *)color; - (UIImage *)imageMaskedWithColor:(UIColor *)maskColor; @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
ZQUIKit/ZQCustomizeBar/UIViewController+ZQCustomizeNavBar.h
// // UIViewController+ZQCustomizeNavBar.h // ZQDemoApp // // Created by 张泉(macro) on 2019/7/26. // Copyright © 2019 张泉. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface ZQCustomNavBar : UIView /// 导航栏背景颜色的透明度(0,1) @property (nonatomic, assign) CGFloat barAlpha; /// 导航栏的vc 自己navBar的颜色 @property (nonatomic, strong) UIColor *barColor UI_APPEARANCE_SELECTOR; @end @interface UIViewController (ZQCustomizeNavBar) // 当被包含在容器(navcontrooler)的VC如 tabarvc 不需要出处理导航栏相关UI应确保将zq_willAppearInjectBlockIgnored置为YES // 这样就会是改VC避免受注入代码的影响! // Default to NO, vc are more likely need customBar. @property (nonatomic, assign) BOOL zq_willAppearInjectBlockIgnored; /// Indicate this view controller prefers its navigation bar hidden or not, /// checked when view controller based navigation bar's appearance is enabled. /// Default to NO, bars are more likely to show. @property (nonatomic, assign) BOOL zq_prefersNavigationBarHidden; /// ///那些不被包含在容器中(UINavigationController)的VC 如果也需要添加自定CustomNavBar 可以更改此属性 /// Default to NO @property (nonatomic, assign) BOOL zq_needCustomNavBar; /// 左滑返回手势是否禁用 /// Default to No @property (nonatomic, assign) BOOL zq_interactivePopDisabled; /// 左滑返回手势的触发范围(默认边缘值 13) @property (nonatomic, assign) CGFloat zq_popEdgeRegionSize; @property (nonatomic, strong, readonly) ZQCustomNavBar *zq_CustomNavBar; @end @interface UINavigationController (ZQCustomizeNavBar) /// The gesture recognizer that actually handles interactive pop. @property (nonatomic, strong, readonly) UIPanGestureRecognizer *zq_fullscreenPopGestureRecognizer; @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
ZQFoundation.h
// // ZQFoundation.h // ZQFoundation // // Created by macro on 2019/9/26. // #if __has_include(<ZQFoundation/ZQFoundation.h>) #import <ZQFoundation/ZQCommon.h> #import <ZQFoundation/ZQUIKit.h> #else #import "ZQCommon.h" #import "ZQUIKit.h" #endif
kelvin943/ZQFoundation
ZQUIKit/ZQTableViewController/Cells/BaseTableViewCell.h
// // BaseTableViewCell.h // MJRefresh // // Created by macro on 2019/9/7. // #import <UIKit/UIKit.h> #import "BaseModel.h" @interface BaseTableViewCell : UITableViewCell @property (nonatomic, strong) id<CellModelBasicProtocol> cellModel; @property (nonatomic, strong) NSIndexPath* indexPath; + (NSString *)cellIdentifier; + (CGFloat)tableView:(UITableView*)tableView rowHeightForObject:(id<CellModelBasicProtocol>)cellModel; @end //cell快速创建 #pragma mark - empty cell @interface ZQEmptyCellItem : BaseModel @property (nonatomic,strong) UIColor *bgColor; + (instancetype)emptyCellItem; + (instancetype)emptyCellItemWithHeight:(CGFloat)height; + (instancetype)emptyCellItemWithBackgroundColor:(UIColor*)color; + (instancetype)emptyCellItemWithHeight:(CGFloat)height backgroundColor:(UIColor*)color; @end @interface ZQEmptyCell: BaseTableViewCell @end #pragma mark - system default cell @interface ZQDefaultCellItem : BaseModel @property (nonatomic, copy) NSString *titleStr; @property (nonatomic, copy) NSString *contentStr; @property (nonatomic,strong) UIColor *bgColor; @property (nonatomic,assign) UIEdgeInsets separatorInset; + (instancetype)cellWithTitleStr:(NSString *)titleStr content:(NSString*)contentStr; + (instancetype)cellWithTitleStr:(NSString *)titleStr content:(NSString*)contentStr bgColor:(UIColor*)color; + (instancetype)cellWithTitleStr:(NSString *)titleStr content:(NSString*)contentStr height:(CGFloat)height; + (instancetype)cellWithTitleStr:(NSString *)titleStr content:(NSString*)contentStr bgColor:(UIColor*)color height:(CGFloat)height; @end @interface ZQDefaultCell : BaseTableViewCell @end #pragma mark - custom default cell @interface ZQCustomDefaultCellItem : BaseModel @property (nonatomic, copy) NSString *titleStr; @property (nonatomic, copy) NSString *subTitleStr; @property (nonatomic, copy) NSString *flagImageIconStr; @property (nonatomic,strong) UIColor *bgColor; @property (nonatomic,assign) UIEdgeInsets separatorInset; + (instancetype)cellWithTitleStr:(NSString *)titleStr subTitle:(NSString*)subTitleStr; @end @interface ZQCustomDefaultCell : BaseTableViewCell @property (nonatomic,strong) UILabel *titleLabel; @property (nonatomic,strong) UILabel *subTitleLabel; @property (nonatomic,strong) UIImageView *flagImageView; @end
kelvin943/ZQFoundation
ZQUIKit/ZQHoverViewController/ZQHoverViewController.h
<filename>ZQUIKit/ZQHoverViewController/ZQHoverViewController.h // // ZQHoverViewController.h // ZQFoundation // // Created by 张泉(Macro) on 2019/10/30. // #import "BaseViewController.h" #import "ZQHoverScrollView.h" NS_ASSUME_NONNULL_BEGIN @interface ZQHoverViewController : BaseViewController @property (nonatomic, assign) BOOL isCanScroll; @property (nonatomic, strong) ZQHoverScrollView * hoverScrollView; @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
ZQUIKit/Common/ZQSegmentView.h
<reponame>kelvin943/ZQFoundation // // ZQSegmentView.h // ZQFoundation // // Created by 张泉(Macro) on 2019/10/12. // /* // suggest init frame - (ZQSegmentView *)segmentView { if (!_segmentView) { _segmentView = [[ZQSegmentView alloc] initWithFrame:CGRectMake(0, 0,SCREENWIDTH , 44)]; _segmentView.menuTitleArray = @[@"待办任务", @"已办任务", @"我提交的"]; _segmentView.selectIndex = 0; _segmentView.hSpacing = 20; _segmentView.layoutType = LayoutTypeFromLeft; _segmentView.delegate = self; } return _segmentView; } */ #import <UIKit/UIKit.h> typedef NS_ENUM(NSUInteger, ZQSegmengViewLayoutType) { ZQSegmengViewLayoutTypeFromLeft, ZQSegmengViewLayoutTypeAverage, }; @class ZQSegmentView; @protocol ZQSegmentViewDelegate <NSObject> @optional - (void)segmentView:(ZQSegmentView *_Nullable)segmentView didSelectIndex:(NSInteger)index; @end NS_ASSUME_NONNULL_BEGIN @interface ZQSegmentView : UIView @property (nonatomic, weak) id<ZQSegmentViewDelegate> delegate; @property (nonatomic, copy) NSArray *menuTitleArray; @property (nonatomic, assign) NSInteger selectIndex; //布局方式 @property (nonatomic,assign) IBInspectable ZQSegmengViewLayoutType layoutType; //左内边距 @property (nonatomic,assign) IBInspectable CGFloat leftPadding; //水平间距 @property (nonatomic,assign) IBInspectable CGFloat hSpacing; //按钮宽高 @property (nonatomic,assign) IBInspectable CGFloat btnWidth; @property (nonatomic,assign) IBInspectable CGFloat btnHeight; @property (nonatomic,assign) IBInspectable BOOL isShowLineView; //按钮字体大小颜色、背景颜色 @property (nonatomic,strong) UIFont * buttonUnSelectFont; @property (nonatomic,strong) UIFont * buttonSelectFont; @property (nonatomic,strong) IBInspectable UIColor * buttonUnSelectColor; @property (nonatomic,strong) IBInspectable UIColor * buttonSelectColor; @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
ZQUIKit/ZQPageViewController/ZQBookViewController.h
<reponame>kelvin943/ZQFoundation<gh_stars>1-10 // // ZQPageViewController.h // ZQFoundation // // 基于 UIPageViewController 封装的分页控制器, // Created by 张泉(Macro) on 2019/10/17. // #import "BaseViewController.h" NS_ASSUME_NONNULL_BEGIN @interface ZQBookViewController : BaseViewController @property (nonatomic,assign,readonly) NSInteger currentIndex; @property (nonatomic,strong) NSArray<__kindof UIViewController *> *viewControllers; - (void)setSelectPageWithIndex:(NSInteger)selectIndex hasNext:(BOOL)hasNext; @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
Example/ZQFoundation/hoverVC.h
// // hoverVC.h // ZQFoundation_Example // // Created by 张泉(Macro) on 2019/10/21. // Copyright © 2019 macro. All rights reserved. // #import <ZQFoundation/ZQFoundation.h> NS_ASSUME_NONNULL_BEGIN @interface hoverVC : HoverTableViewController @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
ZQUIKit/ZQHoverViewController/ZQHoverScrollView.h
// // ZQHoverScrollView.h // ZQFoundation // // Created by 张泉(Macro) on 2019/10/30. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class ZQHoverScrollView; @protocol ZQHoverScrollViewDataSource <NSObject> @required - (UIView*)headViewForHoverView:(ZQHoverScrollView*)hoverView; - (UIView*)hoverViewForHoverView:(ZQHoverScrollView*)hoverView; @optional - (CGFloat)heightForHeadView; - (CGFloat)heightForHoverView; @end @interface ZQHoverScrollView : UIScrollView @property (nonatomic,strong) UIView* headView; @property (nonatomic,strong) UIView* hoverView; @property (nonatomic, weak, nullable) id <ZQHoverScrollViewDataSource> dataSource; @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
ZQUIKit/ZQBaseModel/BaseModel.h
<gh_stars>1-10 // // BaseModel.h // MJRefresh // // Created by macro on 2019/9/6. // #if __has_include(<YYModel/YYModel.h>) #import <YYModel/YYModel.h> #else #import "YYModel.h" #endif #import <Foundation/Foundation.h> @protocol CellModelBasicProtocol <NSObject> @property (nonatomic, assign) Class cellClass; @property (nonatomic, assign) NSInteger cellType; @property (nonatomic, strong) NSNumber* cellHeight; @property (nonatomic, strong) NSIndexPath* indexPath; @property (nonatomic, weak) id cellTarget; @end @interface BaseModel : NSObject <CellModelBasicProtocol,NSCopying, NSCoding, YYModel> @property (nonatomic, copy) NSDictionary *userInfo; @end @interface BaseListModel : BaseModel //数据数组 @property (nonatomic, retain) NSMutableArray* items; //当前页码 @property (nonatomic, retain) NSNumber* page; //当前页面数据数量 @property (nonatomic, retain) NSNumber* rows; //是否有更多 @property (nonatomic, assign) BOOL hasMore; //总数量 @property (nonatomic, assign) NSInteger totals; @end
kelvin943/ZQFoundation
Example/ZQFoundation/ZQViewController.h
<filename>Example/ZQFoundation/ZQViewController.h // // ZQViewController.h // ZQFoundation // // Created by macro on 11/15/2018. // Copyright (c) 2018 macro. All rights reserved. // #import "BaseTableViewController.h" #import "UITableView+ZQAdd.h" @import UIKit; @interface ZQViewController : BaseTableViewController @end
kelvin943/ZQFoundation
ZQCommon/Category/View/UIButton+ZQAdd.h
// // UIButton+ZQAdd.h // ZQDemoApp // // Created by 张泉(macro) on 2019/3/1. // Copyright © 2019 张泉. All rights reserved. // #import <UIKit/UIKit.h> #import <objc/runtime.h> //按钮点击事件回调 typedef void(^TouchUpInsideAction)(UIButton * _Nullable button); //按钮图片和文字布局方式 typedef NS_ENUM(NSInteger, SCButtonLayoutStyle) { SCButtonLayoutStyleImageLeft, SCButtonLayoutStyleImageRight, SCButtonLayoutStyleImageTop, SCButtonLayoutStyleImageBottom, }; NS_ASSUME_NONNULL_BEGIN @interface UIButton (ZQAdd) @property (nullable,nonatomic,copy)TouchUpInsideAction touchUpInsideAction; @end @interface UIButton (Layout) - (void)sc_setLayoutStyle:(SCButtonLayoutStyle)style spacing:(CGFloat)spacing; @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
Example/ZQFoundation/tableVC.h
// // tableVC.h // ZQFoundation_Example // // Created by 张泉(Macro) on 2019/10/23. // Copyright © 2019 macro. All rights reserved. // #import <ZQFoundation/ZQFoundation.h> NS_ASSUME_NONNULL_BEGIN @interface tableVC : BaseTableViewController @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
ZQUIKit/ZQTableViewController/ViewAdaptor/BaseTableViewAdaptor.h
<filename>ZQUIKit/ZQTableViewController/ViewAdaptor/BaseTableViewAdaptor.h // // BaseTableViewAdaptor.h // MJRefresh // // Created by macro on 2019/9/6. // #if __has_include(<MJRefresh/MJRefresh.h>) #import <MJRefresh/MJRefresh.h> #else #import "MJRefresh.h" #endif #import <Foundation/Foundation.h> #import "BaseModel.h" typedef NS_ENUM(NSInteger, ZQTableViewRefreshType){ ZQTableViewRefreshTypePullDown = 1, //下拉 ZQTableViewRefreshTypePullUp , //上拉 }; NS_ASSUME_NONNULL_BEGIN @protocol BaseTableViewAdaptorDelegate <UITableViewDelegate,UIScrollViewDelegate> @optional //选中 cell 后调用 - (void)tableView:(UITableView *)tableView didSelectObject:(id<CellModelBasicProtocol>)object atIndexPath:(NSIndexPath *)indexPath; //对cell设置数据源之后调用 - (void)tableView:(UITableView *)tableView didSetObject:(id<CellModelBasicProtocol>)object cell:(UITableViewCell *)cell; // 下拉刷新回调 - (void)refreshReload:(ZQTableViewRefreshType)pullType; //是否可以编辑cell - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath; //设置tablview编辑样式 - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath; //处理编辑事件 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath; //设置左滑删除标题 - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath; @end @interface BaseTableViewAdaptor : NSObject <UITableViewDelegate, UITableViewDataSource> @property (nonatomic, strong) MJRefreshNormalHeader *mjHeader;//mj下拉刷新控件 @property (nonatomic, strong) MJRefreshBackNormalFooter *mjFooter;//mj上拉加载 @property (nonatomic, weak) id<BaseTableViewAdaptorDelegate> delegate; @property (nonatomic, weak) UITableView *tableView; //数据源 @property (nonatomic, strong) NSMutableArray *items; //是否开启下拉刷新 @property (nonatomic, assign) BOOL pullRefreshEnable; //是否开启上拉加载 @property (nonatomic, assign) BOOL loadMoreEnable; @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
ZQUIKit/ZQBaseViewModel/BaseViewModel.h
<reponame>kelvin943/ZQFoundation<filename>ZQUIKit/ZQBaseViewModel/BaseViewModel.h // // BaseViewModel.h // Pods // // Created by 张泉(macro) on 2019/9/10. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface BaseViewModel : NSObject @end @interface BaseTableViewModel : BaseViewModel @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
ZQCommon/Macro/ZQMacros.h
// // ZQMacros.h // ZQDemoApp // // Created by Macro on 2017/11/14. // Copyright © 2017年 Macro. All rights reserved. // #ifndef ZQMacros_h #define ZQMacros_h #pragma mark - Print #ifdef DEBUG //print #define ZQPrint(format, ...) do { \ fprintf(stderr, "===============================================\n",\ [format UTF8String]);\ fprintf(stderr, "%s【第%d行】%s\n",\ [[[NSString stringWithUTF8String:__FILE__]lastPathComponent]\ UTF8String],__LINE__,__FUNCTION__);\ fprintf(stderr,"%s\n",[[NSString stringWithFormat: format, ## __VA_ARGS__] \ UTF8String]);\ fprintf(stderr, "===============================================\n");\ } while (0) //nslog #define ZQLog(...) NSLog(@"\n=============================================== \n%s【第%d行】\n %@\n===============================================\n",__func__,__LINE__,\ [NSString stringWithFormat:__VA_ARGS__]) #else #define ZQPrint(format, ...) #define ZQLog(...) #endif //打印尺寸 #define LogRect(rect) ZQLog(@"%@", NSStringFromCGRect(rect)); #define ZQLogRect(rect,...) NSLog(@"%@:%@", [NSString stringWithFormat:__VA_ARGS__],NSStringFromCGRect(rect)); #define ZQLogSize(size,...) NSLog(@"%@:%@", [NSString stringWithFormat:__VA_ARGS__],NSStringFromCGSize(size)); #define LogSize(size) ZQLog(@"%@", NSStringFromCGSize(size)); #define LogPoint(point) ZQLog(@"%@", NSStringFromCGPoint(point)); //打印宏展开,展开顺序为先完全展开宏参数,再扫描宏展开后里面的宏 //如果宏内容中含有#和##这两个符号的时候,参数不会被先展开 #define __toString(x) __toString_0(x) #define __toString_0(x) #x #define ZQLogMacro(x) ZQLog(@"%s=\n%s", #x, __toString(x)) //打印代码执行时间,查看执行次数用条件断点 : 执行次数%H //#define TICK CFAbsoluteTime start = CFAbsoluteTimeGetCurrent(); //#define TOCK NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start) #define TICK NSDate *startTime = [NSDate date] #define TOCK NSLog(@"Time: %f", -[startTime timeIntervalSinceNow]) #define START_COUNT_TIME(start) clock_t start = clock() #define END_COUNT_TIME(start) (clock() - start) #pragma mark - Sandbox //获取app主目录 #define kPathAppHome NSHomeDirectory() //获取temp #define kPathTemp NSTemporaryDirectory() //获取沙盒 Document #define kPathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] //获取沙盒 Cache #define kPathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] #pragma mark - GCD //一次性执行 #define GCDOnceBlock(onceBlock)\ static dispatch_once_t onceToken;\ dispatch_once(&onceToken, onceBlock); //在主线程执行 #define dispatch_safe_async_main(block)\ if ([NSThread isMainThread]){\ block();\ }else{\ dispatch_async(dispatch_get_main_queue(), block);\ } //开启异步线程执行 #define dispatch_async_global(block)\ dispatch_async(dispatch_get_global_queue\ (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),\ block); //block 安全执行 #define exec_block(block, ...)\ if (block) { block(__VA_ARGS__); } #pragma mark - NSNotification #define ZQNoticeOnce(_name_,_block_) \ __block id observer = \ [[NSNotificationCenter defaultCenter] \ addObserverForName:_name_ \ object:nil \ queue:nil \ usingBlock:_block_] /* user the follow code NoticeOnce(UIApplicationDidFinishLaunchingNotification, ^(NSNotification *note){ // Do whatever you want [[NSNotificationCenter defaultCenter] removeObserver:observer]; }); */ #pragma mark - Fetch System signton #define ZQShareAppDelegate ((AppDelegate *)[UIApplication sharedApplication].delegate) #define ZQShareWindow [[UIApplication sharedApplication].delegate window] #define ZQShareKeyWindow [UIApplication sharedApplication].keyWindow #define ZQShareUserDefault [NSUserDefaults standardUserDefaults] //获取图片资源 #define ZQGetLocalImage(imageName) [UIImage imageNamed:[NSString stringWithFormat:@"%@",imageName]] //获取当前语言 #define ZQCurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0]) //取消键盘响应 #define ZQHideKeyboard [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];[ZQShareKeyWindow endEditing:YES]; #pragma mark - UIApplicationInfo #define ZQAppName [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"] #define ZQAppBundleID [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"] #define ZQAPPVersion [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] #define ZQAppBulidVersion [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] #pragma mark - Screen #define ZQScreenFrame [UIScreen mainScreen].bounds #define ZQScreenWidth [UIScreen mainScreen].bounds.size.width #define ZQScreenHeight [UIScreen mainScreen].bounds.size.height #define ZQScreenSize [UIScreen mainScreen].bounds.size //状态栏frame #define ZQStatusbarRect [[UIApplication sharedApplication] statusBarFrame] //状态栏高度(刘海屏:44 含 X/XS/XR/XS_MAX,非刘海屏:20) #define ZQStatusBarH ZQStatusbarRect.size.height //导航栏目高度(含状态栏) #define ZQNavBarHeight (ZQStatusBarH + 44) //底部安全区外高度 #define ZQBottomGestureAreaHeight (ZQStatusBarH > 20 ? 34:0) //标签bar 高度 #define ZQTabBarHeight (ZQBottomGestureAreaHeight + 49) //默认的cell高度 #define ZQCellDefaultHeight (44.f) //英文键盘高度 #define ZQEnglishKeyboardHeight (216.f) //中文键盘高度 #define ZQChineseKeyboardHeight (252.f) //需要横屏或者竖屏,获取屏幕宽度与高度 //#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 // 当前Xcode支持iOS8及以上 // //#define SCREEN_WIDTH ([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)]?[UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale:[UIScreen mainScreen].bounds.size.width) //#define SCREENH_HEIGHT ([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)]?[UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale:[UIScreen mainScreen].bounds.size.height) //#define SCREEN_SIZE ([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)]?CGSizeMake([UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale,[UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale):[UIScreen mainScreen].bounds.size) //#else //#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width //#define SCREENH_HEIGHT [UIScreen mainScreen].bounds.size.height //#define SCREEN_SIZE [UIScreen mainScreen].bounds.size //#endif //#pragma mark - /**************** Clang 宏定义警告消除****************/ // #define ArgumentToString(macro) #macro // #define ClangWarningConcat(warning_name) ArgumentToString(clang diagnostic ignored warning_name) // // 参数可直接传入 clang 的 warning 名,warning 列表参考: http:/fuckingclangwarnings.com/ // #define BeginIgnoreClangWarning(warningName) _Pragma("clang diagnostic push") _Pragma(ClangWarningConcat(#warningName)) // #define EndIgnoreClangWarning _Pragma("clang diagnostic pop") // // #define BeginIgnorePerformSelectorLeaksWarning BeginIgnoreClangWarning(-Warc-performSelector-leaks) // #define EndIgnorePerformSelectorLeaksWarning EndIgnoreClangWarning // // #define BeginIgnoreAvailabilityWarning BeginIgnoreClangWarning(-Wpartial-availability) // #define EndIgnoreAvailabilityWarning EndIgnoreClangWarning // // #define BeginIgnoreDeprecatedWarning BeginIgnoreClangWarning(-Wdeprecated-declarations) // #define EndIgnoreDeprecatedWarning EndIgnoreClangWarning #pragma mark - Font #define PFRegularFont(fontSize) [UIFont fontWithName:@"PingFangSC-Regular" size:fontSize] #define PFMediumFont(fontSize) [UIFont fontWithName:@"PingFangSC-Medium" size:fontSize] #define PFSemiboldFont(fontSize) [UIFont fontWithName:@"PingFangSC-Semibold" size:fontSize] #define PFLightFont(fontSize) [UIFont fontWithName:@"PingFangSC-Light" size:fontSize] #define ZQCustomFont(fontName,fontSize) [UIFont fontWithName:fontName size:fontSize] #define ZQSystemFont(fontSize) [UIFont systemFontOfSize:fontSize] #pragma mark - 判断设备 /* #if TARGET_OS_IPHONE //真机 #endif #if TARGET_IPHONE_SIMULATOR //模拟器 #endif */ //判断是否为iPhone #define ZQ_ISiPhone (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) //判断是否为iPad #define ZQ_ISiPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) #pragma mark - 判断机型 //iphone5、iphoneSE 逻辑像是320:568 @2x #define ZQ_IPHONE5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO) //iphone6、iphone6s、iphone7、iphone8 逻辑像素375:667 @2x #define ZQ_IPHONE6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO) //iphone6p、iphone7p、iphone8p 逻辑像素 414:736 @3x #define ZQ_IPHONE6P ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO) //iphonex、iphonexs 逻辑像素 375:812 @3x #define ZQ_IPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO) //iphonexr 逻辑像素 414:896 @2x #define ZQ_IPhoneXR ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(828, 1792), [[UIScreen mainScreen] currentMode].size) : NO) //iphonexs max 逻辑像素 414:896 @3x #define ZQ_IPhoneXS_Max ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size) : NO) //判断是否是刘海屏幕 #define ZQ_IPHONEX ((StatusBarH > 20) ? YES : NO) #pragma mark - 判断系统版本 #define IOS9_OrLater [[[UIDevice currentDevice] systemVersion] doubleValue] >= 9.0 #define IOS10_OrLater [[[UIDevice currentDevice] systemVersion] doubleValue] >= 10.0 #define IOS11_OrLater [[[UIDevice currentDevice] systemVersion] doubleValue] >= 11.0 #define IOS12_OrLater [[[UIDevice currentDevice] systemVersion] doubleValue] >= 12.0 #define IOS13_OrLater [[[UIDevice currentDevice] systemVersion] doubleValue] >= 13.0 #define IOS_8 ([[[UIDevice currentDevice] systemVersion] doubleValue]>=8.0 \ && [[[UIDevice currentDevice] systemVersion] doubleValue]<9.0) #define IOS_9 ([[[UIDevice currentDevice] systemVersion] doubleValue]>=9.0 \ && [[[UIDevice currentDevice] systemVersion] doubleValue]<10.0) #define IOS_10 ([[[UIDevice currentDevice] systemVersion] doubleValue]>=10.0 \ && [[[UIDevice currentDevice] systemVersion] doubleValue]<11.0) #define IOS_11 ([[[UIDevice currentDevice] systemVersion] doubleValue]>=11.0 \ && [[[UIDevice currentDevice] systemVersion] doubleValue]<12.0) #define IOS_12 ([[[UIDevice currentDevice] systemVersion] doubleValue]>=12.0 \ && [[[UIDevice currentDevice] systemVersion] doubleValue]<13.0) #pragma mark - static library bug /*Add this macro before each category implementation, so we don't have to use -all_load or -force_load to load object files from static libraries that only contain categories and no classes. More info: http://developer.apple.com/library/mac/#qa/qa2006/qa1490.html .*/ #ifndef ZQCATEGORY_DUMMY_CLASS #define ZQCATEGORY_DUMMY_CLASS(_name_) \ @interface ZQCATEGORY_DUMMY_CLASS ## _name_ : NSObject @end \ @implementation ZQCATEGORY_DUMMY_CLASS ## _name_ @end #endif #endif /* ZQMacros_h */
kelvin943/ZQFoundation
ZQCommon/ZQCommon.h
// // ZQCommon.h // ZQDemoApp // // Created by Macro on 2018/8/17. // Copyright © 2018年 Macro. All rights reserved. // #if __has_include(<ZQFoundation/ZQCommon.h>) //Macrpo #import <ZQFoundation/ZQMacros.h> #import <ZQFoundation/ZQSingleton.h> //UI #import <ZQFoundation/UIButton+ZQAdd.h> #import <ZQFoundation/UIView+ZQExten.h> #import <ZQFoundation/UIViewController+ZQAdd.h> #import <ZQFoundation/UITableView+ZQAdd.h> //Other #import <ZQFoundation/NSArray+ZQAdd.h> #import <ZQFoundation/NSDictionary+ZQAdd.h> #import <ZQFoundation/NSObject+ZQAdd.h> #import <ZQFoundation/NSString+ZQAdd.h> #import <ZQFoundation/NSTimer+ZQBlock.h> #import <ZQFoundation/UIColor+ZQAdd.h> #import <ZQFoundation/UIImage+ZQAdd.h> #else //Macrpo #import "ZQMacros.h" #import "ZQSingleton.h" //UI #import "UIButton+ZQAdd.h" #import "UIView+ZQExten.h" #import "UIViewController+ZQAdd.h" #import "UITableView+ZQAdd.h" //0ther #import "NSArray+ZQAdd.h" #import "NSDictionary+ZQAdd.h" #import "NSObject+ZQAdd.h" #import "NSString+ZQAdd.h" #import "NSTimer+ZQBlock.h" #import "UIColor+ZQAdd.h" #import "UIImage+ZQAdd.h" #endif
kelvin943/ZQFoundation
ZQCommon/Category/View/UITableView+ZQAdd.h
<filename>ZQCommon/Category/View/UITableView+ZQAdd.h<gh_stars>1-10 // // UITableView+ZQAdd.h // ZQFoundation // // Created by 张泉(macro) on 2019/9/25. // 零行代码为 tableview 添加空数据加载占位图 #import <UIKit/UIKit.h> @interface UITableView (ZQEmptyData) @property (nonatomic, assign) BOOL firstReload; //是否第一次加载 @property (nonatomic, assign) BOOL isShowEmpty; //reload 时是否展示空数据占位图 @property (nonatomic, copy) void(^reloadBlock)(void);//空白页点击事件 @end @interface UICollectionView (ZQEmptyData) @property (nonatomic, assign) BOOL firstReload; @property (nonatomic, assign) BOOL isShowEmpty; //reload 时是否展示空数据占位图 @property (nonatomic, copy) void(^reloadBlock)(void); @end
kelvin943/ZQFoundation
Example/ZQFoundation/TestVC.h
<filename>Example/ZQFoundation/TestVC.h // // TestVC.h // ZQFoundation_Example // // Created by 张泉(Macro) on 2019/10/17. // Copyright © 2019 macro. All rights reserved. // #import <ZQFoundation/ZQFoundation.h> NS_ASSUME_NONNULL_BEGIN @interface TestVC : BaseViewController @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
Example/ZQFoundation/ZQAppDelegate.h
<filename>Example/ZQFoundation/ZQAppDelegate.h // // ZQAppDelegate.h // ZQFoundation // // Created by macro on 11/15/2018. // Copyright (c) 2018 macro. All rights reserved. // @import UIKit; @interface ZQAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
kelvin943/ZQFoundation
ZQUIKit/ZQPageViewController/ZQPageViewController.h
<gh_stars>1-10 // // ZQPageViewController.h // ZQFoundation // // Created by 张泉(Macro) on 2019/10/18. // /** used self.pageVC = [[ZQPageViewController alloc ] init]; [self.view addSubview:self.pageVC.view]; { UIViewController * tempVC = [[UIViewController alloc] init]; tempVC.view.backgroundColor = ZQRandomColor; [self.pageVC addChildViewController:tempVC]; } { UIViewController * tempVC = [[UIViewController alloc] init]; tempVC.view.backgroundColor = ZQRandomColor; [self.pageVC addChildViewController:tempVC]; } { UIViewController * tempVC = [[UIViewController alloc] init]; tempVC.view.backgroundColor = ZQRandomColor; [self.pageVC addChildViewController:tempVC]; } [self.pageVC reladPages]; */ #import "BaseViewController.h" @class ZQPageViewController; @protocol ZQPageViewControllerDelegate <NSObject> @optional - (void)pageViewController:(ZQPageViewController*)pageViewController didScrolledXPercetage:(CGFloat)XPercetage; @end NS_ASSUME_NONNULL_BEGIN @interface ZQPageCollectionCell : UICollectionViewCell @property (nonatomic, weak) __kindof UIViewController *viewController; + (NSString *)reuseIdentifier; - (void)addChildViewIfNeeded; @end @interface ZQPageViewController : BaseViewController // Page VC 滚动的区域,默认全屏滚动 @property (nonatomic, assign) UIEdgeInsets pageContetnInset; @property (nonatomic, weak) id<ZQPageViewControllerDelegate> delegate; - (void)reloadPages; @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
ZQCommon/Category/Other/NSDictionary+ZQAdd.h
// // NSDictionary+ZQAdd.h // ZQFoundation // // Created by macro on 2019/9/11. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface NSDictionary (ZQSafe) - (NSString*)stringObjectForKey:(id)aKey; - (int)intValueForKey:(id)aKey; - (float)floatValueForKey:(id)aKey; - (double)doubleValueForKey:(id)aKey; - (long) longValueForKey:(id) aKey; - (BOOL)boolValueForKey:(id)aKey; - (long long) longLongValueForKey:(id) aKey; - (unsigned long long) unsignedLongLongValueForKey:(id) aKey; - (NSUInteger)unsignedIntegerValueForKey:(id) aKey; - (nullable NSArray*)arrayObjectForKey:(id)aKey; - (nullable NSDictionary*)dictionaryObjectForKey:(id)aKey; - (nullable id)myObjectForKey:(id)aKey; @end @interface NSDictionary (ZQTraversing) - (void)each:(void (^)(id k, id v))block; - (void)eachKey:(void (^)(id k))block; - (void)eachValue:(void (^)(id v))block; @end NS_ASSUME_NONNULL_END
kelvin943/ZQFoundation
ZQCommon/Macro/ZQSingleton.h
// // ZQSingleton.h // ZQCustomView // // Created by Macro on 16/8/29. // Copyright © 2016年 Macro. All rights reserved. // //单例宏 #ifndef ZQSingleton_h #define ZQSingleton_h // .h文件 #define ZQSingletonH(name) \ + (instancetype)shared##name; // .m文件 #define ZQSingletonM(name) \ static id _instance; \ \ + (instancetype)allocWithZone:(struct _NSZone *)zone \ { \ static dispatch_once_t onceToken; \ dispatch_once(&onceToken, ^{ \ _instance = [super allocWithZone:zone]; \ }); \ return _instance; \ } \ \ + (instancetype)shared##name \ { \ static dispatch_once_t onceToken; \ dispatch_once(&onceToken, ^{ \ _instance = [[self alloc] init]; \ }); \ return _instance; \ } \ \ - (id)copyWithZone:(NSZone *)zone \ { \ return _instance; \ }\ \ -(id)mutableCopyWithZone:(NSZone *)zone\ {\ return _instance;\ } #endif /* ZQSingleton_h */
kelvin943/ZQFoundation
ZQUIKit/ZQUIKit.h
<filename>ZQUIKit/ZQUIKit.h // // ZQUIKit.h // ZQFoundation // // Created by Macro on 2019/9/11. // #if __has_include(<ZQFoundation/ZQUIKit.h>) #import <ZQFoundation/ZQToastUtil.h> #import <ZQFoundation/ZQSegmentView.h> #import <ZQFoundation/BaseModel.h> #import <ZQFoundation/BaseViewModel.h> #import <ZQFoundation/BaseTabBarVC.h> #import <ZQFoundation/BaseViewController.h> #import <ZQFoundation/BaseTableViewController.h> #import <ZQFoundation/BaseTableViewCell.h> #import <ZQFoundation/BaseTableViewAdaptor.h> #import <ZQFoundation/UIViewController+ZQCustomizeNavBar.h> #import <ZQFoundation/ZQBookViewController.h> #import <ZQFoundation/ZQPageViewController.h> #import <ZQFoundation/HoverTableViewController.h> #else #import "ZQToastUtil.h" #import "ZQSegmentView.h" #import "BaseModel.h" #import "BaseViewModel.h" #import "BaseTabBarVC.h" #import "BaseViewController.h" #import "BaseTableViewController.h" #import "BaseTableViewCell.h" #import "BaseTableViewAdaptor.h" #import "UIViewController+ZQCustomizeNavBar.h" #import "ZQBookViewController.h" #import "ZQPageViewController.h" #import "HoverTableViewController.h" #endif