repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
393385724/DDMISDKDemo
|
DDMISDK/DDMIAuthViewController.h
|
//
// DDMIAuthViewController.h
// HMLoginDemo
//
// Created by lilingang on 15/8/4.
// Copyright (c) 2015年 lilingang. All rights reserved.
//
#import "DDMIBaseViewController.h"
@class DDMIAuthViewController;
@protocol DDMIAuthViewControllerDelegate <NSObject>
- (void)authViewController:(DDMIAuthViewController *)viewController successWithResponse:(NSDictionary *)response;
- (void)authViewController:(DDMIAuthViewController *)viewController failedWithError:(NSError *)error;
- (void)authViewControllerSwitchLogin;
@end
@interface DDMIAuthViewController : DDMIBaseViewController
@property (nonatomic, weak) id<DDMIAuthViewControllerDelegate> delegate;
@property (nonatomic, assign) DDMIAuthResponseType responseType;
- (instancetype)initWithAppid:(NSString *)appID redirectUrl:(NSString *)redirectUrl;
@end
|
393385724/DDMISDKDemo
|
DDMISDK/DDMIDefines.h
|
<filename>DDMISDK/DDMIDefines.h
//
// DDMIDefines.h
// MDLoginSDK
//
// Created by lilingang on 16/1/19.
// Copyright © 2016年 LiLingang. All rights reserved.
//
#ifndef DDMIDefines_h
#define DDMIDefines_h
#ifndef MIResourceBundlePath
#define MIResourceBundlePath \
[[NSBundle mainBundle] pathForResource: @ "DDMIResource" ofType :@ "bundle"]
#endif
#ifndef MIResourceBundle
#define MIResourceBundle \
[NSBundle bundleWithPath:MIResourceBundlePath]
#endif
#ifndef MILocal
#define MILocal(s) \
[MIResourceBundle localizedStringForKey:s value:s table:@"DDMILocalizable"]
#endif
#ifndef MIImage
#define MIImage(s) \
[UIImage imageWithContentsOfFile:[MIResourceBundlePath stringByAppendingPathComponent:s]]
#endif
#endif /* DDMIDefines_h */
|
393385724/DDMISDKDemo
|
DDMISDK/DDMIHandler.h
|
//
// DDMIHandler.h
// HMLoginDemo
//
// Created by lilingang on 15/8/3.
// Copyright (c) 2015年 lilingang. All rights reserved.
//
/// info.plist 配置 CFBundleURLName为xiaomi
#import <Foundation/Foundation.h>
#import "DDMIUserInfoItem.h"
#import "DDMITypeDefines.h"
@class UIViewController;
typedef NS_ENUM(NSUInteger, DDMIAuthState) {
DDMIAuthStateBegan = 0, /**< 开始 */
DDMIAuthStateSuccess, /**< 成功 */
DDMIAuthStateFail, /**< 失败 */
DDMIAuthStateCancel, /**< 取消 */
};
typedef void(^DDMIAuthEventHandler) (DDMIAuthState state, NSDictionary *response, NSError *error);
typedef void(^DDMIGetProfielEventHandler) (DDMIUserInfoItem *userInfoItem, NSError *error);
@interface DDMIHandler : NSObject
/**
* @brief 向小米终端程序注册第三方应用
*
* @param appid 小米开发者ID
* @param redirectURL 微博开放平台第三方应用授权回调页地址
*
* @return YES ? 成功 : 失败
*/
- (BOOL)registerApp:(NSString *)appid withRedirectURL:(NSString *)redirectURL;
/**
* @brief 小米账号授权
*
* @param type 授权的形式
* @param viewController 当前ViewController
* @param handler 回调方法
*
* @return YES ? 唤起成功 : 唤起失败
*/
- (BOOL)authWithType:(DDMIAuthResponseType)type
controller:(UIViewController *)viewController
handler:(DDMIAuthEventHandler)handler;
/**
* @brief 获取用户信息
*
* @param accessToken 授权获取的accessToken
* @param handler 回调
*
* @return YES ? 唤起成功 : 唤起失败
*/
- (BOOL)getProfileInfoWithAccessToken:(NSString *)accessToken handler:(DDMIGetProfielEventHandler)handler;
@end
|
393385724/DDMISDKDemo
|
DDMISDK/DDMITypeDefines.h
|
//
// DDMITypeDefines.h
// DDMISDKDemo
//
// Created by lilingang on 16/2/29.
// Copyright © 2016年 LiLingang. All rights reserved.
//
#ifndef DDMITypeDefines_h
#define DDMITypeDefines_h
typedef NS_ENUM(NSUInteger, DDMIAuthResponseType) {
DDMIAuthResponseTypeCode, //Authorization Code Flow
DDMIAuthResponseTypeToken, //Implicit Flow
};
#endif /* DDMITypeDefines_h */
|
393385724/DDMISDKDemo
|
DDMISDK/XMPassport.framework/Headers/MPWebViewController.h
|
//
// MPWebViewController.h
// MiPassportFoundation
//
// Created by <NAME> on 13-11-28.
// Copyright (c) 2013年 Xiaomi. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol MPWebViewControllerDelegate;
@interface MPWebViewController : UIViewController
{
UIWebView *webView;
UIButton *closeButton;
UIActivityIndicatorView *indicatorView;
}
@property (nonatomic, weak) id<MPWebViewControllerDelegate> delegate;
- (id)initWithURL:(NSString*) loginURL
authParams:(NSDictionary *)params
cookies:(NSArray *)cookies
redirectURI:(NSString *)redirectURI
delegate:(id<MPWebViewControllerDelegate>)delegate;
- (void)show;
- (void)hide;
@end
@protocol MPWebViewControllerDelegate <NSObject>
- (void)webViewController:(MPWebViewController *)webViewController didRecieveAuthorizationInfo:(NSDictionary *)authorizeInfo;
- (void)webViewController:(MPWebViewController *)webViewController didFailWithError:(NSError *)error;
- (void)webViewControllerDidCancel:(MPWebViewController *)webViewController;
@end
|
mateusfgomes/ICC
|
Trabalho4.c
|
#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
Nº USP: 10734773
Instituto de Ciencias Matematicas e de Computacao - Universidade de Sao Paulo
Trabalho 4
Programa que calcula se ha' ou nao interseccao entre dois planos, duas retas ou plano e reta dadas suas equacoes,
alem disso imprime a matriz escalonada que auxilia a chegar a conclusao.
*/
//Definindo a struct do pivo(numero do canto superior esquerdo, que se altera conforme a recursao),
//com "a" como numerador e "b" como denominador, essa ultima logica vale para o trabalho todo.
typedef struct pivo{
int a;
int b;
}pivo;
//struct para pegar os coeficientes (a, b, c, d) das equacoes. Sendo "a", o numerador, e "b" o denominador desses numeros.
typedef struct fracao{
int a;
int b;
}fracao;
//struct para repor a primeira linha da matriz quando ela for escalonada, pois escalonamos tudo na mesma
typedef struct salvar{
int a;
int b;
}salvar;
//funcao swap() para trocar as linhas da matriz caso necessario, numero a numero
void swap(int* a0, int* a1, int* b0, int* b1){
//variavel temporaria para auxiliar na troca de numeros
int temp;
temp = *a0;
*a0 = *a1;
*a1 = temp;
temp = *b0;
*b0 = *b1;
*b1 = temp;
}
//para auxiliar a funcao mmc abaixo com a mudanca de denominador
void swap_den(int* a, int* b){
int prov;
prov = *a;
*a = *b;
*b = prov;
}
//funcao para calcular o mmc dos denominadores de modo a subtrair os numeros
int mmc (int a, int b){
//zerando o mmc
int mmc = 0;
//criando uma variavel temporaria para auxiliar no calculo
int temp2;
//inversao para facilitar
if(b > a){
swap_den(&a, &b);
}
//se forem multiplos, o mmc e' o maior
if(a % b == 0){
mmc = a;
return mmc;
}
//se nao forem, procura o mmc
for (int i = 2; i <= b; i++){
temp2 = a*i;
if (temp2 % b == 0){
mmc = temp2;
}
}
return mmc;
}
//funcao recursiva para realizar o escalonamento da matriz
void escalonamento(int linha, int coluna, fracao** coords, int linha_inicial, int coluna_inicial){
//inicializando o mmc
int minimo = 0;
//checando as condicoes para executar a funcao
if ((coluna_inicial < 3) && (linha_inicial < linha-1)){
for (int i = (linha_inicial+1); i < linha; i++){
//checando se e' necessario realizar o swap (p/ tornar o pivo != 0), se for, entra
if (coords[linha_inicial][coluna_inicial].a == 0 && coords[i][coluna_inicial].a != 0){
//realizando troca numero a numero
for(int j = coluna_inicial; j < coluna; j++)
swap(&coords[linha_inicial][j].a, &coords[i][j].a, &coords[linha_inicial][j].b, &coords[i][j].b);
}
}
pivo pivo;//declarando a variavel pivo numa struct
//recebendo os numeros do pivo
pivo.a = coords[linha_inicial][coluna_inicial].a;
pivo.b = coords[linha_inicial][coluna_inicial].b;
//declarando a variavel para salvar a linha inicial antes de fazer o escalonamento
salvar salvar[4];
//salvando a linha inicial
for (int j = coluna_inicial; j < coluna; j++){
salvar[j].a = coords[linha_inicial][j].a;
salvar[j].b = coords[linha_inicial][j].b;
}
//realizando o calculo do numero a ser colocado na matriz em escalonamento
for (int i = linha_inicial+1; i < linha; i++){
//declarando a variavel que realiza o calculo da parte de multiplicacao
int multiplicador_a = (coords[i][coluna_inicial].a * pivo.b);
int multiplicador_b = (coords[i][coluna_inicial].b * pivo.a);
for (int j = coluna_inicial; j < coluna; j++){
//multiplicando a linha inicial
coords[linha_inicial][j].a = coords[linha_inicial][j].a * multiplicador_a;
coords[linha_inicial][j].b = coords[linha_inicial][j].b * multiplicador_b;
//fazendo o calculo do mmc
minimo = mmc(coords[linha_inicial][j].b, coords[i][j].b);
//fazendo a conta do numerador
coords[linha_inicial][j].a = (minimo/coords[linha_inicial][j].b) * coords[linha_inicial][j].a;
coords[i][j].a = (minimo/coords[i][j].b) * coords[i][j].a;
//recebendo o denominador com o mmc
coords[i][j].b = minimo;
coords[linha_inicial][j].b = minimo;
//com o mesmo denominador, fazendo a subtracao do numerador
coords[i][j].a = coords[i][j].a - coords[linha_inicial][j].a;
//recolocando as linhas iniciais
coords[linha_inicial][j].a = salvar[j].a;
coords[linha_inicial][j].b = salvar[j].b;
}
}
//verificando se os objetos se intersectam
for (int i = 0; i < linha; i++){
if (coords[i][0].a == 0 && coords[i][1].a == 0 && coords[i][2].a == 0 && coords[i][3].a != 0){
printf("nao\n");
return;
}
}
//realizando a recursao
escalonamento(linha, coluna, coords, linha_inicial+1, coluna_inicial+1);
}
//caso a recursao chegue ao final e nao ha' a = b = c = 0 e d != 0, logo se intersectam
else{
printf("sim\n");
return;
}
}
int main(void){
int linha, coluna;//linhas da matriz
char tipo1, tipo2;//usadas para ver se e' reta ou plano
fracao** coords;//declarando uma matriz de struct
int linha_inicial = 0;//linha que vai comecar a realizar o escalonamento
int coluna_inicial = 0;//coluna que vai comecar a realizar o escalonamento
//escaneando linha e coluna da matriz
scanf("%d%d", &linha, &coluna);
//verificando se o tipo 1 e' plano ou reta
scanf(" %c", &tipo1);
//alocando a matriz de struct na heap
coords = (fracao**) malloc (linha* sizeof(fracao*));
for (int i = 0; i < linha; i++){
coords[i] = (fracao*) malloc ((coluna) * sizeof(fracao));
}
//se for reta, entra para escanear as coordenadas
if (tipo1 == 'r'){
for (int i = 0; i < 2; i++){
for (int j = 0; j < (coluna); j++){
scanf("%d%d", &coords[i][j].a, &coords[i][j].b);
}
}
}
//se for plano, entra aqui para escanear as coordenadas
else if(tipo1 == 'p'){
for (int j = 0; j < (coluna); j++){
scanf("%d%d", &coords[0][j].a, &coords[0][j].b);
}
}
//verificando se o tipo 2 e' reta ou plano
scanf(" %c", &tipo2);
//se o tipo 1 for reta e o 2 tb, entra para escanear as coordenadas do tipo 2
if (tipo2 == 'r' && tipo1 == 'r'){
for (int i = 2; i < 4; i++){
for (int j = 0; j < (coluna); j++){
scanf("%d%d", &coords[i][j].a, &coords[i][j].b);
}
}
}
//se o tipo 1 for plano e o tipo 2 tb, entra para escanear as coordenadas do tipo 2
else if(tipo2 == 'p' && tipo1 == 'p'){
for (int j = 0; j < (coluna); j++){
scanf("%d%d", &coords[1][j].a, &coords[1][j].b);
}
}
//se o tipo 1 for reta e o 2 for plano, entra para escanear as coordenadas do tipo 2
else if(tipo1 == 'r' && tipo2 == 'p'){
for (int j = 0; j < (coluna); j++){
scanf("%d%d", &coords[2][j].a, &coords[2][j].b);
}
}
//se o tipo 1 for plano e o tipo 2 reta, entra para escanear as coordenadas do tipo 2
else if(tipo1 == 'p' && tipo2 == 'r'){
for (int i = 1; i < 3; i++){
for (int j = 0; j < (coluna); j++){
scanf("%d%d", &coords[i][j].a, &coords[i][j].b);
}
}
}
//chamando a funcao para escalonar a matriz escaneada
escalonamento(linha, coluna, coords, linha_inicial, coluna_inicial);
//printando a matriz escalonada com simplificacoes
for (int i = 0; i < linha; i++){
for (int j = 0; j < (coluna); j++){
//se a divisao resultar denominador 1, divide
if (coords[i][j].a % coords[i][j].b == 0){
coords[i][j].a = coords[i][j].a/coords[i][j].b;
coords[i][j].b = coords[i][j].b/coords[i][j].b;
printf("%d\t", coords[i][j].a);
}
//se nao, so' printa
else{
printf("%d/%d\t", coords[i][j].a, coords[i][j].b);
}
}
printf("\n");
}
//liberando a memoria alocada na heap
for (int i = 0; i < linha; i++){
free(coords[i]);
}
free(coords);
return 0;
}
|
mateusfgomes/ICC
|
Trabalho2.c
|
<filename>Trabalho2.c
#include <stdio.h>
#include <math.h>
int main(void){
int n;//n -> numero de usuarios da base de dados
int i;// i -> o numero de itens da base de dados
double t;// t -> o limiar de itens da base de dados
scanf("%d ", &n);
scanf("%d ", &i);
scanf("%lf", &t);
int k,f,g,y;
int usuario1, usuario2;
int contadornotas[n]; //conta quantos notas ao usuario ja foram atribuidas
int mat[n][i];//tabela de usuario x item
int contadordezeros[n]; //conta zeros
int contadordesconhecidos;
int contador_DI;
double nota[n];
double sim[n][n];// matriz de similaridades
double media_do_usuario[n];//vetor de media de todas as notas de cada usuario
double pseudonota;
double soma;
double media;//numerador da média
double contadorzero;//denominador da média
//inicializando matriz de similaridade
for (k = 0; k < n; k++){
for (y = 0; y < i; y++){
sim[k][y] = 0;
}
}
//inicializando o vetor que conta os zeros
for(y = 0; y < n; y++){
contadordezeros[y] = 0;
}
//inicializando o vetor de medias de todos os filmes de cada usuario
for(y = 0; y < i; y++){
media_do_usuario[y] = 0;
}
//leitura matriz usuario x item
for (k = 0; k < n; k++){
for (f = 0; f < i; f++){
scanf("%d", &mat[k][f]);
}
}
//inicializando o vetor que conta os usuarios que ja tem notas
for(y = 0; y < n; y++){
contadornotas[y] = 0;
}
//similaridade entre dois usuarios
for (usuario1 = 0; usuario1 < n; usuario1++){
for (usuario2 = 0; usuario2 < n; usuario2++){
if (usuario1 != usuario2){
int cima = 0;//numerador u.v
double b0 = 0;//denominador 1 ||u||
double b1 = 0;//denominador 2 ||v||
for(f = 0; f < i; f++){
cima = cima + (mat[usuario1][f] * mat[usuario2][f]);
}
for(f = 0; f < i; f++){
b0 = b0 + (mat[usuario1][f] * mat[usuario1][f]);
}
for(f = 0; f < i; f++){
b1 = b1 + (mat[usuario2][f] * mat[usuario2][f]);
}
//cos(u,v) = (u.v)/ (||u|| . ||v||)
sim[usuario1][usuario2] = (cima) / (sqrt(b0) * sqrt(b1));
}
}
}
media = 0;//numerador da média
contadorzero = 0;//denominador da média
//percorre as notas de cada usuario e faz a media delas
for(k = 0; k < n; k++){
contadorzero = 0;
for (y = 0; y < i; y++){
//se a nota for zero, nao conta para a media
if(mat[k][y] != 0){
contadorzero = contadorzero + 1.0;
media = media + mat[k][y];
}
//conta as notas zero encontradas
else if (mat[k][y] == 0){
contadordezeros[k]++;
}
if (y == (i-1)){
media_do_usuario[k] = (double)(media) / (double)contadorzero;
media = 0;
}
}
}
pseudonota = 0;
soma = 0;
contador_DI = 0;
contadordesconhecidos = 0;
for(g = 0; g < n; g++){
for (f = 0; f < i; f++){
if (mat[g][f] == 0){
contadornotas[g] = contadornotas[g] + 1;
for(y = 0; y < n; y++){
if (g != y && (sim[g][y] > t) && mat[y][f] != 0){
pseudonota = pseudonota + ((sim[g][y] * (mat[y][f] - media_do_usuario[y])));
contador_DI++; //conta quantas vezes entrou aqui, logo, quantas vezes calculou a nota;
}
}
// percorre a matriz de similaridades, soma e atribui no vetor
soma = 0;
for(y = 0; y < n; y++){
//se a similaridade for acima da limiar e o outro usuario tiver avaliado o filme tb, soma
if ((sim[g][y] > t) && mat[y][f] != 0 ){
soma += sim[g][y];
}
}
//se o contador for zero, nao fez nenhuma conta
if (contador_DI == 0){ //
printf("DI ");
}
//conta quantos avaliaram o filme
for (k = 0; k < n; k++){
if(mat[k][f] == 0){
contadordesconhecidos++;
}
}
if (contadordesconhecidos == n){
printf("DI ");
}
//para calcular a nota atribuida a um usuario
if (contadordesconhecidos != n && contador_DI != 0){
nota[g] = media_do_usuario[g] + (pseudonota/soma);
printf("%.2lf ", nota[g]);
}
// /n para colocar as notas em linhas
if (contadornotas[g] == contadordezeros[g]){
printf("\n");
}
pseudonota = 0;
}
contadordesconhecidos = 0;
contador_DI = 0;
}
}
}
|
mateusfgomes/ICC
|
Trabalho3.c
|
<filename>Trabalho3.c<gh_stars>0
#include <stdio.h>
#include <stdlib.h>
/*
<NAME>
Instituto de Ciencias Matematicas e de Computacao da Universidade de Sao Paulo (Campus Sao Carlos)
No USP: 10734773
*/
//funcao flood-fill que passa preenchendo uma matriz paralela a' matriz mapa
void flood(int* count, int posicaox, int posicaoy, int pos[9][9], int map[9][9]){
if (posicaox >= 0 && posicaox < 9 && posicaoy >= 0 && posicaoy < 9 && map[posicaox][posicaoy] != 1 && pos[posicaox][posicaoy] == 0){
*count = *count + 1;
pos[posicaox][posicaoy] = *count;
flood(count, posicaox+1, posicaoy, pos, map);
flood(count, posicaox-1, posicaoy, pos, map);
flood(count, posicaox, posicaoy-1, pos, map);
flood(count, posicaox, posicaoy+1, pos, map);
}
return;
}
int main(void){
int i, j; //para rodar os for's
int map[9][9]; //mapa
int posicao[9][9];//matriz para ser percorrida
int posicaox1, posicaox2, posicaoy1, posicaoy2; //x's e y's das posicoes de 1 e 2
int** posrec = NULL; //ponteiro para alocacao de uma matriz na memoria heap
int Nrec; //numero de recursos
int P = 0; //numero de celulas transponiveis
int contador; //numero que aumenta enquanto o flood-fill percorre a matriz
//zerando a matriz da posicao de 1
for (i = 0; i < 9; i++){
for (j = 0; j < 9; j++){
posicao[i][j] = 0;
}
}
//recebendo a matriz do mapa
for (i = 0; i < 9; i++){
for (j = 0; j < 9; j++){
scanf("%d", &map[i][j]);
}
}
//pegando as posicoes dos jogadores
scanf("%d %d", &posicaox1, &posicaoy1);
scanf("%d %d", &posicaox2, &posicaoy2);
scanf("%d", &Nrec); //escaneando o numero de recursos
//inicializando e1 e e2,
double e1;
double e2;
//alocando uma matriz na memoria heap para armazenar a localizacao dos recursos
posrec = (int**)calloc(Nrec, sizeof(int*));
for (i = 0; i < Nrec; i++){
posrec[i] = (int*) calloc(2, sizeof(int));
}
//armazenando a posicao do recurso na memoria
for (i = 0; i < Nrec; i++){
for (j = 0; j < 2; j++){
scanf("%d", &posrec[i][j]);
}
}
for(int i = 0; i < 9; i++){
for (j = 0; j < 9; j++){
if (map[i][j] == 0){
P++;
}
}
}
contador = 0;
//calculando as N distancias ate os n recursos possiveis (essa funcao flood-fill se executa uma vez so' de modo a preencher uma matriz paralela
//a matriz mapa com a distancia da base do jogador ate qualquer ponto do mapa considerando a movimentacao dada (SUL, NORTE, OESTE, LESTE))
flood(&contador, posicaox1, posicaoy1, posicao, map);
//inicializando a variavel que armazenara' a parte do somatorio do problema
double somatorio = 0;
//inicializando a variavel que armazenara' (retirando da matriz ja percorrida pelo flood-fill) as distancias do jogador ate os N recursos
int e = 0;
//realizando o somatorio da equacao
for (int i = 0; i < Nrec; i++){
//realizando o numerador da fracao do somatorio
e = posicao[posrec[i][0]][posrec[i][1]];
//somando
somatorio += e / (double)P;
}
//realizando o calculo da expressao dada, para o jogador 1
e1 = (1 / (double) Nrec)*somatorio;
printf("%lf\n", e1);
//zerando a matriz posicao percorrida pelo flood-fill anterior de modo a prepara'-la para o proximo flood-fill
for(int i = 0; i < 9; i++){
for (int j = 0; j < 9; j++){
posicao[i][j] = 0;
}
}
//resetando como 0 a variavel para recalcular o posicionamento
contador = 0;
//o mesmo que ocorreu com o jogador 1 ate a linha 129
flood(&contador, posicaox2, posicaoy2, posicao, map);
somatorio = 0;
e = 0;
for (int i = 0; i < Nrec; i++){
e = posicao[posrec[i][0]][posrec[i][1]];
somatorio += e / (double)P;
}
e2 = (1 / (double) Nrec)*somatorio;
printf("%lf\n", e2);
//testando os e's para ver qual jogador possui vantagem
if (e2 > e1){
printf("O jogador 1 possui vantagem\n");
} else if(e1 > e2){
printf("O jogador 2 possui vantagem\n");
}
else{
printf("O mapa eh balanceado\n");
}
//liberando o espaco alocado na memoria HEAP para armazenar a posicao dos recursos
for (i = 0; i < Nrec; i++){
free(posrec[i]);
}
free(posrec);
return 0;
}
|
jameskirkwood/port2-nds
|
nds/echo_test/source/main.c
|
<gh_stars>1-10
#include <nds.h>
#include "App.h"
int main() {
defaultExceptionHandler();
vramDefault();
consoleDemoInit();
lcdSwap();
App_init();
while (1) {
swiWaitForVBlank();
App_draw();
App_frame();
}
return 0;
}
|
jameskirkwood/port2-nds
|
nds/echo_test/include/App.h
|
#ifndef APP_H
#define APP_H
// App initialisation
extern void App_init();
// Draw to the screen
extern void App_draw();
// Process one frame
extern void App_frame();
#endif
|
jameskirkwood/port2-nds
|
nds/echo_test/source/App.c
|
<gh_stars>1-10
#include "App.h"
#include <nds.h>
#include <stdio.h>
#include "Port2.h"
#define TICKS_TO_MICROS(ticks) ((ticks) / 33.513982)
// Private
//------------------------------------------------------------------------------
static int echo_ticks;
static float echo_micros;
static float average_micros;
static int timeouts;
// Public
//------------------------------------------------------------------------------
void App_init() {
Port2_init();
average_micros = -1.0; // no data
timeouts = 0;
}
void App_draw() {
consoleClear();
if (average_micros < 0) {
printf("no data");
}
else if (echo_ticks == -1) {
printf("echo timeout");
}
else {
printf(
" ticks | microseconds\n"
"%8d | %12.2f\n\n"
"running avg: %10.2f\n\n"
"timeouts: %10d\n",
echo_ticks, echo_micros,
average_micros, timeouts
);
}
}
void App_frame() {
echo_ticks = Port2_echo();
if (echo_ticks == -1) {
timeouts++;
}
else {
echo_micros = TICKS_TO_MICROS(echo_ticks);
if (average_micros < 0) {
// no data
average_micros = echo_micros;
}
else {
average_micros = (average_micros * 249 + echo_micros) * 0.004;
}
}
}
|
jameskirkwood/port2-nds
|
ino/port2_serial/Port2.h
|
<reponame>jameskirkwood/port2-nds<filename>ino/port2_serial/Port2.h
#import <Arduino.h>
#import <avr/io.h>
#import <avr/interrupt.h>
class Port2 {
private:
static const int READ_BACK_PIN = 12;
static const int BUS_FORWARD_PIN = 3;
// The time to keep driving the NDS side of the bus after sending an IRQ
// The IRQ is sent on the rising edge of BUS_FORWARD_PIN (active high), and
// the NDS side of the bus is driven while the pin is asserted (high).
// Higher values limit the outgoing data rate but improve reliability.
static const int BUS_HOLD_TIME_MICROS = 6;
// The time to wait between asserting the incoming data register's output
// enable pin and reading the data from the Arduino side of the bus
// The incoming data register drives the bus while READ_BACK_PIN (active low)
// is asserted.
static const int REGISTER_READ_TIME_MICROS = 1;
// Assert or de-assert READ_BACK_PIN (active low) = pin 12
static inline void setReadBack(bool oe) {
if (oe) PORTB &= 0b11101111;
else PORTB |= 0b00010000;
}
// Assert or de-assert BUS_FORWARD_PIN (active high) = pin 3
static inline void setBusForward(bool oe) {
if (oe) PORTD |= 0b00001000;
else PORTD &= 0b11110111;
}
// Return the data on the Arduino side of the bus (bus mode must be INPUT)
static inline char getBusData() {
return PIND & 0xf0 | PINB & 0x0f;
}
// Output data on the Arduino side of the bus (bus mode must be OUTPUT)
static inline void setBusData(char data) {
PORTD = PORTD & 0x0f | data & 0xf0;
PORTB = PORTB & 0xf0 | data & 0x0f;
}
// Set the data direction of the Arduino pins used for the bus
// `mode` must be either INPUT or OUTPUT
static inline void setBusMode(int mode) {
if (mode == OUTPUT) {
DDRD |= 0xf0;
DDRB |= 0x0f;
}
else {
DDRD &= 0x0f;
DDRB &= 0xf0;
}
}
// Single-byte buffer for received data
volatile static char data;
volatile static bool unread;
public:
// Call in the setup function and before any other method calls
static inline void init() {
// Configure the register output enable pin
pinMode(READ_BACK_PIN, OUTPUT);
setReadBack(false);
// Configure external interrupt 0
pinMode(2, INPUT); // INT0 is on pin 2
EICRA |= (1 << ISC01); // INT0 on falling edge
EIMSK |= (1 << INT0); // Enable INT0
// Configure the bus lines as inputs
setBusMode(INPUT);
// Configure the bus forward and slot-2 IRQ pin
pinMode(BUS_FORWARD_PIN, OUTPUT);
setBusForward(false);
}
// True if there is new data to be received
static inline bool available() {
return unread;
}
// Return the last byte received (since the buffer contains only one byte)
static inline char receive() {
unread = false;
return data;
}
// Blindly send a byte
static inline void send(char data) {
// Place the data on the Arduino side of the bus
setBusMode(OUTPUT);
setBusData(data);
// Forward the data to the NDS side of the bus and interrupt the NDS
setBusForward(true);
delayMicroseconds(BUS_HOLD_TIME_MICROS);
// Release the both the NDS side and Arduino side of the bus
setBusForward(false);
setBusMode(INPUT);
}
// The interrupt service routine internally used by the external interrupt 0
// handler to capture new data latched in the incoming data register
// (not part of the Port2 interface)
static inline void isr() {
// Output latched data back onto the Arduino side of the bus
setReadBack(true);
delayMicroseconds(REGISTER_READ_TIME_MICROS);
// Read data off the Arduino side of the bus
data = getBusData();
// Release the Arduino side of the bus
setReadBack(false);
unread = true;
}
};
|
jameskirkwood/port2-nds
|
nds/port2_terminal/source/Port2.c
|
#include "Port2.h"
#include <nds.h>
// Private
//------------------------------------------------------------------------------
static void (*input_listener)(u8);
// slot 2 IRQ handler when listening
void listen_isr() {
(*input_listener)(SRAM[0]);
}
// Public
//------------------------------------------------------------------------------
void Port2_init() {
sysSetCartOwner(BUS_OWNER_ARM9);
irqDisable(IRQ_CART);
}
void Port2_listen(void (*listener)(u8)) {
if (listener) {
input_listener = listener;
irqSet(IRQ_CART, &listen_isr);
irqEnable(IRQ_CART);
}
else {
irqDisable(IRQ_CART);
}
}
void Port2_send(u8 data) {
SRAM[0] = data;
}
|
jameskirkwood/port2-nds
|
nds/echo_test/source/Port2.c
|
#include "Port2.h"
#include <nds.h>
// Private
//------------------------------------------------------------------------------
static volatile enum {
PORT2_IDLE,
PORT2_IRQ_WAIT
} Port2_status;
// slot 2 IRQ handler when waiting for an echo reply
// (stops timer 0 and changes to idle state)
void echo_isr() {
TIMER0_CR = 0;
Port2_status = PORT2_IDLE;
}
// Public
//------------------------------------------------------------------------------
void Port2_init() {
sysSetCartOwner(BUS_OWNER_ARM9);
irqDisable(IRQ_CART);
Port2_status = PORT2_IDLE;
}
int Port2_echo() {
Port2_status = PORT2_IRQ_WAIT;
irqSet(IRQ_CART, &echo_isr);
irqEnable(IRQ_CART);
TIMER0_CR = 0;
TIMER0_DATA = 0;
TIMER0_CR = TIMER_ENABLE;
SRAM[0] = 0;
while (Port2_status == PORT2_IRQ_WAIT) {
// timeout after 1 millisecond
if (TIMER0_DATA > 33514) {
TIMER0_CR = 0;
irqDisable(IRQ_CART);
return -1;
}
}
irqDisable(IRQ_CART);
return TIMER0_DATA;
}
|
jameskirkwood/port2-nds
|
nds/port2_terminal/include/Port2.h
|
<reponame>jameskirkwood/port2-nds<gh_stars>1-10
#ifndef PORT2_H
#define PORT2_H
#include <nds.h>
// Module initialisation
extern void Port2_init();
// Register a listener function to be called each time a byte is received.
// Passing a null pointer causes all bytes sent by a Port2 peripheral to be
// ignored (by disabling slot-2 interrupts).
extern void Port2_listen(void (*listener)(u8));
// Send a single byte to any connected Port2 peripheral.
extern void Port2_send(u8 data);
#endif
|
jameskirkwood/port2-nds
|
nds/port2_terminal/source/main.c
|
#include <nds.h>
#include "App.h"
int main() {
defaultExceptionHandler();
videoSetMode(MODE_0_2D);
videoSetModeSub(MODE_0_2D);
consoleInit(NULL, 3,BgType_Text4bpp, BgSize_T_256x256, 31, 0, true, true);
keyboardInit(NULL, 3, BgType_Text4bpp, BgSize_T_256x512, 20, 0, false, true);
keyboardShow();
App_init();
while (1) {
swiWaitForVBlank();
App_draw();
scanKeys();
App_frame();
}
return 0;
}
|
jameskirkwood/port2-nds
|
nds/echo_test/include/Port2.h
|
#ifndef PORT2_H
#define PORT2_H
// Module initialisation
extern void Port2_init();
// Attempt to interrupt a Port2 peripheral and wait for an interrupt in return.
// Returns the round trip response time of the peripheral (including the libnds
// interrupt dispatch latency) in bus clock ticks, if there is a response.
// Returns -1 if there is no response.
extern int Port2_echo();
#endif
|
jameskirkwood/port2-nds
|
nds/port2_terminal/source/App.c
|
<filename>nds/port2_terminal/source/App.c
#include "App.h"
#include <nds.h>
#include <stdio.h>
#include "Port2.h"
// Private
//------------------------------------------------------------------------------
void listener(u8 byte) {
putchar(byte);
}
// Public
//------------------------------------------------------------------------------
void App_init() {
Port2_init();
Port2_listen(&listener);
}
void App_draw() {}
void App_frame() {
int key = keyboardUpdate();
if (key > 0) {
putchar(key);
Port2_send(key);
}
}
|
zhoonit/api
|
c/src/nnstreamer-capi-pipeline.c
|
<reponame>zhoonit/api
/* SPDX-License-Identifier: Apache-2.0 */
/**
* Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved.
*
* @file nnstreamer-capi-pipeline.c
* @date 11 March 2019
* @brief NNStreamer/Pipeline(main) C-API Wrapper.
* This allows to construct and control NNStreamer pipelines.
* @see https://github.com/nnstreamer/nnstreamer
* @author <NAME> <<EMAIL>>
* @bug No known bugs except for NYI items
*/
#include <string.h>
#include <glib.h>
#include <gst/gstbuffer.h>
#include <gst/app/app.h> /* To push data to pipeline */
#include "nnstreamer-capi-private.h"
#include "tensor_if.h"
#include "tensor_typedef.h"
#include "tensor_filter_custom_easy.h"
#include "nnstreamer_plugin_api.h"
#define handle_init(name, h) \
ml_pipeline_common_elem *name= (h); \
ml_pipeline *p; \
ml_pipeline_element *elem; \
int ret = ML_ERROR_NONE; \
check_feature_state (); \
if ((h) == NULL) { \
ml_loge ("The given handle is invalid"); \
return ML_ERROR_INVALID_PARAMETER; \
} \
\
p = name->pipe; \
elem = name->element; \
if (p == NULL || elem == NULL || p != elem->pipe) { \
ml_loge ("The handle appears to be broken."); \
return ML_ERROR_INVALID_PARAMETER; \
} \
\
g_mutex_lock (&p->lock); \
g_mutex_lock (&elem->lock); \
\
if (NULL == g_list_find (elem->handles, name)) { \
ml_loge ("The handle does not exists."); \
ret = ML_ERROR_INVALID_PARAMETER; \
goto unlock_return; \
}
#define handle_exit(h) \
unlock_return: \
g_mutex_unlock (&elem->lock); \
g_mutex_unlock (&p->lock); \
return ret;
/**
* @brief The enumeration for custom data type.
*/
typedef enum
{
PIPE_CUSTOM_TYPE_NONE,
PIPE_CUSTOM_TYPE_IF,
PIPE_CUSTOM_TYPE_FILTER,
PIPE_CUSTOM_TYPE_MAX
} pipe_custom_type_e;
/**
* @brief The struct for custom data.
*/
typedef struct
{
pipe_custom_type_e type;
gchar *name;
gpointer handle;
} pipe_custom_data_s;
static void ml_pipeline_custom_filter_ref (ml_custom_easy_filter_h custom);
static void ml_pipeline_custom_filter_unref (ml_custom_easy_filter_h custom);
static void ml_pipeline_if_custom_ref (ml_pipeline_if_h custom);
static void ml_pipeline_if_custom_unref (ml_pipeline_if_h custom);
/**
* @brief Global lock for pipeline functions.
*/
G_LOCK_DEFINE_STATIC (g_ml_pipe_lock);
/**
* @brief The list of custom data. This should be managed with lock.
*/
static GList *g_ml_custom_data = NULL;
/**
* @brief Finds a position of custom data in the list.
* @note This function should be called with lock.
*/
static GList *
pipe_custom_find_link (const pipe_custom_type_e type, const gchar * name)
{
pipe_custom_data_s *data;
GList *link;
g_return_val_if_fail (name != NULL, NULL);
link = g_ml_custom_data;
while (link) {
data = (pipe_custom_data_s *) link->data;
if (data->type == type && g_str_equal (data->name, name))
break;
link = link->next;
}
return link;
}
/**
* @brief Finds custom data matched with data type and name.
*/
static pipe_custom_data_s *
pipe_custom_find_data (const pipe_custom_type_e type, const gchar * name)
{
pipe_custom_data_s *data;
GList *link;
G_LOCK (g_ml_pipe_lock);
link = pipe_custom_find_link (type, name);
data = (link != NULL) ? (pipe_custom_data_s *) link->data : NULL;
G_UNLOCK (g_ml_pipe_lock);
return data;
}
/**
* @brief Adds new custom data into the list.
*/
static void
pipe_custom_add_data (const pipe_custom_type_e type, const gchar * name,
gpointer handle)
{
pipe_custom_data_s *data;
data = g_new0 (pipe_custom_data_s, 1);
data->type = type;
data->name = g_strdup (name);
data->handle = handle;
G_LOCK (g_ml_pipe_lock);
g_ml_custom_data = g_list_prepend (g_ml_custom_data, data);
G_UNLOCK (g_ml_pipe_lock);
}
/**
* @brief Removes custom data from the list.
*/
static void
pipe_custom_remove_data (const pipe_custom_type_e type, const gchar * name)
{
pipe_custom_data_s *data;
GList *link;
G_LOCK (g_ml_pipe_lock);
link = pipe_custom_find_link (type, name);
if (link) {
data = (pipe_custom_data_s *) link->data;
g_ml_custom_data = g_list_delete_link (g_ml_custom_data, link);
g_free (data->name);
g_free (data);
}
G_UNLOCK (g_ml_pipe_lock);
}
/**
* @brief The callback function called when the element node with custom data is released.
*/
static int
pipe_custom_destroy_cb (void *handle, void *user_data)
{
pipe_custom_data_s *custom_data;
custom_data = (pipe_custom_data_s *) handle;
g_return_val_if_fail (custom_data != NULL, ML_ERROR_INVALID_PARAMETER);
switch (custom_data->type) {
case PIPE_CUSTOM_TYPE_IF:
ml_pipeline_if_custom_unref (custom_data->handle);
break;
case PIPE_CUSTOM_TYPE_FILTER:
ml_pipeline_custom_filter_unref (custom_data->handle);
break;
default:
break;
}
return ML_ERROR_NONE;
}
/**
* @brief Internal function to create a referable element in a pipeline
*/
static ml_pipeline_element *
construct_element (GstElement * e, ml_pipeline * p, const char *name,
ml_pipeline_element_e t)
{
ml_pipeline_element *ret = g_new0 (ml_pipeline_element, 1);
if (ret == NULL) {
ml_loge ("Failed to allocate memory for the pipeline.");
return NULL;
}
ret->element = e;
ret->pipe = p;
ret->name = g_strdup (name);
ret->type = t;
ret->handles = NULL;
ret->src = NULL;
ret->sink = NULL;
ml_tensors_info_initialize (&ret->tensors_info);
ret->size = 0;
ret->maxid = 0;
ret->handle_id = 0;
ret->is_media_stream = FALSE;
g_mutex_init (&ret->lock);
return ret;
}
/**
* @brief Internal function to get the tensors info from the element caps.
*/
static gboolean
get_tensors_info_from_caps (GstCaps * caps, ml_tensors_info_s * info)
{
GstStructure *s;
GstTensorsConfig config;
guint i, n_caps;
gboolean found = FALSE;
ml_tensors_info_initialize (info);
n_caps = gst_caps_get_size (caps);
for (i = 0; i < n_caps; i++) {
s = gst_caps_get_structure (caps, i);
found = gst_tensors_config_from_structure (&config, s);
if (found) {
ml_tensors_info_copy_from_gst (info, &config.info);
break;
}
}
return found;
}
/**
* @brief Handle a sink element for registered ml_pipeline_sink_cb
*/
static void
cb_sink_event (GstElement * e, GstBuffer * b, gpointer user_data)
{
ml_pipeline_element *elem = user_data;
/** @todo CRITICAL if the pipeline is being killed, don't proceed! */
GstMemory *mem[ML_TENSOR_SIZE_LIMIT];
GstMapInfo info[ML_TENSOR_SIZE_LIMIT];
guint i;
guint num_mems;
GList *l;
ml_tensors_data_s *data = NULL;
size_t total_size = 0;
num_mems = gst_buffer_n_memory (b);
if (num_mems > ML_TENSOR_SIZE_LIMIT) {
ml_loge ("Number of memory chunks in a GstBuffer exceed the limit: %u > %u",
num_mems, ML_TENSOR_SIZE_LIMIT);
return;
}
/* set tensor data */
data = g_new0 (ml_tensors_data_s, 1);
if (data == NULL) {
ml_loge ("Failed to allocate memory for tensors data in sink callback.");
return;
}
data->num_tensors = num_mems;
for (i = 0; i < num_mems; i++) {
mem[i] = gst_buffer_peek_memory (b, i);
if (!gst_memory_map (mem[i], &info[i], GST_MAP_READ)) {
nns_loge ("Failed to map the output in sink '%s' callback", elem->name);
num_mems = i;
goto error;
}
data->tensors[i].tensor = info[i].data;
data->tensors[i].size = info[i].size;
total_size += info[i].size;
}
g_mutex_lock (&elem->lock);
/** @todo This assumes that padcap is static */
if (elem->sink == NULL) {
/* Get the sink-pad-cap */
elem->sink = gst_element_get_static_pad (elem->element, "sink");
if (elem->sink) {
/* sinkpadcap available (negotiated) */
GstCaps *caps = gst_pad_get_current_caps (elem->sink);
if (caps) {
gboolean found;
found = get_tensors_info_from_caps (caps, &elem->tensors_info);
gst_caps_unref (caps);
if (found) {
elem->size = 0;
if (elem->tensors_info.num_tensors != num_mems) {
ml_loge
("The sink event of [%s] cannot be handled because the number of tensors mismatches.",
elem->name);
gst_object_unref (elem->sink);
elem->sink = NULL;
goto error;
}
for (i = 0; i < elem->tensors_info.num_tensors; i++) {
size_t sz = ml_tensor_info_get_size (&elem->tensors_info.info[i]);
/* Not configured, yet. */
if (sz == 0)
ml_loge ("The caps for sink(%s) is not configured.", elem->name);
if (sz != data->tensors[i].size) {
ml_loge
("The sink event of [%s] cannot be handled because the tensor dimension mismatches.",
elem->name);
gst_object_unref (elem->sink);
elem->sink = NULL;
goto error;
}
elem->size += sz;
}
} else {
gst_object_unref (elem->sink);
elem->sink = NULL; /* It is not valid */
goto error;
/** @todo What if it keeps being "NULL"? Exception handling at 2nd frame? */
}
}
}
}
/* Get the data! */
if (gst_buffer_get_size (b) != total_size ||
(elem->size > 0 && total_size != elem->size)) {
ml_loge
("The buffersize mismatches. All the three values must be the same: %zu, %zu, %zu",
total_size, elem->size, gst_buffer_get_size (b));
goto error;
}
/* Iterate e->handles, pass the data to them */
for (l = elem->handles; l != NULL; l = l->next) {
ml_pipeline_sink_cb callback;
ml_pipeline_common_elem *sink = l->data;
if (sink->callback_info == NULL)
continue;
callback = sink->callback_info->cb;
if (callback)
callback (data, &elem->tensors_info, sink->callback_info->pdata);
/** @todo Measure time. Warn if it takes long. Kill if it takes too long. */
}
error:
g_mutex_unlock (&elem->lock);
for (i = 0; i < num_mems; i++) {
gst_memory_unmap (mem[i], &info[i]);
}
if (data) {
g_free (data);
data = NULL;
}
return;
}
/**
* @brief Handle a appsink element for registered ml_pipeline_sink_cb
*/
static GstFlowReturn
cb_appsink_new_sample (GstElement * e, gpointer user_data)
{
GstSample *sample;
GstBuffer *buffer;
/* get the sample from appsink */
sample = gst_app_sink_pull_sample (GST_APP_SINK (e));
buffer = gst_sample_get_buffer (sample);
cb_sink_event (e, buffer, user_data);
gst_sample_unref (sample);
return GST_FLOW_OK;
}
/**
* @brief Callback for bus message.
*/
static void
cb_bus_sync_message (GstBus * bus, GstMessage * message, gpointer user_data)
{
ml_pipeline *pipe_h;
pipe_h = (ml_pipeline *) user_data;
if (pipe_h == NULL)
return;
switch (GST_MESSAGE_TYPE (message)) {
case GST_MESSAGE_EOS:
pipe_h->isEOS = TRUE;
break;
case GST_MESSAGE_STATE_CHANGED:
if (GST_MESSAGE_SRC (message) == GST_OBJECT_CAST (pipe_h->element)) {
GstState old_state, new_state;
gst_message_parse_state_changed (message, &old_state, &new_state, NULL);
pipe_h->pipe_state = (ml_pipeline_state_e) new_state;
ml_logd ("The pipeline state changed from %s to %s.",
gst_element_state_get_name (old_state),
gst_element_state_get_name (new_state));
if (pipe_h->state_cb.cb) {
pipe_h->state_cb.cb (pipe_h->pipe_state, pipe_h->state_cb.user_data);
}
}
break;
default:
break;
}
}
/**
* @brief Clean up each element of the pipeline.
*/
static void
free_element_handle (gpointer data)
{
ml_pipeline_common_elem *item = (ml_pipeline_common_elem *) data;
g_free (item->callback_info);
g_free (item);
}
/**
* @brief Private function for ml_pipeline_destroy, cleaning up nodes in namednodes
*/
static void
cleanup_node (gpointer data)
{
ml_pipeline_element *e = data;
g_mutex_lock (&e->lock);
if (e->type == ML_PIPELINE_ELEMENT_APP_SRC && !e->pipe->isEOS) {
int eos_check_cnt = 0;
/** to push EOS event, the pipeline should be in PLAYING state */
gst_element_set_state (e->pipe->element, GST_STATE_PLAYING);
if (gst_app_src_end_of_stream (GST_APP_SRC (e->element)) != GST_FLOW_OK) {
ml_logw ("Failed to set EOS in %s", e->name);
}
while (!e->pipe->isEOS) {
eos_check_cnt++;
/** check EOS every 1ms */
g_usleep (1000);
if (eos_check_cnt >= EOS_MESSAGE_TIME_LIMIT) {
ml_loge ("Failed to get EOS message");
break;
}
}
}
if (e->custom_destroy) {
e->custom_destroy (e->custom_data, e);
}
g_free (e->name);
if (e->src)
gst_object_unref (e->src);
if (e->sink)
gst_object_unref (e->sink);
/** @todo CRITICAL. Stop the handle callbacks if they are running/ready */
if (e->handle_id > 0) {
g_signal_handler_disconnect (e->element, e->handle_id);
e->handle_id = 0;
}
if (e->handles)
g_list_free_full (e->handles, free_element_handle);
e->handles = NULL;
ml_tensors_info_free (&e->tensors_info);
g_mutex_unlock (&e->lock);
g_mutex_clear (&e->lock);
g_free (e);
}
/**
* @brief Private function to release the pipeline resources
*/
static void
cleanup_resource (gpointer data)
{
pipeline_resource_s *res = data;
/* check resource type and free data */
if (g_str_has_prefix (res->type, "tizen")) {
release_tizen_resource (res->handle, res->type);
}
g_free (res->type);
g_free (res);
}
/**
* @brief Converts predefined element in pipeline description.
*/
static int
convert_element (ml_pipeline_h pipe, const gchar * description, gchar ** result,
gboolean is_internal)
{
gchar *converted;
int status = ML_ERROR_NONE;
g_return_val_if_fail (pipe, ML_ERROR_INVALID_PARAMETER);
g_return_val_if_fail (description && result, ML_ERROR_INVALID_PARAMETER);
/* init null */
*result = NULL;
converted = g_strdup (description);
/* convert pre-defined element for Tizen */
status = convert_tizen_element (pipe, &converted, is_internal);
if (status == ML_ERROR_NONE) {
ml_logd ("Converted pipeline: %s", converted);
*result = converted;
} else {
g_free (converted);
}
return status;
}
/**
* @brief Handle tensor-filter options.
*/
static void
process_tensor_filter_option (ml_pipeline_element * e)
{
gchar *fw = NULL;
gchar *model = NULL;
pipe_custom_data_s *custom_data;
g_object_get (G_OBJECT (e->element), "framework", &fw, "model", &model, NULL);
if (fw && g_ascii_strcasecmp (fw, "custom-easy") == 0) {
/* ref to tensor-filter custom-easy handle. */
custom_data = pipe_custom_find_data (PIPE_CUSTOM_TYPE_FILTER, model);
if (custom_data) {
ml_pipeline_custom_filter_ref (custom_data->handle);
e->custom_destroy = pipe_custom_destroy_cb;
e->custom_data = custom_data;
}
}
g_free (fw);
g_free (model);
}
/**
* @brief Handle tensor-if options.
*/
static void
process_tensor_if_option (ml_pipeline_element * e)
{
gint cv = 0;
gchar *cv_option = NULL;
pipe_custom_data_s *custom_data;
g_object_get (G_OBJECT (e->element), "compared-value", &cv,
"compared-value-option", &cv_option, NULL);
if (cv == 5) {
/* cv is TIFCV_CUSTOM, ref to tensor-if custom handle. */
custom_data = pipe_custom_find_data (PIPE_CUSTOM_TYPE_IF, cv_option);
if (custom_data) {
ml_pipeline_if_custom_ref (custom_data->handle);
e->custom_destroy = pipe_custom_destroy_cb;
e->custom_data = custom_data;
}
}
g_free (cv_option);
}
/**
* @brief Iterate elements and prepare element handle.
*/
static int
iterate_element (ml_pipeline * pipe_h, GstElement * pipeline,
gboolean is_internal)
{
GstIterator *it = NULL;
int status = ML_ERROR_NONE;
g_return_val_if_fail (pipe_h && pipeline, ML_ERROR_INVALID_PARAMETER);
g_mutex_lock (&pipe_h->lock);
it = gst_bin_iterate_elements (GST_BIN (pipeline));
if (it != NULL) {
gboolean done = FALSE;
GValue item = G_VALUE_INIT;
GObject *obj;
gchar *name;
/* Fill in the hashtable, "namednodes" with named Elements */
while (!done) {
switch (gst_iterator_next (it, &item)) {
case GST_ITERATOR_OK:
obj = g_value_get_object (&item);
if (GST_IS_ELEMENT (obj)) {
GstElement *elem = GST_ELEMENT (obj);
GstPluginFeature *feature =
GST_PLUGIN_FEATURE (gst_element_get_factory (elem));
const gchar *plugin_name =
gst_plugin_feature_get_plugin_name (feature);
const gchar *element_name = gst_plugin_feature_get_name (feature);
/* validate the availability of the plugin */
if (!is_internal && ml_check_plugin_availability (plugin_name,
element_name) != ML_ERROR_NONE) {
status = ML_ERROR_NOT_SUPPORTED;
done = TRUE;
break;
}
name = gst_element_get_name (elem);
if (name != NULL) {
ml_pipeline_element_e element_type = ML_PIPELINE_ELEMENT_UNKNOWN;
if (g_str_equal (element_name, "tensor_sink")) {
element_type = ML_PIPELINE_ELEMENT_SINK;
} else if (g_str_equal (element_name, "appsrc")) {
element_type = ML_PIPELINE_ELEMENT_APP_SRC;
} else if (g_str_equal (element_name, "appsink")) {
element_type = ML_PIPELINE_ELEMENT_APP_SINK;
} else if (g_str_equal (element_name, "valve")) {
element_type = ML_PIPELINE_ELEMENT_VALVE;
} else if (g_str_equal (element_name, "input-selector")) {
element_type = ML_PIPELINE_ELEMENT_SWITCH_INPUT;
} else if (g_str_equal (element_name, "output-selector")) {
element_type = ML_PIPELINE_ELEMENT_SWITCH_OUTPUT;
} else if (g_str_equal (element_name, "tensor_if") ||
g_str_equal (element_name, "tensor_filter")) {
element_type = ML_PIPELINE_ELEMENT_COMMON;
} else {
/** @todo CRITICAL HANDLE THIS! */
}
/* check 'sync' property in sink element */
if (element_type == ML_PIPELINE_ELEMENT_SINK ||
element_type == ML_PIPELINE_ELEMENT_APP_SINK) {
gboolean sync = FALSE;
g_object_get (G_OBJECT (elem), "sync", &sync, NULL);
if (sync) {
ml_logw
("It is recommended to apply 'sync=false' property to a sink element in most AI applications. Otherwise, inference results of large neural networks will be frequently dropped by the synchronization mechanism at the sink element.");
}
}
if (element_type != ML_PIPELINE_ELEMENT_UNKNOWN) {
ml_pipeline_element *e;
e = construct_element (elem, pipe_h, name, element_type);
if (e != NULL) {
if (g_str_equal (element_name, "tensor_if"))
process_tensor_if_option (e);
else if (g_str_equal (element_name, "tensor_filter"))
process_tensor_filter_option (e);
g_hash_table_insert (pipe_h->namednodes, g_strdup (name), e);
} else {
/* allocation failure */
status = ML_ERROR_OUT_OF_MEMORY;
done = TRUE;
}
}
g_free (name);
}
}
g_value_reset (&item);
break;
case GST_ITERATOR_RESYNC:
case GST_ITERATOR_ERROR:
ml_logw
("There is an error or a resync-event while inspecting a pipeline. However, we can still execute the pipeline.");
/* fallthrough */
case GST_ITERATOR_DONE:
done = TRUE;
}
}
g_value_unset (&item);
/** @todo CRITICAL check the validity of elem=item registered in e */
gst_iterator_free (it);
}
g_mutex_unlock (&pipe_h->lock);
return status;
}
/**
* @brief Internal function to construct the pipeline.
* If is_internal is true, this will ignore the permission in Tizen.
*/
static int
construct_pipeline_internal (const char *pipeline_description,
ml_pipeline_state_cb cb, void *user_data, ml_pipeline_h * pipe,
gboolean is_internal)
{
GError *err = NULL;
GstElement *pipeline;
gchar *description = NULL;
int status = ML_ERROR_NONE;
ml_pipeline *pipe_h;
check_feature_state ();
if (!pipe || !pipeline_description)
return ML_ERROR_INVALID_PARAMETER;
/* init null */
*pipe = NULL;
if ((status = ml_initialize_gstreamer ()) != ML_ERROR_NONE)
return status;
/* prepare pipeline handle */
pipe_h = g_new0 (ml_pipeline, 1);
if (pipe_h == NULL) {
ml_loge ("Failed to allocate handle for pipeline.");
return ML_ERROR_OUT_OF_MEMORY;
}
g_mutex_init (&pipe_h->lock);
pipe_h->isEOS = FALSE;
pipe_h->pipe_state = ML_PIPELINE_STATE_UNKNOWN;
pipe_h->namednodes =
g_hash_table_new_full (g_str_hash, g_str_equal, g_free, cleanup_node);
pipe_h->resources =
g_hash_table_new_full (g_str_hash, g_str_equal, g_free, cleanup_resource);
/* convert predefined element and launch the pipeline */
status =
convert_element ((ml_pipeline_h) pipe_h, pipeline_description,
&description, is_internal);
if (status != ML_ERROR_NONE)
goto failed;
pipeline = gst_parse_launch (description, &err);
g_free (description);
if (pipeline == NULL || err) {
ml_loge ("Cannot parse and launch the given pipeline = [%s], %s",
pipeline_description, (err) ? err->message : "unknown reason");
g_clear_error (&err);
if (pipeline)
gst_object_unref (pipeline);
status = ML_ERROR_STREAMS_PIPE;
goto failed;
}
g_assert (GST_IS_PIPELINE (pipeline));
pipe_h->element = pipeline;
/* bus and message callback */
pipe_h->bus = gst_element_get_bus (pipeline);
g_assert (pipe_h->bus);
gst_bus_enable_sync_message_emission (pipe_h->bus);
pipe_h->signal_msg = g_signal_connect (pipe_h->bus, "sync-message",
G_CALLBACK (cb_bus_sync_message), pipe_h);
/* state change callback */
pipe_h->state_cb.cb = cb;
pipe_h->state_cb.user_data = user_data;
/* iterate elements and prepare element handle */
status = iterate_element (pipe_h, pipeline, is_internal);
/* finally set pipeline state to PAUSED */
if (status == ML_ERROR_NONE) {
status = ml_pipeline_stop ((ml_pipeline_h) pipe_h);
if (status == ML_ERROR_NONE) {
/**
* Let's wait until the pipeline state is changed to paused.
* Otherwise, the following APIs like 'set_property' may incur
* unintended behaviors. But, don't need to return any error
* even if this state change is not finished within the timeout,
* just replying on the caller.
*/
gst_element_get_state (pipeline, NULL, NULL, 10 * GST_MSECOND);
}
}
failed:
if (status != ML_ERROR_NONE) {
/* failed to construct the pipeline */
ml_pipeline_destroy ((ml_pipeline_h) pipe_h);
} else {
*pipe = pipe_h;
}
return status;
}
/**
* @brief Construct the pipeline (more info in nnstreamer.h)
*/
int
ml_pipeline_construct (const char *pipeline_description,
ml_pipeline_state_cb cb, void *user_data, ml_pipeline_h * pipe)
{
/* not an internal pipeline construction */
return construct_pipeline_internal (pipeline_description, cb, user_data, pipe,
FALSE);
}
#if defined (__TIZEN__)
/**
* @brief Construct the pipeline (Tizen internal, see nnstreamer-tizen-internal.h)
*/
int
ml_pipeline_construct_internal (const char *pipeline_description,
ml_pipeline_state_cb cb, void *user_data, ml_pipeline_h * pipe)
{
/* Tizen internal pipeline construction */
return construct_pipeline_internal (pipeline_description, cb, user_data, pipe,
TRUE);
}
#endif /* __TIZEN__ */
/**
* @brief Destroy the pipeline (more info in nnstreamer.h)
*/
int
ml_pipeline_destroy (ml_pipeline_h pipe)
{
ml_pipeline *p = pipe;
GstStateChangeReturn scret;
GstState state;
guint check_paused_cnt = 0;
check_feature_state ();
if (p == NULL)
return ML_ERROR_INVALID_PARAMETER;
g_mutex_lock (&p->lock);
/* Before changing the state, remove all callbacks. */
p->state_cb.cb = NULL;
g_hash_table_remove_all (p->namednodes);
g_hash_table_remove_all (p->resources);
if (p->element) {
/* Pause the pipeline if it's playing */
scret = gst_element_get_state (p->element, &state, NULL, 10 * GST_MSECOND); /* 10ms */
if (scret != GST_STATE_CHANGE_FAILURE && state == GST_STATE_PLAYING) {
scret = gst_element_set_state (p->element, GST_STATE_PAUSED);
if (scret == GST_STATE_CHANGE_FAILURE) {
g_mutex_unlock (&p->lock);
ml_loge
("Failed to wait until state changed PLAYING to PAUSED. For the detail, please check the GStreamer log messages.");
return ML_ERROR_STREAMS_PIPE;
}
}
g_mutex_unlock (&p->lock);
while (p->pipe_state == ML_PIPELINE_STATE_PLAYING) {
check_paused_cnt++;
/** check PAUSED every 1ms */
g_usleep (1000);
if (check_paused_cnt >= WAIT_PAUSED_TIME_LIMIT) {
ml_loge ("Failed to wait until state changed to PAUSED");
break;
}
}
g_mutex_lock (&p->lock);
/* Stop (NULL State) the pipeline */
scret = gst_element_set_state (p->element, GST_STATE_NULL);
if (scret != GST_STATE_CHANGE_SUCCESS) {
g_mutex_unlock (&p->lock);
ml_loge
("Failed to wait until state changed to NULL(STOP). For the detail, please check the GStreamer log messages.");
return ML_ERROR_STREAMS_PIPE;
}
if (p->bus) {
g_signal_handler_disconnect (p->bus, p->signal_msg);
gst_object_unref (p->bus);
}
gst_object_unref (p->element);
p->element = NULL;
}
/* Destroy registered callback handles and resources */
g_hash_table_destroy (p->namednodes);
g_hash_table_destroy (p->resources);
p->namednodes = p->resources = NULL;
g_mutex_unlock (&p->lock);
g_mutex_clear (&p->lock);
g_free (p);
return ML_ERROR_NONE;
}
/**
* @brief Get the pipeline state (more info in nnstreamer.h)
*/
int
ml_pipeline_get_state (ml_pipeline_h pipe, ml_pipeline_state_e * state)
{
ml_pipeline *p = pipe;
GstState _state;
GstStateChangeReturn scret;
check_feature_state ();
if (p == NULL || state == NULL)
return ML_ERROR_INVALID_PARAMETER;
*state = ML_PIPELINE_STATE_UNKNOWN;
g_mutex_lock (&p->lock);
scret = gst_element_get_state (p->element, &_state, NULL, GST_MSECOND); /* Do it within 1ms! */
g_mutex_unlock (&p->lock);
if (scret == GST_STATE_CHANGE_FAILURE) {
ml_loge
("Failed to get the state of the pipeline. For the detail, please check the GStreamer log messages.");
return ML_ERROR_STREAMS_PIPE;
}
*state = (ml_pipeline_state_e) _state;
return ML_ERROR_NONE;
}
/****************************************************
** NNStreamer Pipeline Start/Stop Control **
****************************************************/
/**
* @brief Start/Resume the pipeline! (more info in nnstreamer.h)
*/
int
ml_pipeline_start (ml_pipeline_h pipe)
{
ml_pipeline *p = pipe;
GstStateChangeReturn scret;
int status = ML_ERROR_NONE;
check_feature_state ();
if (p == NULL)
return ML_ERROR_INVALID_PARAMETER;
g_mutex_lock (&p->lock);
/* check the resources when starting the pipeline */
if (g_hash_table_size (p->resources)) {
GHashTableIter iter;
gpointer key, value;
/* iterate all handle and acquire res if released */
g_hash_table_iter_init (&iter, p->resources);
while (g_hash_table_iter_next (&iter, &key, &value)) {
if (g_str_has_prefix (key, "tizen")) {
status = get_tizen_resource (pipe, key);
if (status != ML_ERROR_NONE)
goto done;
}
}
}
scret = gst_element_set_state (p->element, GST_STATE_PLAYING);
if (scret == GST_STATE_CHANGE_FAILURE) {
ml_loge
("Failed to set the state of the pipeline to PLAYING. For the detail, please check the GStreamer log messages.");
status = ML_ERROR_STREAMS_PIPE;
}
done:
g_mutex_unlock (&p->lock);
return status;
}
/**
* @brief Pause the pipeline! (more info in nnstreamer.h)
*/
int
ml_pipeline_stop (ml_pipeline_h pipe)
{
ml_pipeline *p = pipe;
GstStateChangeReturn scret;
check_feature_state ();
if (p == NULL)
return ML_ERROR_INVALID_PARAMETER;
g_mutex_lock (&p->lock);
scret = gst_element_set_state (p->element, GST_STATE_PAUSED);
g_mutex_unlock (&p->lock);
if (scret == GST_STATE_CHANGE_FAILURE) {
ml_loge
("Failed to set the state of the pipeline to PAUSED. For the detail, please check the GStreamer log messages.");
return ML_ERROR_STREAMS_PIPE;
}
return ML_ERROR_NONE;
}
/****************************************************
** NNStreamer Pipeline Sink/Src Control **
****************************************************/
/**
* @brief Register a callback for sink (more info in nnstreamer.h)
*/
int
ml_pipeline_sink_register (ml_pipeline_h pipe, const char *sink_name,
ml_pipeline_sink_cb cb, void *user_data, ml_pipeline_sink_h * h)
{
ml_pipeline_element *elem;
ml_pipeline *p = pipe;
ml_pipeline_common_elem *sink;
int ret = ML_ERROR_NONE;
check_feature_state ();
if (h == NULL) {
ml_loge ("The argument sink handle is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
/* init null */
*h = NULL;
if (pipe == NULL) {
ml_loge ("The first argument, pipeline handle is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
if (sink_name == NULL) {
ml_loge ("The second argument, sink name is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
if (cb == NULL) {
ml_loge ("The callback argument, cb, is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
g_mutex_lock (&p->lock);
elem = g_hash_table_lookup (p->namednodes, sink_name);
if (elem == NULL) {
ml_loge ("There is no element named [%s] in the pipeline.", sink_name);
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
if (elem->type != ML_PIPELINE_ELEMENT_SINK &&
elem->type != ML_PIPELINE_ELEMENT_APP_SINK) {
ml_loge ("The element [%s] in the pipeline is not a sink element.",
sink_name);
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
if (elem->handle_id > 0) {
/* no need to connect signal to sink element */
ml_logw ("Sink callback is already registered.");
} else {
/* set callback for new data */
if (elem->type == ML_PIPELINE_ELEMENT_SINK) {
/* tensor_sink */
g_object_set (G_OBJECT (elem->element), "emit-signal", (gboolean) TRUE,
NULL);
elem->handle_id =
g_signal_connect (elem->element, "new-data",
G_CALLBACK (cb_sink_event), elem);
} else {
/* appsink */
g_object_set (G_OBJECT (elem->element), "emit-signals", (gboolean) TRUE,
NULL);
elem->handle_id =
g_signal_connect (elem->element, "new-sample",
G_CALLBACK (cb_appsink_new_sample), elem);
}
if (elem->handle_id == 0) {
ml_loge ("Failed to connect a signal to the element [%s].", sink_name);
ret = ML_ERROR_STREAMS_PIPE;
goto unlock_return;
}
}
sink = g_new0 (ml_pipeline_common_elem, 1);
if (sink == NULL) {
ml_loge ("Failed to allocate the sink handle for %s.", sink_name);
ret = ML_ERROR_OUT_OF_MEMORY;
goto unlock_return;
}
sink->callback_info = g_new (callback_info_s, 1);
if (sink->callback_info == NULL) {
g_free (sink);
ml_loge ("Failed to allocate the sink handle for %s.", sink_name);
ret = ML_ERROR_OUT_OF_MEMORY;
goto unlock_return;
}
sink->pipe = p;
sink->element = elem;
sink->callback_info->cb = cb;
sink->callback_info->pdata = user_data;
*h = sink;
g_mutex_lock (&elem->lock);
elem->maxid++;
sink->id = elem->maxid;
elem->handles = g_list_append (elem->handles, sink);
g_mutex_unlock (&elem->lock);
unlock_return:
g_mutex_unlock (&p->lock);
return ret;
}
/**
* @brief Unregister a callback for sink (more info in nnstreamer.h)
*/
int
ml_pipeline_sink_unregister (ml_pipeline_sink_h h)
{
handle_init (sink, h);
if (elem->handle_id > 0) {
g_signal_handler_disconnect (elem->element, elem->handle_id);
elem->handle_id = 0;
}
elem->handles = g_list_remove (elem->handles, sink);
g_free (sink->callback_info);
g_free (sink);
handle_exit (h);
}
/**
* @brief Parse tensors info of src element.
*/
static int
ml_pipeline_src_parse_tensors_info (ml_pipeline_element * elem)
{
int ret = ML_ERROR_NONE;
if (elem->src == NULL) {
elem->src = gst_element_get_static_pad (elem->element, "src");
elem->size = 0;
if (elem->src == NULL) {
ml_loge
("Failed to get the src pad of the element[%s]. For the detail, please check the GStreamer log messages.",
elem->name);
ret = ML_ERROR_STREAMS_PIPE;
} else {
GstCaps *caps = gst_pad_get_allowed_caps (elem->src);
guint i;
gboolean found = FALSE;
size_t sz;
if (caps) {
found = get_tensors_info_from_caps (caps, &elem->tensors_info);
if (!found && gst_caps_is_fixed (caps)) {
GstStructure *caps_s;
const gchar *mimetype;
caps_s = gst_caps_get_structure (caps, 0);
mimetype = gst_structure_get_name (caps_s);
if (!g_str_equal (mimetype, "other/tensor") &&
!g_str_equal (mimetype, "other/tensors")) {
elem->is_media_stream = TRUE;
}
}
gst_caps_unref (caps);
}
if (found) {
for (i = 0; i < elem->tensors_info.num_tensors; i++) {
sz = ml_tensor_info_get_size (&elem->tensors_info.info[i]);
elem->size += sz;
}
} else {
if (!elem->is_media_stream) {
ml_logw
("Cannot find caps. The pipeline is not yet negotiated for src element [%s].",
elem->name);
gst_object_unref (elem->src);
elem->src = NULL;
ret = ML_ERROR_TRY_AGAIN;
}
}
}
}
return ret;
}
/**
* @brief Get a handle to operate a src (more info in nnstreamer.h)
*/
int
ml_pipeline_src_get_handle (ml_pipeline_h pipe, const char *src_name,
ml_pipeline_src_h * h)
{
ml_pipeline *p = pipe;
ml_pipeline_element *elem;
ml_pipeline_common_elem *src;
int ret = ML_ERROR_NONE;
check_feature_state ();
if (h == NULL) {
ml_loge ("The argument source handle is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
/* init null */
*h = NULL;
if (pipe == NULL) {
ml_loge ("The first argument, pipeline handle is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
if (src_name == NULL) {
ml_loge ("The second argument, source name is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
g_mutex_lock (&p->lock);
elem = g_hash_table_lookup (p->namednodes, src_name);
if (elem == NULL) {
ml_loge ("There is no element named [%s] in the pipeline.", src_name);
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
if (elem->type != ML_PIPELINE_ELEMENT_APP_SRC) {
ml_loge ("The element [%s] in the pipeline is not a source element.",
src_name);
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
src = *h = g_new0 (ml_pipeline_common_elem, 1);
if (src == NULL) {
ml_loge ("Failed to allocate the src handle for %s.", src_name);
ret = ML_ERROR_OUT_OF_MEMORY;
goto unlock_return;
}
src->pipe = p;
src->element = elem;
g_mutex_lock (&elem->lock);
elem->maxid++;
src->id = elem->maxid;
elem->handles = g_list_append (elem->handles, src);
ml_pipeline_src_parse_tensors_info (elem);
g_mutex_unlock (&elem->lock);
unlock_return:
g_mutex_unlock (&p->lock);
return ret;
}
/**
* @brief Close a src node (more info in nnstreamer.h)
*/
int
ml_pipeline_src_release_handle (ml_pipeline_src_h h)
{
handle_init (src, h);
elem->handles = g_list_remove (elem->handles, src);
g_free (src);
handle_exit (h);
}
/**
* @brief Push a data frame to a src (more info in nnstreamer.h)
*/
int
ml_pipeline_src_input_data (ml_pipeline_src_h h, ml_tensors_data_h data,
ml_pipeline_buf_policy_e policy)
{
GstBuffer *buffer;
GstMemory *mem;
gpointer mem_data;
gsize mem_size;
GstFlowReturn gret;
ml_tensors_data_s *_data;
unsigned int i;
handle_init (src, h);
_data = (ml_tensors_data_s *) data;
if (!_data) {
ml_loge ("The given param data is invalid.");
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
if (_data->num_tensors < 1 || _data->num_tensors > ML_TENSOR_SIZE_LIMIT) {
ml_loge ("The tensor size is invalid. It should be 1 ~ %u; where it is %u",
ML_TENSOR_SIZE_LIMIT, _data->num_tensors);
ret = ML_ERROR_INVALID_PARAMETER;
goto destroy_data;
}
ret = ml_pipeline_src_parse_tensors_info (elem);
if (ret != ML_ERROR_NONE) {
ml_logw
("The pipeline is not ready to accept inputs. The input is ignored.");
goto destroy_data;
}
if (!elem->is_media_stream) {
if (elem->tensors_info.num_tensors != _data->num_tensors) {
ml_loge
("The src push of [%s] cannot be handled because the number of tensors in a frame mismatches. %u != %u",
elem->name, elem->tensors_info.num_tensors, _data->num_tensors);
ret = ML_ERROR_INVALID_PARAMETER;
goto destroy_data;
}
for (i = 0; i < elem->tensors_info.num_tensors; i++) {
size_t sz = ml_tensor_info_get_size (&elem->tensors_info.info[i]);
if (sz != _data->tensors[i].size) {
ml_loge
("The given input tensor size (%d'th, %zu bytes) mismatches the source pad (%zu bytes)",
i, _data->tensors[i].size, sz);
ret = ML_ERROR_INVALID_PARAMETER;
goto destroy_data;
}
}
}
/* Create buffer to be pushed from buf[] */
buffer = gst_buffer_new ();
for (i = 0; i < _data->num_tensors; i++) {
mem_data = _data->tensors[i].tensor;
mem_size = _data->tensors[i].size;
mem = gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY,
mem_data, mem_size, 0, mem_size, mem_data,
(policy == ML_PIPELINE_BUF_POLICY_AUTO_FREE) ? g_free : NULL);
gst_buffer_append_memory (buffer, mem);
/** @todo Verify that gst_buffer_append lists tensors/gstmem in the correct order */
}
/* Push the data! */
gret = gst_app_src_push_buffer (GST_APP_SRC (elem->element), buffer);
/* Free data ptr if buffer policy is auto-free */
if (policy == ML_PIPELINE_BUF_POLICY_AUTO_FREE) {
g_free (_data);
_data = NULL;
}
if (gret == GST_FLOW_FLUSHING) {
ml_logw
("The pipeline is not in PAUSED/PLAYING. The input may be ignored.");
ret = ML_ERROR_TRY_AGAIN;
} else if (gret == GST_FLOW_EOS) {
ml_logw ("THe pipeline is in EOS state. The input is ignored.");
ret = ML_ERROR_STREAMS_PIPE;
}
destroy_data:
if (_data != NULL && policy == ML_PIPELINE_BUF_POLICY_AUTO_FREE) {
/* Free data handle */
ml_tensors_data_destroy (data);
}
handle_exit (h);
}
/**
* @brief Gets a handle for the tensors metadata of given src node.
*/
int
ml_pipeline_src_get_tensors_info (ml_pipeline_src_h h, ml_tensors_info_h * info)
{
handle_init (src, h);
if (info == NULL) {
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
ret = ml_pipeline_src_parse_tensors_info (elem);
if (ret == ML_ERROR_NONE) {
ml_tensors_info_create (info);
ml_tensors_info_clone (*info, &elem->tensors_info);
}
handle_exit (h);
}
/****************************************************
** NNStreamer Pipeline Switch/Valve Control **
****************************************************/
/**
* @brief Get a handle to operate a selector (more info in nnstreamer.h)
*/
int
ml_pipeline_switch_get_handle (ml_pipeline_h pipe, const char *switch_name,
ml_pipeline_switch_e * type, ml_pipeline_switch_h * h)
{
ml_pipeline_element *elem;
ml_pipeline *p = pipe;
ml_pipeline_common_elem *swtc;
int ret = ML_ERROR_NONE;
check_feature_state ();
if (h == NULL) {
ml_loge ("The argument switch handle is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
/* init null */
*h = NULL;
if (pipe == NULL) {
ml_loge ("The first argument, pipeline handle, is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
if (switch_name == NULL) {
ml_loge ("The second argument, switch name, is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
g_mutex_lock (&p->lock);
elem = g_hash_table_lookup (p->namednodes, switch_name);
if (elem == NULL) {
ml_loge ("There is no switch element named [%s] in the pipeline.",
switch_name);
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
if (elem->type == ML_PIPELINE_ELEMENT_SWITCH_INPUT) {
if (type)
*type = ML_PIPELINE_SWITCH_INPUT_SELECTOR;
} else if (elem->type == ML_PIPELINE_ELEMENT_SWITCH_OUTPUT) {
if (type)
*type = ML_PIPELINE_SWITCH_OUTPUT_SELECTOR;
} else {
ml_loge
("There is an element named [%s] in the pipeline, but it is not an input/output switch",
switch_name);
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
swtc = *h = g_new0 (ml_pipeline_common_elem, 1);
if (swtc == NULL) {
ml_loge ("Failed to allocate the switch handle for %s.", switch_name);
ret = ML_ERROR_OUT_OF_MEMORY;
goto unlock_return;
}
swtc->pipe = p;
swtc->element = elem;
g_mutex_lock (&elem->lock);
elem->maxid++;
swtc->id = elem->maxid;
elem->handles = g_list_append (elem->handles, swtc);
g_mutex_unlock (&elem->lock);
unlock_return:
g_mutex_unlock (&p->lock);
return ret;
}
/**
* @brief Close the given switch handle (more info in nnstreamer.h)
*/
int
ml_pipeline_switch_release_handle (ml_pipeline_switch_h h)
{
handle_init (swtc, h);
elem->handles = g_list_remove (elem->handles, swtc);
g_free (swtc);
handle_exit (h);
}
/**
* @brief Control the switch (more info in nnstreamer.h)
*/
int
ml_pipeline_switch_select (ml_pipeline_switch_h h, const char *pad_name)
{
GstPad *active_pad, *new_pad;
gchar *active_name;
handle_init (swtc, h);
if (pad_name == NULL) {
ml_loge ("The second argument, pad name, is not valid.");
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
g_object_get (G_OBJECT (elem->element), "active-pad", &active_pad, NULL);
active_name = gst_pad_get_name (active_pad);
if (g_strcmp0 (pad_name, active_name) == 0) {
ml_logi ("Switch is called, but there is no effective changes: %s->%s.",
active_name, pad_name);
g_free (active_name);
gst_object_unref (active_pad);
goto unlock_return;
}
g_free (active_name);
gst_object_unref (active_pad);
new_pad = gst_element_get_static_pad (elem->element, pad_name);
if (new_pad == NULL) {
/* Not Found! */
ml_loge ("Cannot find the pad, [%s], from the switch, [%s].",
pad_name, elem->name);
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
g_object_set (G_OBJECT (elem->element), "active-pad", new_pad, NULL);
gst_object_unref (new_pad);
ml_logi ("Switched to [%s] successfully at switch [%s].", pad_name,
elem->name);
handle_exit (h);
}
/**
* @brief Gets the pad names of a switch.
*/
int
ml_pipeline_switch_get_pad_list (ml_pipeline_switch_h h, char ***list)
{
GstIterator *it;
GValue item = G_VALUE_INIT;
gboolean done = FALSE;
GList *dllist = NULL;
GstPad *pad;
int counter = 0;
handle_init (swtc, h);
if (list == NULL) {
ml_loge ("The second argument, list, is not valid.");
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
/* init null */
*list = NULL;
if (elem->type == ML_PIPELINE_ELEMENT_SWITCH_INPUT)
it = gst_element_iterate_sink_pads (elem->element);
else if (elem->type == ML_PIPELINE_ELEMENT_SWITCH_OUTPUT)
it = gst_element_iterate_src_pads (elem->element);
else {
ml_loge
("The element, [%s], is supposed to be input/output switch, but it is not. Internal data structure is broken.",
elem->name);
ret = ML_ERROR_STREAMS_PIPE;
goto unlock_return;
}
while (!done) {
switch (gst_iterator_next (it, &item)) {
case GST_ITERATOR_OK:
pad = GST_PAD (g_value_get_object (&item));
dllist = g_list_append (dllist, gst_pad_get_name (pad));
counter++;
g_value_reset (&item);
break;
case GST_ITERATOR_RESYNC:
g_list_free_full (dllist, g_free); /* This frees all strings as well */
dllist = NULL;
counter = 0;
gst_iterator_resync (it);
break;
case GST_ITERATOR_ERROR:
ml_loge ("Cannot access the list of pad properly of a switch, [%s].",
elem->name);
ret = ML_ERROR_STREAMS_PIPE;
break;
case GST_ITERATOR_DONE:
done = TRUE;
break;
}
}
gst_iterator_free (it);
/* There has been no error with that "while" loop. */
if (ret == ML_ERROR_NONE) {
int i = 0;
GList *l;
*list = g_malloc0 (sizeof (char *) * (counter + 1));
if (*list == NULL) {
ml_loge ("Failed to allocate memory for pad list.");
ret = ML_ERROR_OUT_OF_MEMORY;
goto unlock_return;
}
for (l = dllist; l != NULL; l = l->next) {
(*list)[i] = l->data; /* Allocated by gst_pad_get_name(). Caller has to free it */
i++;
if (i > counter) {
g_list_free_full (dllist, g_free); /* This frees all strings as well */
g_free (*list);
*list = NULL;
ml_loge
("Internal data inconsistency. This could be a bug in nnstreamer. Switch [%s].",
elem->name);
ret = ML_ERROR_STREAMS_PIPE;
goto unlock_return;
}
}
}
g_list_free (dllist); /* This does not free the strings.. fortunately. */
handle_exit (h);
}
/**
* @brief Get a handle to operate a Valve (more info in nnstreamer.h)
*/
int
ml_pipeline_valve_get_handle (ml_pipeline_h pipe, const char *valve_name,
ml_pipeline_valve_h * h)
{
ml_pipeline_element *elem;
ml_pipeline *p = pipe;
ml_pipeline_common_elem *valve;
int ret = ML_ERROR_NONE;
check_feature_state ();
if (h == NULL) {
ml_loge ("The argument valve handle is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
/* init null */
*h = NULL;
if (pipe == NULL) {
ml_loge ("The first argument, pipeline handle, is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
if (valve_name == NULL) {
ml_loge ("The second argument, valve name, is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
g_mutex_lock (&p->lock);
elem = g_hash_table_lookup (p->namednodes, valve_name);
if (elem == NULL) {
ml_loge ("There is no valve element named [%s] in the pipeline.",
valve_name);
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
if (elem->type != ML_PIPELINE_ELEMENT_VALVE) {
ml_loge
("There is an element named [%s] in the pipeline, but it is not a valve",
valve_name);
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
valve = *h = g_new0 (ml_pipeline_common_elem, 1);
if (valve == NULL) {
ml_loge ("Failed to allocate the valve handle for %s.", valve_name);
ret = ML_ERROR_OUT_OF_MEMORY;
goto unlock_return;
}
valve->pipe = p;
valve->element = elem;
g_mutex_lock (&elem->lock);
elem->maxid++;
valve->id = elem->maxid;
elem->handles = g_list_append (elem->handles, valve);
g_mutex_unlock (&elem->lock);
unlock_return:
g_mutex_unlock (&p->lock);
return ret;
}
/**
* @brief Close the given valve handle (more info in nnstreamer.h)
*/
int
ml_pipeline_valve_release_handle (ml_pipeline_valve_h h)
{
handle_init (valve, h);
elem->handles = g_list_remove (elem->handles, valve);
g_free (valve);
handle_exit (h);
}
/**
* @brief Control the valve with the given handle (more info in nnstreamer.h)
*/
int
ml_pipeline_valve_set_open (ml_pipeline_valve_h h, bool open)
{
gboolean drop = FALSE;
handle_init (valve, h);
g_object_get (G_OBJECT (elem->element), "drop", &drop, NULL);
if ((open != false) != (drop != FALSE)) {
/* Nothing to do */
ml_logi ("Valve is called, but there is no effective changes");
goto unlock_return;
}
drop = (open) ? FALSE : TRUE;
g_object_set (G_OBJECT (elem->element), "drop", drop, NULL);
handle_exit (h);
}
/********************************************************
** NNStreamer Element Property Control in Pipeline **
********************************************************/
/**
* @brief Gets an element handle in NNStreamer pipelines to control its properties.
*/
int
ml_pipeline_element_get_handle (ml_pipeline_h pipe, const char *element_name,
ml_pipeline_element_h * elem_h)
{
int ret = ML_ERROR_NONE;
ml_pipeline_element *elem;
ml_pipeline_common_elem *common_elem;
ml_pipeline *p = pipe;
/* Check input parameter */
if (pipe == NULL) {
ml_loge ("The first argument, pipeline handle, is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
if (element_name == NULL) {
ml_loge ("The second argument, element name, is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
if (elem_h == NULL) {
ml_loge ("The argument element handle is not valid.");
return ML_ERROR_INVALID_PARAMETER;
}
*elem_h = NULL;
g_mutex_lock (&p->lock);
/* 1. Search element in lookup table first */
elem = g_hash_table_lookup (p->namednodes, element_name);
if (elem == NULL) {
/* 2. Search element in pipeline itself */
GstElement *gst_elem;
gst_elem = gst_bin_get_by_name (GST_BIN (p->element), element_name);
if (gst_elem == NULL) {
ml_loge ("The element named [%s] is not found in the pipeline",
element_name);
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
/* Caching for next search */
elem = construct_element (gst_elem, pipe, element_name,
ML_PIPELINE_ELEMENT_COMMON);
if (elem == NULL) {
ml_loge ("Failed to allocate the internal memory");
ret = ML_ERROR_OUT_OF_MEMORY;
goto unlock_return;
}
g_hash_table_insert (p->namednodes, g_strdup (element_name), elem);
}
/* Type checking */
if (elem->type == ML_PIPELINE_ELEMENT_UNKNOWN) {
ml_loge
("There is an element named [%s] in the pipeline, but it is unknown type.",
element_name);
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
common_elem = *elem_h = g_new0 (ml_pipeline_common_elem, 1);
if (common_elem == NULL) {
ml_loge ("Failed to allocate the internal handler for %s.", element_name);
ret = ML_ERROR_OUT_OF_MEMORY;
goto unlock_return;
}
common_elem->pipe = p;
common_elem->element = elem;
g_mutex_lock (&elem->lock);
elem->maxid++;
common_elem->id = elem->maxid;
elem->handles = g_list_append (elem->handles, common_elem);
g_mutex_unlock (&elem->lock);
unlock_return:
g_mutex_unlock (&p->lock);
return ret;
}
/**
* @brief Releases the given element handle.
*/
int
ml_pipeline_element_release_handle (ml_pipeline_element_h elem_h)
{
handle_init (common_elem, elem_h);
elem->handles = g_list_remove (elem->handles, common_elem);
g_free (common_elem);
handle_exit (elem_h);
}
/**
* @brief Check property existence and its type.
*/
static bool
ml_pipeline_element_check_property (GObjectClass * class,
const char *property_name, const GType type)
{
GParamSpec *pspec = NULL;
/* Check property existence */
pspec = g_object_class_find_property (class, property_name);
if (pspec == NULL) {
ml_loge ("The property name [%s] does not exist.", property_name);
return FALSE;
}
/* Compare property's type with given type */
if (!((pspec->value_type == type) ||
(type == G_TYPE_ENUM && G_TYPE_IS_ENUM (pspec->value_type)) ||
(type == G_TYPE_INT64 && pspec->value_type == G_TYPE_LONG) ||
(type == G_TYPE_UINT64 && pspec->value_type == G_TYPE_ULONG) ||
(type == G_TYPE_INT && G_TYPE_IS_ENUM (pspec->value_type)) ||
(type == G_TYPE_UINT && G_TYPE_IS_ENUM (pspec->value_type)) ||
(type == G_TYPE_DOUBLE && pspec->value_type == G_TYPE_FLOAT))) {
ml_loge ("The type of property name [%s] is '%s'", property_name,
g_type_name (pspec->value_type));
return FALSE;
}
return TRUE;
}
/**
* @brief Sets the value of given element's property in NNStreamer pipelines.
*/
static int
ml_pipeline_element_set_property (ml_pipeline_element_h elem_h,
const char *property_name, gpointer value, GType type)
{
handle_init (common_elem, elem_h);
/* Check the input parameter */
if (property_name == NULL) {
ml_loge ("The second argument, property name is not valid.");
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
/* Check property existence & its type */
if (!ml_pipeline_element_check_property (G_OBJECT_GET_CLASS (elem->element),
property_name, type)) {
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
/* Set property */
if (type == G_TYPE_DOUBLE || type == G_TYPE_FLOAT) {
g_object_set (G_OBJECT (elem->element), property_name,
*(double *) value, NULL);
} else if (type == G_TYPE_INT64) {
g_object_set (G_OBJECT (elem->element), property_name,
*(int64_t *) value, NULL);
} else if (type == G_TYPE_UINT64) {
g_object_set (G_OBJECT (elem->element), property_name,
*(uint64_t *) value, NULL);
} else {
g_object_set (G_OBJECT (elem->element), property_name, value, NULL);
}
handle_exit (elem_h);
}
/**
* @brief Gets the value of given element's property in NNStreamer pipelines.
*/
static int
ml_pipeline_element_get_property (ml_pipeline_element_h elem_h,
const char *property_name, GType type, gpointer pvalue)
{
handle_init (common_elem, elem_h);
/* Check the input parameter */
if (property_name == NULL) {
ml_loge ("The second argument, property_name is not valid.");
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
if (pvalue == NULL) {
ml_loge ("The third argument, value is not valid.");
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
/* Check property existence & its type */
if (!ml_pipeline_element_check_property (G_OBJECT_GET_CLASS (elem->element),
property_name, type)) {
ret = ML_ERROR_INVALID_PARAMETER;
goto unlock_return;
}
/* Get property */
g_object_get (G_OBJECT (elem->element), property_name, pvalue, NULL);
handle_exit (elem_h);
}
/**
* @brief Sets the boolean value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_set_property_bool (ml_pipeline_element_h elem_h,
const char *property_name, const int32_t value)
{
return ml_pipeline_element_set_property (elem_h, property_name,
GINT_TO_POINTER (value), G_TYPE_BOOLEAN);
}
/**
* @brief Sets the string value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_set_property_string (ml_pipeline_element_h elem_h,
const char *property_name, const char *value)
{
return ml_pipeline_element_set_property (elem_h, property_name,
(gpointer) value, G_TYPE_STRING);
}
/**
* @brief Sets the integer value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_set_property_int32 (ml_pipeline_element_h elem_h,
const char *property_name, const int32_t value)
{
return ml_pipeline_element_set_property (elem_h, property_name,
GINT_TO_POINTER (value), G_TYPE_INT);
}
/**
* @brief Sets the integer 64bit value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_set_property_int64 (ml_pipeline_element_h elem_h,
const char *property_name, const int64_t value)
{
return ml_pipeline_element_set_property (elem_h, property_name,
(gpointer) (&value), G_TYPE_INT64);
}
/**
* @brief Sets the unsigned integer value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_set_property_uint32 (ml_pipeline_element_h elem_h,
const char *property_name, const uint32_t value)
{
return ml_pipeline_element_set_property (elem_h, property_name,
GUINT_TO_POINTER (value), G_TYPE_UINT);
}
/**
* @brief Sets the unsigned integer 64bit value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_set_property_uint64 (ml_pipeline_element_h elem_h,
const char *property_name, const uint64_t value)
{
return ml_pipeline_element_set_property (elem_h, property_name,
(gpointer) (&value), G_TYPE_UINT64);
}
/**
* @brief Sets the floating point value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_set_property_double (ml_pipeline_element_h elem_h,
const char *property_name, const double value)
{
return ml_pipeline_element_set_property (elem_h, property_name,
(gpointer) (&value), G_TYPE_DOUBLE);
}
/**
* @brief Sets the enumeration value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_set_property_enum (ml_pipeline_element_h elem_h,
const char *property_name, const uint32_t value)
{
return ml_pipeline_element_set_property (elem_h, property_name,
GUINT_TO_POINTER (value), G_TYPE_ENUM);
}
/**
* @brief Gets the boolean value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_get_property_bool (ml_pipeline_element_h elem_h,
const char *property_name, int32_t * value)
{
return ml_pipeline_element_get_property (elem_h, property_name,
G_TYPE_BOOLEAN, (gpointer) value);
}
/**
* @brief Gets the string value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_get_property_string (ml_pipeline_element_h elem_h,
const char *property_name, char **value)
{
return ml_pipeline_element_get_property (elem_h, property_name,
G_TYPE_STRING, (gpointer) value);
}
/**
* @brief Gets the integer value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_get_property_int32 (ml_pipeline_element_h elem_h,
const char *property_name, int32_t * value)
{
return ml_pipeline_element_get_property (elem_h, property_name,
G_TYPE_INT, (gpointer) value);
}
/**
* @brief Gets the integer 64bit value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_get_property_int64 (ml_pipeline_element_h elem_h,
const char *property_name, int64_t * value)
{
return ml_pipeline_element_get_property (elem_h, property_name,
G_TYPE_INT64, (gpointer) value);
}
/**
* @brief Gets the unsigned integer value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_get_property_uint32 (ml_pipeline_element_h elem_h,
const char *property_name, uint32_t * value)
{
return ml_pipeline_element_get_property (elem_h, property_name,
G_TYPE_UINT, (gpointer) value);
}
/**
* @brief Gets the unsigned integer 64bit value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_get_property_uint64 (ml_pipeline_element_h elem_h,
const char *property_name, uint64_t * value)
{
return ml_pipeline_element_get_property (elem_h, property_name,
G_TYPE_UINT64, (gpointer) value);
}
/**
* @brief Gets the floating point value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_get_property_double (ml_pipeline_element_h elem_h,
const char *property_name, double *value)
{
return ml_pipeline_element_get_property (elem_h, property_name,
G_TYPE_DOUBLE, (gpointer) value);
}
/**
* @brief Gets the enumeration value of element's property in NNStreamer pipelines.
*/
int
ml_pipeline_element_get_property_enum (ml_pipeline_element_h elem_h,
const char *property_name, uint32_t * value)
{
return ml_pipeline_element_get_property (elem_h, property_name,
G_TYPE_ENUM, (gpointer) value);
}
/**
* @brief Gets the element of pipeline itself (GstElement).
*/
GstElement *
ml_pipeline_get_gst_element (ml_pipeline_h pipe)
{
ml_pipeline *p = (ml_pipeline *) pipe;
GstElement *element = NULL;
if (p) {
g_mutex_lock (&p->lock);
element = p->element;
if (element)
gst_object_ref (element);
g_mutex_unlock (&p->lock);
}
return element;
}
/**
* @brief Increases ref count of custom-easy filter.
*/
static void
ml_pipeline_custom_filter_ref (ml_custom_easy_filter_h custom)
{
ml_custom_filter_s *c = (ml_custom_filter_s *) custom;
if (c) {
g_mutex_lock (&c->lock);
c->ref_count++;
g_mutex_unlock (&c->lock);
}
}
/**
* @brief Decreases ref count of custom-easy filter.
*/
static void
ml_pipeline_custom_filter_unref (ml_custom_easy_filter_h custom)
{
ml_custom_filter_s *c = (ml_custom_filter_s *) custom;
if (c) {
g_mutex_lock (&c->lock);
if (c->ref_count > 0)
c->ref_count--;
g_mutex_unlock (&c->lock);
}
}
/**
* @brief Releases custom filter handle.
*/
static void
ml_pipeline_custom_free_handle (ml_custom_filter_s * custom)
{
if (custom) {
g_mutex_lock (&custom->lock);
g_free (custom->name);
ml_tensors_info_destroy (custom->in_info);
ml_tensors_info_destroy (custom->out_info);
g_mutex_unlock (&custom->lock);
g_mutex_clear (&custom->lock);
g_free (custom);
}
}
/**
* @brief Invoke callback for custom-easy filter.
*/
static int
ml_pipeline_custom_invoke (void *data, const GstTensorFilterProperties * prop,
const GstTensorMemory * in, GstTensorMemory * out)
{
int status;
ml_custom_filter_s *c;
ml_tensors_data_h in_data, out_data;
ml_tensors_data_s *_data;
guint i;
c = (ml_custom_filter_s *) data;
in_data = out_data = NULL;
/* internal error? */
if (!c || !c->cb)
return -1;
/* prepare invoke */
status = ml_tensors_data_create_no_alloc (c->in_info, &in_data);
if (status != ML_ERROR_NONE)
goto done;
_data = (ml_tensors_data_s *) in_data;
for (i = 0; i < _data->num_tensors; i++)
_data->tensors[i].tensor = in[i].data;
status = ml_tensors_data_create_no_alloc (c->out_info, &out_data);
if (status != ML_ERROR_NONE)
goto done;
_data = (ml_tensors_data_s *) out_data;
for (i = 0; i < _data->num_tensors; i++)
_data->tensors[i].tensor = out[i].data;
/* call invoke callback */
status = c->cb (in_data, out_data, c->pdata);
done:
/* NOTE: DO NOT free tensor data */
g_free (in_data);
g_free (out_data);
return status;
}
/**
* @brief Registers a custom filter.
*/
int
ml_pipeline_custom_easy_filter_register (const char *name,
const ml_tensors_info_h in, const ml_tensors_info_h out,
ml_custom_easy_invoke_cb cb, void *user_data,
ml_custom_easy_filter_h * custom)
{
int status = ML_ERROR_NONE;
ml_custom_filter_s *c;
GstTensorsInfo in_info, out_info;
check_feature_state ();
if (!name || !cb || !custom)
return ML_ERROR_INVALID_PARAMETER;
/* init null */
*custom = NULL;
if (!ml_tensors_info_is_valid (in) || !ml_tensors_info_is_valid (out))
return ML_ERROR_INVALID_PARAMETER;
/* create and init custom handle */
if ((c = g_new0 (ml_custom_filter_s, 1)) == NULL)
return ML_ERROR_OUT_OF_MEMORY;
g_mutex_init (&c->lock);
g_mutex_lock (&c->lock);
c->name = g_strdup (name);
c->ref_count = 0;
c->cb = cb;
c->pdata = user_data;
ml_tensors_info_create (&c->in_info);
ml_tensors_info_create (&c->out_info);
ml_tensors_info_clone (c->in_info, in);
ml_tensors_info_clone (c->out_info, out);
/* register custom filter */
ml_tensors_info_copy_from_ml (&in_info, in);
ml_tensors_info_copy_from_ml (&out_info, out);
if (NNS_custom_easy_register (name, ml_pipeline_custom_invoke, c,
&in_info, &out_info) != 0) {
nns_loge ("Failed to register custom filter %s.", name);
status = ML_ERROR_INVALID_PARAMETER;
}
g_mutex_unlock (&c->lock);
if (status == ML_ERROR_NONE) {
pipe_custom_add_data (PIPE_CUSTOM_TYPE_FILTER, name, c);
*custom = c;
} else {
ml_pipeline_custom_free_handle (c);
}
return status;
}
/**
* @brief Unregisters the custom filter.
*/
int
ml_pipeline_custom_easy_filter_unregister (ml_custom_easy_filter_h custom)
{
ml_custom_filter_s *c;
int status = ML_ERROR_NONE;
check_feature_state ();
if (!custom)
return ML_ERROR_INVALID_PARAMETER;
c = (ml_custom_filter_s *) custom;
g_mutex_lock (&c->lock);
if (c->ref_count > 0) {
ml_loge
("Failed to unregister custom filter %s, it is used in the pipeline.",
c->name);
status = ML_ERROR_INVALID_PARAMETER;
goto done;
}
if (NNS_custom_easy_unregister (c->name) != 0) {
ml_loge ("Failed to unregister custom filter %s.", c->name);
status = ML_ERROR_INVALID_PARAMETER;
goto done;
}
done:
g_mutex_unlock (&c->lock);
if (status == ML_ERROR_NONE) {
pipe_custom_remove_data (PIPE_CUSTOM_TYPE_FILTER, c->name);
ml_pipeline_custom_free_handle (c);
}
return status;
}
/**
* @brief Increases ref count of tensor_if custom condition.
*/
static void
ml_pipeline_if_custom_ref (ml_pipeline_if_h custom)
{
ml_if_custom_s *c = (ml_if_custom_s *) custom;
if (c) {
g_mutex_lock (&c->lock);
c->ref_count++;
g_mutex_unlock (&c->lock);
}
}
/**
* @brief Decreases ref count of tensor_if custom condition.
*/
static void
ml_pipeline_if_custom_unref (ml_pipeline_if_h custom)
{
ml_if_custom_s *c = (ml_if_custom_s *) custom;
if (c) {
g_mutex_lock (&c->lock);
if (c->ref_count > 0)
c->ref_count--;
g_mutex_unlock (&c->lock);
}
}
/**
* @brief Callback for tensor_if custom condition.
*/
static gboolean
ml_pipeline_if_custom (const GstTensorsInfo * info,
const GstTensorMemory * input, void *data, gboolean * result)
{
int status = 0;
guint i;
ml_if_custom_s *c;
ml_tensors_data_h in_data;
ml_tensors_data_s *_data;
ml_tensors_info_h ml_info;
GstTensorsInfo in_info = *info;
gboolean ret = FALSE;
c = (ml_if_custom_s *) data;
in_data = NULL;
/* internal error? */
if (!c || !c->cb)
return FALSE;
ml_tensors_info_create_from_gst (&ml_info, &in_info);
status = ml_tensors_data_create_no_alloc (ml_info, &in_data);
if (status != ML_ERROR_NONE)
goto done;
_data = (ml_tensors_data_s *) in_data;
for (i = 0; i < _data->num_tensors; i++)
_data->tensors[i].tensor = input[i].data;
/* call invoke callback */
g_mutex_lock (&c->lock);
status = c->cb (in_data, ml_info, result, c->pdata);
g_mutex_unlock (&c->lock);
if (status == 0)
ret = TRUE;
done:
ml_tensors_info_destroy (ml_info);
g_free (in_data);
return ret;
}
/**
* @brief Releases tensor_if custom condition.
*/
static void
ml_pipeline_if_custom_free (ml_if_custom_s * custom)
{
if (custom) {
g_mutex_lock (&custom->lock);
g_free (custom->name);
g_mutex_unlock (&custom->lock);
g_mutex_clear (&custom->lock);
g_free (custom);
}
}
/**
* @brief Registers the tensor_if custom callback.
*/
int
ml_pipeline_tensor_if_custom_register (const char *name,
ml_pipeline_if_custom_cb cb, void *user_data, ml_pipeline_if_h * if_custom)
{
int status = ML_ERROR_NONE;
ml_if_custom_s *c;
check_feature_state ();
if (!name || !cb || !if_custom)
return ML_ERROR_INVALID_PARAMETER;
/* init null */
*if_custom = NULL;
/* create and init custom handle */
if ((c = g_try_new0 (ml_if_custom_s, 1)) == NULL)
return ML_ERROR_OUT_OF_MEMORY;
g_mutex_init (&c->lock);
g_mutex_lock (&c->lock);
c->name = g_strdup (name);
c->ref_count = 0;
c->cb = cb;
c->pdata = user_data;
if (nnstreamer_if_custom_register (name, ml_pipeline_if_custom, c) != 0) {
nns_loge ("Failed to register tensor_if custom condition %s.", name);
status = ML_ERROR_STREAMS_PIPE;
}
g_mutex_unlock (&c->lock);
if (status == ML_ERROR_NONE) {
pipe_custom_add_data (PIPE_CUSTOM_TYPE_IF, name, c);
*if_custom = c;
} else {
ml_pipeline_if_custom_free (c);
}
return status;
}
/**
* @brief Unregisters the tensor_if custom callback.
*/
int
ml_pipeline_tensor_if_custom_unregister (ml_pipeline_if_h if_custom)
{
ml_if_custom_s *c;
int status = ML_ERROR_NONE;
check_feature_state ();
if (!if_custom)
return ML_ERROR_INVALID_PARAMETER;
c = (ml_if_custom_s *) if_custom;
g_mutex_lock (&c->lock);
if (c->ref_count > 0) {
ml_loge
("Failed to unregister custom condition %s, it is used in the pipeline.",
c->name);
status = ML_ERROR_INVALID_PARAMETER;
goto done;
}
if (nnstreamer_if_custom_unregister (c->name) != 0) {
ml_loge ("Failed to unregister tensor_if custom condition %s.", c->name);
status = ML_ERROR_STREAMS_PIPE;
goto done;
}
done:
g_mutex_unlock (&c->lock);
if (status == ML_ERROR_NONE) {
pipe_custom_remove_data (PIPE_CUSTOM_TYPE_IF, c->name);
ml_pipeline_if_custom_free (c);
}
return status;
}
|
CrackerCat/MiniSTL
|
Source/AssociativeContainers/RB-Tree/rb_tree.h
|
<gh_stars>0
#pragma once
#include "Algorithms/algobase/stl_algobase.h"
#include "Allocator/subAllocation/allocator.h"
#include "Function/stl_function.h"
#include "rb_tree_iterator.h"
namespace MiniSTL {
template<class Key, class Value, class KeyOfValue, class Compare,
class Alloc = simpleAlloc<Value>>
class rb_tree {
private:// Internal alias declarations
using base_ptr = __rb_tree_node_base *;
using rb_tree_node = __rb_tree_node<Value>;
using rb_tree_node_allocator = simpleAlloc<rb_tree_node>;
using color_type = rb_tree_color_type;
public:// Basic type declarations
using key_type = Key;
using value_type = Value;
using pointer = value_type *;
using const_pointer = const value_type *;
using reference = value_type &;
using const_reference = const value_type &;
using link_type = rb_tree_node *;
using size_type = size_t;
using difference_type = ptrdiff_t;
public:// Iterator declarations
using iterator = rb_tree_iterator<value_type, reference, pointer>;
using const_iterator =
rb_tree_iterator<value_type, const_reference, const_pointer>;
using reverse_iterator = __reverse_iterator<iterator>;
using const_reverse_iterator = __reverse_iterator<const_iterator>;
private:// operations of node
link_type get_node() { return rb_tree_node_allocator::allocate(); }
void put_node(link_type p) { rb_tree_node_allocator::deallocate(p); }
link_type create_node(const value_type &value) {
link_type temp = get_node();
try {
construct(&temp->value_field, value);
} catch (std::exception &) {
put_node(temp);
}
return temp;
}
link_type clone_node(link_type p) {
link_type temp = create_node(p->value_field);
temp->color = p->color;
temp->left = nullptr;
temp->right = nullptr;
return temp;
}
void destroy_node(link_type p) {
destroy(&p->value_field);
put_node(p);
}
private: // data member
size_type node_count;// 用节点数量表征树的大小
link_type header; // root的父亲,实现技巧
Compare key_compare;
private:// data member getter && setter
// header成员
link_type &root() const noexcept {
return reinterpret_cast<link_type &>(header->parent);
}
link_type &leftmost() const noexcept {
return reinterpret_cast<link_type &>(header->left);
}
link_type &rightmost() const noexcept {
return reinterpret_cast<link_type &>(header->right);
}
// 普通node的快速访问与设定
static link_type &left(link_type p) {
return reinterpret_cast<link_type &>(p->left);
}
static link_type &right(link_type p) {
return reinterpret_cast<link_type &>(p->right);
}
static link_type &parent(link_type p) {
return reinterpret_cast<link_type &>(p->parent);
}
static reference &value(link_type p) { return p->value_field; }
static const Key &key(link_type p) { return KeyOfValue()(value(p)); }
static color_type &color(link_type p) { return p->color; }
// base_node的快速访问与设定
static link_type &left(base_ptr p) {
return reinterpret_cast<link_type &>(p->left);
}
static link_type &right(base_ptr p) {
return reinterpret_cast<link_type &>(p->right);
}
static link_type &parent(base_ptr p) {
return reinterpret_cast<link_type &>(p->parent);
}
static reference &value(base_ptr p) {
return reinterpret_cast<link_type>(p)->value_field;
}
static const Key &key(base_ptr p) {
return KeyOfValue()(value(reinterpret_cast<link_type>(p)));
}
static color_type &color(base_ptr p) {
return reinterpret_cast<link_type>(p)->color;
}
// 求取极值(转交node_base)
static link_type minimum(link_type p) {
return reinterpret_cast<link_type>(__rb_tree_node_base::minimum(p));
}
static link_type maximum(link_type p) {
return reinterpret_cast<link_type>(__rb_tree_node_base::maximum(p));
}
private:// aux interface
link_type copy(link_type, link_type);
void empty_initialize() {
header = get_node();
color(header) = rb_tree_red;
root() = nullptr;
leftmost() = header;
rightmost() = header;
}
private:// rotate && rebalance
void rb_tree_rotate_left(base_ptr, base_ptr &);
void rb_tree_rotate_right(base_ptr, base_ptr &);
void rb_tree_rebalance(base_ptr, base_ptr &);
base_ptr rb_tree_rebalance_for_erase(base_ptr, base_ptr &, base_ptr &,
base_ptr &);
public:// ctor && dtor
rb_tree() : node_count(0), key_compare() { empty_initialize(); }
explicit rb_tree(const Compare &comp) : node_count(0), key_compare(comp) {
empty_initialize();
}
~rb_tree() {
clear();
put_node(header);
}
public:// copy operation
rb_tree(const rb_tree &rhs) : node_count(0), key_compare(rhs.key_compare) {
if (!rhs.root())
empty_initialize();
else {
header = get_node();
color(header) = rb_tree_red;
root() = copy(rhs.root(), header);
leftmost() = minimum(root());
rightmost() = maximum(root());
}
node_count = rhs.node_count;
}
rb_tree &operator=(const rb_tree &);
public:// move operation
rb_tree(rb_tree &&rhs) noexcept {
empty_initialize();
swap(rhs);
}
rb_tree &operator=(rb_tree &&rhs) noexcept {
clear();
swap(rhs);
return *this;
}
public:// getter
const_iterator begin() const noexcept { return leftmost(); }
const_iterator end() const noexcept { return header; }
const_iterator cbegin() const noexcept { return leftmost(); }
const_iterator cend() const noexcept { return header; }
const_reverse_iterator rbegin() const noexcept {
return const_reverse_iterator(end());
}
const_reverse_iterator rend() const noexcept {
return const_reverse_iterator(begin());
}
const_reverse_iterator crbegin() const noexcept {
return const_reverse_iterator(end());
}
const_reverse_iterator crend() const noexcept {
return const_reverse_iterator(begin());
}
bool empty() const noexcept { return node_count == 0; }
size_type size() const noexcept { return node_count; }
Compare key_comp() const noexcept { return Compare(key_compare); }
public:// setter
iterator begin() noexcept { return leftmost(); }
iterator end() noexcept { return header; }
reverse_iterator rbegin() noexcept { return reverse_iterator(end()); }
reverse_iterator rend() noexcept { return reverse_iterator(begin()); }
private:// aux interface for inset
iterator insert_aux(base_ptr, base_ptr, const value_type &);
public:// insert
pair<iterator, bool> insert_unique(const value_type &);
iterator insert_unique(iterator, const value_type &);
template<class InputIterator>
void insert_unique(InputIterator, InputIterator);
iterator insert_equal(iterator, const value_type &);
iterator insert_equal(const value_type &);
template<class InputIterator>
void insert_equal(InputIterator, InputIterator);
private:// aux interface for erase
void erase_aux(link_type) noexcept;
public:// erase
void erase(iterator);
size_type erase(const key_type &);
void erase(iterator, iterator);
void clear() noexcept;
public:// find
iterator find(const key_type &) noexcept;
const_iterator find(const key_type &) const noexcept;
size_type count(const key_type &) const noexcept;
iterator lower_bound(const key_type &) noexcept;
const_iterator lower_bound(const key_type &) const noexcept;
iterator upper_bound(const key_type &) noexcept;
const_iterator upper_bound(const key_type &) const noexcept;
pair<iterator, iterator> equal_range(const key_type &) noexcept;
pair<const_iterator, const_iterator> equal_range(const key_type &) const
noexcept;
public:// swap
void swap(rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &lhs) noexcept {
// swap data members
MiniSTL::swap(header, lhs.header);
MiniSTL::swap(node_count, lhs.node_count);
MiniSTL::swap(key_compare, lhs.key_compare);
}
};
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::iterator
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::insert_aux(
base_ptr x_, base_ptr y_, const value_type &val) {
link_type x = reinterpret_cast<link_type>(x_);
link_type y = reinterpret_cast<link_type>(y_);
link_type z;
if (y == header || x || key_compare(KeyOfValue()(val), key(y))) {
// 待插入节点之父为header||待插入节点自身并不为nullptr(何时触发?)||父节点明确大于待插入值
z = create_node(val);
left(y) = z;// 若y为header,此时leftmost==z
if (y == header) {
root() = z;
rightmost() = z;
} else if (y == leftmost()) {
leftmost() = z;
}
} else {
// 此时必成为y右子
z = create_node(val);
right(y) = z;
if (y == rightmost()) rightmost() = z;
}
parent(z) = y;
left(z) = nullptr;
right(z) = nullptr;
rb_tree_rebalance(z, header->parent);
++node_count;
return iterator(z);
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
void rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::erase_aux(
link_type x) noexcept {
while (x) {
// 递归式删除
erase_aux(right(x));
link_type y = left(x);
destroy_node(x);
x = y;
}
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
void rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::rb_tree_rebalance(
base_ptr x, base_ptr &root) {
x->color = rb_tree_red;
while (x != root && x->parent->color == rb_tree_red) {// 当前父节点为红
if (x->parent == x->parent->parent->left) { // 父亲为爷爷的左子
base_ptr y = x->parent->parent->right; // 伯父
if (y && y->color == rb_tree_red) { // 伯父存在且为红色
x->parent->color = rb_tree_black;
y->color = rb_tree_black;
x->parent->parent->color = rb_tree_red;
x = x->parent->parent;// 将x更新至祖父,准备上溯
} else { // 不存在伯父或其颜色为黑
if (x == x->parent->right) {
x = x->parent;
rb_tree_rotate_left(x, root);// 左旋
}
x->parent->color = rb_tree_black;
x->parent->parent->color = rb_tree_red;
rb_tree_rotate_right(x->parent->parent, root);
}
} else { // 父为右子,与上文对称
base_ptr y = x->parent->parent->left;// 伯父
if (y && y->color == rb_tree_red) {
x->parent->color = rb_tree_black;
y->color = rb_tree_black;
x->parent->parent->color = rb_tree_red;
x = x->parent->parent;// 将x更新至祖父,准备上溯
} else {
if (x == x->parent->left) {
x = x->parent;
rb_tree_rotate_right(x, root);
}
x->parent->color = rb_tree_black;
x->parent->parent->color = rb_tree_red;
rb_tree_rotate_left(x->parent->parent, root);
}
}
}
root->color = rb_tree_black;// root永远为黑色
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::base_ptr
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::rb_tree_rebalance_for_erase(
base_ptr z, base_ptr &root, base_ptr &leftmost, base_ptr &rightmost) {
base_ptr y = z;
base_ptr x = nullptr;
base_ptr x_parent = nullptr;
if (!y->left)// z至多存在一个孩子
x = y->right;
else {// z至少存在一个孩子
if (!y->right) {
x = y->left;
} else {
y = y->right;
while (y->left) y = y->left;
x = y->right;
}
}
if (y != z) {// 若条件成立,此时y为z的后代
z->left->parent = y;
y->left = z->left;
if (y != z->right) {
x_parent = y->parent;
if (x) x->parent = y->parent;
y->parent->left = x;
y->right = z->right;
z->right->parent = y;
} else
x_parent = y;
if (root == z)
root = y;
else if (z->parent->left == z)
z->parent->left = y;
else
z->parent->right = y;
y->parent = z->parent;
MiniSTL::swap(y->color, z->color);
y = z;
} else {
x_parent = y->parent;
if (x) x->parent = y->parent;
if (root == z)
root = x;
else if (z->parent->left == z)
z->parent->left = x;
else
z->parent->right = x;
if (leftmost == z) {
if (!z->right) {
leftmost = z->parent;
} else {
leftmost = __rb_tree_node_base::minimum(x);
}
}
if (rightmost == z) {
if (!z->left) {
rightmost = z->parent;
} else {
rightmost = __rb_tree_node_base::maximum(x);
}
}
}
if (y->color != rb_tree_red) {
while (x != root && (!x || x->color == rb_tree_black))
if (x == x->parent->left) {
base_ptr w = x_parent->right;
if (w->color == rb_tree_red) {
w->color = rb_tree_black;
x_parent->color = rb_tree_red;
rb_tree_rotate_left(x_parent, root);
w = x_parent->right;
}
if ((!w->left || w->left->color == rb_tree_black) && (!w->right || w->right->color == rb_tree_black)) {
w->color = rb_tree_red;
x = x_parent;
x_parent = x_parent->parent;
} else {
if (!w->right || w->right->color == rb_tree_black) {
if (w->left) w->left->color = rb_tree_black;
w->color = rb_tree_red;
rb_tree_rotate_right(w, root);
w = x_parent->right;
}
w->color = x_parent->color;
x_parent->color = rb_tree_black;
if (x->right) w->right->color = rb_tree_black;
rb_tree_rotate_left(x_parent, root);
break;
}
} else {
base_ptr w = x_parent->left;
if (w->color == rb_tree_red) {
w->color = rb_tree_black;
x_parent->color = rb_tree_red;
rb_tree_rotate_right(x_parent, root);
w = x_parent->left;
}
if ((!w->right || w->right->color == rb_tree_black) && (!w->left || w->left->color == rb_tree_black)) {
w->color = rb_tree_red;
x = x_parent;
x_parent = x_parent->parent;
} else {
if (!w->left || w->left->color == rb_tree_black) {
if (w->right) w->right->color = rb_tree_black;
w->color = rb_tree_red;
rb_tree_rotate_left(w, root);
w = x_parent->left;
}
w->color = x_parent->color;
x_parent->color = rb_tree_black;
if (w->left) w->left->color = rb_tree_black;
rb_tree_rotate_right(x_parent, root);
break;
}
}
if (x) x->color = rb_tree_black;
}
return y;
}
// 将x的右子树绕x逆时针旋转,其右子的左子变为了x,而原本的左子变为了x的右子
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline void rb_tree<Key, Value, KeyOfValue, Compare,
Alloc>::rb_tree_rotate_left(base_ptr x, base_ptr &root) {
base_ptr y = x->right;// 旋转点右子
x->right = y->left; // 将x的右子树替换为y的左子树
if (y->left) // 若存在,则确立新的父子关系
y->left->parent = x;
y->parent = x->parent;
// 令y顶替x
if (x == root)
root = y;
else if (x == x->parent->left)
x->parent->left = y;
else
x->parent->right = y;
y->left = x;
x->parent = y;
}
// 右旋与左旋相对称
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline void rb_tree<Key, Value, KeyOfValue, Compare,
Alloc>::rb_tree_rotate_right(base_ptr x, base_ptr &root) {
base_ptr y = x->left;
x->left = y->right;
if (y->right) y->right->parent = x;
y->parent = x->parent;
if (x == root)
root = y;
else if (x == x->parent->right)
x->parent->right = y;
else
x->parent->left = y;
y->right = x;
x->parent = y;
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::iterator rb_tree<
Key, Value, KeyOfValue, Compare, Alloc>::find(const key_type &k) noexcept {
link_type y = header;// 最后一个不小于k的node
link_type x = root();// 当前node
while (x)
if (!key_compare(key(x), k))// x的键值不小于k
y = x, x = left(x);
else
x = right(x);
iterator j = iterator(y);
// 没找到存在两种可能
// 1.k比最大值还大,j已经指向了end
// 2.已经寻至叶子,但此时发现k仍然小于key(j.node) 若找到应有k==key(j.node)
return (j == end()) || key_compare(k, key(j.node)) ? end() : j;
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::const_iterator
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::find(const key_type &k) const
noexcept {
link_type y = header;// 最后一个不小于k的node
link_type x = root();// 当前node
while (x)
if (!key_compare(key(x), k))// x的键值不小于k
y = x, x = left(x);
else
x = right(x);
const_iterator j = const_iterator(y);
// 没找到存在两种可能
// 1.k比最大值还大,j已经指向了end
// 2.已经寻至叶子,但此时发现k仍然小于key(j.node) 若找到应有k==key(j.node)
return (j == end()) || key_compare(k, key(j.node)) ? end() : j;
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::size_type
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::count(const key_type &k) const
noexcept {
pair<const_iterator, const_iterator> p = equal_range(k);
return MiniSTL::distance(p.first, p.second);
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::iterator
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::lower_bound(
const key_type &k) noexcept {
link_type y = header;
link_type x = root();
while (x)
if (!key_compare(key(x), k))
y = x, x = left(x);
else
x = right(x);
return iterator(y);
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::const_iterator
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::lower_bound(
const key_type &k) const noexcept {
link_type y = header;
link_type x = root();
while (x)
if (!key_compare(key(x), k))
y = x, x = left(x);
else
x = right(x);
return const_iterator(y);
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::iterator
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::upper_bound(
const key_type &k) noexcept {
link_type y = header;
link_type x = root();
while (x)
if (key_compare(k, key(x)))
y = x, x = left(x);
else
x = right(x);
return iterator(y);
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::const_iterator
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::upper_bound(
const key_type &k) const noexcept {
link_type y = header;
link_type x = root();
while (x)
if (key_compare(k, key(x)))
y = x, x = left(x);
else
x = right(x);
return const_iterator(y);
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline pair<typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::iterator,
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::iterator>
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::equal_range(
const key_type &k) noexcept {
return pair<iterator, iterator>(lower_bound(k), upper_bound(k));
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline pair<
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::const_iterator,
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::const_iterator>
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::equal_range(
const key_type &k) const noexcept {
return pair<const_iterator, const_iterator>(lower_bound(k), upper_bound(k));
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::operator=(const rb_tree &rhs) {
if (this != &rhs) {
clear();
node_count = 0;
key_compare = rhs.key_compare;
if (!rhs.root()) {
root() = nullptr;
leftmost() = header;
rightmost() = header;
} else {
root() = copy(rhs.root(), header);
leftmost() = minimum(root());
rightmost() = maximum(root());
node_count = rhs.node_count;
}
}
return *this;
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
pair<typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::iterator, bool>
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::insert_unique(
const value_type &val) {
link_type y = header;
link_type x = root();
bool comp = true;
while (x) {
y = x;
comp = key_compare(KeyOfValue()(val), key(x));// value是否小于x的键值
x = comp ? left(x) : right(x);
}
// 此时y必为待插入点的父节点(也必为叶节点)
iterator j(y);
if (comp) { // y键值大于value键值,插于左侧
if (j == begin()) {//待插入点之父为最左节点
return pair<iterator, bool>(insert_aux(x, y, val), true);
} else {
--j;// 调整j准备完成测试(可能与某键值重复)
}
}
if (key_compare(key(j.node), KeyOfValue()(val)))
// 新键值不与旧有键值重复,放心插入
return pair<iterator, bool>(insert_aux(x, y, val), true);
return pair<iterator, bool>(j, false);// 当前value为重复值
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::iterator
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::insert_unique(
iterator pos, const value_type &val) {
if (pos.node == header->left) {// begin()
if (size() > 0 && key_compare(KeyOfValue()(val), key(pos.node)))
return insert_aux(pos.node, pos.node, val);
else
return insert_unique(val).first;
} else if (pos.node == header) {// end()
if (key_compare(key(rightmost()), KeyOfValue()(val)))
return insert_aux(nullptr, rightmost(), val);
else
return insert_unique(val).first;
} else {
iterator before = pos;
--before;
if (key_compare(key(before.node), KeyOfValue()(val)) && key_compare(KeyOfValue()(val), key(pos.node))) {
if (!right(before.node))
return insert_aux(nullptr, before.node, val);
else
return insert_aux(pos.node, pos.node, val);
} else
return insert_unique(val).first;
}
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
template<class InputIterator>
void rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::insert_unique(
InputIterator first, InputIterator last) {
for (; first != last; ++first) insert_unique(*first);
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::iterator
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::insert_equal(
const value_type &val) {
link_type y = header;
link_type x = root();
while (x) {
y = x;
x = key_compare(KeyOfValue()(val), key(x)) ? left(x)
: right(x);// 大则向左
}
return insert_aux(x, y, val);// x为新值插入点,y为其父
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::iterator
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::insert_equal(
iterator pos, const value_type &val) {
if (pos.node == header->left) {// begin()
if (size() > 0 && !key_compare(key(pos.node), KeyOfValue()(val)))
return insert_aux(pos.node, pos.node, value);
else
return insert_equal(val);
} else if (pos.node == header) {// end()
if (!key_compare(KeyOfValue()(val)), key(rightmost()))
return insert_aux(nullptr, rightmost(), val);
else
return insert_equal(val);
} else {
iterator before = pos;
--before;
if (!key_compare(KeyOfValue()(val), key(before.node)) && !key_compare(key(pos.node), KeyOfValue()(val))) {
if (!right(before.node))
return insert_aux(nullptr, before.node, val);
else
return insert_aux(pos.node, pos.node, val);
} else
return insert_equal(val);
}
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
template<class InputIterator>
void rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::insert_equal(
InputIterator first, InputIterator last) {
for (; first != last; ++first) insert_equal(*first);
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
void rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::erase(iterator pos) {
link_type y = reinterpret_cast<link_type>(rb_tree_rebalance_for_erase(
pos.node, header->parent, header->left, header->right));
destroy_node(y);
--node_count;
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::size_type
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::erase(const key_type &k) {
pair<iterator, iterator> p = equal_range(k);
size_type n = MiniSTL::distance(p.first, p.second);
erase(p.first, p.second);
return n;
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
void rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::erase(iterator first,
iterator last) {
if (first == begin() && last == end())
clear();
else
while (first != last) erase(first++);
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
void rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::clear() noexcept {
if (node_count) {
erase_aux(root());
leftmost() = header;
root() = nullptr;
rightmost() = header;
node_count = 0;
}
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
typename rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::link_type
rb_tree<Key, Value, KeyOfValue, Compare, Alloc>::copy(link_type x,
link_type y) {
link_type top = clone_node(x);
top->parent = y;
try {
if (x->right) top->right = copy(right(x), top);
y = top;
x = left(x);
while (x) {
link_type p = clone_node(x);
y->left = p;
p->parent = y;
if (x->right) p->right = copy(right(x), p);
y = p;
x = left(x);
}
} catch (std::exception &) {
erase_aux(top);
}
return top;
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline bool operator==(
const rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &lhs,
const rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &rhs) {
return lhs.size() == rhs.size() && MiniSTL::equal(lhs.cbegin(), lhs.cend(), rhs.cbegin());
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline bool operator!=(
const rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &lhs,
const rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &rhs) {
return !(lhs == rhs);
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline bool operator<(
const rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &lhs,
const rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &rhs) {
return MiniSTL::lexicographical_compare(lhs.cbegin(), lhs.cend(),
rhs.cbegin(), rhs.cend());
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline bool operator>(
const rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &lhs,
const rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &rhs) {
return rhs < lhs;
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline bool operator<=(
const rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &lhs,
const rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &rhs) {
return !(rhs < lhs);
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline bool operator>=(
const rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &lhs,
const rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &rhs) {
return !(lhs < rhs);
}
template<class Key, class Value, class KeyOfValue, class Compare, class Alloc>
inline void swap(
rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &lhs,
rb_tree<Key, Value, KeyOfValue, Compare, Alloc> &rhs) noexcept {
lhs.swap(rhs);
}
}// namespace MiniSTL
|
CrackerCat/MiniSTL
|
Source/Allocator/simpleAlloc/simpleAlloc.h
|
<gh_stars>0
#pragma once
#include <climits>
#include <cstddef>
#include <cstdlib>
#include <iostream>
#include <new>
namespace simpleAlloc {
// just use new and delete to make a allocator
template<class T>
inline T *_allocate(ptrdiff_t size, T *) {
std::set_new_handler(nullptr);
T *tmp =
static_cast<T *>(::operator new(static_cast<size_t>(size * sizeof(T))));
if (tmp == nullptr) {
std::cerr << "out of memory";
exit(-1);
}
return tmp;
}
template<class T>
inline void _deallocate(T *buffer) {
::operator delete(buffer);
}
template<class T1, class T2>
inline void _construct(T1 *p, const T2 &value) {
new (p) T1(value);
}
template<class T>
inline void _destory(T *p) {
p->~T();
}
template<class T>
class allocator {
public:
// alias declarations
using value_type = T;
using pointer = T *;
using const_pointer = const T *;
using reference = T &;
using const_refernce = const T &;
using size_type = size_t;
using difference_type = ptrdiff_t;
template<class U>
struct rebind {
using other = allocator<U>;
};
pointer allocate(size_type n, const void *hint = nullptr) {
return _allocate(static_cast<difference_type>(n), nullptr);
}
void deallocate(pointer p, size_type n) { _deallocate(p); }
void construct(pointer p, const T &value) { _construct(p, value); }
void destroy(pointer p) { _destory(p); }
pointer address(reference x) { return static_cast<pointer>(&x); }
const_pointer const_address(reference x) {
return static_cast<const_pointer>(&x);
}
size_type max_size() const { return size_type(UINT_MAX / sizeof(T)); }
};
}// namespace simpleAlloc
|
CrackerCat/MiniSTL
|
Source/SequenceContainers/Deque/stl_deque.h
|
#pragma once
#include "Allocator/subAllocation/allocator.h"
#include "Allocator/subAllocation/uninitialized.h"
#include "deque_iterator.h"
namespace MiniSTL {
template<class T, class Alloc = simpleAlloc<T>>
class deque {
public:// alias declarations
using value_type = T;
using pointer = T *;
using reference = T &;
using const_reference = const T &;
using size_type = size_t;
using difference_type = ptrdiff_t;
using iterator = __deque_iterator<T, T &, T *>;
using reverse_iterator = MiniSTL::__reverse_iterator<iterator>;
using const_iterator = __deque_iterator<T, const T &, const T *>;
using const_reverse_iterator = MiniSTL::__reverse_iterator<const_iterator>;
private:// internal alias declarations
using map_pointer = pointer *;
using node_allocator = simpleAlloc<value_type>;
using map_allocator = simpleAlloc<pointer>;
private: // data member
iterator start; // 第一个节点
iterator finish;// 最后一个节点
map_pointer map;// 指向节点的指针
size_type map_size;
private:// aux_interface for node
value_type *allocate_node() {
return node_allocator::allocate(__deque_buf_size(sizeof(value_type)));
}
void deallocate_node(value_type *p) {
node_allocator::deallocate(p, __deque_buf_size(sizeof(value_type)));
}
void create_nodes(map_pointer, map_pointer);
void destroy_nodes(map_pointer, map_pointer);
private:// aux_interface for map
void initialize_map(size_type);
void deallocate_map(map_pointer p, size_type n) {
map_allocator::deallocate(p, n);
}
void reallocate_map(size_type, bool);
void reserve_map_at_front(size_type nodes_to_add = 1);
void reserve_map_at_back(size_type nodes_to_add = 1);
iterator reserve_elements_at_front(size_type);
iterator reserve_elements_at_back(size_type);
void new_elements_at_front(size_type);
void new_elements_at_back(size_type);
private:// aux_interface for ctor
size_type initial_map_size() const noexcept { return 8U; }
size_type buffer_size() const noexcept { return iterator::buffer_size(); }
void fill_initialize(const value_type &);
template<class Integer>
void initialize_dispatch(Integer n, Integer val, _true_type) {
initialize_map(static_cast<size_type>(n));
fill_initialize(static_cast<value_type>(val));
}
template<class InputIterator>
void initialize_dispatch(InputIterator first, InputIterator last,
_false_type) {
range_initialize(first, last, iterator_category_t<InputIterator>());
}
template<class InputIterator>
void range_initialize(InputIterator first, InputIterator last,
input_iterator_tag);
template<class ForwardIterator>
void range_initialize(ForwardIterator first, ForwardIterator last,
forward_iterator_tag);
public:// ctor && dtor
deque() : start(), finish(), map(nullptr), map_size(0) {
initialize_map(0);
}
explicit deque(size_type n) : start(), finish(), map(nullptr), map_size(0) {
initialize_map(n);
fill_initialize(value_type());
}
deque(size_type n, const value_type &val)
: start(), finish(), map(nullptr), map_size(0) {
initialize_map(n);
fill_initialize(val);
}
template<class InputIterator>
deque(InputIterator first, InputIterator last) {
initialize_dispatch(first, last, _is_integer_t<InputIterator>());
}
deque(std::initializer_list<value_type> ils) {
range_initialize(ils.begin(), ils.end(), random_access_iterator_tag());
}
~deque();
public:// copy operations
deque(const deque &rhs) {
initialize_map(rhs.size());
MiniSTL::uninitialized_copy(rhs.begin(), rhs.end(), start);
}
deque &operator=(const deque &);
public:// move operations
deque(deque &&);
deque &operator=(deque &&) noexcept;
public:// getter
const_iterator begin() const noexcept { return start; }
const_iterator end() const noexcept { return finish; }
const_iterator cbegin() const noexcept { return start; }
const_iterator cend() const noexcept { return finish; }
const_reverse_iterator crbegin() const noexcept {
return const_reverse_iterator(finish);
}
const_reverse_iterator crend() const noexcept {
return const_reverse_iterator(start);
}
const_reference operator[](size_type n) const noexcept {
return start[static_cast<difference_type>(n)];
}
const_reference front() const noexcept { return *start; }
const_reference back() const noexcept { return *(finish - 1); }
size_type size() const noexcept { return finish - start; }
bool empty() const noexcept { return finish == start; }
public:// setter
iterator begin() noexcept { return start; }
iterator end() noexcept { return finish; }
reverse_iterator rbegin() noexcept { return reverse_iterator(finish); }
reverse_iterator rend() noexcept { return reverse_iterator(start); }
reference operator[](size_type n) {
return start[static_cast<difference_type>(n)];
}
reference front() noexcept { return *start; }
reference back() noexcept { return *(finish - 1); }
private:// aux_interface for push && pop
void push_back_aux(const value_type &);
void push_front_aux(const value_type &);
void pop_back_aux();
void pop_front_aux();
public:// push && pop
void push_back(const value_type &);
void push_front(const value_type &);
void pop_back();
void pop_front();
private:// aux_interface for assign
void fill_assign(size_type, const value_type &);
template<class Integer>
void assign_dispatch(Integer n, Integer val, _true_type) {
fill_assign(static_cast<size_type>(n), static_cast<value_type>(val));
}
template<class InputIterator>
void assign_dispatch(InputIterator first, InputIterator last, _false_type) {
assign_aux(first, last, iterator_category_t<InputIterator>());
}
template<class InputIterator>
void assign_aux(InputIterator, InputIterator, input_iterator_tag);
template<class ForwardIterator>
void assign_aux(ForwardIterator, ForwardIterator, forward_iterator_tag);
public:// assign
void assign(size_type n, const value_type &val) { fill_assign(n, val); }
void assign(std::initializer_list<value_type> ils) {
assign(ils.begin(), ils.end());
}
template<class InputIterator>
void assign(InputIterator first, InputIterator last) {
assign_dispatch(first, last, _is_integer_t<InputIterator>());
}
deque &operator=(std::initializer_list<value_type> ils) {
assign(ils.begin(), ils.end());
return *this;
}
private:// aux_interface for insert
void fill_insert(iterator, size_type, const value_type &);
template<class Integer>
void insert_dispatch(iterator pos, Integer n, Integer val, _true_type) {
fill_insert(pos, static_cast<size_type>(n),
static_cast<value_type>(val));
}
template<class InputIterator>
void insert_dispatch(iterator pos, InputIterator first, InputIterator last,
_false_type) {
range_insert_aux(pos, first, last,
iterator_category_t<InputIterator>());
}
template<class InputIterator>
void range_insert_aux(iterator, InputIterator, InputIterator,
input_iterator_tag);
template<class ForwardIterator>
void range_insert_aux(iterator, ForwardIterator, ForwardIterator,
forward_iterator_tag);
iterator insert_aux(iterator, const value_type &);
void insert_aux(iterator, size_type, const value_type &);
template<class ForwardIterator>
void insert_aux(iterator, ForwardIterator, ForwardIterator, size_type);
public:// insert
iterator insert(iterator, const value_type &);
iterator insert(iterator pos) { return insert(pos, value_type()); }
void insert(iterator pos, size_type n, const value_type &val) {
fill_insert(pos, n, val);
}
template<class InputIterator>
void insert(iterator pos, InputIterator first, InputIterator last) {
insert_dispatch(pos, first, last, _is_integer_t<InputIterator>());
}
public:// erase
iterator erase(iterator);
iterator erase(iterator, iterator);
void clear();
public:// resize
void resize(size_type, const value_type &);
void resize(size_type new_size) { resize(new_size, value_type()); }
public:// swap
void swap(deque &rhs) noexcept;
};
template<class T, class Alloc>
void deque<T, Alloc>::create_nodes(map_pointer nstart, map_pointer nfinish) {
map_pointer cur;
try {
// 为每一个节点配置空间
for (cur = nstart; cur <= nfinish; ++cur) *cur = allocate_node();
} catch (std::exception &) {
destroy_nodes(nstart, cur);
throw;
}
}
template<class T, class Alloc>
void deque<T, Alloc>::destroy_nodes(map_pointer nstart, map_pointer nfinish) {
for (map_pointer n = nstart; n < nfinish; ++n) deallocate_node(*n);
}
template<class T, class Alloc>
void deque<T, Alloc>::initialize_map(size_type n) {
// 所需节点数(整除则多配置一个)
size_type num_nodes = n / buffer_size() + 1;
// 一个map至少管理8个节点,至多管理num_nodes+2个
map_size = MiniSTL::max(initial_map_size(), num_nodes + 2);
map = map_allocator::allocate(map_size);
// 令nstart与nfinish指向map所拥有的全部node的中部,以便日后扩充头尾
map_pointer nstart = map + (map_size - num_nodes) / 2;
map_pointer nfinish = nstart + num_nodes;
try {
create_nodes(nstart, nfinish);
} catch (std::exception &) {
deallocate_map(map, map_size);
map = nullptr;
map_size = 0;
throw;
}
start.set_node(nstart);
finish.set_node(nfinish - 1);
start.cur = start.first;
finish.cur =
finish.first + n % buffer_size();// 若n%buffer_size==0,会多配置一个节点,此时cur指向该节点头部
}
template<class T, class Alloc>
void deque<T, Alloc>::fill_initialize(const value_type &val) {
map_pointer cur;
try {
// 为每个缓冲区设定初值
for (cur = start.node; cur < finish.node; ++cur)
MiniSTL::uninitialized_fill(*cur, *cur + buffer_size(), val);
// 最后一个缓冲区只设定至需要处
MiniSTL::uninitialized_fill(finish.first, finish.cur, val);
} catch (std::exception &) {
destroy(start, iterator(*cur, cur));
throw;
}
}
template<class T, class Alloc>
template<class InputIterator>
void deque<T, Alloc>::range_initialize(InputIterator first, InputIterator last,
input_iterator_tag) {
initialize_map(0);
try {
for (; first != last; ++first) push_back(*first);
} catch (std::exception &) {
clear();
throw;
}
}
template<class T, class Alloc>
template<class ForwardIterator>
void deque<T, Alloc>::range_initialize(ForwardIterator first,
ForwardIterator last,
forward_iterator_tag) {
size_type n = MiniSTL::distance(first, last);
initialize_map(n);
map_pointer cur_node;
try {
for (cur_node = start.node; cur_node < finish.node; ++cur_node) {
ForwardIterator mid = first;
MiniSTL::advance(mid, buffer_size());
MiniSTL::uninitialized_copy(first, last, *cur_node);
first = mid;
}
MiniSTL::uninitialized_copy(first, last, finish.first);
} catch (std::exception &) {
destroy(start, iterator(*cur_node, cur_node));
throw;
}
}
template<class T, class Alloc>
inline void deque<T, Alloc>::reallocate_map(size_type nodes_to_add,
bool add_at_front) {
size_type old_num_nodes = finish.node - start.node + 1;
size_type new_num_nodes = old_num_nodes + nodes_to_add;
map_pointer new_nstart;
if (map_size > 2 * new_num_nodes) {
// 某一端出现失衡,因此释放存储区完成重新中央分配,
// 规定新的nstart,若添加在前端则向后多移动n个单位
new_nstart = map + (map_size - new_num_nodes) / 2 + (add_at_front ? nodes_to_add : 0);
if (new_nstart < start.node)// 整体前移
MiniSTL::copy(start.node, finish.node + 1, new_nstart);
else// 整体后移
MiniSTL::copy_backward(start.node, finish.node + 1,
new_nstart + old_num_nodes);
} else {
size_type new_map_size =
map_size + MiniSTL::max(map_size, nodes_to_add) + 2;
// 分配新空间
map_pointer new_map = map_allocator::allocate(new_map_size);
new_nstart = new_map + (new_map_size - new_num_nodes) / 2 + (add_at_front ? nodes_to_add : 0);
// 拷贝原有内容
MiniSTL::copy(start.node, finish.node + 1, new_nstart);
// 释放原map
map_allocator::deallocate(map, map_size);
// 重新设定map
map = new_map;
map_size = new_map_size;
}
//设定start与finish
start.set_node(new_nstart);
finish.set_node(new_nstart + old_num_nodes - 1);// 注意并非new_num,接下来的设定转交其他函数处理
}
template<class T, class Alloc>
inline deque<T, Alloc> &deque<T, Alloc>::operator=(const deque &rhs) {
const size_type len = size();
if (&rhs != this) {
if (len >= rhs.size())
erase(MiniSTL::copy(rhs.begin(), rhs.end(), start), finish);
else {
const_iterator mid =
rhs.begin() + static_cast<difference_type>(len);
MiniSTL::copy(rhs.begin(), mid, start);
insert(finish, mid, rhs.end());
}
}
return *this;
}
template<class T, class Alloc>
inline void deque<T, Alloc>::reserve_map_at_back(size_type nodes_to_add) {
// map_size-(finish.node-map+1) == 后端剩余node个数
if (nodes_to_add + 1 > map_size - (finish.node - map))
reallocate_map(nodes_to_add, false);
}
template<class T, class Alloc>
inline void deque<T, Alloc>::reserve_map_at_front(size_type nodes_to_add) {
// start.node-map==前端剩余node个数
if (nodes_to_add > static_cast<size_type>(start.node - map))
reallocate_map(nodes_to_add, true);
}
template<class T, class Alloc>
inline typename deque<T, Alloc>::iterator
deque<T, Alloc>::reserve_elements_at_front(size_type n) {
size_type vacancies = start.cur - start.first;
if (n > vacancies) new_elements_at_front(n - vacancies);
return start - static_cast<difference_type>(n);
}
template<class T, class Alloc>
inline typename deque<T, Alloc>::iterator
deque<T, Alloc>::reserve_elements_at_back(size_type n) {
size_type vacancies = finish.last - finish.cur - 1;
if (n > vacancies) new_elements_at_back(n - vacancies);
return finish + static_cast<difference_type>(n);
}
template<class T, class Alloc>
void deque<T, Alloc>::new_elements_at_front(size_type new_elems) {
size_type new_nodes = (new_elems + buffer_size() - 1) / buffer_size();
reserve_map_at_front(new_nodes);
size_type i;
try {
for (i = 1; i <= new_nodes; ++i) *(start.node - i) = allocate_node();
} catch (std::exception &) {
for (size_type j = 1; j < i; ++j) deallocate_node(*(start.node - j));
throw;
}
}
template<class T, class Alloc>
void deque<T, Alloc>::new_elements_at_back(size_type new_elems) {
size_type new_nodes = (new_elems + buffer_size() - 1) / buffer_size();
reserve_map_at_back(new_nodes);
size_type i;
try {
for (i = 1; i <= new_nodes; ++i) *(finish.node + i) = allocate_node();
} catch (std::exception &) {
for (size_type j = 1; j < i; ++j) deallocate_node(*(finish.node + j));
throw;
}
}
template<class T, class Alloc>
inline void deque<T, Alloc>::push_back_aux(const value_type &value) {
value_type value_copy = value;
reserve_map_at_back(); // 若符合条件则重新更换map
*(finish.node + 1) = allocate_node();// 配置新节点
try {
construct(finish.cur, value_copy);
finish.set_node(finish.node + 1);
finish.cur = finish.first;// 更新finish.cur为当前first
} catch (std::exception &) {
deallocate_node(*(finish.node + 1));
throw;
}
}
template<class T, class Alloc>
inline void deque<T, Alloc>::push_front_aux(const value_type &value) {
value_type value_copy = value;
reserve_map_at_front(); // 若符合条件则重新更换map
*(start.node - 1) = allocate_node();// 配置新节点
try {
start.set_node(start.node - 1);
start.cur = start.last - 1;
construct(start.cur, value);
} catch (std::exception &) {
++start;
deallocate_node(*(start.node - 1));
throw;
}
}
template<class T, class Alloc>
inline void deque<T, Alloc>::pop_back_aux() {
node_allocator::deallocate(finish.first);
finish.set_node(finish.node - 1);
finish.cur = finish.last - 1;
destroy(finish.cur);
}
template<class T, class Alloc>
inline void deque<T, Alloc>::pop_front_aux() {
destroy(start.cur);
node_allocator::deallocate(start.first);
start.set_node(start.node + 1);
start.cur = start.first;
}
template<class T, class Alloc>
typename deque<T, Alloc>::iterator deque<T, Alloc>::insert_aux(
iterator pos, const value_type &val) {
difference_type index = pos - start;// 插入点之前的元素个数
value_type value_copy = val;
if (static_cast<size_type>(index) < size() / 2) {// 前移
// 插图见书
push_front(front());// 最前端加入哨兵以作标识,注意此时start发生了改变
iterator front1 = start;
++front1;// 复制后自增效率较高
iterator front2 = front1;
++front2;
pos = start + index;
iterator pos1 = pos;
++pos1;
MiniSTL::copy(front2, pos1, front1);// 移动元素
} else {
// 过程类似于上
push_back(back());
iterator back1 = finish;
--back1;
iterator back2 = back1;
--back2;
pos = start + index;
MiniSTL::copy_backward(pos, back2, back1);
}
*pos = value_copy;
return pos;
}
template<class T, class Alloc>
void deque<T, Alloc>::fill_insert(iterator pos, size_type n,
const value_type &val) {
if (pos.cur == start.cur) {
iterator new_start = reserve_elements_at_front(n);
try {
MiniSTL::uninitialized_fill(new_start, start, val);
start = new_start;
} catch (std::exception &) {
destroy_nodes(new_start.node, start.node);
}
} else if (pos.cur == finish.cur) {
iterator new_finish = reserve_elements_at_back(n);
try {
MiniSTL::uninitialized_fill(finish, new_finish, val);
finish = new_finish;
} catch (std::exception &) {
destroy_nodes(finish.node + 1, new_finish.node + 1);
}
} else
insert_aux(pos, n, val);
}
template<class T, class Alloc>
void deque<T, Alloc>::insert_aux(iterator pos, size_type n,
const value_type &val) {
const difference_type elems_before = pos - start;
size_type length = size();
value_type value_copy = val;
if (elems_before < static_cast<difference_type>(length / 2)) {
iterator new_start = reserve_elements_at_front(n);
iterator old_start = start;
pos = start + elems_before;
try {
if (elems_before >= static_cast<difference_type>(n)) {
iterator start_n = start + static_cast<difference_type>(n);
MiniSTL::uninitialized_copy(start, start_n, new_start);
start = new_start;
MiniSTL::copy(start_n, pos, old_start);
MiniSTL::fill(pos - static_cast<difference_type>(n), pos,
value_copy);
} else {
MiniSTL::uninitialized_copy_fill(start, pos, new_start, start,
value_copy);// extensions
start = new_start;
MiniSTL::fill(old_start, pos, val);
}
} catch (std::exception &) {
destroy_nodes(new_start.node, start.node);
throw;
}
} else {
iterator new_finish = reserve_elements_at_back(n);
iterator old_finish = finish;
const difference_type elems_after =
static_cast<difference_type>(length) - elems_before;
pos = finish - elems_after;
try {
if (elems_after >= static_cast<difference_type>(n)) {
iterator finish_n = finish - static_cast<difference_type>(n);
MiniSTL::uninitialized_copy(finish_n, finish, finish);
finish = new_finish;
MiniSTL::copy_backward(pos, finish_n, old_finish);
MiniSTL::fill(pos, pos + static_cast<difference_type>(n),
value_copy);
} else {
MiniSTL::uninitialized_fill_copy(
finish, pos + static_cast<difference_type>(n), value_copy,
pos,
finish);// extensions
finish = new_finish;
MiniSTL::fill(pos, old_finish, value_copy);
}
} catch (std::exception &) {
destroy_nodes(finish.node + 1, new_finish.node + 1);
throw;
}
}
}
template<class T, class Alloc>
template<class ForwardIterator>
void deque<T, Alloc>::insert_aux(iterator pos, ForwardIterator first,
ForwardIterator last, size_type n) {
const difference_type elems_before = pos - start;
size_type length = size();
if (elems_before < static_cast<difference_type>(length / 2)) {
iterator new_start = reserve_elements_at_front(n);
iterator old_start = start;
pos = start + elems_before;
try {
if (elems_before >= static_cast<difference_type>(n)) {
iterator start_n = start + static_cast<difference_type>(n);
MiniSTL::uninitialized_copy(start, start_n, new_start);
start = new_start;
MiniSTL::copy(start_n, pos, old_start);
MiniSTL::copy(first, last,
pos - static_cast<difference_type>(n));
} else {
ForwardIterator mid = first;
MiniSTL::advance(
mid, static_cast<difference_type>(n) - elems_before);
MiniSTL::uninitialized_copy_copy(start, pos, first, mid,
new_start);// extensions
start = new_start;
MiniSTL::copy(mid, last, old_start);
}
} catch (std::exception &) {
destroy_nodes(new_start.node, start.node);
throw;
}
} else {
iterator new_finish = reserve_elements_at_back(n);
iterator old_finish = finish;
const difference_type elems_after =
static_cast<difference_type>(length) - elems_before;
pos = finish - elems_after;
try {
if (elems_after >= static_cast<difference_type>(n)) {
iterator finish_n = finish - static_cast<difference_type>(n);
MiniSTL::uninitialized_copy(finish_n, finish, finish);
finish = new_finish;
MiniSTL::copy_backward(pos, finish_n, old_finish);
MiniSTL::copy(first, last, pos);
} else {
ForwardIterator mid = first;
MiniSTL::advance(mid, elems_after);
MiniSTL::uninitialized_copy_copy(mid, last, pos, finish,
finish);// extensions
finish = new_finish;
MiniSTL::copy(first, mid, pos);
}
} catch (std::exception &) {
destroy_nodes(finish.node + 1, new_finish.node + 1);
throw;
}
}
}
template<class T, class Alloc>
template<class InputIterator>
void deque<T, Alloc>::range_insert_aux(iterator pos, InputIterator first,
InputIterator last, input_iterator_tag) {
MiniSTL::copy(first, last, inserter(*this, pos));// 插入迭代器
}
template<class T, class Alloc>
template<class ForwardIterator>
void deque<T, Alloc>::range_insert_aux(iterator pos, ForwardIterator first,
ForwardIterator last,
forward_iterator_tag) {
size_type n = MiniSTL::distance(first, last);
if (pos.cur == start.cur) {
iterator new_start = reserve_elements_at_front(n);
try {
MiniSTL::uninitialized_copy(first, last, new_start);
start = new_start;
} catch (std::exception &) {
destroy_nodes(new_start.node, start.node);
throw;
}
} else if (pos.cur == finish.cur) {
iterator new_finish = reserve_elements_at_back(n);
try {
MiniSTL::uninitialized_copy(first, last, finish);
finish = new_finish;
} catch (std::exception &) {
destroy_nodes(finish.node + 1, new_finish.node + 1);
throw;
}
} else
insert_aux(pos, first, last, n);
}
template<class T, class Alloc>
inline deque<T, Alloc>::deque(deque &&rhs) {
initialize_map(0);
if (rhs.map) {
swap(rhs);
}
}
template<class T, class Alloc>
deque<T, Alloc> &deque<T, Alloc>::operator=(deque &&rhs) noexcept {
clear();
swap(rhs);
return *this;
}
template<class T, class Alloc>
inline deque<T, Alloc>::~deque() {
destroy(start, finish);
if (map) {
destroy_nodes(start.node,
finish.node + 1);// 也需要destroy finish.node
deallocate_map(map, map_size);
}
}
template<class T, class Alloc>
inline void deque<T, Alloc>::push_back(const value_type &value) {
// finish的cur指向最后一个元素的下一个位置,因此if语句表征至少还有一个备用空间
if (finish.cur != finish.last - 1) {
construct(finish.cur, value);
++finish.cur;
} else
// 最终缓冲区已无或仅剩一个空间(我认为必然为仅剩一个空间的状态)
push_back_aux(value);
}
template<class T, class Alloc>
inline void deque<T, Alloc>::push_front(const value_type &value) {
if (start.cur != start.first) {
construct(start.cur - 1, value);
--start.cur;
} else
push_front_aux(value);
}
template<class T, class Alloc>
inline void deque<T, Alloc>::pop_back() {
if (finish.cur != finish.first) {
// 缓冲区至少存在一个元素
--finish.cur;
destroy(finish.cur);
} else
pop_back_aux();
}
template<class T, class Alloc>
inline void deque<T, Alloc>::pop_front() {
if (start.cur != start.last - 1) {
destroy(start.cur);
++start.cur;
} else
pop_front_aux();
}
template<class T, class Alloc>
inline void deque<T, Alloc>::clear() {
// 清空所有node,保留唯一缓冲区(需要注意的是尽管map可能存有更多节点,但有[start,finish]占据内存
for (map_pointer node = start.node + 1; node < finish.node;
++node) { //内部均存有元素
destroy(*node, *node + buffer_size());//析构所有元素
node_allocator::deallocate(*node, buffer_size());
}
if (start.node != finish.node) {// 存在头尾两个缓冲区
// 析构其中所有元素
destroy(start.cur, start.last);
destroy(finish.first, finish.cur);
// 保存头部,释放尾部
node_allocator::deallocate(finish.first, buffer_size());
} else
destroy(start.cur, finish.cur);// 利用finish.cur标记末尾
finish = start;
}
template<class T, class Alloc>
typename deque<T, Alloc>::iterator deque<T, Alloc>::erase(iterator pos) {
iterator next = pos + 1;
difference_type index = pos - start;// 清除点前的元素个数
if (index < size() / 2) { // 后移开销较低
MiniSTL::copy_backward(start, pos, pos);
pop_front();
} else {
MiniSTL::copy(next, finish, pos);
pop_back();
}
return start + index;
}
template<class T, class Alloc>
typename deque<T, Alloc>::iterator deque<T, Alloc>::erase(iterator first,
iterator last) {
if (first == start && last == finish) {
clear();
return finish;
} else {
difference_type n = last - first; // 清除区间长度
difference_type elems_before = first - start;// 前方元素个数
if (elems_before < (size() - n) / 2) { // 后移开销较低
MiniSTL::copy_backward(start, first, last);
iterator new_start = start + n;// 标记新起点
destroy(start, new_start); // 析构多余元素
// 释放多余缓冲区
for (map_pointer cur = start.node; cur < new_start.node; ++cur)
node_allocator::deallocate(*cur, buffer_size());
start = new_start;
} else {// 前移开销较低
MiniSTL::copy(last, finish, first);
iterator new_finish = finish - n;// 标记末尾
destroy(new_finish, finish);
// 释放多余缓冲区
for (map_pointer cur = new_finish.node + 1; cur <= finish.node;
++cur)
node_allocator::deallocate(*cur, buffer_size());
finish = new_finish;
}
return start + elems_before;
}
}
template<class T, class Alloc>
typename deque<T, Alloc>::iterator deque<T, Alloc>::insert(
iterator pos, const value_type &value) {
if (pos.cur == start.cur) {
push_front(value);
return start;
} else if (pos.cur == finish.cur) {
push_back(value);
iterator temp = finish - 1;
return temp;
} else
return insert_aux(pos, value);
}
template<class T, class Alloc>
void deque<T, Alloc>::fill_assign(size_type n, const value_type &val) {
if (n > size()) {
MiniSTL::fill(begin(), end(), val);
insert(end(), n - size(), val);
} else {
erase(begin() + n, end());
MiniSTL::fill(begin(), end(), val);
}
}
template<class T, class Alloc>
template<class InputIterator>
void deque<T, Alloc>::assign_aux(InputIterator first, InputIterator last,
input_iterator_tag) {
iterator cur = start;
for (; first != last && cur != finish; ++cur, ++first) *cur = *first;
if (first == last)
erase(cur, finish);
else
insert(cur, first, last);
}
template<class T, class Alloc>
template<class ForwardIterator>
void deque<T, Alloc>::assign_aux(ForwardIterator first, ForwardIterator last,
forward_iterator_tag) {
size_type len = MiniSTL::distance(first, last);
if (len > size()) {
ForwardIterator mid = first;
MiniSTL::advance(mid, size());
MiniSTL::copy(first, mid, start);
insert(end(), mid, last);
} else
erase(MiniSTL::copy(first, last, start), finish);
}
template<class T, class Alloc>
void deque<T, Alloc>::resize(size_type new_size, const value_type &val) {
const size_type len = size();
if (new_size < len)
erase(start + new_size, finish);
else
insert(finish, new_size - len, val);
}
template<class T, class Alloc>
void deque<T, Alloc>::swap(deque &rhs) noexcept {
MiniSTL::swap(start, rhs.start);
MiniSTL::swap(finish, rhs.finish);
MiniSTL::swap(map, rhs.map);
MiniSTL::swap(map_size, rhs.map_size);
}
template<class T, class Alloc>
inline bool operator==(const deque<T, Alloc> &lhs, const deque<T, Alloc> &rhs) {
return lhs.size() == rhs.size() && MiniSTL::equal(lhs.begin(), lhs.end(), rhs.begin());
}
template<class T, class Alloc>
inline bool operator!=(const deque<T, Alloc> &lhs, const deque<T, Alloc> &rhs) {
return !(lhs == rhs);
}
template<class T, class Alloc>
inline bool operator<(const deque<T, Alloc> &lhs, const deque<T, Alloc> &rhs) {
return MiniSTL::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(),
rhs.end());
}
template<class T, class Alloc>
inline bool operator>(const deque<T, Alloc> &lhs, const deque<T, Alloc> &rhs) {
return rhs < lhs;
}
template<class T, class Alloc>
inline bool operator<=(const deque<T, Alloc> &lhs, const deque<T, Alloc> &rhs) {
return !(rhs < lhs);
}
template<class T, class Alloc>
inline bool operator>=(const deque<T, Alloc> &lhs, const deque<T, Alloc> &rhs) {
return !(lhs < rhs);
}
template<class T, class Alloc>
inline void swap(const deque<T, Alloc> &lhs, const deque<T, Alloc> &rhs) {
lhs.swap(rhs);
}
}// namespace MiniSTL
|
CrackerCat/MiniSTL
|
Source/Allocator/subAllocation/alloc.h
|
#pragma once
#include <cstdlib>// malloc and free
#include <cstring>// memcpy
#include <new> // bad_alloc
namespace MiniSTL {
//一级配置器
class _malloc_alloc {
public:
// alias declaration
using malloc_handler = void (*)();
private:
//以下函数指针用以处理内存不足的情况
static void *oom_malloc(size_t);
static void *oom_realloc(void *, size_t);
static malloc_handler _malloc_alloc_oom_handler;
public:
static void *allocate(size_t n) {
void *result = malloc(n);
if (result == nullptr) result = oom_malloc(n);
return result;
}
static void deallocate(void *p, size_t /*n*/) { free(p); }
static void *reallocate(void *p, size_t /*old_sz*/, size_t new_sz) {
void *result = realloc(p, new_sz);
if (result == nullptr) oom_realloc(p, new_sz);
return result;
}
//模拟set_new_handler
//原因在于并未使用new与delete配置内存,因此无法使用set_new_handler
static malloc_handler set_malloc_handler(malloc_handler f) {
malloc_handler old = _malloc_alloc_oom_handler;
_malloc_alloc_oom_handler = f;
return old;
}
};
inline void *_malloc_alloc::oom_malloc(size_t n) {
malloc_handler new_alloc_handler;
void *result;
for (;;) {//不断尝试释放、配置
new_alloc_handler = _malloc_alloc_oom_handler;
if (!new_alloc_handler) throw std::bad_alloc();
(*new_alloc_handler)();//调用handler,试图释放内存
result = malloc(n);
if (result) return result;
}
}
inline void *_malloc_alloc::oom_realloc(void *p, size_t n) {
malloc_handler new_alloc_handler;
void *result;
for (;;) {
new_alloc_handler = _malloc_alloc_oom_handler;
if (!new_alloc_handler) throw std::bad_alloc();
(*new_alloc_handler)();
result = realloc(p, n);
if (result) return result;
}
}
using malloc_alloc = _malloc_alloc;
// freelist参数设定
//区块上调边界,区块上限,freelist个数
// Effective C++所述enum惯用法
enum _freelist_setting {
ALIGN = 8,
MAX_BYTES = 128,
NFREELISTS = MAX_BYTES / ALIGN
};
// 第二级配置器
class _default_alloc {
private:
// 将bytes上调至8的倍数
static size_t ROUND_UP(size_t bytes) {
return (((bytes) + static_cast<size_t>(ALIGN) - 1) & ~(static_cast<size_t>(ALIGN) - 1));
}
private:
// free_list节点
// 由于union特性,并不需要占用额外的内存
union obj {
union obj *free_list_link;//指向下一个节点
char client_data[1]; //指向资源
};
private:
static obj *volatile free_list[NFREELISTS];
// 决定使用第几号节点,从1起算
static size_t FREELIST_INDEX(size_t bytes) {
return (bytes + static_cast<size_t>(ALIGN) - 1) / static_cast<size_t>(ALIGN) - 1;
}
// 传回一个大小为n的对象,并且可能加入大小为n的其它区块到free_list
static void *refill(size_t n);
// 配置一大块空间,可容纳nobjs个大小为size的区块
// 如果不便配置 nobjs可能会降低
static char *chunk_alloc(size_t size, int &nobjs);
// chunk allocation state
static char *start_free;//内存池起始位置,只在chunk_alloc()中变化
static char *end_free; //内存池结束位置,只在chunk_alloc()中变化
static size_t heap_size;
public:
static void *allocate(size_t n);
static void deallocate(void *p, size_t n);
static void *reallocate(void *p, size_t old_sz, size_t new_sz);
};
// 当free_list无可用区块时,重新填充空间
// 新空间取自内存池,默认获取20个节点(区块)
// 若内存池不足,则获取的将小于20
inline void *_default_alloc::refill(size_t n) {
int nobjs = 20;
// 尝试调用chunk_alloc,注意nobjs以pass-by-reference传入
char *chunk = chunk_alloc(n, nobjs);
obj *volatile *my_free_list;
obj *result;
obj *current_obj, *next_obj;
// 若只获取了一个区块则直接分配给调用者,不加入free_list
if (1 == nobjs) return (chunk);
my_free_list = free_list + FREELIST_INDEX(n);
// 在chunk空间内建立free_list
result = reinterpret_cast<obj *>(chunk);
// 引导free_list指向内存池分配的空间
// chunk指向的内存直接分给用户,free_list指向剩下(19或更少)的区块
*my_free_list = next_obj = reinterpret_cast<obj *>(chunk + n);
for (int i = 1;; ++i) {
current_obj = next_obj;
next_obj =
reinterpret_cast<obj *>(reinterpret_cast<char *>(next_obj) + n);
if (nobjs - 1 == i) {
current_obj->free_list_link = nullptr;
break;
} else {
current_obj->free_list_link = next_obj;
}
}
return result;
}
// 默认size为8的整数倍
inline char *_default_alloc::chunk_alloc(size_t size, int &nobjs) {
char *result;
size_t total_bytes = size * nobjs;
size_t bytes_left = end_free - start_free;//内存池剩余空间
if (bytes_left >= total_bytes) {
// 容量满足需求
result = start_free;
start_free += total_bytes;
return result;
} else if (bytes_left > size) {
// 容量至少满足一个区块需求
nobjs = static_cast<int>(bytes_left / size);
total_bytes = size * nobjs;
result = start_free;
start_free += total_bytes;
return result;
} else {
// 内存池一个区块都无法提供
size_t bytes_to_get =
2 * total_bytes + ROUND_UP(heap_size >> 4);// 向heap申请注入的内存,heap_size将随着配置次数增加而增加
if (bytes_left > 0) {
// 当前内存池还有一部分内存,为了不浪费分配给free_list
obj *volatile *my_free_list =
free_list + FREELIST_INDEX(bytes_left);
reinterpret_cast<obj *>(start_free)->free_list_link = *my_free_list;
*my_free_list = reinterpret_cast<obj *>(start_free);
}
// 配置heap空间以补充内存池
start_free = reinterpret_cast<char *>(malloc(bytes_to_get));
if (!start_free) {
// heap空间不足,malloc失败
obj *volatile *my_free_list;
obj *p;
// 在free_list中检查是否有符合需求的区块
for (size_t i = size; i <= static_cast<size_t>(MAX_BYTES);
i += static_cast<size_t>(ALIGN)) {
my_free_list = free_list + FREELIST_INDEX(i);
p = *my_free_list;
if (p) {
// 存在足以分配的区块
*my_free_list = p->free_list_link;// 抽离当前区块
start_free = reinterpret_cast<char *>(p);
end_free = start_free + i;
return (chunk_alloc(
size,
nobjs));// 递归调用以修正nobjs,此时必然进入else_if分支
}
}
end_free = nullptr;// 到处都找不到内存
// 调用第一级适配器观察其能否分配内存,或抛出异常
start_free =
reinterpret_cast<char *>(malloc_alloc::allocate(bytes_to_get));
}
heap_size += bytes_to_get;// 已占用的堆内存
end_free = start_free + bytes_to_get;
return chunk_alloc(size, nobjs);// 调用自身以修正nobjs
}
}
inline void *_default_alloc::allocate(size_t n) {
obj *volatile *my_free_list;
obj *result;
// 若n大于128,则采用第一级适配器
if (n > MAX_BYTES) return (malloc_alloc::allocate(n));
// 选择采用第几区块
my_free_list = free_list + FREELIST_INDEX(n);
result = *my_free_list;
if (result == nullptr) {
// 未找到可用free_list,准备填充free_list
void *r = refill(ROUND_UP(n));
return r;
}
// 调整freelist
*my_free_list = result->free_list_link;
return result;
}
inline void _default_alloc::deallocate(void *p, size_t n) {
// p不可为nullptr
if (n > static_cast<size_t>(MAX_BYTES))
malloc_alloc::deallocate(p, n);
else {
// 寻找对应的free list
obj *volatile *my_free_list = free_list + FREELIST_INDEX(n);
obj *q = reinterpret_cast<obj *>(p);
// 调整free list,回收区块
q->free_list_link = *my_free_list;
*my_free_list = q;
}
}
inline void *_default_alloc::reallocate(void *p, size_t old_sz, size_t new_sz) {
void *result;
size_t copy_sz;
if (old_sz > static_cast<size_t>(MAX_BYTES) && new_sz > static_cast<size_t>(MAX_BYTES))
return realloc(p, new_sz);
if (ROUND_UP(old_sz) == ROUND_UP(new_sz)) return p;
result = allocate(new_sz);
copy_sz = new_sz > old_sz ? old_sz : new_sz;
memcpy(result, p, copy_sz);
deallocate(p, old_sz);
return result;
}
}// namespace MiniSTL
|
CrackerCat/MiniSTL
|
Source/Utils/stl_initializer_list.h
|
#pragma once
#include <cstddef>
namespace MiniSTL {
template<class T>
class initializer_list {
public:// alias declarations
using value_type = T;
using reference = const T &;
using const_reference = const T &;
using size_type = size_t;
using iterator = const T *;
using const_iterator = const T *;
private:// data member
iterator array;
size_type len;
private:// set private ctor so only complier can call it
constexpr initializer_list(const_iterator a, size_type l)
: array(a), len(l) {}
public:// default ctor
constexpr initializer_list() noexcept : array(nullptr), len(0) {}
public:// getter
constexpr size_type size() const noexcept { return len; }
constexpr const_iterator begin() const noexcept { return array; }
constexpr const_iterator end() const noexcept { return array + size(); }
};
template<class T>
constexpr const T *begin(initializer_list<T> ils) noexcept {
return ils.begin();
}
template<class T>
constexpr const T *end(initializer_list<T> ils) noexcept {
return ils.end();
}
}// namespace MiniSTL
|
CrackerCat/MiniSTL
|
Source/Iterator/typeTraits.h
|
<gh_stars>0
#pragma once
namespace MiniSTL {
namespace {
template<bool, class Ta, class Tb>
struct IfThenElse;
template<class Ta, class Tb>
struct IfThenElse<true, Ta, Tb> {
using result = Ta;
};
template<class Ta, class Tb>
struct IfThenElse<false, Ta, Tb> {
using result = Tb;
};
}// namespace
struct _true_type {};
struct _false_type {};
// 默认自定义类型均为non-POD类型
template<class T>
struct _type_traits {
using has_trivial_default_constructor = _false_type;
using has_trivial_copy_constructor = _false_type;
using has_trivial_assignment_operator = _false_type;
using has_trivial_destructor = _false_type;
using is_POD_type = _false_type;
};
template<>
struct _type_traits<bool> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<char> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<unsigned char> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<signed char> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<wchar_t> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<short> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<unsigned short> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<int> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<unsigned int> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<long> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<unsigned long> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<long long> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<unsigned long long> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<float> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<double> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<long double> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<class T>
struct _type_traits<T *> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<class T>
struct _type_traits<const T *> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<char *> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<unsigned char *> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<signed char *> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<const char *> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<const unsigned char *> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
template<>
struct _type_traits<const signed char *> {
using has_trivial_default_constructor = _true_type;
using has_trivial_copy_constructor = _true_type;
using has_trivial_assignment_operator = _true_type;
using has_trivial_destructor = _true_type;
using is_POD_type = _true_type;
};
// is_integer(默认自定义类型为false)
template<class T>
struct _is_integer {
using _integral = _false_type;
};
// simluate C++14
template<class T>
using _is_integer_t = typename _is_integer<T>::_integral;
template<>
struct _is_integer<bool> {
using _integral = _true_type;
};
template<>
struct _is_integer<char> {
using _integral = _true_type;
};
template<>
struct _is_integer<signed char> {
using _integral = _true_type;
};
template<>
struct _is_integer<unsigned char> {
using _integral = _true_type;
};
template<>
struct _is_integer<wchar_t> {
using _integral = _true_type;
};
template<>
struct _is_integer<short> {
using _integral = _true_type;
};
template<>
struct _is_integer<unsigned short> {
using _integral = _true_type;
};
template<>
struct _is_integer<int> {
using _integral = _true_type;
};
template<>
struct _is_integer<unsigned int> {
using _integral = _true_type;
};
template<>
struct _is_integer<long> {
using _integral = _true_type;
};
template<>
struct _is_integer<unsigned long> {
using _integral = _true_type;
};
template<>
struct _is_integer<long long> {
using _integral = _true_type;
};
template<>
struct _is_integer<unsigned long long> {
using _integral = _true_type;
};
}// namespace MiniSTL
|
CrackerCat/MiniSTL
|
Source/SequenceContainers/Stack/stl_stack.h
|
#pragma once
#include "SequenceContainers/Deque/stl_deque.h"
namespace MiniSTL {
template<class T, class Sequence = deque<T>>
class stack;
template<class T, class Sequence>
bool operator==(const stack<T, Sequence> &, const stack<T, Sequence> &);
template<class T, class Sequence>
bool operator<(const stack<T, Sequence> &, const stack<T, Sequence> &);
template<class T, class Sequence>
class stack {
// friend declarations
template<class _T, class _Sequence>
friend bool operator==(const stack<_T, _Sequence> &,
const stack<_T, _Sequence> &);
template<class _T, class _Sequence>
friend bool operator<(const stack<_T, _Sequence> &,
const stack<_T, _Sequence> &);
public:
using value_type = typename Sequence::value_type;
using size_type = typename Sequence::size_type;
using reference = typename Sequence::reference;
using const_reference = typename Sequence::const_reference;
private:// only data member
Sequence c;
public:// ctor
stack() = default;
explicit stack(const Sequence &rhs) : c(rhs) {}
public:// copy operations
stack(const stack &rhs) : c(rhs.c) {}
stack &operator=(const stack &rhs) {
c.operator=(rhs.c);
return *this;
}
public:// move operations
stack(stack &&rhs) noexcept : c(std::move(rhs.c)) {}
stack &operator=(stack &&rhs) noexcept {
c.operator=(std::move(rhs.c));
return *this;
}
public:// getter
bool empty() const noexcept { return c.empty(); }
size_type size() const noexcept { return c.size(); }
const_reference top() const noexcept { return c.back(); }
public:// setter
reference top() { return c.back(); }
public:// push && pop
void push(const value_type &value) { c.push_back(value); }
void pop() { c.pop_back(); }
public:// swap
void swap(stack &rhs) noexcept { MiniSTL::swap(c, rhs.c); }
};
template<class T, class Sequence>
inline bool operator==(const stack<T, Sequence> &lhs,
const stack<T, Sequence> &rhs) {
return lhs.c == rhs.c;
}
template<class T, class Sequence>
inline bool operator<(const stack<T, Sequence> &lhs,
const stack<T, Sequence> &rhs) {
return lhs.c < rhs.c;
}
template<class T, class Sequence>
inline bool operator!=(const stack<T, Sequence> &lhs,
const stack<T, Sequence> &rhs) {
return !(lhs == rhs);
}
template<class T, class Sequence>
inline bool operator>(const stack<T, Sequence> &lhs,
const stack<T, Sequence> &rhs) {
return rhs < lhs;
}
template<class T, class Sequence>
inline bool operator<=(const stack<T, Sequence> &lhs,
const stack<T, Sequence> &rhs) {
return !(rhs < lhs);
}
template<class T, class Sequence>
inline bool operator>=(const stack<T, Sequence> &lhs,
const stack<T, Sequence> &rhs) {
return !(lhs < rhs);
}
template<class T, class Sequence>
inline void swap(stack<T, Sequence> &lhs, stack<T, Sequence> &rhs) noexcept {
lhs.swap(rhs);
}
}// namespace MiniSTL
|
CrackerCat/MiniSTL
|
Source/SequenceContainers/Deque/deque_iterator.h
|
<filename>Source/SequenceContainers/Deque/deque_iterator.h
#pragma once
#include "stl_iterator.h"
#include <cstddef>
namespace MiniSTL {
// 缓冲区大小设定函数(在预设情况下传回可容纳的元素个数)
// 若n不为0,则传回n,表示由用户自定
// 若n为0则采用预设值 预设值根据sz(元素大小)而定
inline size_t __deque_buf_size(size_t sz) {
return sz < 512 ? size_t(512 / sz) : size_t(1);
}
template<class T, class Ref, class Ptr>
struct __deque_iterator {
// alias declarartions
using iterator = __deque_iterator<T, T &, T *>;
using const_iterator = __deque_iterator<T, const T &, const T *>;
using self = __deque_iterator;
using iterator_category = random_access_iterator_tag;
using value_type = T;
using pointer = Ptr;
using reference = Ref;
using size_type = size_t;
using difference_type = ptrdiff_t;
using map_pointer = T **;
// data member
value_type *cur; // 当前缓冲区的当前元素
value_type *first;// 当前缓冲区头
value_type *last; // 当前缓冲区尾(含备用空间)
map_pointer node; // 指向管控中心
static size_t buffer_size() { return __deque_buf_size(sizeof(value_type)); }
// ctor
__deque_iterator()
: cur(nullptr), first(nullptr), last(nullptr), node(nullptr) {}
__deque_iterator(pointer x, map_pointer y)
: cur(x), first(*y), last(*y + buffer_size()), node(y) {}
__deque_iterator(const iterator &rhs)
: cur(rhs.cur), first(rhs.first), last(rhs.last), node(rhs.node) {}
void set_node(map_pointer new_node) {
node = new_node;
first = *new_node;
last = first + static_cast<difference_type>(buffer_size());
}
// dereference
reference operator*() const { return *cur; }
pointer operator->() const { return &(operator*()); }
self &operator++() {
++cur;
if (cur == last) {// 若已抵达尾端
set_node(node + 1);
cur = first;
}
return *this;
}
self operator++(int) {
self temp = *this;
++*this;
return temp;
}
self &operator--() {
if (cur == first) {
set_node(node - 1);
cur = last;
}
--cur;
return *this;
}
self operator--(int) {
self temp = *this;
--*this;
return temp;
}
// random access
self &operator+=(difference_type n) {
difference_type offset = n + (cur - first);
if (offset >= 0 && offset < static_cast<difference_type>(buffer_size())) {
// 不需要跳转
cur += n;
} else {
// off_set小于0则必然需要跳转
difference_type node_offset =
offset > 0
? offset / static_cast<difference_type>(buffer_size())
: -static_cast<difference_type>((-offset - 1) / buffer_size()) - 1;
set_node(node + node_offset);
cur = first + (offset - node_offset * static_cast<difference_type>(buffer_size()));
}
return *this;
}
self operator+(difference_type n) {
self temp = *this;
return temp += n;
}
self &operator-=(difference_type n) { return *this += -n; }
self operator-(difference_type n) {
self temp = *this;
return temp -= n;
}
reference operator[](difference_type n) { return *(*this + n); }
};
template<class T, class Ref, class Ptr>
inline bool operator==(const __deque_iterator<T, Ref, Ptr> &lhs,
const __deque_iterator<T, Ref, Ptr> &rhs) {
return lhs.cur == rhs.cur;
}
// compare with const
template<class T, class RefL, class PtrL, class RefR, class PtrR>
inline bool operator==(const __deque_iterator<T, RefL, PtrL> &lhs,
const __deque_iterator<T, RefR, PtrR> &rhs) {
return lhs.cur == rhs.cur;
}
template<class T, class Ref, class Ptr>
inline bool operator!=(const __deque_iterator<T, Ref, Ptr> &lhs,
const __deque_iterator<T, Ref, Ptr> &rhs) {
return !(lhs == rhs);
}
template<class T, class RefL, class PtrL, class RefR, class PtrR>
inline bool operator!=(const __deque_iterator<T, RefL, PtrL> &lhs,
const __deque_iterator<T, RefR, PtrR> &rhs) {
return !(lhs == rhs);
}
template<class T, class Ref, class Ptr>
inline bool operator<(const __deque_iterator<T, Ref, Ptr> &lhs,
const __deque_iterator<T, Ref, Ptr> &rhs) {
return (lhs.node == rhs.node) ? (lhs.cur < rhs.cur) : (lhs.node < rhs.node);
}
template<class T, class RefL, class PtrL, class RefR, class PtrR>
inline bool operator<(const __deque_iterator<T, RefL, PtrL> &lhs,
const __deque_iterator<T, RefR, PtrR> &rhs) {
return (lhs.node == rhs.node) ? (lhs.cur < rhs.cur) : (lhs.node < rhs.node);
}
template<class T, class Ref, class Ptr>
inline bool operator>(const __deque_iterator<T, Ref, Ptr> &lhs,
const __deque_iterator<T, Ref, Ptr> &rhs) {
return rhs < lhs;
}
template<class T, class RefL, class PtrL, class RefR, class PtrR>
inline bool operator>(const __deque_iterator<T, RefL, PtrL> &lhs,
const __deque_iterator<T, RefR, PtrR> &rhs) {
return rhs < lhs;
}
template<class T, class Ref, class Ptr>
inline bool operator<=(const __deque_iterator<T, Ref, Ptr> &lhs,
const __deque_iterator<T, Ref, Ptr> &rhs) {
return !(rhs < lhs);
}
template<class T, class RefL, class PtrL, class RefR, class PtrR>
inline bool operator<=(const __deque_iterator<T, RefL, PtrL> &lhs,
const __deque_iterator<T, RefR, PtrR> &rhs) {
return !(rhs < lhs);
}
template<class T, class Ref, class Ptr>
inline bool operator>=(const __deque_iterator<T, Ref, Ptr> &lhs,
const __deque_iterator<T, Ref, Ptr> &rhs) {
return !(lhs < rhs);
}
template<class T, class RefL, class PtrL, class RefR, class PtrR>
inline bool operator>=(const __deque_iterator<T, RefL, PtrL> &lhs,
const __deque_iterator<T, RefR, PtrR> &rhs) {
return !(lhs < rhs);
}
template<class T, class Ref, class Ptr>
inline typename __deque_iterator<T, Ref, Ptr>::difference_type operator-(
const __deque_iterator<T, Ref, Ptr> &lhs,
const __deque_iterator<T, Ref, Ptr> &rhs) {
return typename __deque_iterator<T, Ref, Ptr>::difference_type(
__deque_iterator<T, Ref, Ptr>::buffer_size() * (lhs.node - rhs.node - 1) + (lhs.cur - lhs.first) + (rhs.last - rhs.cur));
}
template<class T, class RefL, class PtrL, class RefR, class PtrR>
inline typename __deque_iterator<T, RefL, PtrL>::difference_type operator-(
const __deque_iterator<T, RefL, PtrL> &lhs,
const __deque_iterator<T, RefR, PtrR> &rhs) {
return typename __deque_iterator<T, RefL, PtrL>::difference_type(
__deque_iterator<T, RefL, PtrL>::buffer_size() * (lhs.node - rhs.node - 1) + (lhs.cur - lhs.first) + (rhs.last - rhs.cur));
}
template<class T, class Ref, class Ptr>
inline __deque_iterator<T, Ref, Ptr> operator+(
ptrdiff_t n, const __deque_iterator<T, Ref, Ptr> &x) {
return x + n;
}
}// namespace MiniSTL
|
CrackerCat/MiniSTL
|
Source/AssociativeContainers/Multiset/stl_multiset.h
|
#pragma once
#include "AssociativeContainers/RB-Tree/rb_tree.h"
#include "Function/stl_function.h"
namespace MiniSTL {
// Forward declarations of operators == and <, needed for friend declarations.
template<class Key, class Compare, class Alloc>
class multiset;
template<class Key, class Compare, class Alloc>
inline bool operator==(const multiset<Key, Compare, Alloc> &lhs,
const multiset<Key, Compare, Alloc> &rhs);
template<class Key, class Compare, class Alloc>
inline bool operator<(const multiset<Key, Compare, Alloc> &lhs,
const multiset<Key, Compare, Alloc> &rhs);
template<class Key, class Compare = less<Key>, class Alloc = simpleAlloc<Key>>
class multiset {
// friend declarations
template<class _Key, class _Compare, class _Alloc>
friend bool operator==(const multiset<_Key, _Compare, _Alloc> &lhs,
const multiset<_Key, _Compare, _Alloc> &rhs);
template<class _Key, class _Compare, class _Alloc>
friend bool operator<(const multiset<_Key, _Compare, _Alloc> &lhs,
const multiset<_Key, _Compare, _Alloc> &rhs);
public:
using key_type = Key;
using value_type = Key;
using key_compare = Compare;
using value_compare = Compare;
private:// data member
using rep_type =
rb_tree<key_type, value_type, identity<value_type>, key_compare, Alloc>;
rep_type t;//底层红黑树
public:
using pointer = typename rep_type::const_pointer;
using const_pointer = typename rep_type::const_pointer;
using reference = typename rep_type::const_reference;
using const_reference = typename rep_type::const_reference;
using iterator = typename rep_type::const_iterator;
using const_iterator = typename rep_type::const_iterator;
// TODO:
// using reverse_iterator = typename rep_type::const_reverse_iterator;
// using const_reverse_iterator = typename rep_type::const_reverse_iterator;
using size_type = typename rep_type::size_type;
using difference_type = typename rep_type::difference_type;
public:// ctor
multiset() : t(key_compare()) {}
explicit multiset(const key_compare &comp) : t(comp) {}
template<class InputIterator>
multiset(InputIterator first, InputIterator last) : t(key_compare()) {
t.insert_equal(first, last);
}
template<class InputIterator>
multiset(InputIterator first, InputIterator last, const key_compare &comp)
: t(comp) {
t.insert_equal(first, last);
}
public:// copy operations
multiset(const multiset<Key, Compare, Alloc> &rhs) : t(rhs.t) {}
multiset<Key, Compare, Alloc> &operator=(
const multiset<Key, Compare, Alloc> &rhs) {
t = rhs.t;
return *this;
}
public:// getter
key_compare key_comp() const noexcept { return t.key_comp(); }
value_compare value_comp() const noexcept { return t.key_comp(); }
iterator begin() const noexcept { return t.cbegin(); }
iterator end() const noexcept { return t.cend(); }
const_iterator cbegin() const noexcept { return t.cbegin(); }
const_iterator cend() const noexcept { return t.cend(); }
// TODO:
// reverse_iterator rbegin() const { return t.rbegin(); }
// reverse_iterator rend() const { return t.rend(); }
bool empty() const noexcept { return t.empty(); }
size_type size() const noexcept { return t.size(); }
size_type max_size() const noexcept { return t.max_size(); }
public:// swap
void swap(multiset<Key, Compare, Alloc> &x) noexcept { t.swap(x.t); }
public:// insert && erase
iterator insert(const value_type &x) { return t.insert_equal(x); }
iterator insert(iterator pos, const value_type &x) {
using rep_iterator = typename rep_type::iterator;
return t.insert_equal(reinterpret_cast<rep_iterator &>(pos), x);
}
template<class InputIterator>
void insert(InputIterator first, InputIterator last) {
t.insert_equal(first, last);
}
void erase(iterator pos) {
using rep_iterator = typename rep_type::iterator;
t.erase(reinterpret_cast<rep_iterator &>(pos));
}
size_type erase(const key_type &x) { return t.erase(x); }
void erase(iterator first, iterator last) {
using rep_iterator = typename rep_type::iterator;
t.erase(reinterpret_cast<rep_iterator &>(first),
reinterpret_cast<rep_iterator &>(last));
}
void clear() { t.clear(); }
public:// find && search
iterator find(const key_type &x) const noexcept { return t.find(x); }
size_type count(const key_type &x) const noexcept { return t.count(x); }
iterator lower_bound(const key_type &x) const noexcept {
return t.lower_bound(x);
}
iterator upper_bound(const key_type &x) const noexcept {
return t.upper_bound(x);
}
pair<iterator, iterator> equal_range(const key_type &x) const noexcept {
return t.equal_range(x);
}
};
template<class Key, class Compare, class Alloc>
inline bool operator==(const multiset<Key, Compare, Alloc> &lhs,
const multiset<Key, Compare, Alloc> &rhs) {
return lhs.t == rhs.t;
}
template<class Key, class Compare, class Alloc>
inline bool operator!=(const multiset<Key, Compare, Alloc> &lhs,
const multiset<Key, Compare, Alloc> &rhs) {
return !(lhs.t == rhs.t);
}
template<class Key, class Compare, class Alloc>
inline bool operator<(const multiset<Key, Compare, Alloc> &lhs,
const multiset<Key, Compare, Alloc> &rhs) {
return lhs.t < rhs.t;
}
template<class Key, class Compare, class Alloc>
inline bool operator>(const multiset<Key, Compare, Alloc> &lhs,
const multiset<Key, Compare, Alloc> &rhs) {
return rhs < lhs;
}
template<class Key, class Compare, class Alloc>
inline bool operator<=(const multiset<Key, Compare, Alloc> &lhs,
const multiset<Key, Compare, Alloc> &rhs) {
return !(rhs < lhs);
}
template<class Key, class Compare, class Alloc>
inline bool operator>=(const multiset<Key, Compare, Alloc> &lhs,
const multiset<Key, Compare, Alloc> &rhs) {
return !(lhs < rhs);
}
template<class Key, class Compare, class Alloc>
inline void swap(multiset<Key, Compare, Alloc> &lhs,
multiset<Key, Compare, Alloc> &rhs) {
lhs.swap(rhs);
}
}// namespace MiniSTL
|
darthdie/capacitor
|
ios/Capacitor/Capacitor/CAPBridgedPlugin.h
|
<filename>ios/Capacitor/Capacitor/CAPBridgedPlugin.h<gh_stars>10-100
#import "CAPPluginMethod.h"
#if defined(__cplusplus)
#define CAP_EXTERN extern "C" __attribute__((visibility("default")))
#else
#define CAP_EXTERN extern __attribute__((visibility("default")))
#endif
#define CAPPluginReturnNone @"none"
#define CAPPluginReturnCallback @"callback"
#define CAPPluginReturnPromise @"promise"
#define CAPPluginReturnWatch @"watch"
#define CAPPluginReturnSync @"sync" // not used
@class CAPPluginCall;
@class CAPPlugin;
@protocol CAPBridgedPlugin <NSObject>
+(NSString *)pluginId;
+(NSString *)jsName;
+(NSArray *)pluginMethods;
+(CAPPluginMethod *)getMethod:(NSString *)methodName;
@optional
@end
#define CAP_PLUGIN_CONFIG(plugin_id, js_name) \
CAP_EXTERN void CapacitorRegisterPlugin(Class); \
+ (NSString *)pluginId { return @#plugin_id; } \
+ (NSString *)jsName { return @js_name; } \
+ (void)load { CapacitorRegisterPlugin(self); }
#define CAP_PLUGIN_METHOD(method_name, method_return_type) \
[methods addObject:[[CAPPluginMethod alloc] initWithName:@#method_name returnType:method_return_type]]
#define CAP_PLUGIN(objc_name, js_name, methods_body) \
@interface objc_name : NSObject \
@end \
@interface objc_name (CAPPluginCategory) <CAPBridgedPlugin> \
@end \
@implementation objc_name (CAPPluginCategory) \
+ (NSArray *)pluginMethods { \
NSMutableArray *methods = [NSMutableArray new]; \
methods_body \
return methods; \
} \
+ (CAPPluginMethod *)getMethod:(NSString *)methodName { \
NSArray *methods = [self pluginMethods]; \
for(CAPPluginMethod *method in methods) { \
if([method.name isEqualToString:methodName]) { \
return method; \
} \
} \
return nil; \
} \
CAP_PLUGIN_CONFIG(objc_name, js_name) \
@end
|
darthdie/capacitor
|
ios/CapacitorCordova/CapacitorCordova/Classes/Public/CDVPluginManager.h
|
//
// CDVPluginManager.h
// CapacitorCordova
//
// Created by <NAME> on 26/2/18.
//
#import <Foundation/Foundation.h>
#import "CDVPlugin.h"
@interface CDVPluginManager : NSObject
@property (nonatomic, strong) NSMutableDictionary * pluginsMap;
@property (nonatomic, strong) NSMutableDictionary * pluginObjects;
@property (nonatomic, strong) UIViewController * viewController;
- (id)initWithMapping:(NSMutableDictionary*)mapping viewController:(UIViewController*)viewController;
- (CDVPlugin *)getCommandInstance:(NSString*)pluginName;
@end
|
allanragec/AMLocationBased-iOS
|
Example/LocationBased/CreatePointViewController.h
|
<filename>Example/LocationBased/CreatePointViewController.h
//
// CreatePointViewController.h
// LocationBased
//
// Created by <NAME> on 8/29/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface CreatePointViewController : UIViewController
@end
|
allanragec/AMLocationBased-iOS
|
Example/LocationBased/AMMapUtilsTrigonometry.h
|
//
// UtilsTrigonometry.h
//
// Created by <NAME> on 1/12/15.
// Copyright (c) 2015. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
@interface AMMapUtilsTrigonometry : NSObject
+(double)getHypotenuseWithPointA:(CLLocation *)pointA andPointB:(CLLocation *)pointB;
+(double)getLatitudeDistanceWithPointA:(CLLocation *)pointA andPointB:(CLLocation *)pointB;
+(double)getLongitudeDistanceWithPointA:(CLLocation *)pointA andPointB:(CLLocation *)pointB;
+(double)getTangentWithCathetusOpposite:(double)cathetusOpposite andCathetusAdjacent:(double)cathetusAdjacent;
+(double)getSineWithCathetusOpposite:(double)cathetusOpposite andHypotenuse:(double)hypotenuse;
+(double)getCosineWithHypotenuse:(double)hypotenuse andCathetusAdjacent:(double)cathetusAdjacent;
+(double)getInverseTangentRadians:(double)value;
+(double)getThirdAngleOfTriangleRectangle:(double) angle;
+(double)convertRadiansToDegrees:(double)value;
+(double)convertDegreesToRadians:(double)value;
+(double)getDegreesOfAnotherLocationWithMyLocation:(CLLocation *)myLocation andAnotherLocation:(CLLocation *)anotherLocation;
+(CLLocation*)locationFromDistance:(double)distance andDegrees:(int)degrees withMyLocation:(CLLocation*)myLocation;
+(double)distanceInMetersForLatitude:(double)meters;
+(double)distanceInMetersForLongitude:(double)meters;
+(double)degreeNormalize:(double)value;
@end
|
allanragec/AMLocationBased-iOS
|
Example/LocationBased/AppDelegate.h
|
//
// AppDelegate.h
// LocationBased
//
// Created by <NAME> on 8/29/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
Pro/open62541_namespaces
|
src/main.c
|
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#ifdef UA_NO_AMALGAMATION
# include "ua_types.h"
# include "ua_server.h"
# include "ua_config_standard.h"
# include "ua_network_tcp.h"
# include "ua_log_stdout.h"
#else
# include "open62541.h"
#endif
#include "test_generated.h"
UA_Logger logger = UA_Log_Stdout;
UA_Boolean running = true;
static void stopHandler(int sign) {
UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "received ctrl-c");
running = false;
}
int main(int argc, char** argv) {
signal(SIGINT, stopHandler); /* catches ctrl-c */
/* initialize the server */
UA_ServerConfig config = UA_ServerConfig_standard;
UA_ServerNetworkLayer nl = UA_ServerNetworkLayerTCP(UA_ConnectionConfig_standard, 16664);
config.networkLayers = &nl;
config.networkLayersSize = 1;
UA_Server *server = UA_Server_new(config);
/* create nodes from nodeset */
test_generated(server);
/* start server */
UA_StatusCode retval = UA_Server_run(server, &running); //UA_blocks until running=false
/* ctrl-c received -> clean up */
UA_Server_delete(server);
nl.deleteMembers(&nl);
return (int)retval;
}
|
ESS-Group/clang-sfi
|
integrationtests/MFC_header/source.h
|
int g() {
return 0;
}
int f() {
int a = g();
int b = 5, c = 6;
int e;
e = a + b + c;
g();
if (e) {
return 0;
} else {
return 1;
}
}
|
ESS-Group/clang-sfi
|
src/utils.h
|
#include "clang/AST/AST.h"
using namespace clang;
template <class T>
void deleteFromList(std::vector<T> &src, std::vector<T> &toDelete) {
bool deleted = false;
for (std::vector<const BinaryOperator *>::iterator i = src.begin(); i != src.end(); deleted ? i : i++) {
deleted = false;
for (T c : toDelete) {
if (*i == c) {
i = src.erase(i);
deleted = true;
break;
}
}
}
}
template<class T>
const CompoundStmt *getParentCompoundStmt(const T *stmtOrDecl, ASTContext &Context);
template <class T>
void concatVector(std::vector<T> &dst, std::vector<T> &src) {
dst.insert(dst.end(), src.begin(), src.end());
}
bool isIncDecUO(const UnaryOperator *op);
bool isAssignment(const BinaryOperator *op, bool anyAssign = true);
const Stmt *IgnoreCast(const Stmt *stmt, bool ignoreImplicit = true);
bool isAssignmentOrFC(const Stmt *stmt);
bool isValue(const Stmt *stmt);
bool isValueAssignment(const BinaryOperator *op);
bool isExprAssignment(const BinaryOperator *op);
template <class T>
const T *getFirstChild(const Stmt *parent) {
if (parent == NULL) {
return NULL;
}
for (Stmt::child_iterator i = cast_away_const(parent->child_begin()), e = cast_away_const(parent->child_end());
i != e; ++i) {
if (*i != NULL) {
if (isa<T>(*i)) {
return cast<const T>(*i);
} else if (const T *ret = getFirstChild<T>(*i)) {
return ret;
}
}
}
return NULL;
}
std::vector<const BinaryOperator *> getChildForFindInitForVar(const Stmt *parent, const VarDecl *var,
bool alsoinloop = false, bool alsoinforconstruct = true);
std::vector<const BinaryOperator *> getChildForFindVarAssignment(const Stmt *parent, const VarDecl *var,
bool alsoinloop = true, bool alsoinforconstruct = true,
bool pinited = false);
template <class T, class SD>
const T *getParentOfType(const SD *stmt, ASTContext &Context, int maxDepth = 3) { // MaxDepth = -1 for to the root
if (stmt != NULL && maxDepth != 0) {
int i = 0;
ASTContext::DynTypedNodeList list = Context.getParents(*stmt);
for (auto p : list) {
if (auto ret = dyn_cast_or_null<T>(p.get<Stmt>())) {
return ret;
}
i++;
if (maxDepth != -1 && i > maxDepth) {
return NULL;
}
}
}
return NULL;
}
template <class T>
bool hasParentOfType(const Stmt &stmt, ASTContext &Context) {
return getParentOfType<T>(stmt, Context, -1) != NULL;
}
template <class T>
bool hasParentOfType(const Decl &decl, ASTContext &Context) {
return getParentOfType<T>(decl, Context, -1) != NULL;
}
const FunctionDecl *getParentFunctionDecl(const Stmt *stmt, ASTContext &Context);
bool isPartOfFunction(const Stmt &stmt, ASTContext &Context);
bool isLocal(const Stmt &stmt, ASTContext &Context);
bool isLocal(const Decl &decl, ASTContext &Context);
template <class T>
bool hasChildOfType(const Stmt *stmt) {
if (stmt == NULL) {
return false;
}
for (Stmt::child_iterator i = cast_away_const(stmt->child_begin()), e = cast_away_const(stmt->child_end()); i != e;
++i) {
if (isa<T>(*i)) {
return true;
} else if (hasChildOfType<T>(*i)) {
return true;
}
}
return false;
}
bool isParentOfOrSelf(const Stmt *parent, const Stmt &stmt, ASTContext &Context);
bool isParentOf(const Stmt *parent, const Stmt &stmt, ASTContext &Context);
bool isParentOf(const Stmt &parent, const Stmt &stmt, ASTContext &Context);
bool isParentOf(const Stmt *parent, const Decl &decl, ASTContext &Context);
bool isParentOf(const Stmt &parent, const Decl &decl, ASTContext &Context);
bool isInitializedBefore(const DeclRefExpr &ref, ASTContext &Context);
template <class T>
std::vector<const T *> getChildrenOfType(const Stmt &parent, bool first = true) {
std::vector<const BinaryOperator *> ret;
if (isa<T>(parent) && first) {
ret.push_back(cast<const T>(&parent));
}
for (Stmt::child_iterator i = cast_away_const(parent.child_begin()), e = cast_away_const(parent.child_end());
i != e; ++i) {
if (isa<T>(*i)) {
ret.push_back(cast<T>(*i));
}
std::vector<const T *> children = getChildrenOfType<T>(**i, false);
if (children.size() != 0) {
concatVector<const T *>(ret, children);
}
}
return ret;
}
std::vector<const DeclRefExpr *> getAllRefs(const Stmt &parent, const VarDecl &var);
const DeclRefExpr *getLatestRef(const Stmt &parent, const VarDecl &var);
template <class T>
bool hasStmtOfType(std::vector<const Stmt *> list) {
for (const Stmt *stmt : list) {
if (isa<T>(stmt)) {
return true;
}
}
return false;
}
template <class T>
std::vector<const T *> getStmtsOfType(std::vector<const Stmt *> &list) {
std::vector<const T *> ret;
if (list.empty()) {
return ret;
}
for (const Stmt *stmt : list) {
if (stmt != NULL && isa<T>(stmt)) {
ret.push_back(cast<T>(stmt));
}
}
return ret;
}
template <class T>
bool _comparefunc(const T *st1, const T *st2) {
return st1->getBeginLoc() < st2->getBeginLoc();
}
bool isArithmetic(const BinaryOperator &op);
const BinaryOperator &getBinaryOperatorWithRightedtRHS(const BinaryOperator &op);
template <class T>
std::vector<const T *> getChildrenFlat(const Stmt *parent) {
std::vector<const T *> ret;
for (Stmt::child_iterator i = cast_away_const(parent->child_begin()), e = cast_away_const(parent->child_end());
i != e; ++i) {
if (*i != NULL) {
if (isa<Expr>(*i)) {
const Expr *expr = cast<Expr>(*i)->IgnoreImplicit()->IgnoreParenCasts();
if (isa<T>(expr)) {
ret.push_back(cast<T>(expr));
}
} else if (isa<T>(*i)) {
ret.push_back(cast<T>(*i));
}
}
}
return ret;
}
const DeclRefExpr *getDeclRefExprOfImplicitConstructExpr(const MaterializeTemporaryExpr *matexpr);
template <class T>
std::vector<const T *> getArgumentsOfType(const CallExpr *call) {
std::vector<const T *> ret;
const Expr *const *args = call->getArgs();
for (int i = 0; i < call->getNumArgs(); i++) {
const Expr *arg = args[i];
if (isa<MaterializeTemporaryExpr>(arg)) {
if (const DeclRefExpr *ref = getDeclRefExprOfImplicitConstructExpr(cast<MaterializeTemporaryExpr>(arg))) {
if (isa<T>(ref)) {
ret.push_back(ref);
}
}
}
if (arg->IgnoreImpCasts() != NULL && arg->IgnoreImpCasts()->IgnoreParenCasts() != NULL &&
isa<T>(arg->IgnoreImpCasts()->IgnoreParenCasts())) {
ret.push_back(cast<const T>(arg->IgnoreImpCasts()->IgnoreParenCasts()));
}
}
return ret;
}
bool isVisible(const Decl &decl, const Stmt &position, ASTContext &Context);
|
ESS-Group/clang-sfi
|
src/SFIAction.h
|
<gh_stars>0
#ifndef SFIASTACTION_H
#define SFIASTACTION_H
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/FrontendActions.h"
#include "FaultInjector.h"
#include <string>
using namespace clang;
class SFIAction : public ASTFrontendAction {
public:
SFIAction(std::vector<std::string> pinjectornames, FaultInjectorOptions &pfiOpt);
void EndSourceFileAction() override;
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef file) override;
private:
std::string fileName;
std::vector<std::string> injectornames;
FaultInjectorOptions &fiOpt;
};
#endif
|
ESS-Group/clang-sfi
|
src/FaultInjector.h
|
#ifndef FAULTINJECTOR_H
#define FAULTINJECTOR_H
#include <sstream>
#include <string>
#include "clang/AST/AST.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/Frontend/CompilerInstance.h"
#include "GenericRewriter.h"
class MatchHandler;
using namespace clang;
using namespace clang::ast_matchers;
class FaultInjectorOptions {
public:
bool verbose;
std::string patchDir;
std::string rootDir;
std::vector<std::string> fileList;
bool matchMacro;
};
class FaultInjector : public MatchFinder::MatchCallback {
public:
class StmtBinding {
public:
class Location {
public:
unsigned int line;
unsigned int column;
Location(unsigned int pLine, unsigned int pColumn) : line(pLine), column(pColumn) {};
Location() {};
std::string toString() {
std::stringstream ss;
ss << line << ":" << column;
return ss.str();
}
};
class Range {
public:
Location begin;
Location end;
Range(Location pBegin, Location pEnd) : begin(pBegin), end(pEnd), valid(true) {};
Range() : valid(false){};
bool isValid() {
return valid;
};
std::string toString() {
if (isValid()) {
std::stringstream ss;
ss << begin.toString() << " - " << end.toString() << std::endl;
return ss.str();
} else {
return "INVALID";
}
}
private:
bool valid;
};
StmtBinding(std::string binding, const Decl &decl, bool left = false)
: binding(binding) {
this->left = left;
this->decl = &decl;
decllist.push_back(&decl);
isStmt = false;
isList = false;
}
StmtBinding(std::string binding, const Stmt &stmt, bool left = false)
: binding(binding) {
this->left = left;
this->stmt = &stmt;
stmtlist.push_back(&stmt);
isStmt = true;
isList = false;
}
StmtBinding(std::string binding, std::vector<const Decl *> list, bool left = false)
: binding(binding), decllist(list.begin(), list.end()) {
this->left = left;
isStmt = false;
isList = true;
}
StmtBinding(std::string binding, std::vector<const Stmt *> list, bool left = false)
: binding(binding), stmtlist(list.begin(), list.end()) {
this->left = left;
isStmt = true;
isList = true;
}
void calculateRange(ASTContext &Context) {
SourceLocation begin, end;
if (isList) {
if (isStmt) {
for (int i = 0; i < stmtlist.size(); i++) {
if (i == 0) {
begin = stmtlist[0]->getBeginLoc();
end = stmtlist[0]->getEndLoc();
} else {
SourceLocation _begin = stmtlist[i]->getBeginLoc(), _end = stmtlist[i]->getEndLoc();
if (end < _end) {
end = _end;
}
if (_begin < begin) {
begin = _begin;
}
}
}
} else {
for (int i = 0; i < decllist.size(); i++) {
if (i == 0) {
begin = decllist[0]->getBeginLoc();
end = decllist[0]->getEndLoc();
} else {
SourceLocation _begin = decllist[i]->getBeginLoc(), _end = decllist[i]->getEndLoc();
if (end < _end) {
end = _end;
}
if (_begin < begin) {
begin = _begin;
}
}
}
}
} else {
if (isStmt) {
begin = stmt->getBeginLoc();
end = stmt->getEndLoc();
} else {
begin = decl->getBeginLoc();
end = decl->getEndLoc();
}
}
if (begin.isValid() && end.isValid()) {
FullSourceLoc fBegin = Context.getFullLoc(begin), fEnd = Context.getFullLoc(end);
location = Range(Location(fBegin.getLineNumber(), fBegin.getColumnNumber()),
Location(fEnd.getLineNumber(), fEnd.getColumnNumber()));
}
}
const void *get() {
if (isList) {
if (isStmt) {
return &stmtlist;
} else {
return &decllist;
}
} else {
if (isStmt) {
return stmt;
} else {
return decl;
}
}
}
bool isStmt;
bool isList;
std::string binding;
const Stmt *stmt;
const Decl *decl;
std::vector<const Stmt *> stmtlist;
std::vector<const Decl *> decllist;
Range location;
bool left;
};
FaultInjector *createMatchHandler(std::string binding);
protected:
FaultInjector();
public:
~FaultInjector();
FaultInjector(const FaultInjector &that) = delete;
static std::unique_ptr<FaultInjector> create(const std::string &name);
virtual void run(const MatchFinder::MatchResult &Result);
template <typename SD>
void run_stmt_or_decl(const MatchFinder::MatchResult &Result, SourceManager &SM, std::string binding, SD &stmtOrDecl);
template<class T>
void push(std::string binding, const T &stmtOrDecl, bool left = false);
template<class T>
void push(std::string binding, std::vector<const T *> list);
/// Perform injections for a list of StmtBindings.
virtual void inject(std::vector<StmtBinding> target, ASTContext &Context);
/// Perform an injection for a specific StmtBinding in the provided Rewriter.
/// \return True if the rewriting was successful.
virtual bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) = 0;
/// Generate a patch for a single StmtBinding.
virtual void generatePatchFile(StmtBinding current, ASTContext &Context, GenericRewriter &R);
// default false
virtual bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context);
virtual bool checkStmt(const Decl &stmt, std::string binding, ASTContext &Context);
void matchAST(ASTContext &Context);
virtual std::string toString() = 0;
std::vector<StmtBinding> locations;
bool matchMacroDefinition, matchMacroExpansion;
void setMatchMacro(bool match);
void setMatchMacro(bool matchDef, bool matchExp);
void nodeCallback(std::string binding, const Stmt &stmt, bool left = false);
void nodeCallback(std::string binding, const Decl &decl, bool left = false);
void nodeCallback(std::string binding, std::vector<const Stmt *> list);
void nodeCallback(std::string binding, std::vector<const Decl *> list);
void setCI(CompilerInstance *CI);
void setVerbose(bool v);
void setPatchDirectory(std::string directory);
void setFileName(std::string name);
void setRootDir(std::string);
void setFileList(std::vector<std::string> list);
protected:
static void dumpStmt(const Stmt *stmt, ASTContext &Context);
static std::string stmtToString(const Stmt *stmt, const LangOptions &langOpts);
static void dumpStmt(const Decl *decl);
static std::string stmtToString(const Decl *decl, const LangOptions &langOpts);
static std::string sourceLocationToString(SourceLocation loc, const SourceManager &sourceManager);
static std::string sourceRangeToString(SourceRange range, const SourceManager &sourceManager);
static std::string sourceRangeToString(const Stmt *stmt, const SourceManager &sourceManager);
static std::string sourceRangeToString(const Decl *decl, const SourceManager &sourceManager);
static std::string rewriteBufferToString(RewriteBuffer &buffer);
std::string getEditedString(Rewriter &rewrite, ASTContext &Context);
void printStep(StmtBinding current, const SourceManager &sourceManager, const LangOptions &langOpts, int i = 0,
int size = 0); // with printing statements
void printStep(StmtBinding current, const SourceManager &sourceManager, int i = 0, int size = 0); // only position
MatchFinder Matcher; // child classes have to add Matchers
void _sort();
static bool comparefunc(StmtBinding st1, StmtBinding st2);
bool verbose;
std::string patchDir;
CompilerInstance *CI;
std::string fileName;
std::string rootDir;
std::vector<std::string> fileList;
std::vector<std::string> bindings;
};
#include "FaultInjectors/_all.h"
#endif
|
ESS-Group/clang-sfi
|
src/GenericRewriter.h
|
#ifndef REWRITER_H
#define REWRITER_H
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/CompilerInstance.h"
using namespace clang;
/// GenericRewrite is actually an adapter to clang::Rewriter, but since
/// multiple methods can be just passed through, we extend clang::Rewriter.
/// But GenericRewriter cannot be used in all places a clang::Rewriter is used.
class GenericRewriter : private clang::Rewriter {
public:
using clang::Rewriter::setSourceMgr;
using clang::Rewriter::getSourceMgr;
using clang::Rewriter::getLangOpts;
using clang::Rewriter::buffer_begin;
using clang::Rewriter::buffer_end;
using clang::Rewriter::getRewrittenText;
bool RemoveText(SourceRange range, RewriteOptions opts = RewriteOptions());
bool ReplaceText(SourceRange range, StringRef NewStr);
bool InsertText(SourceLocation Loc, StringRef Str, bool InsertAfter = true, bool indentNewLines = false);
bool startAndEndArePartOfTheSameExpansion(SourceRange range);
bool containsMacroExpansion(SourceRange range);
bool rangeIsFreeOfMacroExpansions(SourceRange range);
int numberNestedMacros(SourceLocation loc);
SourceLocation getDirectExpansionLoc(SourceLocation loc);
/// Check if the file given by \p patchingFileName is in the "project", i.e. is the main file or lies in the source tree.
bool considerFile(SourceLocation loc);
void setCI(CompilerInstance *CI);
void setFileName(std::string fileName);
void setRootDir(std::string rootDir);
void setFileList(std::vector<std::string> fileList);
private:
CompilerInstance *CI;
std::string fileName;
std::string rootDir = "";
std::vector<std::string> fileList;
};
#endif
|
ESS-Group/clang-sfi
|
src/FaultConstraints.h
|
<reponame>ESS-Group/clang-sfi
#ifndef FAULTCONSTRAINTS_H
#define FAULTCONSTRAINTS_H
#include "clang/AST/AST.h"
using namespace clang;
constexpr int MAXSTATEMENTNUMFORCONSTRAINT = 5;
constexpr bool DONOTDELETEDECLSTMTINCONSTRAINT = false;
constexpr bool RETURNISAJUMP = true;
constexpr bool DONTCOUNTBREAKINSWITCHCASEFORBLOCKSIZE = true;
bool isaJumpStmt(const Stmt &stmt, bool returnIsAJump = true);
bool C9(const Stmt *stmt, ASTContext *Context = NULL, bool returnIsAJump = RETURNISAJUMP,
int maxNum = MAXSTATEMENTNUMFORCONSTRAINT, bool noDeclStmt = DONOTDELETEDECLSTMTINCONSTRAINT);
bool C8(const IfStmt *ifS);
bool isaImplicit(const Stmt &stmt);
const Stmt *getParentIgnoringImplicit(const Stmt &stmt, ASTContext &Context);
const Stmt *getParentIgnoringParenCasts(const Stmt &stmt, ASTContext &Context);
struct CaseChilds {
std::vector<const Stmt *> stmts;
bool endWithBreak;
};
CaseChilds getCaseChilds(const SwitchCase *sc, ASTContext &Context);
int childCount(const Stmt &stmt);
int childCount(const Stmt &stmt, ASTContext &Context);
int childCount(const Stmt &stmt);
bool C2(const Stmt &stmt, ASTContext &Context);
bool C2(const Decl &decl, ASTContext &Context);
#endif
|
ESS-Group/clang-sfi
|
integrationtests/MFC_PROJECT/library.h
|
int libraryfunction(int a);
int removablefunctioncall();
inline int headerfunction() {
int a = 5;
int b = 6;
int c = 7;
int d = 8;
removablefunctioncall();
return 0;
}
|
ESS-Group/clang-sfi
|
src/FaultInjectors/_all.h
|
#ifndef _ALL_H
#define _ALL_H
#include <iostream>
#include "clang/ASTMatchers/ASTMatchers.h"
#include "FaultConstraints.h"
#include "FaultInjector.h"
#include "utils.h"
#include "GenericRewriter.h"
using namespace clang::ast_matchers;
#include "llvm/Support/Debug.h"
using namespace llvm;
class MIFSInjector : public FaultInjector {
public:
MIFSInjector();
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class SMIFSInjector : public MIFSInjector {
public:
std::string toString() override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class MIAInjector : public FaultInjector {
public:
MIAInjector();
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class SMIAInjector : public MIAInjector {
public:
std::string toString() override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class MIEBInjector : public FaultInjector {
public:
MIEBInjector();
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class SMIEBInjector : public MIEBInjector {
public:
std::string toString() override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class WAEPInjector : public FaultInjector {
public:
WAEPInjector();
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class WPFVInjector : public FaultInjector {
public:
WPFVInjector();
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class MFCInjector : public FaultInjector {
public:
MFCInjector();
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class MLOCInjector : public FaultInjector {
public:
MLOCInjector();
std::string toString() override;
// void inject(std::vector<StmtBinding> target, ASTContext &Context)
// override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
// GenericRewriter inject(StmtBinding current, ASTContext &Context, bool left);
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class MLACInjector : public FaultInjector {
public:
MLACInjector();
std::string toString() override;
// void inject(std::vector<StmtBinding> target, ASTContext &Context)
// override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
// GenericRewriter inject(StmtBinding current, ASTContext &Context, bool left);
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class MVIVInjector : public FaultInjector {
public:
MVIVInjector();
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Decl &decl, std::string binding, ASTContext &Context) override;
};
class MVIVInjectorSAFE : public FaultInjector {
public:
MVIVInjectorSAFE();
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Decl &decl, std::string binding, ASTContext &Context) override;
};
class MVAVInjector : public FaultInjector {
public:
MVAVInjector(bool alsoOverwritten = false);
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
protected:
bool alsoOverwritten;
};
class MVAVInjectorSAFE : public FaultInjector {
public:
MVAVInjectorSAFE(bool alsoOverwritten = false);
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Decl &decl, std::string binding, ASTContext &Context) override;
protected:
bool alsoOverwritten;
};
class OMVAVInjector : public MVAVInjector {
public:
OMVAVInjector();
std::string toString() override;
};
class WVAVInjector : public FaultInjector {
public:
WVAVInjector(bool alsoOverwritten = false);
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
protected:
bool alsoOverwritten;
};
class WVAVInjectorSAFE : public FaultInjector {
public:
WVAVInjectorSAFE(bool alsoOverwritten = false);
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Decl &decl, std::string binding, ASTContext &Context) override;
protected:
bool alsoOverwritten;
};
class OWVAVInjector : public WVAVInjector {
public:
OWVAVInjector();
std::string toString() override;
};
class MVAEInjector : public FaultInjector {
public:
MVAEInjector(bool alsoOverwritten = false);
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
protected:
bool alsoOverwritten;
};
class MVAEInjectorSAFE : public FaultInjector {
public:
MVAEInjectorSAFE();
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Decl &decl, std::string binding, ASTContext &Context) override;
protected:
bool alsoOverwritten;
};
class OMVAEInjector : public MVAEInjector {
public:
OMVAEInjector();
std::string toString() override;
};
class MLPAInjector : public FaultInjector {
public:
MLPAInjector();
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class SMLPAInjector : public MLPAInjector {
public:
std::string toString() override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class MIESInjector : public FaultInjector {
public:
MIESInjector();
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
class MRSInjector : public FaultInjector {
public:
MRSInjector();
std::string toString() override;
bool inject(StmtBinding current, ASTContext &Context, GenericRewriter &R) override;
bool checkStmt(const Stmt &stmt, std::string binding, ASTContext &Context) override;
};
#endif
|
ESS-Group/clang-sfi
|
src/SFIASTConsumer.h
|
<filename>src/SFIASTConsumer.h
#ifndef SFIASTCONSUMER_H
#define SFIASTCONSUMER_H
#include "clang/AST/ASTConsumer.h"
#include "clang/Frontend/CompilerInstance.h"
#include "FaultInjector.h"
using namespace clang;
class SFIASTConsumer : public ASTConsumer {
public:
SFIASTConsumer(std::string name, std::vector<std::unique_ptr<FaultInjector>> injectors, CompilerInstance *CI);
void HandleTranslationUnit(ASTContext &Context) override;
private:
std::string fileName;
std::vector<std::unique_ptr<FaultInjector>> faultInjectors;
};
#endif
|
sss85921/pd2-angrybird
|
mainwindow.h
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTimer>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QList>
#include <QGraphicsview>
#include <QDialog>
#include <QGraphicsItem>
#include <stdlib.h>
#include <time.h>
#include <QLabel>
#include <QPixmap>
#include <math.h>
#include <QtMath>
#include <QtCore/qmath.h>
#include <QKeyEvent>
#include <QFileDialog>
#include <QMouseEvent>
#include <QWidget>
#include <QVBoxLayout>
#include <QDebug>
#include <QDialog>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
int click=0;
int press=0;
int num=0;
int hit=100;
int hit_pig_1=0;
int hit_pig_2=0;
int hit_pig_3=0;
int hit_pig_4=0;
int hit_pig_num;
int bird_order=1;
int stop;
float tx=0;
float ty=0;
float x_release ;
float y_release ;
float x_start = 160;
float y_start = 460;
float bird_x;
float bird_y;
float r_x;
float r_y;
float now_speed_y;
float now_speed_x;
float now_bird_y;
float now_bird_x;
float v;
float v_horizontal;
float v_vertical;
float egg_pos_x;
float egg_pos_y;
float egg_speed_horizontal;
float egg_speed_vertical;
float egg_start_x;
float egg_start_y;
QTimer *timer;
public slots:
void on_pushButton_clicked();
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void timer_for_bird();
void bird_fly();
private slots:
void on_pushButton_2_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
|
tomolt/tiny-library-collection
|
tests/all_tests.c
|
#include <stdlib.h>
#define DH_IMPLEMENT_HERE
#include "dh_cuts.h"
void calm_suite(void);
void hashtable_suite(void);
void dh_cuts_suite(void);
int main()
{
dh_init(stdout);
dh_branch (
calm_suite();
)
dh_branch (
hashtable_suite();
)
dh_branch (
dh_cuts_suite();
)
dh_summarize();
return EXIT_SUCCESS;
}
|
tomolt/tiny-library-collection
|
dh_cuts.h
|
/* dh_cuts.h - Dynamic Hierarchy C Unit Testing System
*
* ISC License
*
* Copyright (c) 2018, 2019, 2020 <NAME>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* You can find an up-to-date copy of this file under
* https://www.github.com/tomolt/dh_cuts
*/
/*
* DH_OPTION_ASCII_ONLY
* DH_OPTION_PEDANTIC
* DH_OPTION_EPSILON
*/
#ifndef DH_CUTS_H
#define DH_CUTS_H
#include <setjmp.h>
#include <stdio.h>
struct dh_branch_saves_ {
int saved_depth;
void *saved_jump;
};
void dh_init(FILE *pipe);
void dh_summarize(void);
void dh_push(char const *format, ...);
void dh_pop(void);
#define dh_branch(code) { \
struct dh_branch_saves_ s; \
sigjmp_buf my_jmp; \
int signal = sigsetjmp(my_jmp, 1); \
dh_branch_beg_(signal, &my_jmp, &s); \
if (!signal) { \
code \
} \
dh_branch_end_(&s); \
}
#ifndef DH_OPTION_EPSILON
# define DH_OPTION_EPSILON 0.00001
#endif
#define dh_throw(format, ...) dh_throw_(__LINE__, format, __VA_ARGS__)
#define dh_assert(cond) dh_assert_(__LINE__, cond, #cond)
#define dh_assertiq(a, b) dh_assertiq_(__LINE__, a, b, #a "==" #b)
#define dh_assertfq(a, b) dh_assertfq_(__LINE__, a, b, DH_OPTION_EPSILON, #a "==" #b)
#define dh_assertsq(a, b) dh_assertsq_(__LINE__, a, b, #a "==" #b)
#define dh_asserteq(a, b, e) dh_assertfq_(__LINE__, a, b, e, #a "==" #b)
/* internal functions that have to be visible. */
/* do not call these directly. */
void dh_throw_(int ln, char const *format, ...);
void dh_assert_(int ln, int cond, char const *str);
void dh_assertiq_(int ln, long long a, long long b, char const *str);
void dh_assertfq_(int ln, double a, double b, double e, char const *str);
void dh_assertsq_(int ln, char const *a, char const *b, char const *str);
void dh_branch_beg_(int signal, sigjmp_buf *my_jmp, struct dh_branch_saves_ *s);
void dh_branch_end_(struct dh_branch_saves_ *s);
#endif
#ifdef DH_IMPLEMENT_HERE
#if DH_OPTION_ASCII_ONLY
# define TEXT_DOTS ".."
# define TEXT_HIER "\\ "
# define TEXT_ARROW "<-"
# define TEXT_LINE "--"
#else
# define TEXT_DOTS "\u2024\u2024"
# define TEXT_HIER "\u2514 "
# define TEXT_ARROW "\u2190"
# define TEXT_LINE "\u2500\u2500"
#endif
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <signal.h>
#define MAX_NAME_LENGTH 200
#define MAX_DEPTH 50
enum { FAIL, CRASH };
enum { THROW, ASSERT };
#define NO_LINENO -1
static int const dh_caught_signals[] = { SIGILL, SIGFPE, SIGSEGV, SIGBUS, SIGSYS, SIGPIPE, 0 };
struct dh_this {
sigjmp_buf *crash_jump;
int stack_depth;
char const *stack[MAX_DEPTH];
};
struct dh_sink {
FILE *pipe;
int print_depth;
int error_count;
int crash_count;
};
static struct dh_this dh_this;
static struct dh_sink dh_sink;
static char const *dh_name_of_signal_(int signal)
{
switch (signal) {
case SIGILL: return "illegal instruction (SIGILL)"; break;
case SIGFPE: return "arithmetic exception (SIGFPE)"; break;
case SIGSEGV: return "segmentation fault (SIGSEGV)"; break;
case SIGBUS: return "bus error (SIGBUS)"; break;
case SIGSYS: return "illegal system call (SIGSYS)"; break;
case SIGPIPE: return "broken pipe (SIGPIPE)"; break;
/* the default path should never be taken, */
/* as only the above signals are actually caught. */
default: return "unknown signal"; break;
}
}
static void dh_signal_handler_(int signal)
{
if (dh_this.crash_jump != NULL) {
if (signal == SIGFPE) {
/* source: https://msdn.microsoft.com/en-us/library/xdkz3x12.aspx */
/* _fpreset(); TODO */
}
/* signal will never be 0, so we can pass it */
/* directly to longjmp without hesitation. */
/* source: /usr/include/bits/signum-generic.h */
siglongjmp(*dh_this.crash_jump, signal);
} else {
/* if there is no recovery point, we can't do anything about the signal. */
/* this situation should not arise during normal operation. */
}
}
void dh_init(FILE *pipe)
{
dh_sink.pipe = pipe;
struct sigaction action;
memset(&action, 0, sizeof(struct sigaction));
action.sa_handler = dh_signal_handler_;
sigemptyset(&action.sa_mask);
/* TODO error checking */
int i;
for (i = 0; dh_caught_signals[i] != 0; ++i) {
sigaction(dh_caught_signals[i], &action, NULL);
}
}
void dh_summarize(void)
{
#if !DH_OPTION_PEDANTIC
if (dh_sink.error_count != 0 || dh_sink.crash_count != 0)
#endif
{
fprintf(dh_sink.pipe,
TEXT_LINE " %d failures, %d crashes " TEXT_LINE "\n",
dh_sink.error_count, dh_sink.crash_count);
}
}
void dh_push(char const *format, ...)
{
char *str = malloc(MAX_NAME_LENGTH);
va_list va;
va_start(va, format);
vsnprintf(str, MAX_NAME_LENGTH, format, va);
va_end(va);
dh_this.stack[dh_this.stack_depth++] = str;
}
void dh_pop(void)
{
free((char *)dh_this.stack[--dh_this.stack_depth]);
if (dh_sink.print_depth > dh_this.stack_depth)
dh_sink.print_depth = dh_this.stack_depth;
}
static void dh_print_nesting_(int depth)
{
int i;
for (i = 0; i < depth; ++i)
fputs(TEXT_DOTS, dh_sink.pipe);
fputs(TEXT_HIER, dh_sink.pipe);
}
static void dh_report_(int kind, int signal, int ln, char const *msg)
{
char const *kind_name, *signal_name;
switch (kind) {
case FAIL:
++dh_sink.error_count;
kind_name = "FAIL";
switch (signal) {
case THROW: signal_name = "throw"; break;
case ASSERT: signal_name = "assert"; break;
}
break;
case CRASH:
++dh_sink.crash_count;
kind_name = "CRASH";
signal_name = dh_name_of_signal_(signal);
break;
}
int depth = dh_sink.print_depth;
while (depth < dh_this.stack_depth) {
dh_print_nesting_(depth);
fputs(dh_this.stack[depth], dh_sink.pipe);
fputs("\n", dh_sink.pipe);
++depth;
}
dh_sink.print_depth = dh_this.stack_depth;
dh_print_nesting_(dh_sink.print_depth);
fprintf(dh_sink.pipe, "triggered %s", signal_name);
if (ln != NO_LINENO) {
fprintf(dh_sink.pipe, " in line %03d", ln);
}
if (msg != NULL) {
fprintf(dh_sink.pipe, ": %s", msg);
}
fprintf(dh_sink.pipe, "\t\t" TEXT_ARROW " %s\n", kind_name);
}
void dh_branch_beg_(int signal, sigjmp_buf *my_jmp, struct dh_branch_saves_ *s)
{
if (signal) {
dh_report_(CRASH, signal, NO_LINENO, NULL);
} else {
*s = (struct dh_branch_saves_){dh_this.stack_depth, (void *)dh_this.crash_jump};
dh_this.crash_jump = my_jmp;
}
}
void dh_branch_end_(struct dh_branch_saves_ *s)
{
dh_this.crash_jump = s->saved_jump;
/* restore the stack in case of a crash. */
/* also helps recovering from missing dh_pop()'s, */
/* though you *really* shouldn't rely on this behaviour. */
while (dh_this.stack_depth > s->saved_depth)
dh_pop();
}
void dh_throw_(int ln, char const *format, ...)
{
char *str = malloc(MAX_NAME_LENGTH);
va_list va;
va_start(va, format);
vsnprintf(str, MAX_NAME_LENGTH, format, va);
va_end(va);
dh_report_(FAIL, THROW, ln, str);
free(str);
}
void dh_assert_(int ln, int cond, char const *str)
{
if (!cond) dh_report_(FAIL, ASSERT, ln, str);
}
void dh_assertiq_(int ln, long long a, long long b, char const *str)
{
dh_assert_(ln, a == b, str);
}
void dh_assertfq_(int ln, double a, double b, double e, char const *str)
{
/* because of the rounding behaviour of floating-point numbers, two expressions */
/* that mathematically should evaluate to the same value can actually differ in */
/* the lower digits. For user convenience dh_assertfq() therefore allow a small */
/* difference between a and b. */
/* If the user wants to use another epsilon value, he can either define his own */
/* epsilon via DH_OPTION_EPSILON or write his own macro wrapping dh_assertfq_(). */
/* If exact comparison is wanted, one can always use dh_assert(a == b). */
double d = a - b;
if (d < 0.0) d = -d; /* same as: d = fabsf(d); */
dh_assert_(ln, d <= e, str);
}
void dh_assertsq_(int ln, char const *a, char const *b, char const *str)
{
dh_assert_(ln, strcmp(a, b) != 0, str);
}
#endif
|
tomolt/tiny-library-collection
|
tests/hashtable_suite.c
|
<reponame>tomolt/tiny-library-collection<filename>tests/hashtable_suite.c
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "dh_cuts.h"
#define HT_IMPLEMENT_HERE
#include "hashtable.h"
char *my_strdup(char const *string)
{
size_t length = strlen(string) + 1;
char *copy = malloc(length * sizeof(char));
memcpy(copy, string, length);
return copy;
}
void test_insertions(void)
{
#define NUM_ITERATIONS 5000
dh_push("batch insertions and lookups");
struct HT ht = htNew(500, sizeof(int));
int values[NUM_ITERATIONS];
char const *keys[NUM_ITERATIONS];
for (int i = 0; i < NUM_ITERATIONS; ++i) {
dh_push("insertion #%d", i);
int rd = rand() % 0xFFFF;
char buf[50];
sprintf(buf, "%x", rd);
char const *name = my_strdup(buf);
htSet(&ht, name, strlen(name), &rd);
values[i] = rd;
keys[i] = name;
dh_pop();
}
for (int i = 0; i < NUM_ITERATIONS; ++i) {
dh_push("lookup #%d", i);
int has = htHas(&ht, keys[i], strlen(keys[i]));
dh_assert(has);
if (has) {
dh_assertiq(*(int*)htGet(&ht, keys[i], strlen(keys[i])), values[i]);
}
dh_pop();
}
htFree(&ht);
dh_pop();
}
void hashtable_suite(void)
{
dh_push("hashtable");
test_insertions();
dh_pop();
}
|
tomolt/tiny-library-collection
|
tests/calm_suite.c
|
#include <stdlib.h>
#include <math.h>
#include "dh_cuts.h"
#define CM_IMPLEMENT_HERE
#include "calm.h"
const double EPSILON = 0.0001;
static int cmp_v4(cm_v4 a, cm_v4 b)
{
float ac[4], bc[4];
cm_recv_v4(a, ac);
cm_recv_v4(b, bc);
for (int i = 0; i < 4; i++) {
if (fabs(ac[i] - bc[i]) > EPSILON)
return 0;
}
return 1;
}
static int cmp_m16(cm_m16 a, cm_m16 b)
{
float ac[16], bc[16];
cm_recv_m16(a, ac);
cm_recv_m16(b, bc);
for (int i = 0; i < 16; i++) {
if (fabs(ac[i] - bc[i]) > EPSILON)
return 0;
}
return 1;
}
void test_calm_mul_m16(void)
{
dh_push("multiplying two matrices");
const cm_m16 a = cm_send_m16((float[]){
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16});
const cm_m16 b = cm_send_m16((float[]){
17, 18, 19, 20,
21, 22, 23, 24,
25, 26, 27, 28,
29, 30, 31, 32});
const cm_m16 r = cm_dot_m16(a, b);
const cm_m16 E = cm_send_m16((float[]){
538, 612, 686, 760,
650, 740, 830, 920,
762, 868, 974, 1080,
874, 996, 1118, 1240});
dh_assert(cmp_m16(r, E));
dh_pop();
}
void test_inverse_m16_success(void)
{
dh_push("compute correct matrix inverse");
const cm_m16 m = cm_send_m16((float[]){
1, 4, 2, 3,
0, 1, 4, 4,
-1, 0, 1, 0,
2, 0, 4, 1});
const cm_m16 r = cm_inverse_m16(m);
const cm_m16 E = cm_send_m16((float[]){
1/65.0, -4/65.0, -38/65.0, 13/65.0,
20/65.0, -15/65.0, 20/65.0, 0/65.0,
1/65.0, -4/65.0, 27/65.0, 13/65.0,
-6/65.0, 24/65.0, -32/65.0, -13/65.0});
dh_assert(cmp_m16(r, E));
dh_pop();
}
void test_inverse_m16_failure(void)
{
dh_push("identify failing matrix inverse");
const cm_m16 m = cm_send_m16((float[]){
1, 5, 0, 13,
2, 6, 0, 14,
3, 7, 0, 15,
4, 8, 0, 16});
const cm_m16 r = cm_inverse_m16(m);
const cm_m16 E = cm_identity_m16();
dh_assert(cmp_m16(r, E));
dh_pop();
}
void test_calm_look_at(void)
{
dh_push("build look at matrix");
const cm_m16 r = cm_lookat_m16(
cm_new_v3(4.0, 3.0, 3.0),
cm_new_v3(0.0, 0.0, 0.0),
cm_new_v3(0.0, 1.0, 0.0));
const cm_m16 E = cm_send_m16((float[]){
0.6, -0.411597, 0.685994, 0.0,
0.0, 0.857493, 0.514496, 0.0,
-0.8, -0.308697, 0.514496, 0.0,
0.0, 0.0, -5.830953, 1.0});
dh_assert(cmp_m16(r, E));
dh_pop();
}
void test_calm_qt_from_axis(void)
{
dh_push("make quaternion from axis");
const cm_v4 A = cm_norm_v3(cm_new_v3(0.3, 0.4, 0.6));
const cm_qt Q = cm_new_qt(A, 1.5);
const cm_qt E = cm_new_v4(0.261825, 0.3491, 0.523649, 0.731689);
dh_assert(cmp_v4(Q, E));
dh_pop();
}
void test_calm_m16_from_qt(void)
{
dh_push("matrix from quaternion");
const cm_v4 A = cm_norm_v3(cm_new_v3(0.3, 0.4, 0.6));
const cm_qt Q = cm_new_qt(A, 1.5);
const cm_m16 r = cm_qt_to_m16(Q);
const cm_m16 E = cm_send_m16((float[]){
0.207841, -0.583491, 0.785073, 0.0,
0.949103, 0.314478, -0.017537, 0.0,
-0.236656, 0.748760, 0.619155, 0.0,
0.0, 0.0, 0.0, 1.0});
dh_assert(cmp_m16(r, E));
dh_pop();
}
void test_calm_qt_cumulate(void)
{
dh_push("cumulate quaternions");
const cm_v4 A1 = cm_norm_v3(cm_new_v3(0.3, 0.4, 0.6));
const cm_qt Q1 = cm_new_qt(A1, 1.5f);
const cm_v4 A2 = cm_norm_v3(cm_new_v3(0.9, 0.2, 0.7));
const cm_qt Q2 = cm_new_qt(A2, 2.93f);
const cm_qt R = cm_cum_qt(Q1, Q2);
const cm_qt E = cm_new_v4(0.473386, -0.084835, 0.720199, -0.500023);
dh_assert(cmp_v4(R, E));
dh_pop();
}
void calm_suite(void)
{
dh_push("3D Math");
test_calm_mul_m16();
test_inverse_m16_success();
test_inverse_m16_failure();
test_calm_look_at();
test_calm_qt_from_axis();
test_calm_m16_from_qt();
test_calm_qt_cumulate();
dh_pop();
}
|
tomolt/tiny-library-collection
|
calm.h
|
<reponame>tomolt/tiny-library-collection
/* calm.h - C Accelerated Linear Maths library
*
* MIT License
*
* Copyright (c) 2018 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* This file was originally distributed as part of <NAME>'s personal
* tiny library collection. (https://www.github.com/tomolt/tiny-library-collection)
*/
#ifndef CM_CALM_H
#define CM_CALM_H
typedef float cm_f1;
// TEMP
#define CM_BACKEND 0
#define CM_BACKEND_FALLBACK 0
#define CM_BACKEND_SSE 1
/* If the user didn't supply a CM_BACKEND, then choose automatically. */
#ifndef CM_BACKEND
# if defined(__SSE__) || _M_IX86_FP > 0 || _M_X64 > 0
# define CM_BACKEND CM_BACKEND_SSE
# else
# define CM_BACKEND CM_BACKEND_FALLBACK
# endif
#endif
#if CM_BACKEND == CM_BACKEND_SSE
#error "SSE SHOULD BE DISABLED RIGHT NOW!"
# include <xmmintrin.h>
typedef __m128 cm_f4_;
# if defined(_MSC_VER)
# define CM_DEF _vectorcall
# define CM_ALIGN16 __declspec(align(16))
# elif defined(__GNUC__)
# define CM_DEF
# define CM_ALIGN16 __attribute__((aligned(16)))
# elif defined(__clang__)
# define CM_DEF __attribute__ ((vectorcall))
# define CM_ALIGN16 __attribute__((aligned(16)))
# else
# define CM_DEF
# define CM_ALIGN16
# endif
#else
typedef struct { cm_f1 c[4]; } cm_f4_;
# define CM_DEF
#endif
/* M_PI isn't actually officially part of the C standard library.
* In case it's missing, you can use CM_PI instead. */
#define CM_PI 3.1415926535897932
typedef cm_f4_ cm_v4;
CM_DEF cm_v4 cm_new_v4(cm_f1 a, cm_f1 b, cm_f1 c, cm_f1 d);
CM_DEF cm_v4 cm_send_v4(cm_f1 c[4]);
CM_DEF cm_v4 cm_send1_v4(cm_f1 a);
CM_DEF cm_v4 cm_add_v4(cm_v4 l, cm_v4 r);
CM_DEF cm_v4 cm_sub_v4(cm_v4 l, cm_v4 r);
CM_DEF cm_v4 cm_mul_v4(cm_v4 l, cm_v4 r);
CM_DEF void cm_recv_v4(cm_v4 f, cm_f1 o[4]);
CM_DEF cm_f1 cm_hsum_v4(cm_v4 f);
CM_DEF cm_v4 cm_scale_v4(cm_v4 f, cm_f1 s);
CM_DEF cm_f1 cm_dot_v4(cm_v4 l, cm_v4 r);
CM_DEF cm_f1 cm_length_v4(cm_v4 v);
CM_DEF cm_v4 cm_norm_v4(cm_v4 v);
typedef cm_f4_ cm_v3;
#define cm_new_v3(a, b, c) cm_new_v4(a, b, c, 0.0f)
CM_DEF cm_f1 cm_dot_v3(cm_v4 l, cm_v4 r);
CM_DEF cm_f1 cm_length_v3(cm_v4 v);
CM_DEF cm_v4 cm_norm_v3(cm_v4 v);
CM_DEF cm_f1 cm_hsum_v3(cm_v4 f);
CM_DEF cm_v4 cm_cross_v3(cm_v4 l, cm_v4 r);
typedef struct { cm_v4 c[4]; } cm_m16;
CM_DEF cm_m16 cm_identity_m16(void);
CM_DEF cm_m16 cm_new_m16(cm_v4 a, cm_v4 b, cm_v4 c, cm_v4 d);
CM_DEF cm_m16 cm_send_m16(cm_f1 c[16]);
CM_DEF void cm_recv_m16(cm_m16 m, cm_f1 c[16]);
CM_DEF cm_m16 cm_add_m16(cm_m16 l, cm_m16 r);
CM_DEF cm_m16 cm_sub_m16(cm_m16 l, cm_m16 r);
CM_DEF cm_v4 cm_apply_m16(cm_m16 m, cm_v4 f);
CM_DEF cm_m16 cm_transpose_m16(cm_m16 m);
CM_DEF cm_m16 cm_inverse_m16(cm_m16 m);
CM_DEF cm_m16 cm_dot_m16(cm_m16 l, cm_m16 r);
CM_DEF cm_m16 cm_translate_m16(cm_m16 m, cm_v4 f);
CM_DEF cm_m16 cm_scale_m16(cm_m16 m, cm_v4 v);
CM_DEF cm_m16 cm_orthogonal_m16(cm_f1 left, cm_f1 right, cm_f1 bottom, cm_f1 top, cm_f1 near, cm_f1 far);
CM_DEF cm_m16 cm_frustum_m16(cm_f1 left, cm_f1 right, cm_f1 bottom, cm_f1 top, cm_f1 znear, cm_f1 zfar);
CM_DEF cm_m16 cm_perspective_m16(cm_f1 fovyInDegrees, cm_f1 aspectRatio, cm_f1 znear, cm_f1 zfar);
CM_DEF cm_m16 cm_lookat_m16(cm_v4 position, cm_v4 target, cm_v4 upVector);
/* TODO utilize */
typedef cm_v4 cm_qt;
CM_DEF cm_qt cm_conj_qt(cm_qt q);
CM_DEF cm_qt cm_apply_qt(cm_qt q, cm_v4 v);
CM_DEF cm_qt cm_new_qt(cm_v4 axis, cm_f1 angle);
CM_DEF cm_qt cm_cum_qt(cm_qt a, cm_qt b);
CM_DEF cm_qt cm_slerp_qt(cm_qt a, cm_qt b, cm_f1 t);
CM_DEF cm_m16 cm_qt_to_m16(cm_qt q);
#endif
#ifdef CM_IMPLEMENT_HERE
#include <math.h>
#include <string.h> /* For memcpy only. TODO get rid of this dependency */
#if CM_BACKEND == CM_BACKEND_SSE
CM_DEF cm_v4 cm_new_v4(cm_f1 a, cm_f1 b, cm_f1 c, cm_f1 d) {
return _mm_setr_ps(a, b, c, d);
}
CM_DEF cm_v4 cm_send_v4(cm_f1 c[4]) {
return _mm_setr_ps(c[0], c[1], c[2], c[3]);
}
CM_DEF cm_v4 cm_send1_v4(cm_f1 a) {
return _mm_set1_ps(a);
}
CM_DEF cm_v4 cm_add_v4(cm_v4 l, cm_v4 r) {
return _mm_add_ps(l, r);
}
CM_DEF cm_v4 cm_sub_v4(cm_v4 l, cm_v4 r) {
return _mm_sub_ps(l, r);
}
CM_DEF cm_v4 cm_mul_v4(cm_v4 l, cm_v4 r) {
return _mm_mul_ps(l, r);
}
#define cm_spread_v4(f, i) _mm_shuffle_ps(f, f, _MM_SHUFFLE(i, i, i, i))
CM_DEF void cm_recv_v4(cm_v4 f, cm_f1 o[4]) {
CM_ALIGN16 cm_f1 i[4];
_mm_store_ps(i, f);
memcpy(o, i, sizeof(cm_f1[4]));
}
CM_DEF cm_m16 cm_transpose_m16(cm_m16 m) {
cm_m16 o = m;
_MM_TRANSPOSE4_PS(o.c[0], o.c[1], o.c[2], o.c[3]);
return o;
}
CM_DEF cm_v4 cm_cross_v3(cm_v4 l, cm_v4 r) {
cm_v4 lyzx = _mm_shuffle_ps(l, l, _MM_SHUFFLE(3, 0, 2, 1));
cm_v4 rzxy = _mm_shuffle_ps(r, r, _MM_SHUFFLE(3, 1, 0, 2));
cm_v4 lzxy = _mm_shuffle_ps(l, l, _MM_SHUFFLE(3, 1, 0, 2));
cm_v4 ryzx = _mm_shuffle_ps(r, r, _MM_SHUFFLE(3, 0, 2, 1));
return cm_sub_v4(cm_mul_v4(lyzx, rzxy), cm_mul_v4(ryzx, lzxy));
}
#else // CM_BACKEND == CM_BACKEND_FALLBACK
CM_DEF cm_v4 cm_new_v4(cm_f1 a, cm_f1 b, cm_f1 c, cm_f1 d) {
return (cm_v4){{a, b, c, d}};
}
CM_DEF cm_v4 cm_send_v4(cm_f1 c[4]) {
return (cm_v4){{c[0], c[1], c[2], c[3]}}; // TODO clean this up
}
CM_DEF cm_v4 cm_send1_v4(cm_f1 a) {
return (cm_v4){{a, a, a, a}};
}
CM_DEF void cm_recv_v4(cm_v4 f, cm_f1 o[4]) {
memcpy(o, f.c, sizeof(cm_f1[4]));
}
CM_DEF cm_v4 cm_add_v4(cm_v4 l, cm_v4 r) {
return (cm_v4){{l.c[0]+r.c[0], l.c[1]+r.c[1], l.c[2]+r.c[2], l.c[3]+r.c[3]}};
}
CM_DEF cm_v4 cm_sub_v4(cm_v4 l, cm_v4 r) {
return (cm_v4){{l.c[0]-r.c[0], l.c[1]-r.c[1], l.c[2]-r.c[2], l.c[3]-r.c[3]}};
}
CM_DEF cm_v4 cm_mul_v4(cm_v4 l, cm_v4 r) {
return (cm_v4){{l.c[0]*r.c[0], l.c[1]*r.c[1], l.c[2]*r.c[2], l.c[3]*r.c[3]}};
}
CM_DEF cm_v4 cm_spread_v4(cm_v4 f, int i) {
return (cm_v4){{f.c[i], f.c[i], f.c[i], f.c[i]}};
}
CM_DEF cm_v4 cm_cross_v3(cm_v4 l, cm_v4 r) {
return (cm_v4){{
l.c[1]*r.c[2] - l.c[2]*r.c[1],
l.c[2]*r.c[0] - l.c[0]*r.c[2],
l.c[0]*r.c[1] - l.c[1]*r.c[0]}};
}
CM_DEF cm_m16 cm_transpose_m16(cm_m16 m) {
cm_m16 o;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
o.c[j].c[i] = m.c[i].c[j];
}
return o;
}
CM_DEF cm_m16 cm_inverse_m16(cm_m16 mat) {
/* Implementation lifted from OpenTK, but heavily modified for libcalm.
* https://svn.code.sf.net/p/opentk/code/trunk/Source/OpenTK/Math/Matrix4.cs
* Just to be safe, here's their license:
*
* Copyright (c) 2006 - 2008 The Open Toolkit library.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* */
// TODO test whether this function accidentally
// overwrites mat outside of its own scope.
int colIdx[4] = {0}, rowIdx[4] = {0};
int pivotIdx[4] = {-1, -1, -1, -1};
int icol = 0, irow = 0;
for (int i = 0; i < 4; i++) {
// Find the largest pivot value
cm_f1 maxPivot = 0.0f;
for (int j = 0; j < 4; j++) {
if (pivotIdx[j] != 0) {
for (int k = 0; k < 4; ++k) {
if (pivotIdx[k] == -1) {
cm_f1 absVal = fabs(mat.c[j].c[k]);
if (absVal > maxPivot) {
maxPivot = absVal;
irow = j, icol = k;
}
} else if (pivotIdx[k] > 0) {
return cm_identity_m16();
}
}
}
}
pivotIdx[icol]++;
// Swap rows over so pivot is on diagonal
if (irow != icol) {
cm_v4 f = mat.c[irow];
mat.c[irow] = mat.c[icol];
mat.c[icol] = f;
}
rowIdx[i] = irow, colIdx[i] = icol;
cm_f1 pivot = mat.c[icol].c[icol];
// check for singular matrix
if (pivot == 0.0f) {
return cm_identity_m16();
}
// Scale row so it has a unit diagonal
mat.c[icol].c[icol] = 1.0f;
mat.c[icol] = cm_scale_v4(mat.c[icol], 1.0f / pivot);
// Do elimination of non-diagonal elements
for (int j = 0; j < 4; ++j) {
// check this isn't on the diagonal
if (icol != j) {
cm_f1 f = mat.c[j].c[icol];
mat.c[j].c[icol] = 0.0f;
mat.c[j] = cm_sub_v4(mat.c[j], cm_scale_v4(mat.c[icol], f));
}
}
}
for (int j = 3; j >= 0; --j) {
int ir = rowIdx[j], ic = colIdx[j];
for (int k = 0; k < 4; ++k) {
cm_f1 f = mat.c[k].c[ir];
mat.c[k].c[ir] = mat.c[k].c[ic];
mat.c[k].c[ic] = f;
}
}
return mat;
}
CM_DEF cm_qt cm_cum_qt(cm_qt a, cm_qt b) {
return (cm_qt) {{
b.c[3] * a.c[0] + b.c[0] * a.c[3] + b.c[1] * a.c[2] - b.c[2] * a.c[1],
b.c[3] * a.c[1] + b.c[1] * a.c[3] + b.c[2] * a.c[0] - b.c[0] * a.c[2],
b.c[3] * a.c[2] + b.c[2] * a.c[3] + b.c[0] * a.c[1] - b.c[1] * a.c[0],
b.c[3] * a.c[3] - b.c[0] * a.c[0] - b.c[1] * a.c[1] - b.c[2] * a.c[2]}};
}
#endif
/* ~~~~ 4D VECTORS ~~~~ */
CM_DEF cm_f1 cm_hsum_v4(cm_v4 f) {
cm_f1 c[4];
cm_recv_v4(f, c);
return c[0] + c[1] + c[2] + c[3];
}
CM_DEF cm_v4 cm_scale_v4(cm_v4 f, cm_f1 s) {
cm_v4 b = cm_send1_v4(s);
return cm_mul_v4(f, b);
}
CM_DEF cm_f1 cm_dot_v4(cm_v4 l, cm_v4 r) {
return cm_hsum_v4(cm_mul_v4(l, r));
}
CM_DEF cm_f1 cm_length_v4(cm_v4 v) {
return sqrtf(cm_dot_v4(v, v));
}
CM_DEF cm_v4 cm_norm_v4(cm_v4 v) {
cm_f1 length = cm_length_v4(v);
return cm_scale_v4(v, 1.0 / length);
}
/* ~~~~ 3D VECTORS ~~~~ */
CM_DEF cm_f1 cm_dot_v3(cm_v4 l, cm_v4 r) {
return cm_hsum_v3(cm_mul_v4(l, r));
}
CM_DEF cm_f1 cm_length_v3(cm_v4 v) {
return sqrtf(cm_dot_v3(v, v));
}
CM_DEF cm_v4 cm_norm_v3(cm_v4 v) {
cm_f1 length = cm_length_v3(v);
return cm_scale_v4(v, 1.0 / length);
}
CM_DEF cm_f1 cm_hsum_v3(cm_v4 f) {
cm_f1 c[4];
cm_recv_v4(f, c);
return c[0] + c[1] + c[2];
}
/* ~~~~ 4x4 MATRICES ~~~~ */
CM_DEF cm_m16 cm_identity_m16(void) {
cm_m16 m;
m.c[0] = cm_new_v4(1.0, 0.0, 0.0, 0.0);
m.c[1] = cm_new_v4(0.0, 1.0, 0.0, 0.0);
m.c[2] = cm_new_v4(0.0, 0.0, 1.0, 0.0);
m.c[3] = cm_new_v4(0.0, 0.0, 0.0, 1.0);
return m;
}
CM_DEF cm_m16 cm_new_m16(cm_v4 a, cm_v4 b, cm_v4 c, cm_v4 d) {
return (cm_m16){{a, b, c, d}};
}
CM_DEF cm_m16 cm_send_m16(cm_f1 f[16])
{
return (cm_m16){{
cm_send_v4(&f[ 0]),
cm_send_v4(&f[ 4]),
cm_send_v4(&f[ 8]),
cm_send_v4(&f[12])}};
}
CM_DEF void cm_recv_m16(cm_m16 m, cm_f1 c[16]) {
/* TODO maybe optimize? */
cm_recv_v4(m.c[0], &c[0]);
cm_recv_v4(m.c[1], &c[4]);
cm_recv_v4(m.c[2], &c[8]);
cm_recv_v4(m.c[3], &c[12]);
}
CM_DEF cm_m16 cm_add_m16(cm_m16 l, cm_m16 r) {
cm_m16 o;
for (int i = 0; i < 4; i++)
o.c[i] = cm_add_v4(l.c[i], r.c[i]);
return o;
}
CM_DEF cm_m16 cm_sub_m16(cm_m16 l, cm_m16 r) {
cm_m16 o;
for (int i = 0; i < 4; i++)
o.c[i] = cm_sub_v4(l.c[i], r.c[i]);
return o;
}
CM_DEF cm_v4 cm_apply_m16(cm_m16 m, cm_v4 f) {
cm_v4 c0 = cm_mul_v4(m.c[0], cm_spread_v4(f, 0));
cm_v4 c1 = cm_mul_v4(m.c[1], cm_spread_v4(f, 1));
cm_v4 c2 = cm_mul_v4(m.c[2], cm_spread_v4(f, 2));
cm_v4 c3 = cm_mul_v4(m.c[3], cm_spread_v4(f, 3));
return cm_add_v4(cm_add_v4(c0, c1), cm_add_v4(c2, c3));
}
CM_DEF cm_m16 cm_dot_m16(cm_m16 l, cm_m16 r) {
cm_m16 o;
for (int c = 0; c < 4; c++) {
o.c[c] = cm_mul_v4(l.c[0], cm_spread_v4(r.c[c], 0));
o.c[c] = cm_add_v4(o.c[c], cm_mul_v4(l.c[1], cm_spread_v4(r.c[c], 1)));
o.c[c] = cm_add_v4(o.c[c], cm_mul_v4(l.c[2], cm_spread_v4(r.c[c], 2)));
o.c[c] = cm_add_v4(o.c[c], cm_mul_v4(l.c[3], cm_spread_v4(r.c[c], 3)));
}
return o;
}
CM_DEF cm_m16 cm_translate_m16(cm_m16 m, cm_v4 f) {
cm_m16 o = m; /* TODO check whether this really copies the underlying __m128's. */
o.c[3] = cm_add_v4(m.c[3], f);
return o;
}
CM_DEF cm_m16 cm_scale_m16(cm_m16 m, cm_v4 v) {
/* TODO optimize! */
float f[4];
cm_recv_v4(v, f);
cm_m16 o;
cm_v4 s;
s = cm_new_v4(f[0], 0.0f, 0.0f, 0.0f);
o.c[0] = cm_mul_v4(m.c[0], s);
s = cm_new_v4(0.0f, f[1], 0.0f, 0.0f);
o.c[1] = cm_mul_v4(m.c[1], s);
s = cm_new_v4(0.0f, 0.0f, f[2], 0.0f);
o.c[2] = cm_mul_v4(m.c[2], s);
o.c[3] = m.c[3];
return o;
}
CM_DEF cm_m16 cm_orthogonal_m16(cm_f1 left, cm_f1 right, cm_f1 bottom, cm_f1 top, cm_f1 near, cm_f1 far) {
cm_v4 a = cm_new_v4( 2.0f / (right - left), 0.0f, 0.0f, 0.0f);
cm_v4 b = cm_new_v4(0.0f, 2.0f / (top - bottom), 0.0f, 0.0f);
cm_v4 c = cm_new_v4(0.0f, 0.0f, -2.0f / (far - near), 0.0f);
cm_f1 tx = -(right + left) / (right - left);
cm_f1 ty = -(top + bottom) / (top - bottom);
cm_f1 tz = -(far + near) / (far - near);
cm_v4 t = cm_new_v4(tx, ty, tz, 1.0f);
return cm_new_m16(a, b, c, t);
}
CM_DEF cm_m16 cm_frustum_m16(cm_f1 left, cm_f1 right, cm_f1 bottom, cm_f1 top, cm_f1 znear, cm_f1 zfar) {
cm_f1 znear2 = 2.0 * znear;
cm_f1 width = right - left;
cm_f1 height = top - bottom;
cm_f1 depth = zfar - znear;
cm_m16 matrix;
matrix.c[0] = cm_new_v4(znear2 / width, 0.0f, 0.0f, 0.0f);
matrix.c[1] = cm_new_v4(0.0f, znear2 / height, 0.0f, 0.0f);
matrix.c[2] = cm_new_v4((right + left) / width, (top + bottom) / height, (-zfar - znear) / depth, -1.0f);
matrix.c[3] = cm_new_v4(0.0f, 0.0f, (-znear2 * zfar) / depth, 0.0f);
return matrix;
}
CM_DEF cm_m16 cm_perspective_m16(cm_f1 fovyInDegrees, cm_f1 aspectRatio, cm_f1 znear, cm_f1 zfar) {
cm_f1 ymax = znear * tanf(fovyInDegrees * CM_PI / 360.0f);
cm_f1 xmax = ymax * aspectRatio;
return cm_frustum_m16(-xmax, xmax, -ymax, ymax, znear, zfar);
}
CM_DEF cm_m16 cm_lookat_m16(cm_v4 position, cm_v4 target, cm_v4 upVector) {
const cm_v4 f = cm_norm_v3(cm_sub_v4(target, position));
const cm_v4 s = cm_norm_v3(cm_cross_v3(f, upVector));
const cm_v4 u = cm_cross_v3(s, f);
cm_m16 matrix = cm_new_m16(s, u, cm_scale_v4(f, -1.0f), cm_send1_v4(0.0f));
matrix = cm_transpose_m16(matrix);
cm_f1 sp = cm_dot_v3(s, position);
cm_f1 up = cm_dot_v3(u, position);
cm_f1 fp = cm_dot_v3(f, position);
matrix.c[3] = cm_new_v4(-sp, -up, fp, 1.0f);
return matrix;
}
/* ~~~~ QUATERNIONS ~~~~ */
CM_DEF cm_qt cm_conj_qt(cm_qt q) {
return cm_mul_v4(q, cm_new_v4(-1.0, -1.0, -1.0, 1.0));
}
CM_DEF cm_qt cm_apply_qt(cm_qt q, cm_v4 v) {
// Optimized quaternion application by <NAME>
cm_f1 c[4];
cm_recv_v4(q, c);
cm_v4 p = *(cm_v4*)&q;
cm_v4 t = cm_scale_v4(cm_cross_v3(p, v), 2.0f);
return cm_add_v4(cm_add_v4(v, cm_scale_v4(t, c[3])), cm_cross_v3(p, t));
}
CM_DEF cm_qt cm_new_qt(cm_v4 axis, cm_f1 angle) {
/* TODO optimize */
cm_f1 h = angle / 2.0f;
cm_f1 s = sinf(h);
cm_f1 c[4];
cm_recv_v4(axis, c);
return cm_new_v4(c[0] * s, c[1] * s, c[2] * s, cos(h));
}
#if 0
CM_DEF cm_qt cm_cum_qt(cm_qt a, cm_qt b) {
/* TODO optimize! */
cm_f1 ac[4], bc[4];
cm_recv_v4(a, ac);
cm_recv_v4(b, bc);
cm_v4 a3 = cm_new_v4(ac[0], ac[1], ac[2], 0.0f);
cm_v4 b3 = cm_new_v4(bc[0], bc[1], bc[2], 0.0f);
cm_f1 ws = ac[3] * bc[3] - cm_dot_v3(a3, b3);
cm_v4 w = cm_new_v4(0.0f, 0.0f, 0.0f, ws);
cm_v4 as = cm_scale_v4(a3, bc[3]);
cm_v4 bs = cm_scale_v4(b3, ac[3]);
cm_v4 v = cm_add_v4(cm_cross_v3(a3, b3), cm_add_v4(as, bs));
return cm_add_v4(v, w);
}
#endif
CM_DEF cm_qt cm_slerp_qt(cm_qt a, cm_qt b, cm_f1 t) {
// Calculate angle between a and b
cm_f1 cosHalfTheta = cm_dot_v4(a, b);
// if a = b or a = -b then theta = 0 and we can return a
if (fabs(cosHalfTheta) >= 1.0)
return a;
// Calculate temporary values
cm_f1 halfTheta = acos(cosHalfTheta);
cm_f1 sinHalfTheta = sqrt(1.0 - cosHalfTheta * cosHalfTheta);
// if theta = 180 degrees then result is not fully defined
// we could rotate around any axis normal to a or b
if (fabs(sinHalfTheta) < 0.001)
return cm_add_v4(cm_scale_v4(a, 0.5f), cm_scale_v4(b, 0.5f));
cm_f1 ratioA = sin((1.0 - t) * halfTheta) / sinHalfTheta;
cm_f1 ratioB = sin( t * halfTheta) / sinHalfTheta;
// Calculate quaternion
return cm_add_v4(cm_scale_v4(a, ratioA), cm_scale_v4(b, ratioB));
}
CM_DEF cm_m16 cm_qt_to_m16(cm_qt q) {
/* TODO optimize? */
cm_f1 c[4];
cm_recv_v4(q, c);
cm_m16 a = cm_new_m16(
cm_new_v4( c[3], -c[2], c[1], -c[0]),
cm_new_v4( c[2], c[3], -c[0], -c[1]),
cm_new_v4(-c[1], c[0], c[3], -c[2]),
cm_new_v4( c[0], c[1], c[2], c[3])
);
cm_m16 b = cm_new_m16(
cm_new_v4( c[3], -c[2], c[1], c[0]),
cm_new_v4( c[2], c[3], -c[0], c[1]),
cm_new_v4(-c[1], c[0], c[3], c[2]),
cm_new_v4(-c[0], -c[1], -c[2], c[3])
);
return cm_dot_m16(a, b);
}
#endif
|
tomolt/tiny-library-collection
|
hashtable.h
|
/* hashtable.h - A Robin Hood-hashing hashtable implementation
*
* MIT License
*
* Copyright (c) 2018 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* This file was originally distributed as part of <NAME>'s personal
* tiny library collection. (https://www.github.com/tomolt/tiny-library-collection)
*/
#ifndef HASHTABLE_H
#define HASHTABLE_H
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
struct HT_key
{
char const *name;
short length;
uint32_t hash;
};
struct HT
{
size_t cap;
int eSize;
int fill;
struct HT_key *keys;
char *values;
};
struct HT htNew(size_t cap, int eSize);
void htFree(struct HT *ht);
void htSet(struct HT *ht, void const *name, short length, void *value);
void htDel(struct HT *ht, void const *name, short length);
bool htHas(struct HT *ht, void const *name, short length);
void *htGet(struct HT *ht, void const *name, short length);
#endif
#ifdef HT_IMPLEMENT_HERE
#include <stdlib.h>
#include <string.h>
static double const load_factor = 0.8;
static void memswap(void *a, void *b, size_t size)
{
char t[size];
memcpy(t, a, size);
memcpy(a, b, size);
memcpy(b, t, size);
}
static uint32_t hash_func(char const *data, short length)
{
uint32_t hash = 33;
for (short i = 0; i < length; ++i) {
hash += data[i];
hash += hash << 10;
hash ^= hash >> 6;
}
hash += hash << 3;
hash ^= hash >> 11;
hash += hash << 15;
return hash;
}
struct search_result { bool found; int slot; };
static int fold_slot(struct HT *ht, uint32_t slot)
{ return slot % ht->cap; }
static int distance(struct HT *ht, struct HT_key key, int slot)
{ int d = slot - fold_slot(ht, key.hash); if (d < 0) { d += ht->cap; } return d; }
static int advance(struct HT *ht, int slot)
{ return fold_slot(ht, slot + 1); }
static bool does_match(struct HT_key a, struct HT_key b)
{ return a.hash == b.hash && a.length == b.length && memcmp(a.name, b.name, a.length) == 0; }
static void mark_tombstone(struct HT_key *key)
{ key->name = NULL; }
static bool is_tombstone(struct HT_key key)
{ return key.name == NULL; }
static struct HT_key make_key(char const *name, short length)
{ return (struct HT_key){name, length, hash_func(name, length)}; }
static char *value_at(struct HT *ht, int slot)
{ return &ht->values[slot * ht->eSize]; }
static int evict(struct HT *ht, struct HT_key key, int slot)
{
return distance(ht, key, slot) > distance(ht, ht->keys[slot], slot) ? slot
: evict(ht, key, advance(ht, slot));
}
static void insert_at(struct HT *ht, struct HT_key key, void *value, int slot)
{
memswap(&ht->keys[slot], &key, sizeof(key));
memswap(value_at(ht, slot), value, ht->eSize);
if (!is_tombstone(key))
insert_at(ht, key, value, evict(ht, key, advance(ht, slot)));
}
static struct search_result locate_at(struct HT *ht, struct HT_key key, int slot)
{
if (does_match(ht->keys[slot], key))
return (struct search_result){true, slot};
else if (distance(ht, key, slot) > distance(ht, ht->keys[slot], slot))
return (struct search_result){false, slot};
else
return locate_at(ht, key, advance(ht, slot));
}
static struct search_result locate(struct HT *ht, struct HT_key key)
{ return locate_at(ht, key, fold_slot(ht, key.hash)); }
static void rebuild(struct HT *ht, size_t cap)
{
struct HT new = htNew(cap, ht->eSize);
new.fill = ht->fill;
for (size_t i = 0; i < ht->cap; ++i) {
struct HT_key key = ht->keys[i];
if (!is_tombstone(key)) {
int slot = evict(&new, key, fold_slot(&new, key.hash));
insert_at(&new, key, value_at(ht, i), slot);
}
}
htFree(ht);
memcpy(ht, &new, sizeof(new));
}
struct HT htNew(size_t cap, int eSize)
{
struct HT ht = {cap, eSize, 0, NULL, NULL};
ht.keys = calloc(cap, sizeof(*ht.keys));
ht.values = calloc(cap, eSize);
for (unsigned int i = 0; i < cap; ++i)
ht.keys[i].hash = i;
return ht;
}
void htFree(struct HT *ht)
{
free(ht->keys);
free(ht->values);
}
void htSet(struct HT *ht, void const *name, short length, void *value)
{
if ((double)(ht->fill + 1) / (double)ht->cap > load_factor)
rebuild(ht, ht->cap * 2);
struct HT_key key = make_key(name, length);
struct search_result search = locate(ht, key);
if (search.found) {
memcpy(value_at(ht, search.slot), value, ht->eSize);
} else {
++ht->fill;
char buf[ht->eSize];
memcpy(buf, value, ht->eSize);
insert_at(ht, key, buf, search.slot);
}
}
void htDel(struct HT *ht, void const *name, short length)
{
struct search_result search = locate(ht, make_key(name, length));
if (search.found) {
mark_tombstone(&ht->keys[search.slot]);
--ht->fill;
if ((double)ht->fill / (double)ht->cap < 0.5 * load_factor)
rebuild(ht, ht->cap / 2);
}
}
bool htHas(struct HT *ht, void const *name, short length)
{
return locate(ht, make_key(name, length)).found;
}
void *htGet(struct HT *ht, void const *name, short length)
{
struct search_result search = locate(ht, make_key(name, length));
return search.found ? value_at(ht, search.slot) : NULL;
}
#endif
|
tomolt/tiny-library-collection
|
tests/dh_cuts_suite.c
|
<reponame>tomolt/tiny-library-collection
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "dh_cuts.h"
static void test_crash_recovery(void)
{
dh_push("crash recovery");
pid_t pid = fork();
if (pid == 0) {
freopen("/dev/null", "w", stdout);
dh_branch( raise(SIGFPE); )
exit(0);
}
if (pid > 0) {
int ret = 0;
waitpid(pid, &ret, 0);
dh_assert(ret == 0);
}
dh_pop();
}
void dh_cuts_suite(void)
{
dh_push("dh_cuts");
test_crash_recovery();
dh_pop();
}
|
DonRumata710/NetCowork
|
include/netcoworkserver.h
|
<gh_stars>0
#ifndef NETCOWORKSERVER_H
#define NETCOWORKSERVER_H
#include "netcoworkprovider.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <set>
#include <memory>
class CreationFilter
{
public:
virtual bool allow(QTcpSocket* socket, uint32_t class_id) = 0;
};
class ClassFilter : public CreationFilter
{
public:
ClassFilter(std::set<uint32_t> _private_classes);
virtual bool allow(QTcpSocket* socket, uint32_t class_id) override;
private:
std::set<uint32_t> private_classes;
};
class NetCoworkServer : public QTcpServer, public NetCoworkProvider
{
Q_OBJECT
public:
NetCoworkServer();
virtual void start(const std::string& address, uint16_t port) override;
virtual void stop() override;
enum class CreationPolicy
{
SERVER_ONLY,
CUSTOM,
ALL
};
void set_creation_policy(CreationPolicy new_policy);
bool set_filter(std::unique_ptr<CreationFilter>);
public slots:
void onNewConnection();
void onDataReady();
protected:
virtual void send_data(Message& data) override;
virtual void send_data(Message&& msg) override;
virtual void respond(Message& msg) override;
virtual void respond(Message&& msg) override;
virtual bool is_server() override;
virtual bool creation_filter(uint32_t class_id) override;
private:
void send_data(const QByteArray& data);
void respond(const QByteArray& data);
private:
std::vector<QTcpSocket*> sockets;
CreationPolicy policy = CreationPolicy::SERVER_ONLY;
std::unique_ptr<CreationFilter> filter;
};
#endif // NETCOWORKSERVER_H
|
DonRumata710/NetCowork
|
Generator/printer.h
|
<filename>Generator/printer.h
#ifndef PRINTER_H
#define PRINTER_H
#include "class.h"
#include "struct.h"
#include "function.h"
#include "enum.h"
#include <string>
#include <fstream>
class Printer
{
public:
explicit Printer(const std::string& folder_path = std::string("."));
bool print_class(const Class& c);
private:
void print_line(const std::string& line);
void print_dependency(const std::string& type);
void increase_offset();
void decrease_offset();
std::string get_type_name(const CodeElement* element);
void start_class(const std::string& name, const std::string& parent = std::string(), const std::string& template_type = std::string());
void print_function(const CodeElement* ret_type, const std::string& func_name,
const std::vector<Parameter>& parameters, bool is_const, const std::string& class_name = std::string());
void print_function(const std::string& ret_type, const std::string& func_name,
const std::vector<Parameter>& parameters, bool is_const, const std::string& class_name = std::string());
std::string get_parameter_str(const Parameter& param);
void finish_class();
private:
std::string path;
std::ofstream current_file;
std::string offset;
std::string current_class;
};
#endif // PRINTER_H
|
DonRumata710/NetCowork
|
Generator/struct.h
|
#ifndef STRUCT_H
#define STRUCT_H
#include "codeelement.h"
#include "parameter.h"
#include <string>
#include <vector>
class Struct : public CodeElement
{
public:
explicit Struct(const std::string& name);
Struct(const Struct& other);
Struct(Struct&& other);
void add_member(const Parameter& param);
private:
std::vector<Parameter> members;
};
#endif // TYPES_H
|
DonRumata710/NetCowork
|
Examples/Example2/ball.h
|
#ifndef BALL_H
#define BALL_H
#include <QPoint>
#include <QObject>
#include <QGraphicsEllipseItem>
#include <QDebug>
class Ball : public QObject, public QGraphicsEllipseItem
{
Q_OBJECT
public:
Ball(QPointF pos = QPointF());
~Ball() = default;
void set_pos(QPointF new_pos);
QPointF get_pos() const;
void set_direction(float new_direction);
float get_direction() const;
void set_speed(float new_speed);
float get_speed() const;
static float get_radius();
private:
float speed;
};
#endif // BALL_H
|
DonRumata710/NetCowork
|
Generator/dependency.h
|
<filename>Generator/dependency.h
#ifndef DEPENDENCY_H
#define DEPENDENCY_H
#include <string>
#include "codeelement.h"
class Dependency : public CodeElement
{
public:
Dependency(const std::string& _filename, const std::string& _type_name, Type_enum _type);
virtual std::string get_module() const override;
private:
std::string filename;
};
#endif // DEPENDENCY_H
|
DonRumata710/NetCowork
|
include/netcoworkclient.h
|
<filename>include/netcoworkclient.h<gh_stars>0
#ifndef NETCOWORKCLIENT_H
#define NETCOWORKCLIENT_H
#include "netcoworkprovider.h"
#include <QTcpSocket>
class NetCoworkClient : public QObject, public NetCoworkProvider
{
Q_OBJECT
public:
NetCoworkClient();
virtual void start(const std::string& address, uint16_t port) override;
virtual void stop() override;
public slots:
void onConnected();
void onDataReady();
protected:
virtual void send_data(Message& data) override;
virtual void send_data(Message&& msg) override;
virtual void respond(Message& msg) override;
virtual void respond(Message&& msg) override;
virtual bool is_server() override;
private:
QTcpSocket socket;
uint16_t expeted_data = 0;
};
#endif // NETCOWORKCLIENT_H
|
DonRumata710/NetCowork
|
include/netcoworker.h
|
#ifndef NETCOWORKER_H
#define NETCOWORKER_H
#include "message.h"
#include <QObject>
#include <QDataStream>
class NetCoworkFactory;
class NetCoworker : public QObject
{
Q_OBJECT
public:
explicit NetCoworker(const NetCoworkFactory* _factory, uint32_t object_id = UINT32_MAX);
virtual void handle_call(Message& msg) = 0;
uint32_t get_class_id() const;
uint32_t get_object_id() const;
const NetCoworkFactory* get_factory() const;
protected:
void send_func_call(Message& msg) const;
private:
friend class NetCoworkProvider;
void set_object_id(uint32_t new_object_id);
private:
const NetCoworkFactory* factory;
uint32_t object_id = UINT32_MAX;
};
#endif // NETCOWORKER_H
|
DonRumata710/NetCowork
|
Generator/interfacemodel.h
|
#ifndef INTERFACEMODEL_H
#define INTERFACEMODEL_H
#include "dependency.h"
#include "class.h"
#include "struct.h"
#include "enum.h"
#include "simpletypeelement.h"
#include "printer.h"
#include <set>
class InterfaceModel
{
public:
InterfaceModel();
void print(Printer& printer);
const CodeElement* get_type(const std::string& type) const;
Dependency* add_dependency(const Dependency&);
Class* add_class(const Class& new_class);
Class* add_class(Class&& new_class);
Struct* add_struct(const Struct& new_struct);
Struct* add_struct(Struct&& new_struct);
Enum* add_enumeration(const Enum& new_enum);
Enum* add_enumeration(Enum&& new_enum);
Function* add_function(const Function& new_enum);
Function* add_function(Function&& new_enum);
std::vector<Class> get_classes() const;
std::vector<Struct> get_sturctures() const;
std::vector<Enum> get_enumerations() const;
std::vector<Function> get_functions() const;
private:
std::vector<Dependency> dependencies;
std::vector<Class> classes;
std::vector<Struct> structs;
std::vector<Enum> enums;
std::vector<Function> functions;
std::unordered_map<std::string, SimpleType> types;
};
#endif // INTERFACEMODEL_H
|
DonRumata710/NetCowork
|
Generator/filehandler.h
|
#ifndef FILEHANDLER_H
#define FILEHANDLER_H
#include <fstream>
#include <sstream>
class FileHandler
{
public:
FileHandler(const std::string& file);
bool is_open() const;
bool is_end() const;
std::string next_word();
const std::string& get_filename() const;
size_t get_line_num() const;
private:
std::ifstream file_stream;
std::istringstream line_stream;
std::string word;
std::string filename;
size_t line_num = 1;
std::string line;
};
#endif
|
DonRumata710/NetCowork
|
Examples/Example2/game.h
|
<reponame>DonRumata710/NetCowork
#ifndef GAME_H
#define GAME_H
#include <QGraphicsView>
#include <QHostAddress>
#include <QPaintEvent>
#include <QTimer>
#include "generated/Ball_net.h"
#include "generated/Platform_net.h"
#include "ball.h"
#include "platform.h"
class Game : public QGraphicsView
{
Q_OBJECT
public:
explicit Game(QWidget *parent = nullptr);
~Game() override;
void add_item(QGraphicsItem* item);
static Game* get_instance();
signals:
public slots:
void start(uint16_t port, const QString& addr);
void step();
private:
void create_server(uint16_t port);
void create_client(const QString& addr, uint16_t port);
void drawPlatform(int16_t pos, QPainter& painter, int step, bool on_top);
virtual void keyPressEvent(QKeyEvent* event) override;
virtual void keyReleaseEvent(QKeyEvent *event) override;
void set_plarform_pos(int16_t pos);
void game_inner_logic();
private:
std::unique_ptr<NetCoworkProvider> provider;
std::vector<BallSync<Ball>*> balls;
BallProcessor<Ball>* ball_processor = nullptr;
PlatformSync<Platform>* platform = nullptr;
PlatformSync<Platform>* opponent_platform = nullptr;
PlatformProcessor<Platform>* platform_processor = nullptr;
QTimer timer;
bool right_button = false;
bool left_button = false;
bool isServer = false;
const static size_t TIME_STEP = 50;
static Game* instance;
};
#endif // GAME_H
|
DonRumata710/NetCowork
|
Generator/property.h
|
#ifndef PROPERTY_H
#define PROPERTY_H
#include "parameter.h"
struct Property
{
Parameter parameter;
std::string getter;
std::string setter;
};
#endif // PROPERTY_H
|
DonRumata710/NetCowork
|
Generator/function.h
|
<filename>Generator/function.h
#ifndef FUNCTION_H
#define FUNCTION_H
#include "types.h"
#include "codeelement.h"
#include "parameter.h"
#include <vector>
class Function : public CodeElement
{
public:
explicit Function(const std::string& name);
void add_param(const Parameter& type);
const Parameter* get_param(size_t i) const;
size_t get_params_count() const;
const std::vector<Parameter>& get_parameters() const;
private:
std::vector<Parameter> params;
};
#endif // FUNCTION_H
|
DonRumata710/NetCowork
|
include/netcoworkfactory.h
|
#ifndef NETCOWORKFACTORY_H
#define NETCOWORKFACTORY_H
#include "netcoworker.h"
class NetCoworkFactory
{
friend class NetCoworkProvider;
friend class NetCoworkServer;
public:
virtual ~NetCoworkFactory() = default;
uint32_t get_class_id() const;
void send_func_call(Message& msg, const NetCoworker* coworker) const;
protected:
NetCoworkFactory(NetCoworkProvider* provider);
void set_class_id(uint32_t id);
virtual NetCoworker* create_object() const = 0;
virtual std::string get_name() const = 0;
virtual Message get_sync_message(NetCoworker* obj) const = 0;
virtual void sync(NetCoworker* obj, Message& msg) const = 0;
void add_object(NetCoworker* obj);
private:
uint32_t class_id = UINT32_MAX;
NetCoworkProvider* provider;
};
#endif // NETCOWORKFACTORY_H
|
DonRumata710/NetCowork
|
Generator/class.h
|
<filename>Generator/class.h
#ifndef CLASS_H
#define CLASS_H
#include "function.h"
#include "property.h"
#include "dependency.h"
#include <vector>
#include <set>
class Class : public CodeElement
{
public:
explicit Class(const std::string& name);
Class(const Class& other);
Class(Class&& other);
void add_dependency(const Dependency* dependency);
void add_property(const Property& type);
void add_property(Property&& type);
void add_properties(const std::vector<Property>& properties);
void add_properties(std::vector<Property>&& properties);
void add_function(const Function& func);
void add_function(Function&& func);
const std::set<const CodeElement*>& get_dependencies() const;
const std::vector<Property>& get_properties() const;
const std::vector<Function>& get_functions() const;
private:
void add_dependencies(const Function& func);
void add_properties_dependency(const std::vector<Property>& properties);
private:
std::vector<Property> properties;
std::vector<Function> functions;
std::set<const CodeElement*> dependencies;
};
#endif // CLASS_H
|
DonRumata710/NetCowork
|
include/netcoworkprovider.h
|
<filename>include/netcoworkprovider.h
#ifndef NETCOWORKPROVIDER_H
#define NETCOWORKPROVIDER_H
#include "message.h"
#include "netcoworkfactory.h"
#include <functional>
class NetCoworker;
class NetCoworkProvider
{
public:
virtual ~NetCoworkProvider() = default;
virtual void start(const std::string& address, uint16_t port) = 0;
virtual void stop() = 0;
void send_func_call(Message& data, const NetCoworker* obj);
void add_local_object(NetCoworker* object);
template<class Factory>
Factory* register_new_class()
{
Factory* factory = new Factory(this);
add_new_factory(std::unique_ptr<NetCoworkFactory>(factory));
return factory;
}
virtual bool is_server() = 0;
void set_add_object_callback(std::function<void (NetCoworker*, uint32_t, uint32_t)> func);
void set_add_class_callback(std::function<void (NetCoworkFactory*, uint32_t)> func);
protected:
virtual void send_data(Message& msg) = 0;
virtual void send_data(Message&& msg) = 0;
virtual void respond(Message& msg) = 0;
virtual void respond(Message&& msg) = 0;
void process_func(Message& data);
const NetCoworkFactory* get_factory(uint32_t i);
uint32_t factory_count() const;
NetCoworker* get_object(uint32_t i) const;
uint32_t object_count();
private:
void add_new_factory(std::unique_ptr<NetCoworkFactory> factory);
virtual bool creation_filter(uint32_t class_id);
private:
std::vector<NetCoworker*> coworkers;
std::vector<std::unique_ptr<NetCoworkFactory>> factories;
std::map<std::string, uint32_t> class_ids;
std::function<void (NetCoworker*, uint32_t, uint32_t)> obj_callback;
std::function<void (NetCoworkFactory*, uint32_t)> class_callback;
std::vector<NetCoworker*> requests;
std::vector<std::pair<Message, const NetCoworker*>> messages;
};
#endif // NETCOWORKPROVIDER_H
|
DonRumata710/NetCowork
|
Examples/Example1/mainwindow.h
|
<filename>Examples/Example1/mainwindow.h<gh_stars>0
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QPushButton>
#include <QMainWindow>
#include "generated/NetObject_net.h"
namespace Ui {
class MainWindow;
}
QMainWindow* getMainWindow();
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(NetCoworkProvider* _provider, QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_bStart_clicked(bool checked);
private:
virtual void mouseMoveEvent(QMouseEvent *event) override;
private:
Ui::MainWindow *ui;
NetCoworkProvider* provider;
NetObjectSync<QPushButton>* obj = nullptr;
NetObjectProcessor<QPushButton>* nop = nullptr;
};
#endif // MAINWINDOW_H
|
DonRumata710/NetCowork
|
Generator/types.h
|
<reponame>DonRumata710/NetCowork
#ifndef TYPES_H
#define TYPES_H
#include "enumutil.h"
#define Token(DO) \
DO(TOKEN_IMPORT, "import") \
DO(TOKEN_CLASS, "class") \
DO(TOKEN_STRUCT, "struct") \
DO(TOKEN_ENUM, "enum") \
DO(TOKEN_FUNCTION, "function") \
DO(TOKEN_GETTER, "get") \
DO(TOKEN_SETTER, "set") \
DO(TOKEN_OPENING_BRACE, "{") \
DO(TOKEN_CLOSING_BRACE, "}") \
DO(TOKEN_OPENING_PARENTHESIS, "(") \
DO(TOKEN_CLOSING_PARENTHESIS, ")") \
DO(TOKEN_COMMA, ",") \
DO(TOKEN_ASSIGNMENT, "=") \
DO(TOKEN_SEMICOLON, ";") \
DO(TOKEN_COLON, ":") \
DO(TOKEN_DOT, ".") \
DO(TOKEN_NONE, "")
ENUM_WITH_NAMES(Token)
STR_TO_ENUM_DECL(Token)
//enum class Token
//{
// CLASS,
// STRUCT,
// ENUM,
// FUNCTION,
// PROPERTY,
// OPENING_BRACE,
// CLOSING_BRACE,
// OPENING_PARENTHESIS,
// CLOSING_PARENTHESIS,
// NONE
//};
#define Type(DO) \
DO(Type, NONE, "NONE") \
DO(Type, UI64, "ui64") \
DO(Type, UI32, "ui32") \
DO(Type, UI16, "ui16") \
DO(Type, UI8, "ui8") \
DO(Type, I64, "i64") \
DO(Type, I32, "i32") \
DO(Type, I16, "i16") \
DO(Type, I8, "i8") \
DO(Type, FLOAT, "float") \
DO(Type, DFLOAT, "double") \
DO(Type, CHAR, "char") \
DO(Type, STRING, "string") \
DO(Type, FUNCTION, "function") \
DO(Type, STRUCT, "struct") \
DO(Type, CLASS, "class") \
DO(Type, ENUM, "enum")
ENUM_C_WITH_NAMES(Type)
STR_TO_ENUM_DECL(Type)
ENUM_TO_STR_DECL(Type)
//enum class Type
//{
// UI64,
// UI32,
// UI16,
// UI8,
// I64,
// I32,
// I16,
// I8,
// CHAR,
// STRING,
// FUNCTION,
// STRUCT,
// CLASS,
// NONE
//};
#endif // TYPES_H
|
DonRumata710/NetCowork
|
include/message.h
|
<reponame>DonRumata710/NetCowork<gh_stars>0
#ifndef MESSAGE_H
#define MESSAGE_H
#include <QDataStream>
#include <QString>
#include <string>
class Message
{
public:
Message();
explicit Message(const QByteArray& _data);
explicit Message(QByteArray&& _data);
Message(Message&& msg);
Message& operator=(Message&& msg);
static Message get_message(QIODevice* device);
size_t get_size() const;
template<typename T>
void add_value(const T& value)
{
stream << value;
}
template<>
void add_value(const std::string& value)
{
stream << QString(value.c_str());
}
template<typename val_type>
val_type get_value()
{
val_type val;
stream >> val;
return val;
}
std::string get_string();
void set_metadata(uint32_t new_class_id, uint32_t new_object_id, uint32_t new_func_id = UINT32_MAX);
uint32_t get_class_id() const;
void set_class_id(uint32_t new_class_id);
uint32_t get_object_id();
void set_object_id(uint32_t new_object_id);
uint32_t get_func_id();
void set_func_id(uint32_t new_func_id);
QByteArray get_data() const;
private:
uint32_t class_id = UINT32_MAX;
uint32_t object_id = UINT32_MAX;
uint32_t func_id = UINT32_MAX;
QByteArray data;
QDataStream stream;
};
#endif // MESSAGE_H
|
DonRumata710/NetCowork
|
Examples/Example2/mainwindow.h
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <netcoworkprovider.h>
#include <QMainWindow>
#include <QAbstractButton>
#include <QHostAddress>
namespace Ui {
class MainWindow;
}
QMainWindow* getMainWindow();
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_bStart_clicked();
void on_bSettings_clicked();
void on_bExit_clicked();
void on_buttonBox_accepted();
void on_buttonBox_clicked(QAbstractButton *button);
private:
virtual bool hasHeightForWidth() const override;
virtual int heightForWidth(int w) const override;
private:
Ui::MainWindow *ui;
QString address = "localhost";
uint16_t port = 1024;
};
#endif // MAINWINDOW_H
|
DonRumata710/NetCowork
|
Generator/simpletypeelement.h
|
#ifndef SIMPLETYPEELEMENT_H
#define SIMPLETYPEELEMENT_H
#include "types.h"
#include "codeelement.h"
class SimpleType : public CodeElement
{
public:
explicit SimpleType(Type_enum type);
private:
std::string get_typename(Type_enum type) const;
};
#endif // SIMPLETYPEELEMENT_H
|
DonRumata710/NetCowork
|
Generator/enumutil.h
|
<filename>Generator/enumutil.h
#ifndef ENUMUTIL_H
#define ENUMUTIL_H
#include <unordered_map>
#define DECLARE_ENUM(VAL) VAL,
#define DECLARE_ENUM_WITH_VAL(NAME, VAL) NAME = VAL,
#define DECLARE_ENUM_WITH_NAMES(VAL, STR) DECLARE_ENUM(VAL)
#define DECLARE_ENUM_WITH_NAMES_VAL(NAME, STR, VAL) DECLARE_ENUM_WITH_VAL(NAME, VAL)
#define DECLARE_ENUM_WITH_VAL_NAMES(NAME, VAL, STR) DECLARE_ENUM_WITH_VAL(NAME, VAL)
#define DECLARE_ENUM_C(TYPE, VAL) VAL,
#define DECLARE_ENUM_C_WITH_VAL(TYPE, NAME, VAL) NAME = VAL,
#define DECLARE_ENUM_C_WITH_NAMES(TYPE, VAL, STR) DECLARE_ENUM(VAL)
#define DECLARE_ENUM_C_WITH_NAMES_VAL(TYPE, NAME, STR, VAL) DECLARE_ENUM_WITH_VAL(NAME, VAL)
#define DECLARE_ENUM_C_WITH_VAL_NAMES(TYPE, NAME, VAL, STR) DECLARE_ENUM_WITH_VAL(NAME, VAL)
#define ENUM(NAME) \
enum NAME##_enum \
{ \
NAME(DECLARE_ENUM) \
};
#define ENUM_C(NAME) \
enum class NAME##_enum \
{ \
NAME(DECLARE_ENUM_C) \
};
#define ENUM_WITH_VAL(NAME) \
enum NAME##_enum \
{ \
NAME(DECLARE_ENUM_WITH_VAL) \
};
#define ENUM_C_WITH_VAL(NAME) \
enum class NAME##_enum \
{ \
NAME(DECLARE_ENUM_C_WITH_VAL) \
};
#define ENUM_WITH_NAMES(NAME) \
enum NAME##_enum \
{ \
NAME(DECLARE_ENUM_WITH_NAMES) \
};
#define ENUM_C_WITH_NAMES(NAME) \
enum class NAME##_enum \
{ \
NAME(DECLARE_ENUM_C_WITH_NAMES) \
};
#define ENUM_WITH_NAMES_VAL(NAME) \
enum NAME##_enum \
{ \
NAME(DECLARE_ENUM_WITH_NAMES_VAL) \
};
#define ENUM_C_WITH_NAMES_VAL(NAME) \
enum class NAME##_enum \
{ \
NAME(DECLARE_ENUM_C_WITH_NAMES_VAL) \
};
#define ENUM_WITH_VAL_NAMES(NAME) \
enum NAME##_enum \
{ \
NAME(DECLARE_ENUM_WITH_VAL_NAMES) \
};
#define ENUM_C_WITH_VAL_NAMES(NAME) \
enum class NAME##_enum \
{ \
NAME(DECLARE_ENUM_C_WITH_VAL_NAMES) \
};
#define STR_TO_ENUM_DECL(NAME) extern std::unordered_map<std::string, NAME##_enum> NAME##_from_str;
#define DECLARE_STR_TO_ENUM(VAL) { #VAL, VAL },
#define DECLARE_STR_TO_ENUM_WITH_NAMES(VAL, STR) { STR, VAL },
#define DECLARE_STR_TO_ENUM_WITH_VAL(NAME, VAL) { #NAME, NAME },
#define DECLARE_STR_TO_ENUM_WITH_VAL_NAMES(NAME, VAL, STR) { STR, NAME },
#define DECLARE_STR_TO_ENUM_WITH_NAMES_VAL(NAME, STR, VAL) { STR, NAME },
#define STR_TO_ENUM(NAME) \
std::unordered_map<std::string, NAME##_enum> NAME##_from_str = { \
NAME(DECLARE_STR_TO_ENUM) \
};
#define STR_TO_ENUM_WTIH_VAL(NAME) \
std::unordered_map<std::string, NAME##_enum> NAME##_from_str = { \
NAME(DECLARE_STR_TO_ENUM_WITH_VAL) \
};
#define STR_TO_ENUM_WITH_NAMES(NAME) \
std::unordered_map<std::string, NAME##_enum> NAME##_from_str = { \
NAME(DECLARE_STR_TO_ENUM_WITH_NAMES) \
};
#define STR_TO_ENUM_WITH_VAL_NAMES(NAME) \
std::unordered_map<std::string, NAME##_enum> NAME##_from_str = { \
NAME(DECLARE_STR_TO_ENUM_WITH_VAL_NAMES) \
};
#define STR_TO_ENUM_WITH_NAMES_VAL(NAME) \
std::unordered_map<std::string, NAME##_enum> NAME##_from_str = { \
NAME(DECLARE_STR_TO_ENUM_WITH_NAMES_VAL) \
};
#define DECLARE_STR_TO_ENUM_C(TYPE, VAL) { #VAL, TYPE##_enum::##VAL },
#define DECLARE_STR_TO_ENUM_C_WITH_NAMES(TYPE, VAL, STR) { STR, TYPE##_enum::##VAL },
#define DECLARE_STR_TO_ENUM_C_WITH_VAL(TYPE, NAME, VAL) { #NAME, TYPE##_enum::##NAME },
#define DECLARE_STR_TO_ENUM_C_WITH_VAL_NAMES(TYPE, NAME, VAL, STR) { STR, TYPE##_enum::##NAME },
#define DECLARE_STR_TO_ENUM_C_WITH_NAMES_VAL(TYPE, NAME, STR, VAL) { STR, TYPE##_enum::##NAME },
#define STR_TO_ENUM_C(NAME) \
std::unordered_map<std::string, NAME##_enum> NAME##_from_str = { \
NAME(DECLARE_STR_TO_ENUM_C) \
};
#define STR_TO_ENUM_C_WTIH_VAL(NAME) \
std::unordered_map<std::string, NAME##_enum> NAME##_from_str = { \
NAME(DECLARE_STR_TO_ENUM_C_WITH_VAL) \
};
#define STR_TO_ENUM_C_WITH_NAMES(NAME) \
std::unordered_map<std::string, NAME##_enum> NAME##_from_str = { \
NAME(DECLARE_STR_TO_ENUM_C_WITH_NAMES) \
};
#define STR_TO_ENUM_C_WITH_VAL_NAMES(NAME) \
std::unordered_map<std::string, NAME##_enum> NAME##_from_str = { \
NAME(DECLARE_STR_TO_ENUM_C_WITH_VAL_NAMES) \
};
#define STR_TO_ENUM_C_WITH_NAMES_VAL(NAME) \
std::unordered_map<std::string, NAME##_enum> NAME##_from_str = { \
NAME(DECLARE_STR_TO_ENUM_C_WITH_NAMES_VAL) \
};
#define ENUM_TO_STR_DECL(NAME) extern std::unordered_map<NAME##_enum, std::string> NAME##_to_str;
#define DECLARE_ENUM_TO_STR(VAL) { VAL, #VAL },
#define DECLARE_ENUM_TO_STR_WITH_NAMES(VAL, STR) { VAL, STR },
#define DECLARE_ENUM_TO_STR_WITH_VAL(NAME, VAL) { NAME, #NAME },
#define DECLARE_ENUM_TO_STR_WITH_VAL_NAMES(NAME, VAL, STR) { NAME, STR },
#define DECLARE_ENUM_TO_STR_WITH_NAMES_VAL(NAME, STR, VAL) { NAME, STR },
#define ENUM_TO_STR(NAME) \
std::unordered_map<NAME##_enum, std::string> NAME##_to_str = { \
NAME(DECLARE_ENUM_TO_STR) \
};
#define ENUM_TO_STR_WTIH_VAL(NAME) \
std::unordered_map<NAME##_enum, std::string> NAME##_to_str = { \
NAME(DECLARE_ENUM_TO_STR_WITH_VAL) \
};
#define ENUM_TO_STR_WITH_NAMES(NAME) \
std::unordered_map<NAME##_enum, std::string> NAME##_to_str = { \
NAME(DECLARE_ENUM_TO_STR_WITH_NAMES) \
};
#define ENUM_TO_STR_WITH_VAL_NAMES(NAME) \
std::unordered_map<NAME##_enum, std::string> NAME##_to_str = { \
NAME(DECLARE_ENUM_TO_STR_WITH_VAL_NAMES) \
};
#define ENUM_TO_STR_WITH_NAMES_VAL(NAME) \
std::unordered_map<NAME##_enum, std::string> NAME##_to_str = { \
NAME(DECLARE_ENUM_TO_STR_WITH_NAMES_VAL) \
};
#define DECLARE_ENUM_C_TO_STR(TYPE, VAL) { TYPE##_enum::##VAL, #VAL },
#define DECLARE_ENUM_C_TO_STR_WITH_NAMES(TYPE, VAL, STR) { TYPE##_enum::##VAL, STR },
#define DECLARE_ENUM_C_TO_STR_WITH_VAL(TYPE, NAME, VAL) { TYPE##_enum::##NAME, #NAME },
#define DECLARE_ENUM_C_TO_STR_WITH_VAL_NAMES(TYPE, NAME, VAL, STR) { TYPE##_enum::##NAME, STR },
#define DECLARE_ENUM_C_TO_STR_WITH_NAMES_VAL(TYPE, NAME, STR, VAL) { TYPE##_enum::##NAME, STR },
#define ENUM_C_TO_STR(NAME) \
std::unordered_map<NAME##_enum, std::string> NAME##_to_str = { \
NAME(DECLARE_ENUM_C_TO_STR) \
};
#define ENUM_C_TO_STR_WTIH_VAL(NAME) \
std::unordered_map<NAME##_enum, std::string> NAME##_to_str = { \
NAME(DECLARE_ENUM_C_TO_STR_WITH_VAL) \
};
#define ENUM_C_TO_STR_WITH_NAMES(NAME) \
std::unordered_map<NAME##_enum, std::string> NAME##_to_str = { \
NAME(DECLARE_ENUM_C_TO_STR_WITH_NAMES) \
};
#define ENUM_C_TO_STR_WITH_VAL_NAMES(NAME) \
std::unordered_map<NAME##_enum, std::string> NAME##_to_str = { \
NAME(DECLARE_ENUM_C_TO_STR_WITH_VAL_NAMES) \
};
#define ENUM_C_TO_STR_WITH_NAMES_VAL(NAME) \
std::unordered_map<NAME##_enum, std::string> NAME##_to_str = { \
NAME(DECLARE_ENUM_C_TO_STR_WITH_NAMES_VAL) \
};
#endif // ENUMUTIL_H
|
DonRumata710/NetCowork
|
Generator/codeelement.h
|
<filename>Generator/codeelement.h<gh_stars>0
#ifndef CODEELEMENT_H
#define CODEELEMENT_H
#include "types.h"
class CodeElement
{
friend std::hash<CodeElement>;
public:
CodeElement(Type_enum _type, const std::string& _name);
CodeElement(const CodeElement& ce);
CodeElement(CodeElement&& other);
virtual ~CodeElement() = default;
Type_enum get_type() const;
const std::string& get_name() const;
virtual std::string get_module() const { return ""; }
private:
const Type_enum type;
const std::string name;
};
#endif // CODEELEMENT_H
|
DonRumata710/NetCowork
|
Generator/parameter.h
|
<filename>Generator/parameter.h
#ifndef PARAMETER_H
#define PARAMETER_H
#include "types.h"
#include "codeelement.h"
struct Parameter
{
const CodeElement* element;
std::string value_name;
};
#endif // PARAMETERS_H
|
DonRumata710/NetCowork
|
Examples/Example2/platform.h
|
#ifndef PLATFORM_H
#define PLATFORM_H
#include <QObject>
#include <QGraphicsItem>
#include <cstdint>
class Platform : public QObject, public QGraphicsItem
{
Q_OBJECT
public:
Platform(uint16_t pos = 0);
void set_field_size(int size);
void set_h_pos(int p);
void set_field(QWidget* f);
void set_pos(uint16_t new_pos);
uint16_t get_pos() const;
static uint16_t get_width();
protected:
QRectF realRect() const;
QRectF boundingRect() const override;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
private:
uint16_t pos = 0;
int field_size = 0;
int h_pos = 0;
static const uint16_t width = 60;
};
#endif // PLATFORM_H
|
DonRumata710/NetCowork
|
Generator/enum.h
|
<gh_stars>0
#ifndef ENUM_H
#define ENUM_H
#include "codeelement.h"
#include <map>
class Enum : public CodeElement
{
public:
explicit Enum(const std::string& name);
void add_value(const std::string& name, int64_t val);
void add_value(std::string&& name, int64_t val);
void add_value(const std::pair<std::string, int64_t>& val);
void add_value(std::pair<std::string, int64_t>&& val);
bool check_value(const std::string& name) const;
int64_t get_value(const std::string& name) const;
private:
std::map<std::string, int64_t> values;
};
#endif // ENUM_H
|
colfrog/cx
|
cxs.c
|
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cx.h"
void
cx_set_path(char *path, bool absolute, char *buf, size_t buflen)
{
char ibuf[buflen];
memset(ibuf, 0, buflen);
memset(buf, 0, buflen);
#ifdef CX_DATA_DIR
const char *data_path = CX_DATA_DIR;
#else
const char *data_path = getenv("XDG_DATA_HOME");
if (data_path == NULL)
data_path = "~/.local/share";
#endif
if (absolute)
strncpy(ibuf, path, buflen - 1);
else
snprintf(ibuf, buflen, "%s/%s/%s", data_path, CX_DIR_NAME, path);
if (ibuf[0] == '~')
snprintf(buf, buflen, "%s%s", getenv("HOME"), ibuf + 1);
else
strncpy(buf, ibuf, buflen);
buf[buflen - 1] = '\0';
return;
}
|
colfrog/cx
|
cx.h
|
<gh_stars>10-100
#include <stdbool.h>
#include <sys/types.h>
#ifdef __GLIBC__
#define _BSD_SOURCE
#include <strings.h>
#include <getopt.h>
#include <sys/stat.h>
#endif
#ifndef CX_DIR_NAME
#define CX_DIR_NAME "cx"
#endif
#ifndef CX_DATA_DIR
// #define CX_DATA_DIR "~/.local/share"
#endif
#define DEFAULT_SOCKET_NAME "socket"
#define DEFAULT_DATAFILE_NAME "data"
#define DEFAULT_LOCKFILE_NAME "lock"
void cx_set_path(char *, bool, char *, size_t);
|
colfrog/cx
|
cxd.c
|
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <regex.h>
#include <sqlite3.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "cx.h"
#define MAXMSGLEN (PATH_MAX + 512)
static sqlite3 *db;
static int so;
/*
* Database queries to compile for later use during init.
* They will be placed in cdbq, where the indexes will stay true.
*/
static char *dbq[] = {
#define DB_TAB_CREATE 0
/*
* allows us to initialize the database
* table information:
* id: the unique entry's ID
* path: the entry's filesystem path
* name: the name of the directory, without the rest of the path
* prio: the entry's priority
* locked: whether the priority is locked
* laccs: last access time as a unix timestamp in seconds
* naccs: the amount of times the directory was accessed
*/
"CREATE TABLE IF NOT EXISTS dtab (id INTEGER UNIQUE PRIMARY KEY, path VARCHAR(1024) UNIQUE, name VARCHAR(256), prio INTEGER, locked INTEGER, laccs INTEGER, naccs INTEGER);",
#define DB_INSERT 1
/* allows us to insert new entries, only requires to set the path and name */
"INSERT INTO dtab SELECT MAX(id) + 1, ?1, ?2, 0, 0, strftime('%s', 'now', 'utc'), 1 FROM dtab;",
#define DB_REMOVE_BY_PATH 2
/* allows us to delete entries matching the path */
"DELETE FROM dtab WHERE path = ?1;",
#define DB_REMOVE_BY_PRIO 3
/* allows us to delete entries with a priority lower than defined */
"DELETE FROM dtab WHERE prio < ?1;",
#define DB_REMOVE_BY_ID 4
/* allows us to delete entries from their ID */
"DELETE FROM dtab WHERE id = ?1;",
#define DB_GET_LOOKUP_ROWS 5
/* allows us to get all of the information needed to match a path */
"SELECT id, path, name, prio FROM dtab ORDER BY prio DESC;",
#define DB_GET_PRIO_INFO_FROM_PATH 6
/* allows us to get all of the information needed to recalculate this entry's priority */
"SELECT id, prio, strftime('%s', 'now', 'utc'), laccs, naccs FROM dtab WHERE locked = 0 AND path = ?1;",
#define DB_GET_PRIO_INFO_FROM_ID 7
"SELECT id, prio, strftime('%s', 'now', 'utc'), laccs, naccs FROM dtab WHERE locked = 0 AND id = ?1;",
#define DB_GET_ALL_PRIO_INFO 8
/* allows us to get all of the information needed to recalculate all entries' priorities */
"SELECT id, prio, strftime('%s', 'now', 'utc'), laccs, naccs FROM dtab WHERE locked = 0;",
#define DB_SET_PRIO_FROM_PATH 9
/* allows us to set an entry's priority from its path */
"UPDATE dtab SET prio = ?1 WHERE path = ?2;",
#define DB_SET_PRIO_FROM_ID 10
/* allows us to set an entry's priority from its ID */
"UPDATE dtab SET prio = ?1 WHERE id = ?2;",
#define DB_SET_LOCK_FROM_PATH 11
/* allows us to set the lock of an entry from its path */
"UPDATE dtab SET locked = ?1 WHERE path = ?2;",
#define DB_SET_LOCK_FROM_ID 12
/* allows us to set the lock of an entry from its ID */
"UPDATE dtab SET locked = ?1 WHERE id = ?2;",
#define DB_PATH_ACCESSED 13
/* allows us to update the entry's information from its path */
"UPDATE dtab SET naccs = naccs + 1, laccs = strftime('%s', 'now', 'utc') WHERE path = ?1;",
#define DB_ID_ACCESSED 14
/* allows us to update the entry's information from its ID */
"UPDATE dtab SET naccs = naccs + 1, laccs = strftime('%s', 'now', 'utc') WHERE id = ?1;",
#define DB_GET_MAX_ID 15
#define DB_GET_ROW_COUNT 15
/* allows us to find out how many rows the database is holding */
"SELECT MAX(id) FROM dtab;",
#define DB_GET_ID_FROM_PATH 16
/* allows us to grab the ID of the entry with the given path */
"SELECT id FROM dtab WHERE path = ?1;",
#define DB_GET_ALL_ROWS 17
/* allows us to dump the database information */
"SELECT * FROM dtab ORDER BY prio DESC;",
#define DB_TOGGLE_LOCK_FROM_PATH 18
/* allows us to toggle the lock in one query using the PATH */
"UPDATE dtab SET locked = NOT locked WHERE path = ?1;",
#define DB_TOGGLE_LOCK_FROM_ID 19
/* allows us to toggle the lock in one query using the ID */
"UPDATE dtab SET locked = NOT locked WHERE id = ?1;"
};
/* compiled database queries will be stored here */
static sqlite3_stmt *cdbq[sizeof(dbq)];
/* options */
static char *optstr = "dD:s:";
static char *usage = "cxd [-d] [-D dbpath] [-s socket]";
static bool daemonopt;
static bool Dflag;
static char *datapath;
static char *lockpath;
static int lockfd;
static bool sflag;
static char *socketpath;
static int show_usage(void);
void cxd_atexit(void);
static void read_sock(void);
static int get_message(int, char *);
static void hook_command(int, char *);
static void setup_socket(char *);
static void open_db(char *);
static void acquire_lockfile(char *, bool);
static int get_id_from_message(char *);
static bool is_string_numerical(char *);
static int remove_trailing_slashes(char *);
static void handle_match(int, char *);
static void handle_matchn(int, char *);
static void handle_push(int, char *);
static void handle_dump(int, char *);
static void handle_togglelock(int, char *);
static void handle_lock(int, char *);
static void handle_unlock(int, char *);
static void handle_setprio(int, char *);
static void handle_remove(int, char *);
static void recalculate_prios(void);
static int calc_prio(sqlite_int64, sqlite_int64, int);
static void find_file_regex(const regex_t *re, char *buf, size_t bufsize);
static void find_file_iter(const char *msg, int n, char *buf, size_t bufsize);
static int find_entry(char *);
static void remove_by_path(char *);
static void remove_by_id(int);
static void set_prio_from_path(char *, int *);
static void set_prio_from_id(int, int *);
static void set_lock_from_id(int, int);
static void set_lock_from_path(char *, int);
struct command {
char *name;
void (*func)(int cl, char *message);
};
static struct command proto_commands[] = {
/* match a regex */
{"MATCH", handle_match},
/* match at most n regexes */
{"MATCHN", handle_matchn},
/* push directory */
{"PUSH", handle_push},
/* dump the array to the connection */
{"DUMP", handle_dump},
{"TOGGLELOCK", handle_togglelock},
{"LOCK", handle_lock},
{"UNLOCK", handle_unlock},
{"SETPRIO", handle_setprio},
{"REMOVE", handle_remove},
/* null entry to know when to stop */
{NULL, NULL}
};
int
main(int argc, char **argv)
{
int c;
char buf[PATH_MAX + 1];
memset(buf, 0, sizeof(buf));
while ((c = getopt(argc, argv, optstr)) != -1) {
switch(c) {
case 'd':
daemonopt = true;
break;
case 'D':
Dflag = true;
datapath = optarg;
break;
case 's':
sflag = true;
socketpath = optarg;
break;
default:
return show_usage();
}
}
/* daemonize if asked */
if (daemonopt && fork())
return 0;
atexit(cxd_atexit);
/* check whether the path defined in macros exists */
cx_set_path("", false, buf, sizeof(buf));
if (access(buf, X_OK) != 0)
/* it doesn't exist, create it */
mkdir(buf, 0755);
lockpath = DEFAULT_LOCKFILE_NAME;
cx_set_path(lockpath, false, buf, sizeof(buf));
lockpath = buf;
acquire_lockfile(lockpath, !daemonopt);
if (socketpath == NULL)
socketpath = DEFAULT_SOCKET_NAME;
cx_set_path(socketpath, sflag, buf, sizeof(buf));
socketpath = buf;
setup_socket(socketpath);
if (datapath == NULL)
datapath = DEFAULT_DATAFILE_NAME;
cx_set_path(datapath, Dflag, buf, sizeof(buf));
datapath = buf;
open_db(datapath);
read_sock();
return 0;
}
void
cxd_atexit()
{
sqlite3_close_v2(db);
fcntl(lockfd, F_UNLCK, NULL);
}
static int
show_usage()
{
write(1, usage, sizeof(usage));
write(1, "\n", 1);
return 2;
}
static void
acquire_lockfile(char *path, bool verbose)
{
lockfd = open(path, O_RDWR | O_CREAT, 0644);
chmod(path, S_IWUSR | S_IRUSR);
if (lockfd < 0)
err(errno, "failed to open the lock file");
pid_t pid = getpid();
struct flock fl;
memset(&fl, 0, sizeof(fl));
fl.l_start = 0;
fl.l_len = 0;
fl.l_pid = pid;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_CUR;
if (fcntl(lockfd, F_SETLK, &fl) == -1) {
if (verbose)
fputs("failed to acquire lockfile. is cxd already running?", stderr);
exit(1);
}
return;
}
static void
open_db(char *path)
{
sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
int i;
const char *p;
/* compile the queries */
for (i = 0; i < (sizeof(dbq)/8); i++) {
#if SQLITE_VERSION_NUMBER >= 3020000
sqlite3_prepare_v3(db, dbq[i], strlen(dbq[i]), SQLITE_PREPARE_PERSISTENT, &cdbq[i], &p);
#else
sqlite3_prepare_v2(db, dbq[i], strlen(dbq[i]), &cdbq[i], &p);
#endif
/* make sure the table exists */
if (i == 0) {
sqlite3_step(cdbq[DB_TAB_CREATE]);
sqlite3_reset(cdbq[DB_TAB_CREATE]);
}
}
return;
}
static void
setup_socket(char *path)
{
struct sockaddr_un sun;
size_t size;
/* eventually this should be done when we're closing */
unlink(path);
so = socket(AF_UNIX, SOCK_STREAM, 0);
if (so < 0)
err(errno, "failed to create socket");
memset(sun.sun_path, 0, sizeof(sun.sun_path));
sun.sun_family = AF_UNIX;
if (strlen(path) > sizeof(sun.sun_path)) {
err(1, "Path too long");
} else {
strncpy(sun.sun_path, path, sizeof(sun.sun_path));
}
size = sizeof(struct sockaddr_un);
if (bind(so, (struct sockaddr *)&sun, size) == -1)
err(errno, "failed to bind socket to \"%s\"", path);
if (listen(so, 5) == -1)
err(errno, "failed to listen to socket");
return;
}
static void
read_sock()
{
char buf[PATH_MAX + 1];
int ret;
int cl = 0;
bool connected = false;
while (connected || ((cl = accept(so, NULL, NULL)) != -1 && (connected = true))) {
memset(buf, 0, sizeof(buf));
ret = get_message(cl, buf);
if (ret || buf[0] == '\0') {
close(cl);
connected = false;
continue;
}
hook_command(cl, buf);
}
err(errno, "failed to read from socket");
/* NOT REACHED */
return;
}
static int
get_message(int cl, char *buf)
{
int i;
int ret;
for (i = 0; (ret = read(cl, buf + i, 1)) != -1 && buf[i] != '\0' && buf[i] != EOF; i++) {
if (i == PATH_MAX) {
/* message too long */
return 1;
}
}
buf[i] = '\0';
if (ret == -1 || buf[i] == EOF)
return 1;
return 0;
}
static void
hook_command(int cl, char *message)
{
struct command cmd;
int cmdlen;
int i;
for (i = 0; proto_commands[i].name != NULL; i++) {
cmd = proto_commands[i];
cmdlen = strlen(cmd.name);
if (strncmp(message, cmd.name, cmdlen) == 0 &&
(message[cmdlen] == '\0' || message[cmdlen] == ' ')) {
/* strip the command */
message += cmdlen;
while (*message == ' ')
message++;
/* call the function acting on it */
cmd.func(cl, message);
break;
}
}
return;
}
static void
handle_match(int cl, char *message)
{
int ret;
char buf[4096];
memset(buf, 0, sizeof(buf));
/* make sure equivalent paths can compare */
remove_trailing_slashes(message);
/* make sure our information is accurate */
recalculate_prios();
/* compile the regex */
regex_t re;
ret = regcomp(&re, message, REG_ICASE | REG_NOSUB);
if (ret)
find_file_regex(&re, buf, sizeof(buf));
else
find_file_iter(message, strlen(message)/2, buf, sizeof(buf));
write(cl, buf, strlen(buf) + 1);
regfree(&re);
return;
}
static void
handle_matchn(int cl, char *message)
{
long int i, n;
char *path, *name;
regex_t re;
for (i = 0; isdigit(message[i]); i++)
;
if (i == 0) {
write(cl, "\0", 1);
return;
}
remove_trailing_slashes(message);
recalculate_prios();
char *digits_end = message + i++;
while (message[i] == ' ' && message[i] != '\0')
;
char *msg_start = message + i;
regcomp(&re, msg_start, REG_ICASE | REG_NOSUB);
i = 0;
n = strtol(message, &digits_end, 10);
while (sqlite3_step(cdbq[DB_GET_LOOKUP_ROWS]) == SQLITE_ROW && (n == -1 || i < n)) {
path = (char *)sqlite3_column_text(cdbq[DB_GET_LOOKUP_ROWS], 1);
name = (char *)sqlite3_column_text(cdbq[DB_GET_LOOKUP_ROWS], 2);
if (access(path, X_OK) != 0) {
/* that path is gone, remove it and keep going */
remove_by_path(path);
continue;
}
if (regexec(&re, name, 0, NULL, 0) == 0) {
write(cl, path, strlen(path));
write(cl, "\n", 1);
i++;
}
}
write(cl, "\0", 1);
sqlite3_reset(cdbq[DB_GET_LOOKUP_ROWS]);
regfree(&re);
}
static void
handle_push(int cl, char *message)
{
sqlite3_stmt *stmt;
int i, j;
int id;
char name[256];
memset(name, 0, sizeof(name));
int msglen = remove_trailing_slashes(message);
if (msglen > PATH_MAX || access(message, X_OK) != 0)
return;
id = find_entry(message);
if (id >= 0) {
/* the entry exists, tell the database to update it */
stmt = cdbq[DB_ID_ACCESSED];
sqlite3_bind_int(stmt, 1, id);
} else {
/* the entry doesn't exist, parse the name from the path and add to db */
j = 0;
for (i = 0; message[i] != '\0' && j < sizeof(name) - 1; i++) {
if (message[i] == '/')
j = 0;
else
name[j++] = message[i];
}
name[j] = '\0';
/* now that we've got the name, insert the new entry to sqlite */
stmt = cdbq[DB_INSERT];
sqlite3_bind_text(stmt, 1, message, strlen(message), SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, name, strlen(name), SQLITE_STATIC);
}
sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
set_prio_from_path(message, NULL);
return;
}
static void
handle_dump(int cl, char *message)
{
char buf[8096];
sqlite3_stmt *stmt = cdbq[DB_GET_ALL_ROWS];
/* make sure our information is up to date */
recalculate_prios();
while (sqlite3_step(stmt) == SQLITE_ROW) {
snprintf(buf, 8096, "id: %d | path: %s | name: %s |"
" priority: %u | priority locked: %d | last access: %lld | access count: %d\n",
sqlite3_column_int(stmt, 0), /* id */
sqlite3_column_text(stmt, 1), /* path */
sqlite3_column_text(stmt, 2), /* name */
sqlite3_column_int(stmt, 3), /* prio */
sqlite3_column_int(stmt, 4), /* locked */
sqlite3_column_int64(stmt, 5), /* laccs */
sqlite3_column_int(stmt, 6)); /* naccs */
write(cl, buf, strlen(buf));
}
sqlite3_reset(stmt);
write(cl, "\0", 1);
return;
}
static void
handle_togglelock(int cl, char *message)
{
sqlite3_stmt *stmt;
int id;
if (is_string_numerical(message)) {
id = get_id_from_message(message);
stmt = cdbq[DB_TOGGLE_LOCK_FROM_ID];
sqlite3_bind_int(stmt, 1, id);
} else {
stmt = cdbq[DB_TOGGLE_LOCK_FROM_PATH];
sqlite3_bind_text(stmt, 1, message, strlen(message), SQLITE_STATIC);
}
sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return;
}
static void
handle_lock(int cl, char *message)
{
int id;
if (is_string_numerical(message)) {
id = get_id_from_message(message);
set_lock_from_id(id, 1);
} else {
set_lock_from_path(message, 1);
}
return;
}
static void
handle_unlock(int cl, char *message)
{
int id;
if (is_string_numerical(message)) {
id = get_id_from_message(message);
set_lock_from_id(id, 0);
} else {
set_lock_from_path(message, 0);
}
return;
}
static void
handle_setprio(int cl, char *message)
{
errno = 0;
int msglen = strlen(message);
char *idend = index(message, ' ');
char *msgend = message + msglen;
int id = strtol(message, &idend, 0);
int prio = strtol(message + (int)(msgend - (idend + 1)), &msgend, 0);
if (errno == 0) {
set_lock_from_id(id, 1);
set_prio_from_id(id, &prio);
} else {
errno = 0;
}
return;
}
static void
handle_remove(int cl, char *message)
{
int id;
if (is_string_numerical(message)) {
id = get_id_from_message(message);
remove_by_id(id);
} else {
remove_by_path(message);
}
return;
}
static int
remove_trailing_slashes(char *str)
{
int i;
size_t len = strlen(str);
for (i = len - 1; str[i] == '/' && i > 0; i--)
str[i] = '\0';
return i + 1;
}
static bool
is_string_numerical(char *str)
{
int i, strsize = strlen(str);
for (i = 0; i < strsize; i++)
if (!isdigit(str[i]))
return false;
return true;
}
static int
get_id_from_message(char *message)
{
errno = 0;
char *end = index(message, ' ');
int msglen = strlen(message);
if (end == NULL)
end = message + msglen;
int id = strtol(message, &end, 0);
if (errno == 0) {
return id;
} else {
errno = 0;
return -1;
}
}
static void
recalculate_prios()
{
sqlite3_stmt *stmt = cdbq[DB_GET_ALL_PRIO_INFO];
sqlite3_int64 now, laccs;
int naccs, prio, id;
while (sqlite3_step(stmt) == SQLITE_ROW) {
id = sqlite3_column_int(stmt, 0);
now = sqlite3_column_int64(stmt, 2);
laccs = sqlite3_column_int64(stmt, 3);
naccs = sqlite3_column_int(stmt, 4);
prio = calc_prio(now, laccs, naccs);
set_prio_from_id(id, &prio);
}
sqlite3_reset(stmt);
return;
}
static int
calc_prio(sqlite_int64 now, sqlite_int64 laccs, int naccs)
{
int dt = now - laccs;
int a = 2;
int x;
if (dt < 600)
x = (double)naccs * 2 * a;
else if (dt >= 600 && dt < 3600)
x = (double)naccs * a;
else if (dt >= 3600)
x = (double)naccs / a;
else
x = (double)naccs / (2 * a);
return x;
}
static void
find_file_regex(const regex_t *re, char *buf, size_t bufsize)
{
char *path, *name;
while(sqlite3_step(cdbq[DB_GET_LOOKUP_ROWS]) == SQLITE_ROW) {
path = (char *)sqlite3_column_text(cdbq[DB_GET_LOOKUP_ROWS], 1);
name = (char *)sqlite3_column_text(cdbq[DB_GET_LOOKUP_ROWS], 2);
if (access(path, X_OK) != 0) {
/* that path is gone, remove it and keep going */
remove_by_path(path);
continue;
}
if (regexec(re, name, 0, NULL, 0) == 0) {
strncpy(buf, path, bufsize - 1);
strcat(buf, "\n");
break;
}
}
sqlite3_reset(cdbq[DB_GET_LOOKUP_ROWS]);
}
static void
find_file_iter (const char *msg, int n, char *buf, size_t bufsize)
{
char *path, *name;
size_t i, len, bm;
while(sqlite3_step(cdbq[DB_GET_LOOKUP_ROWS]) == SQLITE_ROW) {
path = (char *)sqlite3_column_text(cdbq[DB_GET_LOOKUP_ROWS], 1);
name = (char *)sqlite3_column_text(cdbq[DB_GET_LOOKUP_ROWS], 2);
bm = 0;
len = strlen(name);
if (access(path, X_OK) != 0) {
/* that path is gone, remove it and keep going */
remove_by_path(path);
continue;
}
for (i = 0; i < len; i++) {
if (name[i] == msg[i])
bm++;
else
bm = 0;
if (bm > n) {
strncpy(buf, path, bufsize - 1);
strcat(buf, "\n");
break;
}
}
}
sqlite3_reset(cdbq[DB_GET_LOOKUP_ROWS]);
}
static int
find_entry(char *path)
{
int id, ret;
sqlite3_stmt *stmt = cdbq[DB_GET_ID_FROM_PATH];
sqlite3_bind_text(stmt, 1, path, strlen(path), SQLITE_STATIC);
ret = sqlite3_step(stmt);
if (ret == SQLITE_ROW)
id = sqlite3_column_int(stmt, 0);
else
id = -1;
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return id;
}
static void
remove_by_path(char *path)
{
sqlite3_stmt *stmt = cdbq[DB_REMOVE_BY_PATH];
sqlite3_bind_text(stmt, 1, path, strlen(path), SQLITE_STATIC);
sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return;
}
static void
remove_by_id(int id)
{
sqlite3_stmt *stmt = cdbq[DB_REMOVE_BY_ID];
sqlite3_bind_int(stmt, 1, id);
sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return;
}
static void
set_lock_from_id(int id, int lockval)
{
sqlite3_stmt *stmt = cdbq[DB_SET_LOCK_FROM_ID];
sqlite3_bind_int(stmt, 1, lockval);
sqlite3_bind_int(stmt, 2, id);
sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return;
}
static void
set_lock_from_path(char *path, int lockval)
{
sqlite3_stmt *stmt = cdbq[DB_SET_LOCK_FROM_PATH];
sqlite3_bind_int(stmt, 1, lockval);
sqlite3_bind_text(stmt, 2, path, strlen(path), SQLITE_STATIC);
sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return;
}
static void
set_prio_from_id(int id, int *prio)
{
int nprio;
sqlite3_stmt *stmt;
int naccs;
sqlite3_int64 now, laccs;
if (prio == NULL) {
stmt = cdbq[DB_GET_PRIO_INFO_FROM_ID];
sqlite3_bind_int(stmt, 1, id);
if (sqlite3_step(stmt) != SQLITE_ROW)
return;
now = sqlite3_column_int64(stmt, 2);
naccs = sqlite3_column_int64(stmt, 3);
laccs = sqlite3_column_int(stmt, 4);
nprio = calc_prio(now, laccs, naccs);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
} else {
nprio = *prio;
}
stmt = cdbq[DB_SET_PRIO_FROM_ID];
sqlite3_bind_int(stmt, 1, nprio);
sqlite3_bind_int(stmt, 2, id);
sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return;
}
static void
set_prio_from_path(char *path, int *prio)
{
int nprio;
sqlite3_stmt *stmt;
int naccs;
sqlite3_int64 now, laccs;
if (prio == NULL) {
stmt = cdbq[DB_GET_PRIO_INFO_FROM_PATH];
sqlite3_bind_text(stmt, 1, path, strlen(path), SQLITE_STATIC);
if (sqlite3_step(stmt) != SQLITE_ROW)
return;
now = sqlite3_column_int64(stmt, 2);
naccs = sqlite3_column_int64(stmt, 3);
laccs = sqlite3_column_int(stmt, 4);
nprio = calc_prio(now, laccs, naccs);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
} else {
nprio = *prio;
}
stmt = cdbq[DB_SET_PRIO_FROM_PATH];
sqlite3_bind_int(stmt, 1, nprio);
sqlite3_bind_text(stmt, 2, path, strlen(path), SQLITE_STATIC);
sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return;
}
|
colfrog/cx
|
cxc.c
|
<reponame>colfrog/cx
#include <sys/socket.h>
#include <sys/param.h>
#include <sys/un.h>
#include <err.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cx.h"
static char optstr[] = "-dlurtS:i:n:s:p:";
static char usage[] = "cxc [-dlurt] [-S <prio>] [-i <id>] [-n match_count] [-p <path>] [-s <socket path>] [--] <string to match>";
static bool dflag;
static bool lflag;
static bool uflag;
static bool tflag;
static bool Sflag;
static bool sflag;
static bool pflag;
static int prio;
static int id = -1;
static char *pushpath;
static char *socketpath;
static int show_usage(void);
static int setup_connection(char *path);
static char *get_match(int so, int n, char *to_match, char *buf, size_t bufsize);
static void push_path(int so, char *str);
static void write_dump(int so);
static void set_locked(int);
static void set_unlocked(int);
static void toggle_lock(int);
static void set_prio(int);
int
main(int argc, char *argv[])
{
int n = 1;
char buf[PATH_MAX + 1];
memset(buf, 0, sizeof(buf));
char match[PATH_MAX + 1];
memset(match, 0, sizeof(match));
if (argc == 1)
return show_usage();
char c;
bool should_match = true;
while ((c = getopt(argc, argv, optstr)) != -1) {
should_match = false;
switch(c) {
case 'd':
dflag = true;
break;
case 'l':
lflag = true;
break;
case 'u':
uflag = true;
break;
case 't':
tflag = true;
break;
case 'S':
Sflag = true;
prio = atoi(optarg);
if (errno)
err(errno, "failed to parse requested priority");
break;
case 'n':
n = atoi(optarg);
should_match = true;
if (errno)
err(errno, "failed to parse requested match count");
break;
case 'i':
id = atoi(optarg);
if (errno)
err(errno, "failed to parse requested id");
break;
case 's':
should_match = true;
sflag = true;
socketpath = optarg;
break;
case 'p':
pflag = true;
pushpath = optarg;
break;
case '-':
goto opt_loop_end;
default:
break;
}
}
opt_loop_end:
if (!sflag)
socketpath = DEFAULT_SOCKET_NAME;
cx_set_path(socketpath, sflag, buf, sizeof(buf));
socketpath = buf;
int so = setup_connection(socketpath);
if (so == -1)
err(errno, "failed to setup the socket");
if (lflag)
set_locked(so);
if (uflag)
set_unlocked(so);
if (tflag)
toggle_lock(so);
if (Sflag)
set_prio(so);
if (dflag)
write_dump(so);
if (pflag)
push_path(so, pushpath);
if (should_match) {
get_match(so, n, argv[argc - 1], match, PATH_MAX + 1);
if (match[0] == '\0') {
write(2, "No matching entry\n", 18);
write(1, ".\n", 2);
} else {
write(1, match, strlen(match));
}
}
close(so);
return 0;
}
static int
show_usage()
{
write(2, usage, sizeof(usage));
write(2, "\n", 1);
return 2;
}
static int
setup_connection(char *path)
{
struct sockaddr_un sun;
memset(&sun, 0, sizeof(sun));
int so = socket(AF_UNIX, SOCK_STREAM, 0);
if (strlen(path) > sizeof(sun.sun_path)) {
err(1, "Path too long");
} else {
strncpy(sun.sun_path, path, sizeof(sun.sun_path));
}
sun.sun_family = AF_UNIX;
int ret = connect(so, (struct sockaddr *)&sun, sizeof(sun));
if (ret == -1)
err(1, "Couldn't connect to the socket at %s. Is cxd running?", path);
return so;
}
static void
push_path(int so, char *str)
{
char message[PATH_MAX + 256];
snprintf(message, PATH_MAX + 256, "PUSH %s", str);
int ret = write(so, message, strlen(message));
if (ret == -1)
err(errno, "Failed to write to the socket. Is cxd running?");
return;
}
static char *
get_match(int so, int n, char *to_match, char *buf, size_t bufsize)
{
if (to_match == NULL)
return NULL;
char message[PATH_MAX + 256];
memset(message, 0, sizeof(message));
memset(buf, 0, bufsize);
snprintf(message, sizeof(message), "MATCHN %d %s", n, to_match);
write(so, message, strlen(message) + 1);
int ret, i = 0;
while (i < bufsize && (ret = read(so, buf + i, 1)) != -1 && buf[i] != '\0')
i++;
buf[i] = '\0';
return buf;
}
static void
write_dump(int so)
{
char message[] = "DUMP";
write(so, message, sizeof(message));
char c;
while (read(so, &c, 1) != -1 && c != '\0')
write(1, &c, 1);
return;
}
static void
set_locked(int so)
{
if (id == -1)
err(1, "-l requires -i");
char buf[256];
snprintf(buf, 256, "LOCK %d", id);
write(so, buf, strlen(buf));
return;
}
static void
set_unlocked(int so)
{
if (id == -1)
err(1, "-u requires -i");
char buf[256];
snprintf(buf, 256, "UNLOCK %d", id);
write(so, buf, strlen(buf));
return;
}
static void
toggle_lock(int so)
{
if (id == -1)
err(1, "-t requires -i");
char buf[256];
snprintf(buf, 256, "TOGGLELOCK %d", id);
write(so, buf, strlen(buf));
return;
}
static void
set_prio(int so)
{
if (id == -1)
err(1, "-S requires -i");
char buf[256];
snprintf(buf, 256, "SETPRIO %d %d", id, prio);
write(so, buf, strlen(buf));
return;
}
|
nevzatseferoglu/boulder-dash
|
src/headers/main.h
|
#include "common.h"
enum textureAll textureType;
extern void initSDL(void);
extern void initGame(void);
extern void initStage(void);
extern void releaseTools(void);
extern void doInput(void);
extern void prepareWindow(void);
extern void presentWindow(void);
extern void loadMedia(void);
SDL_Texture* scoreBoard;
SDL_Texture* diamondBoard;
SDL_Texture* levelBoard;
SDL_Texture* timeBoard;
SDL_Texture* entireMap;
SDL_Texture* boulderDash;
SDL_Texture* howtoplay;
Uint32 oldTime;
SDL_bool quit = SDL_TRUE;
struct gameState state;
struct currentOwnershipTools current;
struct mainTools gameTools;
struct Stage gameStage;
struct soundTools sounds;
struct boardTools boards[TEXT_NUMBER];
struct levelTools levels[LEVEL_NUMBER];
|
nevzatseferoglu/boulder-dash
|
src/map.c
|
#include "headers/map.h"
void loadMap(void);
void drawExtraImage(void);
char* intToString(int number);
void levelUptoBorder(int i);
void frameIncrement(void);
void startScreen(void);
void menu(void);
void endSceen(void);
void scoreTable(void);
int x = 0 , y = 0 , i = 0;
void initMap(void)
{
loadMap();
renderText();
}
void loadMap(void)
{
char* temp = NULL;
char fileName[50] = {'\0'};
for(i = 0 ; i < LEVEL_NUMBER ; ++i)
{
sprintf (fileName,"levels/level_%d.txt",i+1);
levels[i].level = readFile(fileName);
temp = levels[i].level;
if(levels[i].level == NULL)
{
fprintf(stderr,"levels[%d] Char* Variable could not be loaded !\n",i);
exit(-1);
}
levels[i].map = malloc(sizeof(int*)*levels[i].width);
if (!levels[i].map)
{
printf ("\nMemory Allocation Failure !\n\n");
exit (-1);
}
for (int j = 0; j < levels[i].width; j++)
{
*(levels[i].map+j) = malloc(sizeof(int)*levels[i].height);
if (!*(levels[i].map+j))
{
printf ("\nMemory Allocation Failure !\n");
exit (-1);
}
}
levels[i].saveMap = malloc(sizeof(int*)*levels[i].width);
if (!levels[i].saveMap)
{
printf ("\nMemory Allocation Failure !\n\n");
exit (-1);
}
for (int j = 0; j < levels[i].width; j++)
{
*(levels[i].saveMap+j) = malloc(sizeof(int)*levels[i].height);
if (!*(levels[i].saveMap+j))
{
printf ("\nMemory Allocation Failure !\n");
exit (-1);
}
}
levels[i].flagMap = malloc(sizeof(int*)*levels[i].width);
if (!levels[i].flagMap)
{
printf ("\nMemory Allocation Failure !\n\n");
exit (-1);
}
for (int j = 0; j < levels[i].width; j++)
{
*(levels[i].flagMap+j) = calloc(levels[i].height,sizeof(int));
if (!*(levels[i].flagMap+j))
{
printf ("\nMemory Allocation Failure !\n");
exit (-1);
}
}
levels[i].deathFlag = malloc(sizeof(int*)*levels[i].width);
if (!levels[i].deathFlag)
{
printf ("\nMemory Allocation Failure !\n\n");
exit (-1);
}
for (int j = 0; j < levels[i].width; j++)
{
*(levels[i].deathFlag+j) = calloc(levels[i].height,sizeof(int));
if (!*(levels[i].deathFlag+j))
{
printf ("\nMemory Allocation Failure !\n");
exit (-1);
}
}
for(y = 0 ; y < levels[i].height ; ++y)
{
for(x = 0 ; x < levels[i].width ; ++x)
{
if(*temp == 'b') levels[i].map[x][y] = border , levels[i].saveMap[x][y] = border;
else if(*temp == 'd') levels[i].map[x][y] = diamond , levels[i].saveMap[x][y] = diamond;
else if(*temp == '.') levels[i].map[x][y] = empty , levels[i].saveMap[x][y] = empty;
else if(*temp == 'l') levels[i].map[x][y] = levelPort , levels[i].saveMap[x][y] = levelPort;
else if(*temp == 'm') levels[i].map[x][y] = miner , levels[i].saveMap[x][y] = miner;
else if(*temp == 'r') levels[i].map[x][y] = rock , levels[i].saveMap[x][y] = rock;
else if(*temp == 's') levels[i].map[x][y] = spider , levels[i].saveMap[x][y] = spider;
else if(*temp == 'e') levels[i].map[x][y] = earth , levels[i].saveMap[x][y] = earth;
if(*(temp+1)== '\n')
temp+=2;
else
++temp;
}
}
levelUptoBorder(i);
memset(fileName,0,50);
free(levels[i].level);
temp = NULL;
}
}
void drawMap(void)
{
for(y = 0 ; y < levels[current.current_level_id].height ; y++)
{
for(x = 0 ; x < levels[current.current_level_id].width ; x++)
{
switch(levels[current.current_level_id].map[x][y])
{
case miner:
if(current.minerFlag == STANDING_FLAG)
blit(levels[current.current_level_id].gameTexture.miner.standingAnimation[levels[current.current_level_id].gameTexture.miner.minerStandingAnimation],x*TILE_SIZE + -gameTools.camera.x,y*TILE_SIZE + -gameTools.camera.y,TILE_SIZE,TILE_SIZE);
else if(current.minerFlag == LEFT_WALKING_FLAG)
blit(levels[current.current_level_id].gameTexture.miner.walkingLeftAnimation[levels[current.current_level_id].gameTexture.miner.minerWalkingLeftAnimation],x*TILE_SIZE + -gameTools.camera.x,y*TILE_SIZE + -gameTools.camera.y,TILE_SIZE,TILE_SIZE);
else if(current.minerFlag == RIGHT_WALKING_FLAG)
blit(levels[current.current_level_id].gameTexture.miner.walkingRightAnimation[levels[current.current_level_id].gameTexture.miner.minerWalkingRightAnimation],x*TILE_SIZE + -gameTools.camera.x,y*TILE_SIZE + -gameTools.camera.y,TILE_SIZE,TILE_SIZE);
else if(current.minerFlag == UP_WALKING_FLAG)
blit(levels[current.current_level_id].gameTexture.miner.walkingUpAnimation[levels[current.current_level_id].gameTexture.miner.minerWalkingUpAnimation],x*TILE_SIZE + -gameTools.camera.x,y*TILE_SIZE + -gameTools.camera.y,TILE_SIZE,TILE_SIZE);
else if(current.minerFlag == DOWN_WALKING_FLAG)
blit(levels[current.current_level_id].gameTexture.miner.walkingDownAnimation[levels[current.current_level_id].gameTexture.miner.minerWalkingDownAnimation],x*TILE_SIZE + -gameTools.camera.x,y*TILE_SIZE + -gameTools.camera.y,TILE_SIZE,TILE_SIZE);
break;
case empty:
blit(levels[current.current_level_id].gameTexture.emptyTexture[levels[current.current_level_id].gameTexture.emptyAnimation],x*TILE_SIZE + -gameTools.camera.x,y*TILE_SIZE + -gameTools.camera.y,TILE_SIZE,TILE_SIZE);
break;
case border:
blit(levels[current.current_level_id].gameTexture.borderTexture[levels[current.current_level_id].gameTexture.borderAnimation],x*TILE_SIZE + -gameTools.camera.x,y*TILE_SIZE + -gameTools.camera.y,TILE_SIZE,TILE_SIZE);
break;
case earth:
blit(levels[current.current_level_id].gameTexture.earthTexture[levels[current.current_level_id].gameTexture.earthAnimation],x*TILE_SIZE + -gameTools.camera.x,y*TILE_SIZE + -gameTools.camera.y,TILE_SIZE,TILE_SIZE);
break;
case diamond:
blit(levels[current.current_level_id].gameTexture.diamondTexture[levels[current.current_level_id].gameTexture.diamondAnimation],x*TILE_SIZE + -gameTools.camera.x,y*TILE_SIZE + -gameTools.camera.y,TILE_SIZE,TILE_SIZE);
break;
case levelPort:
blit(levels[current.current_level_id].gameTexture.levelPortTexture[levels[current.current_level_id].gameTexture.levelPortAnimation],x*TILE_SIZE + -gameTools.camera.x,y*TILE_SIZE + -gameTools.camera.y,TILE_SIZE,TILE_SIZE);
break;
case rock:
blit(levels[current.current_level_id].gameTexture.rockTexture[levels[current.current_level_id].gameTexture.rockAnimation],x*TILE_SIZE + -gameTools.camera.x,y*TILE_SIZE + -gameTools.camera.y,TILE_SIZE,TILE_SIZE);
break;
case spider:
blit(levels[current.current_level_id].gameTexture.spiderTexture[levels[current.current_level_id].gameTexture.spiderAnimation],x*TILE_SIZE + -gameTools.camera.x,y*TILE_SIZE + -gameTools.camera.y,TILE_SIZE,TILE_SIZE);
break;
}
}
}
frameIncrement();
drawExtraImage();
}
void drawEntireMap(void)
{
blit(entireMap , 0 , 0 , SCREEN_WIDTH ,SCREEN_HEIGHT);
}
void drawExtraImage(void)
{
blit(levelBoard , 200*1 , 10 , BOARD_WIDTH,BOARD_HEIGHT);
blit(timeBoard , 200*2 , 10 , BOARD_WIDTH,BOARD_HEIGHT);
blit(diamondBoard , 200*3 , 10 , BOARD_WIDTH,BOARD_HEIGHT);
blit(scoreBoard , 200*4 , 10 , 180,BOARD_HEIGHT);
blit(boards[2].texture , 185*1+50 , 6 , 75,40); /* Level Board */
blit(boards[3].texture , 188*2+56 , 6 , 80,40); /* Time Board */
blit(boards[1].texture , 191*3+59 , 6 , 80,40); /* Diamond Board */
blit(boards[0].texture , 188*4+56 , 6, 170,40); /* Score Board */
}
void levelUptoBorder(int i)
{
for(y = 0 ; y < levels[i].height ; ++y)
{
for(x = 0 ; x < levels[i].width ; ++x)
{
if(levels[i].map[x][y] == levelPort)
{
levels[i].levelUpX = x;
levels[i].levelUpY = y;
levels[i].map[x][y] = border;
}
if(levels[i].saveMap[x][y] == levelPort)
{
levels[i].levelUpX = x;
levels[i].levelUpY = y;
levels[i].saveMap[x][y] = border;
}
}
}
}
void frameIncrement(void)
{
if(!state.pause || state.startScreen)
{
if(current.frameSpeed % 2 == 0)
{
++levels[current.current_level_id].gameTexture.miner.minerStandingAnimation;
if(levels[current.current_level_id].gameTexture.miner.minerStandingAnimation == STANDING) levels[current.current_level_id].gameTexture.miner.minerStandingAnimation = 0;
++levels[current.current_level_id].gameTexture.miner.minerWalkingLeftAnimation;
if(levels[current.current_level_id].gameTexture.miner.minerWalkingLeftAnimation == LEFT_WALKING) levels[current.current_level_id].gameTexture.miner.minerWalkingLeftAnimation = 0;
++levels[current.current_level_id].gameTexture.miner.minerWalkingRightAnimation;
if(levels[current.current_level_id].gameTexture.miner.minerWalkingRightAnimation == RIGHT_WALKING) levels[current.current_level_id].gameTexture.miner.minerWalkingRightAnimation = 0;
++levels[current.current_level_id].gameTexture.miner.minerWalkingUpAnimation;
if(levels[current.current_level_id].gameTexture.miner.minerWalkingUpAnimation == UP_WALKING) levels[current.current_level_id].gameTexture.miner.minerWalkingUpAnimation = 0;
++levels[current.current_level_id].gameTexture.miner.minerWalkingDownAnimation;
if(levels[current.current_level_id].gameTexture.miner.minerWalkingDownAnimation == DOWN_WALKING) levels[current.current_level_id].gameTexture.miner.minerWalkingDownAnimation = 0;
}
++levels[current.current_level_id].gameTexture.emptyAnimation;
if(levels[current.current_level_id].gameTexture.emptyAnimation == 1) levels[current.current_level_id].gameTexture.emptyAnimation = 0;
++levels[current.current_level_id].gameTexture.borderAnimation;
if(levels[current.current_level_id].gameTexture.borderAnimation == 1) levels[current.current_level_id].gameTexture.borderAnimation = 0;
++levels[current.current_level_id].gameTexture.earthAnimation;
if(levels[current.current_level_id].gameTexture.earthAnimation == 1) levels[current.current_level_id].gameTexture.earthAnimation = 0;
++levels[current.current_level_id].gameTexture.diamondAnimation;
if(levels[current.current_level_id].gameTexture.diamondAnimation == 4) levels[current.current_level_id].gameTexture.diamondAnimation = 0;
++levels[current.current_level_id].gameTexture.levelPortAnimation;
if(levels[current.current_level_id].gameTexture.levelPortAnimation == 4) levels[current.current_level_id].gameTexture.levelPortAnimation = 0;
++levels[current.current_level_id].gameTexture.rockAnimation;
if(levels[current.current_level_id].gameTexture.rockAnimation == 3) levels[current.current_level_id].gameTexture.rockAnimation = 0;
++levels[current.current_level_id].gameTexture.spiderAnimation;
if(levels[current.current_level_id].gameTexture.spiderAnimation == 4) levels[current.current_level_id].gameTexture.spiderAnimation = 0;
}
}
void startScreen(void)
{
int x = 0 , y = 0;
if(!(state.startScreen && state.HowToPlay))
{
for(y = 2*(-1)*levels[current.current_level_id].height ; y < 2*levels[current.current_level_id].height ; ++y)
{
for(x = 2*(-1)*levels[current.current_level_id].width ; x < 2*levels[current.current_level_id].width ; ++x)
{
if(x < 4)
blit(levels[current.current_level_id].gameTexture.rockTexture[levels[current.current_level_id].gameTexture.rockAnimation] , x*TILE_SIZE , y*TILE_SIZE , TILE_SIZE,TILE_SIZE);
else
blit(levels[current.current_level_id].gameTexture.emptyTexture[levels[current.current_level_id].gameTexture.emptyAnimation] , x*TILE_SIZE , y*TILE_SIZE , TILE_SIZE,TILE_SIZE);
if( y > 20 && (x > 3 || x < 20))
blit(levels[current.current_level_id].gameTexture.earthTexture[levels[current.current_level_id].gameTexture.earthAnimation] , x*TILE_SIZE , y*TILE_SIZE , TILE_SIZE,TILE_SIZE);
if( x > 38 && y <= 20)
blit(levels[current.current_level_id].gameTexture.rockTexture[levels[current.current_level_id].gameTexture.rockAnimation] , x*TILE_SIZE , y*TILE_SIZE , TILE_SIZE,TILE_SIZE);
}
}
if(state.boulderDash <= SCREEN_HEIGHT/2 - 300) blit(boulderDash,SCREEN_WIDTH/2 - 325,state.boulderDash,640,320);
else blit(boulderDash,SCREEN_WIDTH/2 - 325,SCREEN_HEIGHT/2 - 300,640,320);
menu();
frameIncrement();
state.boulderDash += 4;
}
else
{
blit(howtoplay,0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
}
}
void endSceen(void)
{
for(y = 2*(-1)*levels[current.current_level_id].height ; y < 2*levels[current.current_level_id].height ; ++y)
{
for(x = 2*(-1)*levels[current.current_level_id].width ; x < 2*levels[current.current_level_id].width ; ++x)
{
if(x < 4)
blit(levels[current.current_level_id].gameTexture.rockTexture[levels[current.current_level_id].gameTexture.rockAnimation] , x*TILE_SIZE , y*TILE_SIZE , TILE_SIZE,TILE_SIZE);
else
blit(levels[current.current_level_id].gameTexture.emptyTexture[levels[current.current_level_id].gameTexture.emptyAnimation] , x*TILE_SIZE , y*TILE_SIZE , TILE_SIZE,TILE_SIZE);
if( y > 20 && (x > 3 || x < 20))
blit(levels[current.current_level_id].gameTexture.earthTexture[levels[current.current_level_id].gameTexture.earthAnimation] , x*TILE_SIZE , y*TILE_SIZE , TILE_SIZE,TILE_SIZE);
if( x > 38 && y <= 20)
blit(levels[current.current_level_id].gameTexture.rockTexture[levels[current.current_level_id].gameTexture.rockAnimation] , x*TILE_SIZE , y*TILE_SIZE , TILE_SIZE,TILE_SIZE);
}
}
if(state.boulderDash <= SCREEN_HEIGHT/2 - 300) blit(boulderDash,SCREEN_WIDTH/2 - 325,state.boulderDash,640,320);
else blit(boulderDash,SCREEN_WIDTH/2 - 325,SCREEN_HEIGHT/2 - 300,640,320);
scoreTable();
frameIncrement();
state.boulderDash += 4;
}
void menu(void)
{
if(state.boulderDash > SCREEN_HEIGHT/2 - 300)
{
blit(boards[4].texture , 485 , 440 , 260 , 50);
blit(boards[5].texture , 485 , 440 + 2*TILE_SIZE , 260 , 50);
blit(boards[6].texture , 485 , 440 + 4*TILE_SIZE , 260 , 50);
blit(levels[current.current_level_id].gameTexture.miner.walkingRightAnimation[levels[current.current_level_id].gameTexture.miner.minerWalkingRightAnimation] , state.cursorPos.x , state.cursorPos.y , TILE_SIZE , TILE_SIZE);
}
}
void scoreTable(void)
{
blit(boards[4].texture,505,440,260,50);
blit(boards[5].texture,485,580,310,40);
blit(scoreBoard,485, 440+2*TILE_SIZE,290,BOARD_HEIGHT+30);
blit(boards[0].texture,390,430+2*TILE_SIZE,280,70);
}
|
nevzatseferoglu/boulder-dash
|
src/headers/input.h
|
<reponame>nevzatseferoglu/boulder-dash
#include "common.h"
extern struct mainTools gameTools;
extern void releaseTools(void);
extern SDL_bool quit;
|
nevzatseferoglu/boulder-dash
|
src/check.c
|
<gh_stars>1-10
#include "headers/check.h"
int checkArrayFrontier(int x , int y);
int checkBorder(int x, int y);
int checkEarth(int x, int y);
int checkDiamond(int x , int y);
int checkRock(int x, int y , int direction);
int checkEmpty(int x , int y);
int checkBorder(int x, int y)
{
if(levels[current.current_level_id].map[x][y] == border)
return TRUE;
else
return FALSE;
}
int checkEmpty(int x , int y)
{
if(levels[current.current_level_id].map[x][y] == empty)
return TRUE;
else
return FALSE;
}
int checkEarth(int x, int y)
{
if(levels[current.current_level_id].map[x][y] == earth)
return TRUE;
else
return FALSE;
}
int checkDiamond(int x , int y)
{
if(levels[current.current_level_id].map[x][y] == diamond)
return TRUE;
else
return FALSE;
}
int checkLevel(int x , int y)
{
if(levels[current.current_level_id].map[x][y] == levelPort)
return TRUE;
else
return FALSE;
}
int checkRock(int x, int y , int direction)
{
if(direction == SDL_SCANCODE_LEFT)
{
if(levels[current.current_level_id].map[x-1][y] == empty)
{
return TRUE;
}
else
{
return FALSE;
}
}
else if(direction == SDL_SCANCODE_RIGHT )
{
if(levels[current.current_level_id].map[x+1][y] == empty)
{
return TRUE;
}
else
{
return FALSE;
}
}
else
return FALSE;
}
int checkArrayFrontier(int x , int y)
{
int i , j;
for(i = 0 ; i < levels[current.current_level_id].width ; ++i)
{
if(levels[current.current_level_id].map[i][0] == levels[current.current_level_id].map[x][y])
return FALSE;
}
for(i = 0 ; i < levels[current.current_level_id].width ; ++i)
{
if(levels[current.current_level_id].map[i][levels[current.current_level_id].height-1] == levels[current.current_level_id].map[x][y])
return FALSE;
}
for(j = 0 ; j < levels[current.current_level_id].height ; ++j)
{
if(levels[current.current_level_id].map[0][j] == levels[current.current_level_id].map[x][y])
return FALSE;
}
for(j = 0 ; j < levels[current.current_level_id].height ; ++j)
{
if(levels[current.current_level_id].map[levels[current.current_level_id].width-1][j] == levels[current.current_level_id].map[x][y])
return FALSE;
}
return TRUE;
}
|
nevzatseferoglu/boulder-dash
|
src/input.c
|
<reponame>nevzatseferoglu/boulder-dash
#include "headers/input.h"
void doKeyUp(SDL_KeyboardEvent *event)
{
if (event->keysym.scancode < MAX_KEYBOARD_KEYS)
{
gameTools.keyboard[event->keysym.scancode] = 0;
}
}
void doKeyDown(SDL_KeyboardEvent *event)
{
if (event->keysym.scancode < MAX_KEYBOARD_KEYS)
{
gameTools.keyboard[event->keysym.scancode] = 1;
}
}
void doInput(void)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
Mix_HaltMusic();
quit = SDL_FALSE;
break;
case SDL_KEYDOWN:
doKeyDown(&event.key);
break;
case SDL_KEYUP:
doKeyUp(&event.key);
break;
default:
break;
}
}
}
|
nevzatseferoglu/boulder-dash
|
src/headers/check.h
|
#include "common.h"
extern enum textureAll textureType;
extern struct Stage gameStage;
extern struct levelTools levels[LEVEL_NUMBER];
extern struct currentOwnershipTools current;
|
nevzatseferoglu/boulder-dash
|
src/texture.c
|
#include "headers/texture.h"
void loadaudios(void);
void load_FontFormat(void);
void LoadExtraImage(void);
SDL_Texture* loadTexture(char* fileName)
{
SDL_Texture* tempTexture = NULL;
SDL_Surface* loadedSurface = IMG_Load(fileName);
if(!loadedSurface)
{
fprintf(stderr,"Surface IMG could not be loaded ! IMG Error %s ",SDL_GetError());
exit(-1);
}
tempTexture = SDL_CreateTextureFromSurface(gameTools.renderer , loadedSurface);
if(!tempTexture)
{
fprintf(stderr,"Texture IMG could not be loaded ! SDL Error %s ",SDL_GetError());
exit(-1);
}
SDL_FreeSurface(loadedSurface);
return tempTexture ;
}
void loadMedia(void)
{
for(int i = 0 ; i < LEVEL_NUMBER ; ++i)
{
levels[i].gameTexture.miner.standingAnimation[0] = loadTexture("./images/Miner/Standing/s1.png");
levels[i].gameTexture.miner.standingAnimation[1] = loadTexture("./images/Miner/Standing/s2.png");
levels[i].gameTexture.miner.walkingRightAnimation[0] = loadTexture("./images/Miner/WalkingRight/r1.png");
levels[i].gameTexture.miner.walkingRightAnimation[1] = loadTexture("./images/Miner/WalkingRight/r2.png");
levels[i].gameTexture.miner.walkingRightAnimation[2] = loadTexture("./images/Miner/WalkingRight/r3.png");
levels[i].gameTexture.miner.walkingLeftAnimation[0] = loadTexture("./images/Miner/WalkingLeft/l1.png");
levels[i].gameTexture.miner.walkingLeftAnimation[1] = loadTexture("./images/Miner/WalkingLeft/l2.png");
levels[i].gameTexture.miner.walkingLeftAnimation[2] = loadTexture("./images/Miner/WalkingLeft/l3.png");
levels[i].gameTexture.miner.walkingUpAnimation[0] = loadTexture("./images/Miner/WalkingUp/u1.png");
levels[i].gameTexture.miner.walkingUpAnimation[1] = loadTexture("./images/Miner/WalkingUp/u2.png");
levels[i].gameTexture.miner.walkingUpAnimation[2] = loadTexture("./images/Miner/WalkingUp/u3.png");
levels[i].gameTexture.miner.walkingUpAnimation[3] = loadTexture("./images/Miner/WalkingUp/u4.png");
levels[i].gameTexture.miner.walkingDownAnimation[0] = loadTexture("./images/Miner/WalkingDown/d1.png");
levels[i].gameTexture.miner.walkingDownAnimation[1] = loadTexture("./images/Miner/WalkingDown/d2.png");
levels[i].gameTexture.miner.walkingDownAnimation[2] = loadTexture("./images/Miner/WalkingDown/d3.png");
levels[i].gameTexture.miner.walkingDownAnimation[3] = loadTexture("./images/Miner/WalkingDown/d4.png");
levels[i].gameTexture.emptyTexture[0] = loadTexture("./images/SolidBackground/Empty.png");
levels[i].gameTexture.borderTexture[0] = loadTexture("./images/SolidBackground/Border.png");
levels[i].gameTexture.earthTexture[0] = loadTexture("./images/SolidBackground/Earth.png");
levels[i].gameTexture.diamondTexture[0] = loadTexture("./images/Diamond/Diamond1.png");
levels[i].gameTexture.diamondTexture[1] = loadTexture("./images/Diamond/Diamond2.png");
levels[i].gameTexture.diamondTexture[2] = loadTexture("./images/Diamond/Diamond3.png");
levels[i].gameTexture.diamondTexture[3] = loadTexture("./images/Diamond/Diamond4.png");
levels[i].gameTexture.levelPortTexture[0] = loadTexture("./images/LevelPort/Port1.png");
levels[i].gameTexture.levelPortTexture[1] = loadTexture("./images/LevelPort/Port2.png");
levels[i].gameTexture.levelPortTexture[2] = loadTexture("./images/LevelPort/Port3.png");
levels[i].gameTexture.levelPortTexture[3] = loadTexture("./images/LevelPort/Port4.png");
levels[i].gameTexture.rockTexture[0] = loadTexture("./images/Rock/Rock1.png");
levels[i].gameTexture.rockTexture[1] = loadTexture("./images/Rock/Rock2.png");
levels[i].gameTexture.rockTexture[2] = loadTexture("./images/Rock/Rock3.png");
levels[i].gameTexture.spiderTexture[0] = loadTexture("./images/Spider/Spider1.png");
levels[i].gameTexture.spiderTexture[1] = loadTexture("./images/Spider/Spider2.png");
levels[i].gameTexture.spiderTexture[2] = loadTexture("./images/Spider/Spider3.png");
levels[i].gameTexture.spiderTexture[3] = loadTexture("./images/Spider/Spider4.png");
}
LoadExtraImage();
loadaudios();
}
void loadBackground(void)
{
int x = 0 , y = 0;
for(y = 2*(-1)*levels[current.current_level_id].height ; y < 2*levels[current.current_level_id].height ; ++y)
{
for(x = 2*(-1)*levels[current.current_level_id].width ; x < 2*levels[current.current_level_id].width ; ++x)
{
blit(levels[current.current_level_id].gameTexture.emptyTexture[0] , x*TILE_SIZE , y*TILE_SIZE , TILE_SIZE,TILE_SIZE);
}
}
}
void loadaudios(void)
{
memset(&sounds,0,sizeof(sounds));
sounds.startScreenMusic = Mix_LoadMUS( "./audios/Title_Screen.wav" );
if( sounds.startScreenMusic == NULL )
{
fprintf( stderr,"Failed to load beat music! SDL_mixer Error: %s\n", Mix_GetError() );
exit(-1);
}
sounds.backgroundMusic = Mix_LoadMUS( "./audios/Boulder_World.wav" );
if( sounds.backgroundMusic == NULL )
{
fprintf( stderr,"Failed to load beat music! SDL_mixer Error: %s\n", Mix_GetError() );
exit(-1);
}
sounds.endGame = Mix_LoadMUS( "./audios/rockford.wav" );
if( sounds.endGame == NULL )
{
fprintf( stderr,"Failed to load beat music! Mix Error: %s\n", Mix_GetError() );
exit(-1);
}
sounds.collectDiamond = Mix_LoadWAV("./audios/collectDiamond.wav");
if(sounds.collectDiamond == NULL)
{
fprintf(stderr,"Failed to load chunk diamondCollect ! SDL_mixer Error : %s\n",Mix_GetError());
exit(-1);
}
sounds.dropRock = Mix_LoadWAV("./audios/dropRock.wav");
if(sounds.dropRock == NULL)
{
fprintf(stderr,"Failed to load chunk dropRock ! SDL_mixer Error : %s\n",Mix_GetError());
exit(-1);
}
sounds.moveEarth = Mix_LoadWAV("./audios/moveEarth.wav");
if(sounds.moveEarth == NULL)
{
fprintf(stderr,"Failed to load chunk moveEarth ! SDL_mixer Error : %s\n",Mix_GetError());
exit(-1);
}
sounds.gameover = Mix_LoadWAV("./audios/gameover.wav");
if(sounds.gameover == NULL)
{
fprintf(stderr,"Failed to load chunk gameover ! SDL_mixer Error : %s\n",Mix_GetError());
exit(-1);
}
sounds.levelUp = Mix_LoadWAV("./audios/levelUp.wav");
if(sounds.levelUp == NULL)
{
fprintf(stderr,"Failed to load chunk levelUp ! SDL_mixer Error : %s\n",Mix_GetError());
exit(-1);
}
current.levelUpFlag = TRUE;
Mix_VolumeChunk(sounds.gameover,CHUNK_VOLUME+100);
Mix_VolumeChunk(sounds.levelUp,CHUNK_VOLUME+100);
Mix_VolumeChunk(sounds.moveEarth,CHUNK_VOLUME);
Mix_VolumeChunk(sounds.dropRock,CHUNK_VOLUME);
Mix_VolumeChunk(sounds.collectDiamond,CHUNK_VOLUME-15);
Mix_VolumeMusic(MUSIC_VOLUME);
Mix_PlayMusic( sounds.startScreenMusic, -1 );
}
void LoadExtraImage(void)
{
scoreBoard = NULL;
diamondBoard = NULL;
levelBoard = NULL;
timeBoard = NULL;
boulderDash = NULL;
howtoplay = NULL;
scoreBoard = loadTexture("./images/Board/scoreBoard.png");
if(!scoreBoard)
{
fprintf(stderr,"scoreBoard could not be initialized !");
exit(-1);
}
diamondBoard = loadTexture("./images/Board/diamondBoard.png");
if(!diamondBoard)
{
fprintf(stderr,"diamondBoard could not be initialized !");
exit(-1);
}
timeBoard = loadTexture("./images/Board/timeBoard.png");
if(!timeBoard)
{
fprintf(stderr,"timeBoard could not be initialized !");
exit(-1);
}
levelBoard = loadTexture("./images/Board/levelBoard.png");
if(!levelBoard)
{
fprintf(stderr,"levelBoard could not be initialized !");
exit(-1);
}
boulderDash = loadTexture("./images/Intro/boulderDash.png");
if(!boulderDash)
{
fprintf(stderr,"boulderDash could not be initialized !");
exit(-1);
}
howtoplay = loadTexture("./images/Intro/howtoplay.png");
if(!howtoplay)
{
fprintf(stderr,"how to play could not be initialized !");
exit(-1);
}
}
void renderText(void)
{
int i;
SDL_Color color = {255,255,255,255};
SDL_Color colorMenu = {255,255,0,255};
for(i = 0 ; i < TEXT_NUMBER ; ++i)
memset(boards+i,0,sizeof(boards[i]));
boards[0].color = color;
boards[1].color = color;
boards[2].color = color;
boards[3].color = color;
boards[4].color = colorMenu; /* Start Game */
boards[5].color = colorMenu; /* How to Play */
boards[6].color = colorMenu; /* Exit Game */
boards[7].color = colorMenu; /* Esc */
for(i = 0 ; i < TEXT_NUMBER ; ++i)
boards[i].fontSize = 50;
for(i = 0 ; i < TEXT_NUMBER ; ++i)
{
if(i > 3)
{
boards[i].font = TTF_OpenFont("./TrueTypes/gameMenu.ttf",boards[i].fontSize);
if(boards[i].font == NULL)
{
fprintf(stderr,"boards[%d] could not be opened from file ! TTF_Error() : %s",i,TTF_GetError());
exit(-1);
}
TTF_SetFontStyle(boards[i].font ,TTF_STYLE_UNDERLINE);
}
else
{
boards[i].font = TTF_OpenFont("./TrueTypes/game.ttf",boards[i].fontSize);
if(boards[i].font == NULL)
{
fprintf(stderr,"boards[%d] could not be opened from file ! TTF_Error() : %s",i,TTF_GetError());
exit(-1);
}
TTF_SetFontStyle(boards[i].font , TTF_STYLE_ITALIC);
}
}
}
|
nevzatseferoglu/boulder-dash
|
src/headers/defs.h
|
#define TRUE 1
#define FALSE 0
#define SCREEN_WIDTH 1280
#define SCREEN_HEIGHT 720
#define MAX_KEYBOARD_KEYS 350
#define LEVEL_NUMBER 10
#define TILE_SIZE 30
#define TILE_TYPE 8
#define FILE_NAME_SIZE 50
#define BOARD_WIDTH 114
#define BOARD_HEIGHT 40
#define TEXT_NUMBER 8
#define CHUNK_VOLUME 20
#define MUSIC_VOLUME 9
#define MAX_LINE 255
#define STANDING 2
#define RIGHT_WALKING 3
#define LEFT_WALKING 3
#define UP_WALKING 4
#define DOWN_WALKING 4
#define STANDING_FLAG 0
#define LEFT_WALKING_FLAG 1
#define RIGHT_WALKING_FLAG 2
#define UP_WALKING_FLAG 3
#define DOWN_WALKING_FLAG 4
#define DIAMOND_TILE__TYPE_AMOUNT 4
#define LEVELPORT_TILE__TYPE_AMOUNT 4
#define SPIDER_TILE__TYPE_AMOUNT 4
#define ROCK_TILE__TYPE_AMOUNT 3
#define BORDER_TILE__TYPE_AMOUNT 1
#define EARTH_TILE__TYPE_AMOUNT 1
#define EMPTY_TILE__TYPE_AMOUNT 1
#define MAX_FRAME_SPEED 6
|
nevzatseferoglu/boulder-dash
|
src/init.c
|
<reponame>nevzatseferoglu/boulder-dash
#include "headers/init.h"
static int initFlag = SDL_INIT_EVERYTHING;
static int rendererFlag = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ;
static int windowFlag = SDL_WINDOW_OPENGL;
static int rendererIndex = -1; /* The index of the rendering driver to initizalize the first oen supporting the requested flags */
static int imgFlag = IMG_INIT_PNG;
void initSDL(void)
{
if( SDL_Init(initFlag) < 0 )
{
fprintf(stderr,"SDL could not be initialized ! SDL Error : %s",SDL_GetError());
exit(-1); // escape statement to exit
}
gameTools.window = SDL_CreateWindow("Boulder Dash",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
SCREEN_WIDTH,
SCREEN_HEIGHT,
windowFlag);
if(!gameTools.window)
{
fprintf(stderr,"Window could not be initialized ! SDL Error : %s",SDL_GetError());
exit(-1); // escape statement to exit
}
gameTools.renderer = SDL_CreateRenderer(gameTools.window,
rendererIndex,
rendererFlag);
if(!gameTools.renderer)
{
fprintf(stderr,"Renderer could not be initialized ! SDL Error : %s",SDL_GetError());
exit(-1);
}
if( !(IMG_Init(imgFlag) & imgFlag) )
{
fprintf(stderr,"IMG_Init could not be initialized ! IMG Error : %s",IMG_GetError());
exit(-1);
}
if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 )
{
fprintf(stderr,"SDL_mixer could not be initialized! SDL_mixer Error: %s\n", Mix_GetError() );
exit(-1);
}
if(TTF_Init())
{
fprintf(stderr,"SDL_ttf could not be initialized! SDL_ttf Error : %s\n",TTF_GetError());
exit(-1);
}
}
void initGame(void)
{
int i = 0;
for(i = 0 ; i < TEXT_NUMBER ; ++i)
memset(boards+i,0,sizeof(boards[i]));
for(i = 0 ; i < LEVEL_NUMBER ; ++i)
memset(levels+i,0,sizeof(levels[i]));
memset(¤t,0,sizeof(current));
memset(&state,0,sizeof(state));
state.startScreen = TRUE;
state.cursorPos.x = 450;
state.cursorPos.y = 445;
state.startGamePos.x = 450;
state.startGamePos.y = 445;
state.howToPlayPos.x = 450;
state.howToPlayPos.y = 505;
state.exitGamePos.x = 450;
state.exitGamePos.y = 565;
}
void releaseTools(void)
{
int i , j;
SDL_DestroyWindow(gameTools.window);
gameTools.window = NULL;
SDL_DestroyRenderer(gameTools.renderer);
gameTools.renderer = NULL;
Mix_FreeMusic(sounds.backgroundMusic);
sounds.backgroundMusic = NULL;
Mix_FreeMusic(sounds.startScreenMusic);
sounds.startScreenMusic = NULL;
Mix_FreeChunk( sounds.collectDiamond );
sounds.collectDiamond = NULL;
Mix_FreeChunk( sounds.gameover );
sounds.gameover = NULL;
Mix_FreeChunk( sounds.levelUp );
sounds.levelUp = NULL;
Mix_FreeChunk( sounds.dropRock );
sounds.dropRock = NULL;
Mix_FreeChunk( sounds.moveEarth );
sounds.moveEarth = NULL;
for(i = 0 ; i < TEXT_NUMBER ; ++i)
{
SDL_DestroyTexture(boards[i].texture);
boards[i].texture = NULL;
if(i<4)
free(boards[i].message);
TTF_CloseFont(boards[i].font);
boards[i].font = NULL;
}
for(i = 0 ; i < LEVEL_NUMBER ; ++i)
{
for(j = 0 ; j < EMPTY_TILE__TYPE_AMOUNT ; ++j)
{
SDL_DestroyTexture(levels[i].gameTexture.emptyTexture[j]);
levels[i].gameTexture.emptyTexture[j] = NULL;
}
for(j = 0 ; j < BORDER_TILE__TYPE_AMOUNT ; ++j)
{
SDL_DestroyTexture(levels[i].gameTexture.borderTexture[j]);
levels[i].gameTexture.borderTexture[j] = NULL;
}
for(j = 0 ; j < EARTH_TILE__TYPE_AMOUNT ; ++j)
{
SDL_DestroyTexture(levels[i].gameTexture.earthTexture[j]);
levels[i].gameTexture.earthTexture[j] = NULL;
}
for(j = 0 ; j < DIAMOND_TILE__TYPE_AMOUNT ; ++j)
{
SDL_DestroyTexture(levels[i].gameTexture.diamondTexture[j]);
levels[i].gameTexture.diamondTexture[j] = NULL;
}
for(j = 0 ; j < LEVELPORT_TILE__TYPE_AMOUNT ; ++j)
{
SDL_DestroyTexture(levels[i].gameTexture.levelPortTexture[j]);
levels[i].gameTexture.levelPortTexture[j] = NULL;
}
for(j = 0 ; j < ROCK_TILE__TYPE_AMOUNT ; ++j)
{
SDL_DestroyTexture(levels[i].gameTexture.rockTexture[j]);
levels[i].gameTexture.rockTexture[j] = NULL;
}
for(j = 0 ; j < SPIDER_TILE__TYPE_AMOUNT ; ++j)
{
SDL_DestroyTexture(levels[i].gameTexture.spiderTexture[j]);
levels[i].gameTexture.spiderTexture[j] = NULL;
}
for(j = 0 ; j < STANDING ; ++j)
{
SDL_DestroyTexture(levels[i].gameTexture.miner.standingAnimation[j]);
levels[i].gameTexture.miner.standingAnimation[j] = NULL;
}
for(j = 0 ; j < RIGHT_WALKING ; ++j)
{
SDL_DestroyTexture(levels[i].gameTexture.miner.walkingRightAnimation[j]);
levels[i].gameTexture.miner.walkingRightAnimation[j] = NULL;
}
for(j = 0 ; j < LEFT_WALKING ; ++j)
{
SDL_DestroyTexture(levels[i].gameTexture.miner.walkingLeftAnimation[j]);
levels[i].gameTexture.miner.walkingLeftAnimation[j] = NULL;
}
for(j = 0 ; j < UP_WALKING ; ++j)
{
SDL_DestroyTexture(levels[i].gameTexture.miner.walkingUpAnimation[j]);
levels[i].gameTexture.miner.walkingUpAnimation[j] = NULL;
}
for(j = 0 ; j < DOWN_WALKING ; ++j)
{
SDL_DestroyTexture(levels[i].gameTexture.miner.walkingDownAnimation[j]);
levels[i].gameTexture.miner.walkingDownAnimation[j] = NULL;
}
}
TTF_Quit();
Mix_Quit();
IMG_Quit();
SDL_Quit();
}
|
nevzatseferoglu/boulder-dash
|
src/headers/move.h
|
#include "common.h"
extern enum textureAll textureType;
extern int checkArrayFrontier(int x , int y);
extern int checkBorder(int x, int y);
extern int checkEarth(int x, int y);
extern int checkDiamond(int x , int y);
extern int checkRock(int x, int y , int direction);
extern int checkEmpty(int x , int y);
extern int checkLevel(int x , int y);
extern void blit(SDL_Texture *texture, int x, int y , int w , int h);
extern SDL_Texture* entireMap;
extern Uint32 oldTime;
extern struct gameState state;
extern struct mainTools gameTools;
extern struct Stage gameStage;
extern struct soundTools sounds;
extern struct levelTools levels[LEVEL_NUMBER];
extern struct boardTools boards[TEXT_NUMBER];
extern struct currentOwnershipTools current;
extern SDL_bool quit;
|
nevzatseferoglu/boulder-dash
|
src/headers/init.h
|
<reponame>nevzatseferoglu/boulder-dash
#include "common.h"
extern struct mainTools gameTools;
extern void prepareWindow(void);
extern struct soundTools sounds;
struct boardTools boards[TEXT_NUMBER];
extern struct currentOwnershipTools current;
extern struct levelTools levels[LEVEL_NUMBER];
extern struct gameState state;
extern enum textureAll textureType;
|
nevzatseferoglu/boulder-dash
|
src/headers/texture.h
|
<reponame>nevzatseferoglu/boulder-dash<gh_stars>1-10
#include "common.h"
extern enum textureAll textureType;
extern struct mainTools gameTools;
extern void blit(SDL_Texture *texture, int x, int y , int w , int h);
extern struct soundTools sounds;
extern struct boardTools boards[TEXT_NUMBER];
extern struct levelTools levels[LEVEL_NUMBER];
extern struct gameState state;
extern SDL_Texture* scoreBoard;
extern SDL_Texture* diamondBoard;
extern SDL_Texture* levelBoard;
extern SDL_Texture* timeBoard;
extern SDL_Texture* entireMap;
extern SDL_Texture* boulderDash;
extern SDL_Texture* howtoplay;
extern struct currentOwnershipTools current;
|
nevzatseferoglu/boulder-dash
|
src/headers/drawIssue.h
|
#include "common.h"
extern struct mainTools gameTools;
extern struct gameState state;
extern void drawInitialBackground(void);
extern void loadBackground(void);
|
nevzatseferoglu/boulder-dash
|
src/headers/camera.h
|
<gh_stars>1-10
#include "common.h"
extern struct Stage gameStage;
extern struct mainTools gameTools;
extern struct levelTools levels[LEVEL_NUMBER];
extern struct currentOwnershipTools current;
|
nevzatseferoglu/boulder-dash
|
src/headers/stage.h
|
<filename>src/headers/stage.h
#include "common.h"
extern struct mainTools gameTools;
extern struct gameState state;
extern void drawMap(void);
extern void initMap(void);
extern void doPlayer(void);
extern void doCamera(void);
extern void startScreen(void);
extern void endSceen(void);
|
nevzatseferoglu/boulder-dash
|
src/camera.c
|
#include "headers/camera.h"
void doCamera(void)
{
current.centerPos.x = (SCREEN_WIDTH/2);
current.centerPos.y = (SCREEN_HEIGHT/2);
gameTools.camera.x = ((current.minerPos.x)*TILE_SIZE + TILE_SIZE/2 - current.centerPos.x);
gameTools.camera.y = ((current.minerPos.y)*TILE_SIZE + TILE_SIZE/2 - current.centerPos.y);
if(gameTools.camera.x < 0)
{
gameTools.camera.x = 0;
}
if(gameTools.camera.y < 0)
{
gameTools.camera.y = 0;
}
if( gameTools.camera.x > levels[current.current_level_id].width*TILE_SIZE - SCREEN_WIDTH)
{
gameTools.camera.x = levels[current.current_level_id].width*TILE_SIZE - SCREEN_WIDTH;
}
if( gameTools.camera.y > levels[current.current_level_id].height*TILE_SIZE - SCREEN_HEIGHT)
{
gameTools.camera.y = levels[current.current_level_id].height*TILE_SIZE - SCREEN_HEIGHT;
}
}
|
nevzatseferoglu/boulder-dash
|
src/headers/structs.h
|
enum textureAll{
miner,empty,border,earth,diamond,levelPort,rock, spider
};
struct gameState{
int pause;
int gameover;
int startScreen;
int boulderDash;
SDL_Point cursorPos;
SDL_Point startGamePos;
SDL_Point howToPlayPos;
SDL_Point exitGamePos;
int startGame;
int HowToPlay;
int ExitGame;
int Esc;
int endGame;
int passedLevel;
};
struct Delegate{
void (*logic)(void);
void (*draw)(void);
};
struct mainTools{
SDL_Window* window;
SDL_Renderer* renderer;
struct Delegate gameParts;
int keyboard[MAX_KEYBOARD_KEYS];
SDL_Point camera;
};
struct minerTools{
SDL_Texture* standingAnimation[STANDING];
int minerStandingAnimation;
SDL_Texture* walkingRightAnimation[RIGHT_WALKING];
int minerWalkingRightAnimation;
SDL_Texture* walkingLeftAnimation[LEFT_WALKING];
int minerWalkingLeftAnimation;
SDL_Texture* walkingUpAnimation[UP_WALKING];
int minerWalkingUpAnimation;
SDL_Texture* walkingDownAnimation[DOWN_WALKING];
int minerWalkingDownAnimation;
};
struct totalTexture{
struct minerTools miner;
SDL_Texture* emptyTexture[EMPTY_TILE__TYPE_AMOUNT];
int emptyAnimation;
SDL_Texture* borderTexture[BORDER_TILE__TYPE_AMOUNT];
int borderAnimation;
SDL_Texture* earthTexture[EARTH_TILE__TYPE_AMOUNT];
int earthAnimation;
SDL_Texture* diamondTexture[DIAMOND_TILE__TYPE_AMOUNT];
int diamondAnimation;
SDL_Texture* levelPortTexture[LEVELPORT_TILE__TYPE_AMOUNT];
int levelPortAnimation;
SDL_Texture* rockTexture[ROCK_TILE__TYPE_AMOUNT];
int rockAnimation;
SDL_Texture* spiderTexture[SPIDER_TILE__TYPE_AMOUNT];
int spiderAnimation;
};
struct Stage{
SDL_Point camera;
};
struct soundTools{
Mix_Music* backgroundMusic;
Mix_Music* startScreenMusic;
Mix_Music* endGame;
Mix_Chunk* moveEarth;
Mix_Chunk* dropRock;
Mix_Chunk* collectDiamond;
Mix_Chunk* levelUp;
Mix_Chunk* gameover;
};
struct boardTools{
SDL_Texture* texture;
TTF_Font* font;
char* message;
int fontSize;
SDL_Color color;
};
struct levelTools{
struct totalTexture gameTexture;
char* level;
int id;
int width;
int height;
int **map;
int **saveMap;
int **flagMap;
int **deathFlag;
int diamond_number;
int totalDiamondNumber;
int levelScore;
Uint32 pausePassedTime;
Uint32 time;
Uint32 elapsedTime;
int levelUpX;
int levelUpY;
int entryCheck;
};
struct currentOwnershipTools{
int reachedScore;
int collectedDiamond;
int current_level_id;
Uint32 printTime;
int levelUpFlag;
SDL_Point minerPos;
SDL_Point centerPos;
int minerFlag;
int frameSpeed;
};
|
nevzatseferoglu/boulder-dash
|
src/headers/map.h
|
<filename>src/headers/map.h
#include "common.h"
extern struct mainTools gameTools;
extern enum textureAll textureType;
extern struct Stage gameStage;
extern void blit(SDL_Texture *texture, int x, int y , int w , int h);
extern char* readFile(char*);
extern struct boardTools boards[TEXT_NUMBER];
extern SDL_Texture* scoreBoard;
extern SDL_Texture* diamondBoard;
extern SDL_Texture* levelBoard;
extern SDL_Texture* timeBoard;
extern SDL_Texture* entireMap;
extern SDL_Texture* boulderDash;
extern SDL_Texture* howtoplay;
extern struct gameState state;
extern void renderText(void);
extern struct levelTools levels[LEVEL_NUMBER];
extern struct currentOwnershipTools current;
|
nevzatseferoglu/boulder-dash
|
src/fileOperation.c
|
#include "headers/fileOperation.h"
void increase(char** level);
char* readFile(char* map_file_name)
{
int i;
size_t result;
int fileSize;
int currentPosition;
int tempNumber;
int quit = TRUE;
char junk1[MAX_LINE] = {'\0'};
char junk2[MAX_LINE] = {'\0'};
char analyseLine[MAX_LINE] = {'\0'};
FILE* fptr = NULL;
fptr = fopen(map_file_name,"rb");
if(fptr == NULL)
{
fprintf(stderr,"Error ! , file could not be opened");
exit(-1);
}
sscanf(fgets(analyseLine,MAX_LINE,fptr),"%s%s%d",junk1,junk2,&tempNumber);
for(i = 0 ; i < LEVEL_NUMBER && quit ; ++i)
{
if(tempNumber == i+1)
{
levels[i].id = tempNumber;
sscanf(fgets(analyseLine,MAX_LINE,fptr),"%s%s%d",junk1,junk2,&tempNumber);
levels[i].width = tempNumber;
sscanf(fgets(analyseLine,MAX_LINE,fptr),"%s%s%d",junk1,junk2,&tempNumber);
levels[i].height = tempNumber;
sscanf(fgets(analyseLine,MAX_LINE,fptr),"%s%s%d",junk1,junk2,&tempNumber);
levels[i].diamond_number = tempNumber;
sscanf(fgets(analyseLine,MAX_LINE,fptr),"%s%s%d",junk1,junk2,&tempNumber);
levels[i].time = tempNumber;
quit = FALSE;
}
}
fseek(fptr,1,SEEK_CUR); /* Incrementing File Position at ones to reach the map data in specific file */
currentPosition = ftell(fptr);
fseek (fptr, 0 , SEEK_END);
fileSize = ftell(fptr);
rewind(fptr);
fileSize -= currentPosition;
fseek(fptr, currentPosition , SEEK_SET);
levels[i-1].level = (char*) malloc(sizeof(char)*(fileSize+1));
if (levels[i-1].level == NULL)
{
fprintf (stderr,"Memory error\n");
exit (-1);
}
memset(levels[i-1].level,0,fileSize+1);
result = fread (levels[i-1].level,1,fileSize,fptr);
if (result != fileSize)
{
fprintf (stderr,"Reading error\n");
exit (-1);
}
levels[i-1].level[fileSize] = '\0';
fclose(fptr);
return levels[i-1].level;
}
|
nevzatseferoglu/boulder-dash
|
src/move.c
|
#include "headers/move.h"
void getMinerLocation(int* x , int* y);
void getSpiderLocation(int* x, int* y);
void dropTilltheEmptyRock(int x , int y);
void dropTilltheEmptyDiamond(int x , int y);
void moveSpider(int x,int y,int* preDirection);
void dropRightLeft(int x , int y);
void searchAndDropRock(void);
void searchAndDropDiamond(void);
char* intToString(int number,int boardNumber);
void boardIssue(void);
void checkStatus(void);
void goNextLevel(void);
void deathCheck(void);
void fillTrue(void);
void prepLevel(void);
void getTotalDiamondNumber(void);
void goBackToLevel(void);
void frameSpeedIssues(void);
void timeCalculating(void);
Uint32 timeSum = 0;
int preDirection = 1;
int up = 1;
int right = 2;
int down = 3;
int left = 4;
int x,y;
int i,j;
int spiderX = -1;
int spiderY = -1;
void doPlayer(void)
{
frameSpeedIssues();
if(!levels[current.current_level_id].entryCheck)
{
prepLevel();
levels[current.current_level_id].entryCheck = TRUE;
}
getMinerLocation(&x , &y);
getSpiderLocation(&spiderX , &spiderY);
searchAndDropRock();
searchAndDropDiamond();
fillTrue();
if(spiderX != -1 && spiderY != -1)
moveSpider(spiderX,spiderY,&preDirection);
if (gameTools.keyboard[SDL_SCANCODE_LEFT] && !state.pause)
{
current.minerFlag = LEFT_WALKING_FLAG;
if(!(state.startScreen || state.endGame))
{
if(!checkBorder(x-1,y))
{
if(checkEmpty(x-1,y))
{
levels[current.current_level_id].map[x-1][y] = miner;
levels[current.current_level_id].map[x][y] = empty;
}
else if(checkEarth(x-1,y))
{
if(levels[current.current_level_id].deathFlag[x-1][y] == TRUE)
levels[current.current_level_id].deathFlag[x-1][y] = -1;
levels[current.current_level_id].map[x-1][y] = miner;
levels[current.current_level_id].map[x][y] = empty;
Mix_PlayChannel(-1,sounds.moveEarth,0);
}
else if(checkDiamond(x-1,y))
{
if(levels[current.current_level_id].deathFlag[x-1][y] == TRUE)
levels[current.current_level_id].deathFlag[x-1][y] = -1;
levels[current.current_level_id].map[x-1][y] = miner;
levels[current.current_level_id].map[x][y] = empty;
--(levels[current.current_level_id].totalDiamondNumber);
++(current.collectedDiamond);
current.reachedScore += 10;
Mix_PlayChannel(-1,sounds.collectDiamond,0);
}
else if(levels[current.current_level_id].map[x-1][y] == rock && checkRock(x-1,y,SDL_SCANCODE_LEFT))
{
levels[current.current_level_id].map[x-1][y] = miner;
levels[current.current_level_id].map[x-2][y] = rock;
levels[current.current_level_id].map[x][y] = empty;
}
else if(checkLevel(x-1,y))
{
goNextLevel();
}
}
}
}
else if (gameTools.keyboard[SDL_SCANCODE_RIGHT] && !state.pause)
{
current.minerFlag = RIGHT_WALKING_FLAG;
if(!(state.startScreen || state.endGame))
{
if(!checkBorder(x+1,y))
{
if(checkEmpty(x+1,y))
{
levels[current.current_level_id].map[x+1][y] = miner;
levels[current.current_level_id].map[x][y] = empty;
}
else if(checkEarth(x+1,y))
{
if(levels[current.current_level_id].deathFlag[x+1][y] == TRUE)
levels[current.current_level_id].deathFlag[x+1][y] = -1;
levels[current.current_level_id].map[x+1][y] = miner;
levels[current.current_level_id].map[x][y] = empty;
Mix_PlayChannel(-1,sounds.moveEarth,0);
}
else if(checkDiamond(x+1,y))
{
if(levels[current.current_level_id].deathFlag[x+1][y] == TRUE)
levels[current.current_level_id].deathFlag[x+1][y] = -1;
levels[current.current_level_id].map[x+1][y] = miner;
levels[current.current_level_id].map[x][y] = empty;
--(levels[current.current_level_id].totalDiamondNumber);
++(current.collectedDiamond);
current.reachedScore += 10;
Mix_PlayChannel(-1,sounds.collectDiamond,0);
}
else if(levels[current.current_level_id].map[x+1][y] == rock && checkRock(x+1,y,SDL_SCANCODE_RIGHT))
{
levels[current.current_level_id].map[x+1][y] = miner;
levels[current.current_level_id].map[x+2][y] = rock;
levels[current.current_level_id].map[x][y] = empty;
}
else if(checkLevel(x+1,y))
{
goNextLevel();
}
}
}
}
else if (gameTools.keyboard[SDL_SCANCODE_UP] && !state.pause)
{
current.minerFlag = UP_WALKING_FLAG;
if(!(state.startScreen || state.endGame))
{
if(!checkBorder(x,y-1))
{
if(checkEmpty(x,y-1))
{
levels[current.current_level_id].map[x][y-1] = miner;
levels[current.current_level_id].map[x][y] = empty;
}
else if(checkEarth(x,y-1))
{
if(levels[current.current_level_id].deathFlag[x][y-1] == TRUE)
levels[current.current_level_id].deathFlag[x][y-1] = -1;
levels[current.current_level_id].map[x][y-1] = miner;
levels[current.current_level_id].map[x][y] = empty;
Mix_PlayChannel(-1,sounds.moveEarth,0);
}
else if(checkDiamond(x,y-1))
{
if(levels[current.current_level_id].deathFlag[x][y-1] == TRUE)
levels[current.current_level_id].deathFlag[x][y-1] = -1;
levels[current.current_level_id].map[x][y-1] = miner;
levels[current.current_level_id].map[x][y] = empty;
--(levels[current.current_level_id].totalDiamondNumber);
++(current.collectedDiamond);
current.reachedScore += 10;
Mix_PlayChannel(-1,sounds.collectDiamond,0);
}
else if(checkLevel(x,y-1))
{
goNextLevel();
}
}
}
else
{
if(state.cursorPos.y > 445 ) state.cursorPos.y -= 2*TILE_SIZE;
}
}
else if (gameTools.keyboard[SDL_SCANCODE_DOWN] && !state.pause)
{
current.minerFlag = DOWN_WALKING_FLAG;
if(!(state.startScreen || state.endGame))
{
if(!checkBorder(x,y+1))
{
if(checkEmpty(x,y+1))
{
levels[current.current_level_id].map[x][y+1] = miner;
levels[current.current_level_id].map[x][y] = empty;
}
else if(checkEarth(x,y+1))
{
levels[current.current_level_id].map[x][y+1] = miner;
levels[current.current_level_id].map[x][y] = empty;
Mix_PlayChannel(-1,sounds.moveEarth,0);
}
else if(checkDiamond(x,y+1))
{
levels[current.current_level_id].map[x][y+1] = miner;
levels[current.current_level_id].map[x][y] = empty;
--(levels[current.current_level_id].totalDiamondNumber);
++(current.collectedDiamond);
current.reachedScore += 10;
Mix_PlayChannel(-1,sounds.collectDiamond,0);
}
else if(checkLevel(x,y+1))
{
goNextLevel();
}
}
}
else
{
if(state.cursorPos.y <= 505) state.cursorPos.y += 2*TILE_SIZE;
}
}
else if(gameTools.keyboard[SDL_SCANCODE_M]) /* Mute level music which exist */
{
if( Mix_PlayingMusic() == 0 )
{
Mix_PlayMusic( sounds.backgroundMusic, -1 );
}
else
{
if( Mix_PausedMusic() == 1 ) Mix_ResumeMusic();
else Mix_PauseMusic();
}
}
else if(gameTools.keyboard[SDL_SCANCODE_R] && !state.pause) /* Restarting Level */
{
goBackToLevel();
}
else if(gameTools.keyboard[SDL_SCANCODE_P]) /* Pausing Game */
{
if( Mix_PlayingMusic() == 0 )
{
Mix_PlayMusic( sounds.backgroundMusic, -1 );
}
else
{
if( Mix_PausedMusic() == 1 ) Mix_ResumeMusic();
else Mix_PauseMusic();
}
if(state.pause)
state.pause = FALSE;
else
state.pause = TRUE;
}
else if(gameTools.keyboard[SDL_SCANCODE_RETURN])
{
if(state.endGame == TRUE)
{
quit = SDL_FALSE;
}
if(state.cursorPos.y == state.startGamePos.y)
{
state.startScreen = FALSE;
Mix_HaltMusic();
if( Mix_PlayingMusic() == 0 )
{
Mix_PlayMusic( sounds.backgroundMusic, -1 );
}
else
{
if( Mix_PausedMusic() == 1 ) Mix_ResumeMusic();
else Mix_PauseMusic();
}
}
else if(state.cursorPos.y == state.howToPlayPos.y)
{
state.HowToPlay = TRUE;
}
else if(state.cursorPos.y == state.exitGamePos.y)
{
state.ExitGame = TRUE;
quit = SDL_FALSE;
}
}
else if(gameTools.keyboard[SDL_SCANCODE_ESCAPE])
{
state.HowToPlay = FALSE;
state.ExitGame = FALSE;
}
else
{
current.minerFlag = STANDING_FLAG;
}
if(state.pause)
{
levels[current.current_level_id].pausePassedTime = (SDL_GetTicks()+oldTime) * 0.001 - levels[current.current_level_id].elapsedTime - timeSum;
}
else
{
timeCalculating();
boardIssue();
checkStatus();
}
}
void getMinerLocation(int* x , int* y)
{
for(j = 0 ; j < levels[current.current_level_id].height ; j++)
{
for(i = 0 ; i < levels[current.current_level_id].width ; i++)
{
if(levels[current.current_level_id].map[i][j] == miner)
{
*x = i , current.minerPos.x = i;
*y = j , current.minerPos.y = j;
}
}
}
}
void getSpiderLocation(int* x , int* y)
{
for(j = 0 ; j < levels[current.current_level_id].height ; j++)
{
for(i = 0 ; i < levels[current.current_level_id].width ; i++)
{
if(levels[current.current_level_id].map[i][j] == spider)
{
*x = i;
*y = j;
}
}
}
}
void dropTilltheEmptyRock(int x , int y)
{
if(levels[current.current_level_id].map[x][y+1] == empty)
{
levels[current.current_level_id].map[x][y+1] = rock;
levels[current.current_level_id].flagMap[x][y+1] = TRUE;
levels[current.current_level_id].map[x][y] = empty;
levels[current.current_level_id].flagMap[x][y] = FALSE;
if(levels[current.current_level_id].map[x][y+2] != empty && levels[current.current_level_id].map[x][y+2] != miner)
Mix_PlayChannel(-1,sounds.dropRock,0);
}
else if(levels[current.current_level_id].map[x-1][y+1] == empty && levels[current.current_level_id].map[x-1][y] == empty && ((levels[current.current_level_id].map[x][y+1] == rock) || (levels[current.current_level_id].map[x][y+1] == diamond)))
{
levels[current.current_level_id].map[x-1][y+1] = rock;
levels[current.current_level_id].flagMap[x-1][y+1] = TRUE;
levels[current.current_level_id].map[x][y] = empty;
levels[current.current_level_id].flagMap[x][y] = FALSE;
if(levels[current.current_level_id].map[x-1][y+2] != empty && levels[current.current_level_id].map[x-1][y+2] != miner)
Mix_PlayChannel(-1,sounds.dropRock,0);
}
else if(levels[current.current_level_id].map[x+1][y+1] == empty && levels[current.current_level_id].map[x+1][y] == empty && ((levels[current.current_level_id].map[x][y+1] == rock) || (levels[current.current_level_id].map[x][y+1] == diamond)))
{
levels[current.current_level_id].map[x+1][y+1] = rock;
levels[current.current_level_id].flagMap[x+1][y+1] = TRUE;
levels[current.current_level_id].map[x][y] = empty;
levels[current.current_level_id].flagMap[x][y] = FALSE;
if(levels[current.current_level_id].map[x+1][y+2] != empty && levels[current.current_level_id].map[x+1][y+2] != miner)
Mix_PlayChannel(-1,sounds.dropRock,0);
}
}
void dropTilltheEmptyDiamond(int x , int y)
{
if(levels[current.current_level_id].map[x][y+1] == empty)
{
levels[current.current_level_id].map[x][y+1] = diamond;
levels[current.current_level_id].flagMap[x][y+1] = TRUE;
levels[current.current_level_id].map[x][y] = empty;
levels[current.current_level_id].flagMap[x][y] = FALSE;
}
else if(levels[current.current_level_id].map[x-1][y+1] == empty && levels[current.current_level_id].map[x-1][y] == empty && ((levels[current.current_level_id].map[x][y+1] == rock) || (levels[current.current_level_id].map[x][y+1] == diamond)))
{
levels[current.current_level_id].map[x-1][y+1] = diamond;
levels[current.current_level_id].flagMap[x-1][y+1] = TRUE;
levels[current.current_level_id].map[x][y] = empty;
levels[current.current_level_id].flagMap[x][y] = FALSE;
}
else if(levels[current.current_level_id].map[x+1][y+1] == empty && levels[current.current_level_id].map[x+1][y] == empty && ((levels[current.current_level_id].map[x][y+1] == rock) || (levels[current.current_level_id].map[x][y+1] == diamond)))
{
levels[current.current_level_id].map[x+1][y+1] = diamond;
levels[current.current_level_id].flagMap[x+1][y+1] = TRUE;
levels[current.current_level_id].map[x][y] = empty;
levels[current.current_level_id].flagMap[x][y] = FALSE;
}
}
void moveSpider(int x,int y,int* preDirection)
{
if(*preDirection == 1 && levels[current.current_level_id].map[x][y-1] == empty)
{
levels[current.current_level_id].map[x][y-1] = spider;
levels[current.current_level_id].map[x][y] = empty;
}
else
{
if(*preDirection == 1)
*preDirection = 2;
if(*preDirection == 2 && levels[current.current_level_id].map[x+1][y] == empty)
{
levels[current.current_level_id].map[x+1][y] = spider;
levels[current.current_level_id].map[x][y] = empty;
}
else
{
if(*preDirection == 2)
*preDirection = 3;
if(*preDirection == 3 && levels[current.current_level_id].map[x][y+1] == empty)
{
levels[current.current_level_id].map[x][y+1] = spider;
levels[current.current_level_id].map[x][y] = empty;
}
else
{
if(*preDirection == 3)
*preDirection = 4;
if(*preDirection == 4 && levels[current.current_level_id].map[x-1][y] == empty)
{
levels[current.current_level_id].map[x-1][y] = spider;
levels[current.current_level_id].map[x][y] = empty;
}
else
{
if(*preDirection == 4)
*preDirection = 1;
}
}
}
}
}
void searchAndDropRock(void)
{
for(j = 0 ; j < levels[current.current_level_id].height ; j++)
{
for(i = 0 ; i < levels[current.current_level_id].width ; i++)
{
if(levels[current.current_level_id].map[i][j] == rock && levels[current.current_level_id].flagMap[i][j] == 0)
{
dropTilltheEmptyRock(i,j);
}
}
}
for(j = 0 ; j < levels[current.current_level_id].height ; ++j)
{
for(i = 0 ; i < levels[current.current_level_id].width ; ++i)
levels[current.current_level_id].flagMap[i][j] = 0;
}
}
void searchAndDropDiamond(void)
{
for(j = 0 ; j < levels[current.current_level_id].height ; j++)
{
for(i = 0 ; i < levels[current.current_level_id].width ; i++)
{
if(levels[current.current_level_id].map[i][j] == diamond && levels[current.current_level_id].flagMap[i][j] == 0)
{
dropTilltheEmptyDiamond(i,j);
}
}
}
for(j = 0 ; j < levels[current.current_level_id].height ; ++j)
{
for(i = 0 ; i < levels[current.current_level_id].width ; ++i)
levels[current.current_level_id].flagMap[i][j] = 0;
}
}
void boardIssue(void)
{
SDL_Surface* surf[TEXT_NUMBER] = {'\0'};
boards[0].message = intToString(current.reachedScore,0); /* scoreBoard */
boards[1].message = intToString(levels[current.current_level_id].totalDiamondNumber,1); /* diamondBoard */
boards[2].message = intToString(current.current_level_id+1,2); /* levelBoard */
boards[3].message = intToString(current.printTime,3); /* timeBoard */
boards[4].message = "Start Game";
boards[5].message = "How To Play";
boards[6].message = "Exit Game";
boards[7].message = "ESC";
if(state.endGame)
{
boards[4].message = "Score";
boards[5].message = "Please Enter to Quit !";
}
for(i = 0 ; i < TEXT_NUMBER ; ++i)
{
surf[i] = TTF_RenderText_Blended(boards[i].font , boards[i].message ,boards[i].color);
if (surf[i] == NULL)
{
TTF_CloseFont(boards[i].font);
fprintf(stderr,"surf[%d] could not be loaded ! TTF_Error() : %s\n",i,TTF_GetError());
exit(-1);
}
}
for(i = 0 ; i < TEXT_NUMBER ; ++i)
{
boards[i].texture = SDL_CreateTextureFromSurface(gameTools.renderer ,surf[i]);
if (boards[i].texture == NULL)
{
fprintf(stderr,"boards[%d].texture could not be loaded ! TTF_Error() : %s\n",i,TTF_GetError());
exit(-1);
}
}
for(i = 0 ; i < TEXT_NUMBER ; ++i)
SDL_FreeSurface(surf[i]);
}
char* intToString(int number,int boardNumber)
{
int i = 0 , digitNumber = 0;
int tempNumber = number;
char* message;
char head = '0';
if(state.endGame)
head = ' ';
if(boardNumber == 0)
{
message = calloc(sizeof(char),10);
for(i = 0 ; i < 9 ; ++i)
{
message[i] = head;
}
message[i] = '\0';
if(tempNumber == 0)
return message;
else
{
while(tempNumber > 0)
{
tempNumber /= 10;
++digitNumber;
}
i = 8;
while(digitNumber > 0)
{
*(message+i) = 48 + number % 10;
number /= 10;
--digitNumber, --i;
}
return message;
}
}
else if(boardNumber == 1 || boardNumber == 3)
{
message = calloc(sizeof(char),4);
for(i = 0 ; i < 3 ; ++i)
{
message[i] = '0';
}
message[i] = '\0';
if(tempNumber == 0)
return message;
else
{
while(tempNumber > 0)
{
tempNumber /= 10;
++digitNumber;
}
i = 2;
while(digitNumber > 0)
{
*(message+i) = 48 + number % 10;
number /= 10;
--digitNumber, --i;
}
return message;
}
}
else if(boardNumber == 2)
{
message = calloc(sizeof(char),3);
for(i = 0 ; i < 2 ; ++i)
{
message[i] = '0';
}
message[i] = '\0';
if(tempNumber == 0)
return message;
else
{
while(tempNumber > 0)
{
tempNumber /= 10;
++digitNumber;
}
i = 1;
while(digitNumber > 0)
{
*(message+i) = 48 + number % 10;
number /= 10;
--digitNumber, --i;
}
return message;
}
}
else
{
message = calloc(sizeof(char),3);
for(i = 0 ; i < 2 ; ++i)
{
message[i] = '0';
}
message[i] = '\0';
return message;
}
}
void checkStatus(void)
{
deathCheck();
if((levels[current.current_level_id].diamond_number <= current.collectedDiamond)&&(current.levelUpFlag))
{
levels[current.current_level_id].map[levels[current.current_level_id].levelUpX][levels[current.current_level_id].levelUpY] = levelPort;
Mix_PlayChannel(-1,sounds.levelUp,0);
current.levelUpFlag = FALSE;
}
}
void goNextLevel(void)
{
current.levelUpFlag = TRUE;
levels[current.current_level_id].levelScore = current.reachedScore;
++current.current_level_id;
if(current.current_level_id == LEVEL_NUMBER)
{
Mix_HaltMusic();
if( Mix_PlayingMusic() == 0 )
{
Mix_PlayMusic( sounds.endGame, -1 );
}
else
{
if( Mix_PausedMusic() == 1 ) Mix_ResumeMusic();
else Mix_PauseMusic();
}
state.endGame = TRUE;
--current.current_level_id;
}
current.collectedDiamond = 0;
}
void deathCheck(void)
{
for(j = 0 ; j < levels[current.current_level_id].height ; ++j)
{
for(i = 0 ; i < levels[current.current_level_id].width ; ++i)
{
if(levels[current.current_level_id].map[i][j] == rock && levels[current.current_level_id].map[i][j+1] == miner && !(levels[current.current_level_id].deathFlag[i][j+1] == -1))
{
levels[current.current_level_id].map[i][j] = empty;
levels[current.current_level_id].map[i][j+1] = rock;
Mix_PlayChannel(-1,sounds.gameover,0);
goBackToLevel();
}
}
}
}
void fillTrue(void)
{
for(j = 0 ; j < levels[current.current_level_id].height ; ++j)
{
for(i = 0 ; i < levels[current.current_level_id].width ; ++i)
{
if(levels[current.current_level_id].map[i][j] == rock && (levels[current.current_level_id].map[i][j+1] == earth || levels[current.current_level_id].map[i][j+1] == diamond))
{
levels[current.current_level_id].deathFlag[i][j+1] = TRUE;
}
}
}
}
void getTotalDiamondNumber(void)
{
for(j = 0 ; j < levels[current.current_level_id].height ; ++j)
{
for(i = 0 ; i < levels[current.current_level_id].width ; ++i)
{
if(levels[current.current_level_id].map[i][j] == diamond)
{
++levels[current.current_level_id].totalDiamondNumber;
}
}
}
}
void prepLevel(void)
{
getTotalDiamondNumber();
}
void goBackToLevel(void)
{
for(j = 0 ; j < levels[current.current_level_id].height ; j++)
{
for(i = 0 ; i < levels[current.current_level_id].width ; i++)
{
levels[current.current_level_id].map[i][j] = levels[current.current_level_id].saveMap[i][j];
}
}
levels[current.current_level_id].totalDiamondNumber += current.collectedDiamond;
current.collectedDiamond = 0;
if(current.current_level_id != 0) current.reachedScore = levels[current.current_level_id - 1].levelScore;
else current.reachedScore = 0;
current.levelUpFlag = TRUE;
}
void frameSpeedIssues(void)
{
if(current.frameSpeed > MAX_FRAME_SPEED)
current.frameSpeed = 0;
else
current.frameSpeed += 1;
}
void timeCalculating(void)
{
timeSum = 0;
for(i = 0 ; i < current.current_level_id ; ++i)
timeSum += (levels[i].elapsedTime + levels[i].pausePassedTime);
levels[current.current_level_id].elapsedTime = (SDL_GetTicks()+oldTime) * 0.001 - timeSum;
levels[current.current_level_id].elapsedTime -= levels[current.current_level_id].pausePassedTime;
current.printTime = levels[current.current_level_id].time - levels[current.current_level_id].elapsedTime;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.