Dataset Viewer (First 5GB)
added
stringdate 2024-11-18 17:54:19
2024-11-19 03:39:31
| created
timestamp[s]date 1970-01-01 00:04:39
2023-09-06 04:41:57
| id
stringlengths 40
40
| metadata
dict | source
stringclasses 1
value | text
stringlengths 13
8.04M
| score
float64 2
4.78
| int_score
int64 2
5
|
---|---|---|---|---|---|---|---|
2024-11-18T17:59:45.382671+00:00 | 2018-10-26T03:19:03 | c5c7d46e02467a9178c30a6a064556faefb501d7 | {
"blob_id": "c5c7d46e02467a9178c30a6a064556faefb501d7",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-26T03:19:03",
"content_id": "e67dcb21c8b2658003c5371f0baa76984ecd2a5a",
"detected_licenses": [
"MIT"
],
"directory_id": "0e3c919dfcef7c6815e6709faabb474595723546",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": "2018-10-26T03:18:05",
"gha_event_created_at": "2018-10-26T03:18:05",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 154771044,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2203,
"license": "MIT",
"license_type": "permissive",
"path": "/01 - Independent Study/UTAustinX_610/TExaSware/C8_SwitchLED/main.c",
"provenance": "stackv2-0000.json.gz:64953",
"repo_name": "RyanTruran/EmbeddedSystems.Playground",
"revision_date": "2018-10-26T03:19:03",
"revision_id": "0374b601ce9138d730d15acd4071275315e316d7",
"snapshot_id": "4c00fff3cbb1cfe0cbefd0b1bd53e44f5d28f10a",
"src_encoding": "ISO-8859-1",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RyanTruran/EmbeddedSystems.Playground/0374b601ce9138d730d15acd4071275315e316d7/01 - Independent Study/UTAustinX_610/TExaSware/C8_SwitchLED/main.c",
"visit_date": "2021-09-25T21:56:03.070406"
} | stackv2 | /*
Runs on TM4C123, Jonathan Valvano 6/17/2013
Module Number: C8
Module Title: Switch controls light
Module Statement: Design two systems that include a switch and LED. The analog system includes
just the switch and LED, and the digital system includes a microcontroller. The switch controls
whether an LED is turned on/off using negative logic. In particular, if the switch is pressed
the LED is off, and if the switch is not pressed the LED is on.
Learning Objectives:
Understanding basic circuit elements like source, ground, switch, LED and resistors.
Application of Ohms Law
Analog circuit design and construction
Interfacing circuit elements to a microcontroller
Programming simple logic.
*/
// PD3 is an output to LED output, positive logic
// PD0 is an input from switch, positive logic
// to set the switch in the simulator type this into command window
// PORTD = 1
// to release the switch in the simulator type this into command window
// PORTD = 0
#define SYSCTL_RCGC2_R (*((volatile unsigned long *)0x400FE108))
#define GPIO_PORTD_DATA_R (*((volatile unsigned long *)0x400073FC))
#define GPIO_PORTD_DIR_R (*((volatile unsigned long *)0x40007400))
#define GPIO_PORTD_AFSEL_R (*((volatile unsigned long *)0x40007420))
#define GPIO_PORTD_DEN_R (*((volatile unsigned long *)0x4000751C))
#define GPIO_PORTD_AMSEL_R (*((volatile unsigned long *)0x40007528))
#define GPIO_PORTD_PCTL_R (*((volatile unsigned long *)0x4000752C))
unsigned long in,out;
int main(void){ unsigned long volatile delay;
SYSCTL_RCGC2_R |= 0x08; // Port D clock
delay = SYSCTL_RCGC2_R; // wait 3-5 bus cycles
GPIO_PORTD_DIR_R |= 0x08; // PD3 output
GPIO_PORTD_DIR_R &= ~0x01; // PD0 input
GPIO_PORTD_AFSEL_R &= ~0x09; // not alternative
GPIO_PORTD_AMSEL_R &= ~0x09; // no analog
GPIO_PORTD_PCTL_R &= ~0x0000F00F; // bits for PD3, PD0
GPIO_PORTD_DEN_R |= 0x09; // enable PD3, PD0
while(1){
in = (GPIO_PORTD_DATA_R&0x01); // in 0 if not pressed, 1 if pressed
out = (in^0x01)<<3; // out 8 if not pressed, 0 if switch pressed
GPIO_PORTD_DATA_R = out;
}
}
| 2.890625 | 3 |
2024-11-18T17:59:45.841807+00:00 | 2021-02-17T00:20:24 | 7b52d9ad341f3fcbe2668fecc9e742585cdf8975 | {
"blob_id": "7b52d9ad341f3fcbe2668fecc9e742585cdf8975",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-17T00:20:24",
"content_id": "fac9494869fda0aa3c1c52c5801fd4206f3bfde2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "30e028fe05e6f72639c9c67e628179c4bb113d41",
"extension": "c",
"filename": "macroexpand.C",
"fork_events_count": 0,
"gha_created_at": "2018-07-16T18:38:17",
"gha_event_created_at": "2021-01-18T03:43:04",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 141178870,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5202,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/lib/hobbes/lang/macroexpand.C",
"provenance": "stackv2-0000.json.gz:65081",
"repo_name": "smunix/hobbes",
"revision_date": "2021-02-17T00:20:24",
"revision_id": "f0dff6e0d0c38aee704b2cb1812097a24511d009",
"snapshot_id": "a9410f99c8317cd8fe94a968b550576cda4dbc1c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/smunix/hobbes/f0dff6e0d0c38aee704b2cb1812097a24511d009/lib/hobbes/lang/macroexpand.C",
"visit_date": "2021-08-01T23:54:34.080921"
} | stackv2 |
#include <hobbes/lang/macroexpand.H>
#include <hobbes/lang/tylift.H>
namespace hobbes {
// walk the expression tree, find all macro references, and expand them
// (because this should be called after type inference, we need to preserve explicit type annotations)
struct macroExpandF : public switchExprC<ExprPtr> {
static ExprPtr mk(const QualTypePtr& qty, Expr* out) {
out->type(qty);
return ExprPtr(out);
}
static ExprPtr mk(const MonoTypePtr& mty, Expr* out) {
return mk(qualtype(mty), out);
}
static ExprPtr mk(const Expr* src, Expr* out) {
return mk(src->type(), out);
}
ExprPtr withConst(const Expr* v) const { return mk(v, v->clone()); }
ExprPtr with(const Fn* v) const { return mk(v, new Fn(v->varNames(), switchOf(v->body(), *this), v->la())); }
ExprPtr with(const MkArray* v) const { return mk(v, new MkArray(switchOf(v->values(), *this), v->la())); }
ExprPtr with(const MkVariant* v) const { return mk(v, new MkVariant(v->label(), switchOf(v->value(), *this), v->la())); }
ExprPtr with(const MkRecord* v) const { return mk(v, new MkRecord(switchOf(v->fields(), *this), v->la())); }
ExprPtr with(const AIndex* v) const { return mk(v, new AIndex(switchOf(v->array(), *this), switchOf(v->index(), *this), v->la())); }
ExprPtr with(const Proj* v) const { return mk(v, new Proj(switchOf(v->record(), *this), v->field(), v->la())); }
ExprPtr with(const Assump* v) const { return mk(v, new Assump(switchOf(v->expr(), *this), v->ty(), v->la())); }
ExprPtr with(const Case* v) const {
ExprPtr de = v->defaultExpr();
if (de.get()) { de = switchOf(de, *this); }
return mk(v, new Case(switchOf(v->variant(), *this), switchOf(v->bindings(), *this), de, v->la()));
}
ExprPtr with(const Switch* v) const {
ExprPtr de = v->defaultExpr();
if (de) { de = switchOf(de, *this); }
return mk(v, new Switch(switchOf(v->expr(), *this), switchOf(v->bindings(), *this), de, v->la()));
}
ExprPtr with(const Var* v) const {
if (v->value() == "and") {
return macroEtaLiftAnd(v->la());
} else if (v->value() == "or") {
return macroEtaLiftOr(v->la());
} else {
return mk(v, v->clone());
}
}
ExprPtr with(const Let* v) const {
return mk(v, new Let(v->var(), switchOf(v->varExpr(), *this), switchOf(v->bodyExpr(), *this), v->la()));
}
ExprPtr with(const LetRec* v) const {
LetRec::Bindings bs;
for (const auto& b : v->bindings()) {
bs.push_back(LetRec::Binding(b.first, switchOf(b.second, *this)));
}
return mk(v, new LetRec(bs, switchOf(v->bodyExpr(), *this), v->la()));
}
ExprPtr with(const App* v) const {
Var* fn = is<Var>(v->fn());
if (fn && fn->value() == "and") {
return macroExpandAnd(switchOf(v->args(), *this), v->la());
} else if (fn && fn->value() == "or") {
return macroExpandOr(switchOf(v->args(), *this), v->la());
} else {
return mk(v, new App(switchOf(v->fn(), *this), switchOf(v->args(), *this), v->la()));
}
}
ExprPtr with(const Assign* v) const {
return mk(v, new Assign(switchOf(v->left(), *this), switchOf(v->right(), *this), v->la()));
}
ExprPtr with(const Pack* v) const {
return mk(v, new Pack(switchOf(v->expr(), *this), v->la()));
}
ExprPtr with(const Unpack* v) const {
return mk(v, new Unpack(v->varName(), switchOf(v->package(), *this), switchOf(v->expr(), *this), v->la()));
}
// x and y = if x then y else false
static ExprPtr macroExpandAnd(const Exprs& es, const LexicalAnnotation& la) {
MonoTypePtr tbool = MonoTypePtr(Prim::make("bool"));
QualTypePtr tbfn = qualtype(Func::make(tuplety(list(tbool, tbool, tbool)), tbool));
return mk(tbool, new App(mk(tbfn, new Var("if", la)), list(es[0], es[1], mk(tbool, new Bool(false, la))), la));
}
// and => \(x,y).x and y
static ExprPtr macroEtaLiftAnd(const LexicalAnnotation& la) {
MonoTypePtr tbool = MonoTypePtr(Prim::make("bool"));
QualTypePtr tafn = qualtype(Func::make(tuplety(list(tbool, tbool)), tbool));
return mk(tafn, new Fn(list<std::string>("x", "y"), macroExpandAnd(list(mk(tbool, new Var("x", la)), mk(tbool, new Var("y", la))), la), la));
}
// x or y = if x then true else y
static ExprPtr macroExpandOr(const Exprs& es, const LexicalAnnotation& la) {
MonoTypePtr tbool = MonoTypePtr(Prim::make("bool"));
QualTypePtr tbfn = qualtype(Func::make(tuplety(list(tbool, tbool, tbool)), tbool));
return mk(tbool, new App(mk(tbfn, new Var("if", la)), list(es[0], mk(tbool, new Bool(true, la)), es[1]), la));
}
// or => \(x,y).x or y
static ExprPtr macroEtaLiftOr(const LexicalAnnotation& la) {
MonoTypePtr tbool = MonoTypePtr(Prim::make("bool"));
QualTypePtr tafn = qualtype(Func::make(tuplety(list(tbool, tbool)), tbool));
return mk(tafn, new Fn(list<std::string>("x", "y"), macroExpandOr(list(mk(tbool, new Var("x", la)), mk(tbool, new Var("y", la))), la), la));
}
};
ExprPtr macroExpand(const ExprPtr& e) {
return switchOf(e, macroExpandF());
}
void initMacroEnvironment(const TEnvPtr& tenv) {
tenv->bind("and", prim<bool(bool,bool)>());
tenv->bind("or", prim<bool(bool,bool)>());
}
}
| 2.171875 | 2 |
2024-11-18T17:59:45.921353+00:00 | 2019-01-23T15:06:00 | 6876d9197d7b19644ccb99e46586273d1aa1add8 | {
"blob_id": "6876d9197d7b19644ccb99e46586273d1aa1add8",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-23T15:06:00",
"content_id": "d215f6d0cae9785c5dffbf3ce9f5758046683382",
"detected_licenses": [
"MIT"
],
"directory_id": "4ab196d49cdeeca362d394464adc7572f3e9f0ea",
"extension": "c",
"filename": "wait.c",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 162658011,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1726,
"license": "MIT",
"license_type": "permissive",
"path": "/Assignments/PA0/CSC501-PA0/csc501-lab0/TMP/wait.c",
"provenance": "stackv2-0000.json.gz:65209",
"repo_name": "jubeenshah/CSC501-Operating-System",
"revision_date": "2019-01-23T15:06:00",
"revision_id": "9e6fdf6bdcf2a462f6fe6d0fa48b1b77f74b0ff0",
"snapshot_id": "60875bf379540eff378a924116c69ed375bc610d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jubeenshah/CSC501-Operating-System/9e6fdf6bdcf2a462f6fe6d0fa48b1b77f74b0ff0/Assignments/PA0/CSC501-PA0/csc501-lab0/TMP/wait.c",
"visit_date": "2020-04-12T17:48:36.918892"
} | stackv2 | /* wait.c - wait */
#include <conf.h>
#include <kernel.h>
#include <proc.h>
#include <q.h>
#include <sem.h>
#include <stdio.h>
#include "lab0.h"
extern int summarizeProcess;
/*------------------------------------------------------------------------
* wait -- make current process wait on a semaphore
*------------------------------------------------------------------------
*/
SYSCALL wait(int sem)
{
STATWORD ps;
struct sentry *sptr;
struct pentry *pptr;
unsigned int timeTaken;
unsigned int startTime = ctr1000;
if(!summarizeProcess) {
globalTableSystemCall[currpid][WAIT].systemCallName = "sys_wait";
globalTableSystemCall[currpid][WAIT].systemCallFrequency = globalTableSystemCall[currpid][WAIT].systemCallFrequency + 1;
}
disable(ps);
if (isbadsem(sem) || (sptr= &semaph[sem])->sstate==SFREE) {
restore(ps);
timeTaken = ctr1000 - startTime;
globalTableSystemCall[currpid][WAIT].systemCallAverageExecTime = globalTableSystemCall[currpid][WAIT].systemCallAverageExecTime + timeTaken;
return(SYSERR);
}
if (--(sptr->semcnt) < 0) {
(pptr = &proctab[currpid])->pstate = PRWAIT;
pptr->psem = sem;
enqueue(currpid,sptr->sqtail);
pptr->pwaitret = OK;
resched();
restore(ps);
timeTaken = ctr1000 - startTime;
globalTableSystemCall[currpid][WAIT].systemCallAverageExecTime = globalTableSystemCall[currpid][WAIT].systemCallAverageExecTime + timeTaken;
return pptr->pwaitret;
}
restore(ps);
timeTaken = ctr1000 - startTime;
globalTableSystemCall[currpid][WAIT].systemCallAverageExecTime = globalTableSystemCall[currpid][WAIT].systemCallAverageExecTime + timeTaken;
return(OK);
}
| 2.390625 | 2 |
2024-11-18T19:30:25.939406+00:00 | 2018-12-10T14:51:58 | 071eb1496330973268412f256571397a45f08fa8 | {
"blob_id": "071eb1496330973268412f256571397a45f08fa8",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-10T15:56:35",
"content_id": "c2f473c4909e61bf456aa21a392e5cd9ffae5319",
"detected_licenses": [
"BSD-2-Clause",
"BSD-3-Clause"
],
"directory_id": "293b19349d4bed21bcb15a7894dac8134494321b",
"extension": "h",
"filename": "advent.h",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 163318031,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 11205,
"license": "BSD-2-Clause,BSD-3-Clause",
"license_type": "permissive",
"path": "/advent.h",
"provenance": "stackv2-0003.json.gz:159291",
"repo_name": "AaronTraas/open-adventure",
"revision_date": "2018-12-10T14:51:58",
"revision_id": "8c6593ad0c06b58c2343869b7e1394645caa474a",
"snapshot_id": "d7c4044193d1c14bd9a21e2dac89d4f566e65278",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/AaronTraas/open-adventure/8c6593ad0c06b58c2343869b7e1394645caa474a/advent.h",
"visit_date": "2020-04-13T16:19:07.180265"
} | stackv2 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdarg.h>
#include <inttypes.h>
#include "dungeon.h"
/* LCG PRNG parameters tested against
* Knuth vol. 2. by the original authors */
#define LCG_A 1093L
#define LCG_C 221587L
#define LCG_M 1048576L
#define LINESIZE 1024
#define TOKLEN 5 // № sigificant characters in a token */
#define NDWARVES 6 // number of dwarves
#define PIRATE NDWARVES // must be NDWARVES-1 when zero-origin
#define DALTLC LOC_NUGGET // alternate dwarf location
#define INVLIMIT 7 // inverntory limit (№ of objects)
#define INTRANSITIVE -1 // illegal object number
#define GAMELIMIT 330 // base limit of turns
#define NOVICELIMIT 1000 // limit of turns for novice
#define WARNTIME 30 // late game starts at game.limit-this
#define FLASHTIME 50 // turns from first warning till blinding flash
#define PANICTIME 15 // time left after closing
#define BATTERYLIFE 2500 // turn limit increment from batteries
#define WORD_NOT_FOUND -1 // "Word not found" flag value for the vocab hash functions.
#define WORD_EMPTY 0 // "Word empty" flag value for the vocab hash functions
#define CARRIED -1 // Player is toting it
#define READ_MODE "rb" // b is not needed for POSIX but harmless
#define WRITE_MODE "wb" // b is not needed for POSIX but harmless
/* Special object-state values - integers > 0 are object-specific */
#define STATE_NOTFOUND -1 // 'Not found" state of treasures */
#define STATE_FOUND 0 // After discovered, before messed with
#define STATE_IN_CAVITY 1 // State value common to all gemstones
/* Special fixed object-state values - integers > 0 are location */
#define IS_FIXED -1
#define IS_FREE 0
/* Map a state property value to a negative range, where the object cannot be
* picked up but the value can be recovered later. Avoid colliding with -1,
* which has its own meaning. */
#define STASHED(obj) (-1 - game.prop[obj])
/*
* DESTROY(N) = Get rid of an item by putting it in LOC_NOWHERE
* MOD(N,M) = Arithmetic modulus
* TOTING(OBJ) = true if the OBJ is being carried
* AT(OBJ) = true if on either side of two-placed object
* HERE(OBJ) = true if the OBJ is at "LOC" (or is being carried)
* CNDBIT(L,N) = true if COND(L) has bit n set (bit 0 is units bit)
* LIQUID() = object number of liquid in bottle
* LIQLOC(LOC) = object number of liquid (if any) at LOC
* FORCED(LOC) = true if LOC moves without asking for input (COND=2)
* DARK(LOC) = true if location "LOC" is dark
* PCT(N) = true N% of the time (N integer from 0 to 100)
* GSTONE(OBJ) = true if OBJ is a gemstone
* FOREST(LOC) = true if LOC is part of the forest
* OUTSID(LOC) = true if locaiton not in the cave
* INSIDE(LOC) = true if locaiton is in the cave or the building at the beginning of the game
* INDEEP(LOC) = true if locaiton is in the Hall of Mists or deeper
* BUG(X) = report bug and exit
*/
#define DESTROY(N) move(N, LOC_NOWHERE)
#define MOD(N,M) ((N) % (M))
#define TOTING(OBJ) (game.place[OBJ] == CARRIED)
#define AT(OBJ) (game.place[OBJ] == game.loc || game.fixed[OBJ] == game.loc)
#define HERE(OBJ) (AT(OBJ) || TOTING(OBJ))
#define CNDBIT(L,N) (tstbit(conditions[L],N))
#define LIQUID() (game.prop[BOTTLE] == WATER_BOTTLE? WATER : game.prop[BOTTLE] == OIL_BOTTLE ? OIL : NO_OBJECT )
#define LIQLOC(LOC) (CNDBIT((LOC),COND_FLUID)? CNDBIT((LOC),COND_OILY) ? OIL : WATER : NO_OBJECT)
#define FORCED(LOC) CNDBIT(LOC, COND_FORCED)
#define DARK(DUMMY) (!CNDBIT(game.loc,COND_LIT) && (game.prop[LAMP] == LAMP_DARK || !HERE(LAMP)))
#define PCT(N) (randrange(100) < (N))
#define GSTONE(OBJ) ((OBJ) == EMERALD || (OBJ) == RUBY || (OBJ) == AMBER || (OBJ) == SAPPH)
#define FOREST(LOC) CNDBIT(LOC, COND_FOREST)
#define OUTSID(LOC) (CNDBIT(LOC, COND_ABOVE) || FOREST(LOC))
#define INSIDE(LOC) (!OUTSID(LOC) || LOC == LOC_BUILDING)
#define INDEEP(LOC) ((LOC) >= LOC_MISTHALL && !OUTSID(LOC))
#define BUG(x) bug(x, #x)
enum bugtype {
SPECIAL_TRAVEL_500_GT_L_GT_300_EXCEEDS_GOTO_LIST,
VOCABULARY_TYPE_N_OVER_1000_NOT_BETWEEN_0_AND_3,
INTRANSITIVE_ACTION_VERB_EXCEEDS_GOTO_LIST,
TRANSITIVE_ACTION_VERB_EXCEEDS_GOTO_LIST,
CONDITIONAL_TRAVEL_ENTRY_WITH_NO_ALTERATION,
LOCATION_HAS_NO_TRAVEL_ENTRIES,
HINT_NUMBER_EXCEEDS_GOTO_LIST,
SPEECHPART_NOT_TRANSITIVE_OR_INTRANSITIVE_OR_UNKNOWN,
ACTION_RETURNED_PHASE_CODE_BEYOND_END_OF_SWITCH,
};
enum speaktype {touch, look, hear, study, change};
enum termination {endgame, quitgame, scoregame};
enum speechpart {unknown, intransitive, transitive};
typedef enum {NO_WORD_TYPE, MOTION, OBJECT, ACTION, NUMERIC} word_type_t;
typedef enum scorebonus {none, splatter, defeat, victory} score_t;
/* Phase codes for action returns.
* These were at one time FORTRAN line numbers.
* The values don't matter, but perturb their order at your peril.
*/
typedef enum {
GO_TERMINATE,
GO_MOVE,
GO_TOP,
GO_CLEAROBJ,
GO_CHECKHINT,
GO_WORD2,
GO_UNKNOWN,
GO_DWARFWAKE,
} phase_codes_t;
typedef long vocab_t; // index into a vocabulary array */
typedef long verb_t; // index into an actions array */
typedef long obj_t; // index into the object array */
typedef long loc_t; // index into the locations array */
typedef long turn_t; // turn counter or threshold */
struct game_t {
int32_t lcg_x;
long abbnum; // How often to print long descriptions
score_t bonus; // What kind of finishing bonus we are getting
loc_t chloc; // pirate chest location
loc_t chloc2; // pirate chest alternate location
turn_t clock1; // # turns from finding last treasure to close
turn_t clock2; // # turns from warning till blinding flash
bool clshnt; // has player read the clue in the endgame?
bool closed; // whether we're all the way closed
bool closng; // whether it's closing time yet
bool lmwarn; // has player been warned about lamp going dim?
bool novice; // asked for instructions at start-up?
bool panic; // has player found out he's trapped?
bool wzdark; // whether the loc he's leaving was dark
bool blooded; // has player drunk of dragon's blood?
long conds; // min value for cond[loc] if loc has any hints
long detail; // level of detail in descriptions
/* dflag controls the level of activation of dwarves:
* 0 No dwarf stuff yet (wait until reaches Hall Of Mists)
* 1 Reached Hall Of Mists, but hasn't met first dwarf
* 2 Met first dwarf, others start moving, no knives thrown yet
* 3 A knife has been thrown (first set always misses)
* 3+ Dwarves are mad (increases their accuracy) */
long dflag;
long dkill; // dwarves killed
long dtotal; // total dwarves (including pirate) in loc
long foobar; // progress in saying "FEE FIE FOE FOO".
long holdng; // number of objects being carried
long igo; // # uses of "go" instead of a direction
long iwest; // # times he's said "west" instead of "w"
long knfloc; // knife location; 0 if none, -1 after caveat
turn_t limit; // lifetime of lamp
loc_t loc; // where player is now
loc_t newloc; // where player is going
turn_t numdie; // number of times killed so far
loc_t oldloc; // where player was
loc_t oldlc2; // where player was two moves ago
obj_t oldobj; // last object player handled
long saved; // point penalty for saves
long tally; // count of treasures gained
long thresh; // current threshold for endgame scoring tier
turn_t trndex; // FIXME: not used, remove on next format bump
turn_t trnluz; // # points lost so far due to turns used
turn_t turns; // counts commands given (ignores yes/no)
char zzword[TOKLEN + 1]; // randomly generated magic word from bird
long abbrev[NLOCATIONS + 1]; // has location been seen?
long atloc[NLOCATIONS + 1]; // head of object linked list per location
long dseen[NDWARVES + 1]; // true if dwarf has seen him
loc_t dloc[NDWARVES + 1]; // location of dwarves, initially hard-wired in
loc_t odloc[NDWARVES + 1]; // prior loc of each dwarf, initially garbage
loc_t fixed[NOBJECTS + 1]; // fixed location of object (if not IS_FREE)
obj_t link[NOBJECTS * 2 + 1]; // object-list links
loc_t place[NOBJECTS + 1]; // location of object
long hinted[NHINTS]; // hinted[i] = true iff hint i has been used.
long hintlc[NHINTS]; // hintlc[i] = how long at LOC with cond bit i
long prop[NOBJECTS + 1]; // object state array */
};
/*
* Game application settings - settings, but not state of the game, per se.
* This data is not saved in a saved game.
*/
struct settings_t {
FILE *logfp;
bool oldstyle;
bool prompt;
};
typedef struct {
char raw[LINESIZE];
vocab_t id;
word_type_t type;
} command_word_t;
typedef enum {EMPTY, RAW, TOKENIZED, GIVEN, PREPROCESSED, PROCESSING, EXECUTED} command_state_t;
typedef struct {
enum speechpart part;
command_word_t word[2];
verb_t verb;
obj_t obj;
command_state_t state;
} command_t;
extern struct game_t game;
extern struct settings_t settings;
extern bool get_command_input(command_t *);
extern void clear_command(command_t *);
extern void speak(const char*, ...);
extern void sspeak(int msg, ...);
extern void pspeak(vocab_t, enum speaktype, bool, int, ...);
extern void rspeak(vocab_t, ...);
extern void echo_input(FILE*, const char*, const char*);
extern bool silent_yes(void);
extern bool yes(const char*, const char*, const char*);
extern void juggle(obj_t);
extern void move(obj_t, loc_t);
extern loc_t put(obj_t, long, long);
extern void carry(obj_t, loc_t);
extern void drop(obj_t, loc_t);
extern int atdwrf(loc_t);
extern long setbit(int);
extern bool tstbit(long, int);
extern void set_seed(int32_t);
extern int32_t randrange(int32_t);
extern long score(enum termination);
extern void terminate(enum termination) __attribute__((noreturn));
extern int savefile(FILE *, int32_t);
extern int suspend(void);
extern int resume(void);
extern int restore(FILE *);
extern long initialise(void);
extern phase_codes_t action(command_t);
extern void state_change(obj_t, int);
extern bool is_valid(struct game_t);
void bug(enum bugtype, const char *) __attribute__((__noreturn__));
/* represent an empty command word */
static const command_word_t empty_command_word = {
.raw = "",
.id = WORD_EMPTY,
.type = NO_WORD_TYPE,
};
/* end */
| 2.015625 | 2 |
2024-11-18T19:30:26.377139+00:00 | 2020-06-08T20:55:15 | 96df20f442b25daae66a082e362715a6de4b86fb | {
"blob_id": "96df20f442b25daae66a082e362715a6de4b86fb",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-08T20:55:15",
"content_id": "cad2f4b43fdebf4f9a4509413b9d37a6a8327feb",
"detected_licenses": [
"MIT"
],
"directory_id": "5e30b5d1b1178e058aeffb0344f2c54a5c1e1561",
"extension": "c",
"filename": "uart.c",
"fork_events_count": 1,
"gha_created_at": "2020-01-09T19:09:51",
"gha_event_created_at": "2020-01-09T19:09:51",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 232884384,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1055,
"license": "MIT",
"license_type": "permissive",
"path": "/uart.c",
"provenance": "stackv2-0003.json.gz:159547",
"repo_name": "wieker/nrf52-cmake-blinky",
"revision_date": "2020-06-08T20:55:15",
"revision_id": "798986a88f42122507b259349e767c5fe886bd72",
"snapshot_id": "ec2b95a01f2a7e2616eb867f8e078717ca1f44fa",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wieker/nrf52-cmake-blinky/798986a88f42122507b259349e767c5fe886bd72/uart.c",
"visit_date": "2020-12-08T04:27:00.866701"
} | stackv2 | //
// Created by wieker on 1/17/20.
//
#include <legacy/nrf_drv_uart.h>
#include <sdk_config.h>
#include <nrf_delay.h>
nrf_drv_uart_t m_uart = NRF_DRV_UART_INSTANCE(0);
void uart_init()
{
nrf_drv_uart_config_t config = NRF_DRV_UART_DEFAULT_CONFIG;
config.pseltxd = 13;
config.pselrxd = NRF_UART_PSEL_DISCONNECTED;
config.pselcts = NRF_UART_PSEL_DISCONNECTED;
config.pselrts = NRF_UART_PSEL_DISCONNECTED;
config.baudrate = (nrf_uart_baudrate_t)NRF_LOG_BACKEND_UART_BAUDRATE;
nrfx_uart_init(&m_uart.uart,
(nrfx_uart_config_t const *)&config,
NULL);
}
int main() {
NRF_P0->DIRSET = 1 << 20 | 1 << 18 | 1 << 26 | 1 << 27;
uart_init();
while (1) {
NRF_P0->OUTSET = 1 << 20 | 1 << 18;
NRF_P0->OUTCLR = 1 << 26 | 1 << 27;
nrf_delay_ms(3000);
NRF_P0->OUTSET = 1 << 26 | 1 << 27;
NRF_P0->OUTCLR = 1 << 20 | 1 << 18;
nrf_delay_ms(3000);
nrfx_uart_tx(&m_uart.uart, (uint8_t *) "ok \r\n", 5);
}
}
| 2.09375 | 2 |
2024-11-18T19:30:26.554335+00:00 | 2017-05-08T15:19:17 | 07ae29750c1f685c1be4f75e2b5b2772b2395cc4 | {
"blob_id": "07ae29750c1f685c1be4f75e2b5b2772b2395cc4",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-08T15:19:17",
"content_id": "e923ab3a610c48ddc436cc0d6af4242a2351bd9e",
"detected_licenses": [
"ISC"
],
"directory_id": "ad5fd7bb38a230bc98f76eefb065c66877a33d5c",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 30546105,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7796,
"license": "ISC",
"license_type": "permissive",
"path": "/src/sysbin/init/main.c",
"provenance": "stackv2-0003.json.gz:159803",
"repo_name": "Alexis211/kogata",
"revision_date": "2017-05-08T15:19:17",
"revision_id": "d1aed44edf1bd6ab9cc11d7c8796051a5ae8e79d",
"snapshot_id": "a0b0a367384c4a4021fa9e71807fbc66d45f131e",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/Alexis211/kogata/d1aed44edf1bd6ab9cc11d7c8796051a5ae8e79d/src/sysbin/init/main.c",
"visit_date": "2021-06-13T20:00:57.119319"
} | stackv2 | #include <string.h>
#include <stdlib.h>
#include <proto/launch.h>
#include <kogata/syscall.h>
#include <kogata/debug.h>
#include <kogata/printf.h>
#include <kogata/btree.h>
bool loop_exec = true;
pid_t giosrv_pid = 0, login_pid = 0, lx_init_pid = 0;
void _parse_cmdline_iter(void* a, void* b) {
dbg_printf(" '%s' -> '%s'\n", a, b);
}
btree_t *parse_cmdline(const char* x) {
btree_t *ret = create_btree(str_key_cmp_fun, free_key_val);
ASSERT(ret != 0);
x = strchr(x, ' ');
if (x == 0) return ret;
while ((*x) != 0) {
while (*x == ' ') x++;
char* eq = strchr(x, '=');
char* sep = strchr(x, ' ');
if (sep == 0) {
if (eq == 0) {
btree_add(ret, strdup(x), strdup(x));
} else {
btree_add(ret, strndup(x, eq - x), strdup(eq + 1));
}
break;
} else {
if (eq == 0 || eq > sep) {
btree_add(ret, strndup(x, sep - x), strndup(x, sep - x));
} else {
btree_add(ret, strndup(x, eq - x), strndup(eq + 1, sep - eq - 1));
}
x = sep + 1;
}
}
btree_iter(ret, _parse_cmdline_iter);
return ret;
}
btree_t* read_cmdline() {
char cmdline_buf[256];
fd_t f = sc_open("io:/cmdline", FM_READ);
if (f == 0) return 0;
size_t len = sc_read(f, 0, 255, cmdline_buf);
cmdline_buf[len] = 0;
sc_close(f);
return parse_cmdline(cmdline_buf);
}
void setup_sys() {
fd_t sysdir_cfg = sc_open("config:/sysdir", FM_READ);
if (sysdir_cfg == 0) PANIC("[init] Could not read config:/sysdir");
char buf[256];
size_t l = sc_read(sysdir_cfg, 0, 255, buf);
buf[l] = 0;
sc_close(sysdir_cfg);
char* eol = strchr(buf, '\n');
if (eol) *eol = 0;
dbg_printf("[init] Using system directory %s\n", buf);
bool ok;
char* sep = strchr(buf, ':');
if (sep == 0) {
ok = sc_fs_subfs("sys", "root", buf, FM_READ | FM_MMAP | FM_READDIR);
} else {
*sep = 0;
ok = sc_fs_subfs("sys", buf, sep +1, FM_READ | FM_MMAP | FM_READDIR);
}
if (!ok) PANIC("[init] Could not bind root:/sys to sys:/");
}
void launch_giosrv(fd_pair_t *root_gip_chan) {
if (giosrv_pid != 0) return;
giosrv_pid = sc_new_proc();
if (giosrv_pid == 0) {
PANIC("[init] Could not create process for giosrv");
}
dbg_printf("[init] Setting up giosrv, pid: %d\n", giosrv_pid);
bool ok;
ok = sc_bind_fs(giosrv_pid, "io", "io");
if (!ok) PANIC("[init] Could not bind io:/ to giosrv");
ok = sc_bind_fs(giosrv_pid, "sys", "sys");
if (!ok) PANIC("[init] Could not bind sys:/ to giosrv");
ok = sc_bind_fs(giosrv_pid, "config", "config");
if (!ok) PANIC("[init] Could not bind config:/ to giosrv");
ok = sc_bind_fd(giosrv_pid, STD_FD_GIOSRV, root_gip_chan->a);
if (!ok) PANIC("[init] Could not bind root GIP channel FD to giosrv");
ok = sc_proc_exec(giosrv_pid, "sys:/bin/giosrv.bin");
if (!ok) PANIC("[init] Could not run giosrv.bin");
dbg_printf("[init] giosrv started.\n");
}
void launch_login(fd_pair_t *root_gip_chan) {
if (login_pid != 0) return;
login_pid = sc_new_proc();
if (login_pid == 0) {
PANIC("[init] Could not create process for login");
}
dbg_printf("[init] Setting up login, pid: %d\n", login_pid);
bool ok;
ok = sc_bind_fs(login_pid, "root", "root");
if (!ok) PANIC("[init] Could not bind root:/ to login");
ok = sc_bind_fs(login_pid, "sys", "sys");
if (!ok) PANIC("[init] Could not bind sys:/ to login");
ok = sc_bind_fs(login_pid, "config", "config");
if (!ok) PANIC("[init] Could not bind config:/ to login");
ok = sc_bind_fd(login_pid, STD_FD_GIP, root_gip_chan->b);
if (!ok) PANIC("[init] Could not bind root GIP channel FD to login");
ok = sc_proc_exec(login_pid, "sys:/bin/login.bin");
if (!ok) PANIC("[init] Could not run login.bin");
dbg_printf("[init] login started.\n");
}
void launch_lx_init(const char* lx_init_app, fd_pair_t *io_chan) {
if (lx_init_pid != 0) return;
lx_init_pid = sc_new_proc();
if (lx_init_pid == 0) {
PANIC("[init] Could not create process for lx_init");
}
dbg_printf("[init] Setting up lx_init, pid: %d\n", lx_init_pid);
bool ok;
ok = sc_bind_fs(lx_init_pid, "io", "io");
if (!ok) PANIC("[init] Could not bind io:/ to lx_init");
ok = sc_bind_fs(lx_init_pid, "root", "root");
if (!ok) PANIC("[init] Could not bind root:/ to lx_init");
ok = sc_bind_fs(lx_init_pid, "sys", "sys");
if (!ok) PANIC("[init] Could not bind sys:/ to lx_init");
ok = sc_bind_fs(lx_init_pid, "config", "config");
if (!ok) PANIC("[init] Could not bind config:/ to lx_init");
char app_path[256];
snprintf(app_path, 256, "/app/%s", lx_init_app);
ok = sc_bind_subfs(lx_init_pid, "app", "sys", app_path, FM_ALL_MODES);
if (!ok) PANIC("[init] Could not bind app:/ to lx_init");
ok = sc_bind_fd(lx_init_pid, STD_FD_STDOUT, io_chan->b);
if (!ok) PANIC("[init] Could not bind stdout channel to lx_init");
ok = sc_bind_fd(lx_init_pid, STD_FD_STDERR, io_chan->b);
if (!ok) PANIC("[init] Could not bind stderr channel to lx_init");
ok = sc_proc_exec(lx_init_pid, "sys:/bin/lx.bin");
if (!ok) PANIC("[init] Could not run lx.bin");
dbg_printf("[init] lx_init started\n");
}
void dump_all(fd_t fd) {
char buf[256];
while(true){
int n = sc_read(fd, 0, 255, buf);
if (n > 0) {
buf[n] = 0;
sc_dbg_print(buf);
} else {
break;
}
}
}
int run_lua(const char* lx_init_app) {
// Setup a channel for stdout/stderr printing
fd_pair_t io_chan;
io_chan = sc_make_channel(false);
if (io_chan.a == 0 || io_chan.b == 0) {
PANIC("[init] Could not create Lua emergency I/O channel.");
}
launch_lx_init(lx_init_app, &io_chan);
while(true) {
dump_all(io_chan.a);
proc_status_t s;
sc_proc_wait(0, false, &s);
if (s.pid != 0) {
if (s.pid == lx_init_pid) {
if (!loop_exec) {
dump_all(io_chan.a);
PANIC("[init] lx_init died!\n");
}
lx_init_pid = 0;
dbg_printf("[init] lx_init_app died, restarting.\n");
launch_lx_init(lx_init_app, &io_chan);
} else {
ASSERT(false);
}
}
sc_usleep(100000);
}
}
int run_no_lua() {
fd_pair_t root_gip_chan;
// Setup GIP channel for communication between giosrv and login
root_gip_chan = sc_make_channel(false);
if (root_gip_chan.a == 0 || root_gip_chan.b == 0) {
PANIC("[init] Could not create root GIP channel.");
}
// Launch giosrv && login
launch_giosrv(&root_gip_chan);
launch_login(&root_gip_chan);
// Make sure no one dies
while(true) {
proc_status_t s;
sc_proc_wait(0, false, &s);
if (s.pid != 0) {
if (s.pid == giosrv_pid) {
if (!loop_exec) PANIC("[init] giosrv died!\n");
giosrv_pid = 0;
dbg_printf("[init] giosrv died, restarting.\n");
launch_giosrv(&root_gip_chan);
} else if (s.pid == login_pid) {
if (!loop_exec) PANIC("[init] login died!\n");
login_pid = 0;
dbg_printf("[init] login died, restarting.\n");
launch_login(&root_gip_chan);
} else {
ASSERT(false);
}
}
sc_usleep(1000000);
}
}
int main(int argc, char **argv) {
dbg_print("[init] Starting up!\n");
// Read kernel cmdline
btree_t *cmdline = read_cmdline();
if (cmdline == 0) PANIC("[init] Could not parse cmdline");
// setup config:
if (btree_find(cmdline, "config") == 0) {
PANIC("[init] No config=xxx option specified on command line");
} else {
char* config = (char*)btree_find(cmdline, "config");
dbg_printf("[init] Loading system configuration: %s\n", config);
ASSERT(strlen(config) < 30);
char buf[50];
snprintf(buf, 50, "/config/%s", config);
bool ok = sc_fs_subfs("config", "root", buf, FM_READ | FM_WRITE | FM_MMAP | FM_READDIR);
if (!ok) PANIC("[init] Could not setup config:");
}
// Setup sys:
setup_sys();
if (btree_find(cmdline, "loop_exec") &&
strcmp(btree_find(cmdline, "loop_exec"), "true"))
loop_exec = false;
if (btree_find(cmdline, "lx_init_app")) {
run_lua(btree_find(cmdline, "lx_init_app"));
} else {
run_no_lua();
}
return 0;
}
/* vim: set ts=4 sw=4 tw=0 noet :*/
| 2.109375 | 2 |
2024-11-18T18:09:46.654755+00:00 | 2020-06-27T14:20:47 | 249fdaba9d0240359cffadbe930df2e406a38b75 | {
"blob_id": "249fdaba9d0240359cffadbe930df2e406a38b75",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-27T14:20:47",
"content_id": "4154a1c7cff68b7767e0bb7d549c8e8fb3916864",
"detected_licenses": [
"Unlicense"
],
"directory_id": "f79574d2c4a625df0188ad5399649126b136ad7c",
"extension": "h",
"filename": "helpers.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 260780556,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1354,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/helpers.h",
"provenance": "stackv2-0003.json.gz:313552",
"repo_name": "sgstechnical/portpopper",
"revision_date": "2020-06-27T14:20:47",
"revision_id": "4c3a8c929708029f673509984a850cd2804a194a",
"snapshot_id": "70d556ea7400c44b01f504239f12dc5db7299016",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sgstechnical/portpopper/4c3a8c929708029f673509984a850cd2804a194a/src/helpers.h",
"visit_date": "2022-11-09T01:03:07.475272"
} | stackv2 | #ifndef _HELPERS_H_
#define _HELPERS_H_
#define GLOBAL_VARIABLE static
#define INTERNAL static
#define LOCAL_VARIABLE static
#define INLINE inline
#define KB(x) ((x)*1024)
#define MB(x) ((x)*1024*1024)
typedef uint32_t b32;
typedef float f32;
#define SETBUF() setvbuf(stdout, NULL, _IONBF, BUFSIZ)
#if DEBUG_ENABLED
#define DEBUG(...) printf(__VA_ARGS__)
#else
#define DEBUG(...)
#endif
#define TEMP_BUFF_SIZE(x,s) char x[s]; x[0] = 0x00
#define TEMP_BUFF(b) TEMP_BUFF_SIZE(b,1024)
#define TEMP_PATH_BUFF(b) TEMP_BUFF_SIZE(b,MAX_PATH)
#define EXPAND_TEMP_BUFF(b) b,(sizeof(b))
#define create_string(b,...) snprintf(b,sizeof(b),__VA_ARGS__)
#define ARRAY_COUNT(x) (sizeof(x)/sizeof(x[0]))
#define clearStruct(s) memory_clear((void*)&s,sizeof(s))
//##############################################################################
//@ String helpers
//##############################################################################
void string_clear(char* str);
size_t string_copy(char* d, const char* s, size_t destMax);
size_t string_length(const char* string);
//##############################################################################
//@ Memory helpers
//##############################################################################
void memory_clear(void*p,size_t s);
void memory_copy(void* dest, void* src, int64_t length);
#endif
| 2.0625 | 2 |
2024-11-18T18:09:46.746201+00:00 | 2023-08-07T20:22:46 | 9facea0eae08b52fc9d5dd274179947a512d04f3 | {
"blob_id": "9facea0eae08b52fc9d5dd274179947a512d04f3",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-07T20:22:46",
"content_id": "046eaac4e11e421f0e474fcc14b03d98f53874cf",
"detected_licenses": [
"Zlib"
],
"directory_id": "d9ea45dbc964799991b9191ae620d2f150652a3d",
"extension": "h",
"filename": "commandlist.c.h",
"fork_events_count": 249,
"gha_created_at": "2013-05-23T22:22:58",
"gha_event_created_at": "2023-08-26T12:27:36",
"gha_language": "C",
"gha_license_id": "Zlib",
"github_id": 10254751,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 14949,
"license": "Zlib",
"license_type": "permissive",
"path": "/Backends/Graphics5/G5onG4/Sources/kinc/backend/graphics5/commandlist.c.h",
"provenance": "stackv2-0003.json.gz:313683",
"repo_name": "Kode/Kinc",
"revision_date": "2023-08-07T20:22:46",
"revision_id": "d90b7478b192c8270e0ee32c0c3ee18977becd7a",
"snapshot_id": "6ebb1cfa11c6e9ed0e153c486f573f1d7dca5664",
"src_encoding": "UTF-8",
"star_events_count": 283,
"url": "https://raw.githubusercontent.com/Kode/Kinc/d90b7478b192c8270e0ee32c0c3ee18977becd7a/Backends/Graphics5/G5onG4/Sources/kinc/backend/graphics5/commandlist.c.h",
"visit_date": "2023-08-08T16:50:01.534587"
} | stackv2 | #include <kinc/graphics4/graphics.h>
#include <kinc/graphics5/commandlist.h>
#include <kinc/graphics5/constantbuffer.h>
#include <kinc/graphics5/indexbuffer.h>
#include <kinc/graphics5/pipeline.h>
#include <kinc/graphics5/vertexbuffer.h>
#include <kinc/log.h>
#include <assert.h>
#include <string.h>
#ifdef KORE_MICROSOFT
#include <malloc.h>
#endif
#define WRITE(type, value) \
if (list->impl.commandIndex + sizeof(type) > KINC_G5ONG4_COMMANDS_SIZE) { \
kinc_log(KINC_LOG_LEVEL_ERROR, "Trying to write too many commands to the command list."); \
return; \
} \
*(type *)(&list->impl.commands[list->impl.commandIndex]) = value; \
list->impl.commandIndex += sizeof(type);
#define READ(type, var) \
if (index + sizeof(type) > KINC_G5ONG4_COMMANDS_SIZE) { \
kinc_log(KINC_LOG_LEVEL_ERROR, "Trying to read beyond the end of the command list?"); \
return; \
} \
type var = *(type *)(&list->impl.commands[index]); \
index += sizeof(type);
typedef enum command {
Clear,
Draw,
SetViewport,
SetScissor,
SetPipeline,
SetVertexBuffers,
SetIndexBuffer,
SetRenderTargets,
SetRenderTargetFace,
DrawInstanced,
SetSampler,
SetTexture,
SetImageTexture,
SetTextureFromRenderTarget,
SetTextureFromRenderTargetDepth,
SetVertexConstantBuffer,
SetFragmentConstantBuffer,
SetBlendConstant,
} command_t;
void kinc_g4_pipeline_get_constant_locations(kinc_g4_pipeline_t *state, kinc_g4_constant_location_t *vertex_locations,
kinc_g4_constant_location_t *fragment_locations, int *vertex_sizes, int *fragment_sizes, int *max_vertex,
int *max_fragment);
void kinc_g5_command_list_init(kinc_g5_command_list_t *list) {}
void kinc_g5_command_list_destroy(kinc_g5_command_list_t *list) {}
void kinc_g5_command_list_begin(kinc_g5_command_list_t *list) {
list->impl.commandIndex = 0;
}
void kinc_g5_command_list_end(kinc_g5_command_list_t *list) {}
void kinc_g5_command_list_clear(kinc_g5_command_list_t *list, struct kinc_g5_render_target *renderTarget, unsigned flags, unsigned color, float depth,
int stencil) {
WRITE(command_t, Clear);
WRITE(unsigned, flags);
WRITE(unsigned, color);
WRITE(float, depth);
WRITE(int, stencil);
}
void kinc_g5_command_list_render_target_to_framebuffer_barrier(kinc_g5_command_list_t *list, struct kinc_g5_render_target *renderTarget) {}
void kinc_g5_command_list_framebuffer_to_render_target_barrier(kinc_g5_command_list_t *list, struct kinc_g5_render_target *renderTarget) {}
void kinc_g5_command_list_texture_to_render_target_barrier(kinc_g5_command_list_t *list, struct kinc_g5_render_target *renderTarget) {}
void kinc_g5_command_list_render_target_to_texture_barrier(kinc_g5_command_list_t *list, struct kinc_g5_render_target *renderTarget) {}
void kinc_g5_command_list_draw_indexed_vertices(kinc_g5_command_list_t *list) {
kinc_g5_command_list_draw_indexed_vertices_from_to(list, 0, list->impl._indexCount);
}
void kinc_g5_command_list_draw_indexed_vertices_from_to(kinc_g5_command_list_t *list, int start, int count) {
WRITE(command_t, Draw);
WRITE(int, start);
WRITE(int, count);
}
void kinc_g5_command_list_draw_indexed_vertices_instanced(kinc_g5_command_list_t *list, int instanceCount) {
kinc_g5_command_list_draw_indexed_vertices_instanced_from_to(list, instanceCount, 0, list->impl._indexCount);
}
void kinc_g5_command_list_draw_indexed_vertices_instanced_from_to(kinc_g5_command_list_t *list, int instanceCount, int start, int count) {
WRITE(command_t, DrawInstanced);
WRITE(int, instanceCount);
WRITE(int, start);
WRITE(int, count);
}
void kinc_g5_command_list_viewport(kinc_g5_command_list_t *list, int x, int y, int width, int height) {
WRITE(command_t, SetViewport);
WRITE(int, x);
WRITE(int, y);
WRITE(int, width);
WRITE(int, height);
}
void kinc_g5_command_list_scissor(kinc_g5_command_list_t *list, int x, int y, int width, int height) {
WRITE(command_t, SetScissor);
WRITE(int, x);
WRITE(int, y);
WRITE(int, width);
WRITE(int, height);
}
void kinc_g5_command_list_disable_scissor(kinc_g5_command_list_t *list) {}
void kinc_g5_command_list_set_pipeline(kinc_g5_command_list_t *list, struct kinc_g5_pipeline *pipeline) {
WRITE(command_t, SetPipeline);
WRITE(kinc_g5_pipeline_t *, pipeline);
}
void kinc_g5_command_list_set_blend_constant(kinc_g5_command_list_t *list, float r, float g, float b, float a) {
WRITE(command_t, SetBlendConstant);
WRITE(float, r);
WRITE(float, g);
WRITE(float, b);
WRITE(float, a);
}
void kinc_g5_command_list_set_vertex_buffers(kinc_g5_command_list_t *list, struct kinc_g5_vertex_buffer **buffers, int *offsets, int count) {
WRITE(command_t, SetVertexBuffers);
WRITE(int, count);
for (int i = 0; i < count; ++i) {
WRITE(kinc_g5_vertex_buffer_t *, buffers[i]);
if (offsets[i] != 0) {
kinc_log(KINC_LOG_LEVEL_ERROR, "kinc_g5_command_list_set_vertex_buffers: offsets not supported");
}
}
}
void kinc_g5_command_list_set_index_buffer(kinc_g5_command_list_t *list, struct kinc_g5_index_buffer *buffer) {
WRITE(command_t, SetIndexBuffer);
WRITE(kinc_g5_index_buffer_t *, buffer);
list->impl._indexCount = buffer->impl.myCount;
}
void kinc_g5_command_list_set_render_targets(kinc_g5_command_list_t *list, struct kinc_g5_render_target **targets, int count) {
WRITE(command_t, SetRenderTargets);
WRITE(int, count);
for (int i = 0; i < count; ++i) {
WRITE(kinc_g5_render_target_t *, targets[i]);
}
}
void kinc_g5_command_list_upload_index_buffer(kinc_g5_command_list_t *list, struct kinc_g5_index_buffer *buffer) {}
void kinc_g5_command_list_upload_vertex_buffer(kinc_g5_command_list_t *list, struct kinc_g5_vertex_buffer *buffer) {}
void kinc_g5_command_list_upload_texture(kinc_g5_command_list_t *list, struct kinc_g5_texture *texture) {}
void kinc_g5_command_list_set_vertex_constant_buffer(kinc_g5_command_list_t *list, struct kinc_g5_constant_buffer *buffer, int offset, size_t size) {
WRITE(command_t, SetVertexConstantBuffer);
WRITE(kinc_g5_constant_buffer_t *, buffer);
}
void kinc_g5_command_list_set_fragment_constant_buffer(kinc_g5_command_list_t *list, struct kinc_g5_constant_buffer *buffer, int offset, size_t size) {
WRITE(command_t, SetFragmentConstantBuffer);
WRITE(kinc_g5_constant_buffer_t *, buffer);
}
void kinc_g5_command_list_execute(kinc_g5_command_list_t *list) {
kinc_g5_pipeline_t *current_pipeline = NULL;
int index = 0;
while (index < list->impl.commandIndex) {
READ(command_t, command);
switch (command) {
case Clear: {
READ(unsigned, flags);
READ(unsigned, color);
READ(float, depth);
READ(int, stencil);
kinc_g4_clear(flags, color, depth, stencil);
break;
}
case Draw: {
READ(int, start);
READ(int, count);
kinc_g4_draw_indexed_vertices_from_to(start, count);
break;
}
case SetViewport: {
READ(int, x);
READ(int, y);
READ(int, width);
READ(int, height);
kinc_g4_viewport(x, y, width, height);
break;
}
case SetScissor: {
READ(int, x);
READ(int, y);
READ(int, width);
READ(int, height);
kinc_g4_scissor(x, y, width, height);
break;
}
case SetPipeline: {
READ(kinc_g5_pipeline_t *, pipeline);
current_pipeline = pipeline;
kinc_g4_set_pipeline(&pipeline->impl.pipe);
break;
}
case SetVertexBuffers: {
READ(int, count);
#ifdef KORE_MICROSOFT
kinc_g4_vertex_buffer_t **buffers = (kinc_g4_vertex_buffer_t **)alloca(sizeof(kinc_g4_vertex_buffer_t *) * count);
#else
kinc_g4_vertex_buffer_t *buffers[count];
#endif
for (int i = 0; i < count; ++i) {
READ(kinc_g5_vertex_buffer_t *, buffer);
buffers[i] = &buffer->impl.buffer;
}
kinc_g4_set_vertex_buffers(buffers, count);
break;
}
case SetIndexBuffer: {
READ(kinc_g5_index_buffer_t *, buffer);
kinc_g4_set_index_buffer(&buffer->impl.buffer);
break;
}
case SetRenderTargets: {
READ(int, count);
#ifdef KORE_MICROSOFT
kinc_g4_render_target_t **buffers = (kinc_g4_render_target_t **)alloca(sizeof(kinc_g4_render_target_t *) * count);
#else
kinc_g4_render_target_t *buffers[count];
#endif
int first_framebuffer_index = -1;
for (int i = 0; i < count; ++i) {
READ(kinc_g5_render_target_t *, buffer);
if (i == 0) {
first_framebuffer_index = buffer->framebuffer_index;
}
buffers[i] = &buffer->impl.target;
}
if (first_framebuffer_index >= 0) {
if (count > 1) {
kinc_log(KINC_LOG_LEVEL_ERROR, "Rendering to backbuffer and render targets at the same time is not supported");
}
kinc_g4_restore_render_target();
}
else {
kinc_g4_set_render_targets(buffers, count);
}
break;
}
case SetRenderTargetFace: {
READ(kinc_g5_render_target_t *, target);
READ(int, face);
kinc_g4_set_render_target_face(&target->impl.target, face);
break;
}
case DrawInstanced: {
READ(int, instanceCount);
READ(int, start);
READ(int, count);
kinc_g4_draw_indexed_vertices_instanced_from_to(instanceCount, start, count);
break;
}
case SetSampler: {
assert(false);
// TODO
break;
}
case SetTexture: {
READ(kinc_g5_texture_unit_t, unit);
READ(kinc_g5_texture_t *, texture);
assert(KINC_G4_SHADER_TYPE_COUNT == KINC_G5_SHADER_TYPE_COUNT);
kinc_g4_texture_unit_t g4_unit;
memcpy(&g4_unit.stages[0], &unit.stages[0], KINC_G4_SHADER_TYPE_COUNT * sizeof(int));
kinc_g4_set_texture(g4_unit, &texture->impl.texture);
break;
}
case SetImageTexture: {
READ(kinc_g5_texture_unit_t, unit);
READ(kinc_g5_texture_t *, texture);
assert(KINC_G4_SHADER_TYPE_COUNT == KINC_G5_SHADER_TYPE_COUNT);
kinc_g4_texture_unit_t g4_unit;
memcpy(&g4_unit.stages[0], &unit.stages[0], KINC_G4_SHADER_TYPE_COUNT * sizeof(int));
kinc_g4_set_image_texture(g4_unit, &texture->impl.texture);
break;
}
case SetTextureFromRenderTarget: {
assert(false);
// TODO
break;
}
case SetTextureFromRenderTargetDepth: {
assert(false);
// TODO
break;
}
case SetVertexConstantBuffer: {
READ(kinc_g5_constant_buffer_t *, buffer);
(void)buffer;
(void)current_pipeline;
kinc_log(KINC_LOG_LEVEL_ERROR, "Constant buffers are not supported on G5onG4 at the moment.");
// if(current_pipeline == NULL) {
// kinc_log(KINC_LOG_LEVEL_ERROR, "Please set the pipeline before setting constant buffers.");
// } else {
// kinc_g4_constant_location_t *constant_locations = current_pipeline->impl.pipe.vertex_locations;
// int *sizes = current_pipeline->impl.pipe.vertex_sizes;
// char *data = buffer->data;
// for(int i = 0; i < current_pipeline->impl.pipe.vertex_count; ++i) {
// // kinc_g4_set
// // kinc_g4_set_vertex_constant_buffer(constant_locations[i], sizes[i], data);
// data += sizes[i];
// }
// }
break;
}
case SetFragmentConstantBuffer: {
READ(kinc_g5_constant_buffer_t *, buffer);
(void)buffer;
kinc_log(KINC_LOG_LEVEL_ERROR, "Constant buffers are not supported on G5onG4 at the moment.");
break;
}
case SetBlendConstant: {
READ(float, r);
READ(float, g);
READ(float, b);
READ(float, a);
kinc_g4_set_blend_constant(r, g, b, a);
}
default:
kinc_log(KINC_LOG_LEVEL_ERROR, "Unknown command %i\n", command);
return;
}
}
}
void kinc_g5_command_list_wait_for_execution_to_finish(kinc_g5_command_list_t *list) {
kinc_g4_flush();
}
void kinc_g5_command_list_get_render_target_pixels(kinc_g5_command_list_t *list, struct kinc_g5_render_target *render_target, uint8_t *data) {
kinc_log(KINC_LOG_LEVEL_ERROR, "kinc_g5_command_list_get_render_target_pixels not implemented");
}
void kinc_g5_command_list_set_render_target_face(kinc_g5_command_list_t *list, kinc_g5_render_target_t *texture, int face) {
WRITE(command_t, SetRenderTargetFace);
WRITE(kinc_g5_render_target_t *, texture);
WRITE(int, face);
}
void kinc_g5_command_list_set_texture(kinc_g5_command_list_t *list, kinc_g5_texture_unit_t unit, kinc_g5_texture_t *texture) {
WRITE(command_t, SetTexture);
WRITE(kinc_g5_texture_unit_t, unit);
WRITE(kinc_g5_texture_t *, texture);
}
void kinc_g5_command_list_set_sampler(kinc_g5_command_list_t *list, kinc_g5_texture_unit_t unit, kinc_g5_sampler_t *sampler) {
WRITE(command_t, SetSampler);
}
void kinc_g5_command_list_set_texture_from_render_target(kinc_g5_command_list_t *list, kinc_g5_texture_unit_t unit, kinc_g5_render_target_t *render_target) {
WRITE(command_t, SetTextureFromRenderTarget);
}
void kinc_g5_command_list_set_texture_from_render_target_depth(kinc_g5_command_list_t *list, kinc_g5_texture_unit_t unit,
kinc_g5_render_target_t *render_target) {
WRITE(command_t, SetTextureFromRenderTargetDepth);
}
void kinc_g5_command_list_set_image_texture(kinc_g5_command_list_t *list, kinc_g5_texture_unit_t unit, kinc_g5_texture_t *texture) {
WRITE(command_t, SetImageTexture);
WRITE(kinc_g5_texture_unit_t, unit);
WRITE(kinc_g5_texture_t *, texture);
}
bool kinc_g5_command_list_init_occlusion_query(kinc_g5_command_list_t *list, unsigned *occlusionQuery) {
return false;
}
void kinc_g5_command_list_delete_occlusion_query(kinc_g5_command_list_t *list, unsigned occlusionQuery) {}
void kinc_g5_command_list_render_occlusion_query(kinc_g5_command_list_t *list, unsigned occlusionQuery, int triangles) {}
bool kinc_g5_command_list_are_query_results_available(kinc_g5_command_list_t *list, unsigned occlusionQuery) {
return false;
}
void kinc_g5_command_list_get_query_result(kinc_g5_command_list_t *list, unsigned occlusionQuery, unsigned *pixelCount) {}
| 2.125 | 2 |
2024-11-18T18:09:47.174766+00:00 | 2020-12-20T17:32:53 | f1031ef481df2bdfce46cd7052bc07426e88877a | {
"blob_id": "f1031ef481df2bdfce46cd7052bc07426e88877a",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-20T17:32:53",
"content_id": "cb7f081cbb2d77398cad86b2d81dcb259f94d41f",
"detected_licenses": [
"MIT"
],
"directory_id": "c5f70ba06763419829e756c1a97afe46e2ccd215",
"extension": "c",
"filename": "ulong.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 189241832,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5390,
"license": "MIT",
"license_type": "permissive",
"path": "/samples/non_fatal_assert_type_operator/ulong.c",
"provenance": "stackv2-0003.json.gz:314325",
"repo_name": "aenachescu/nbp_old",
"revision_date": "2020-12-20T17:32:53",
"revision_id": "70eda61b598c4229d12c92020578da3fddd45015",
"snapshot_id": "69a3848aa5b43b1f35ed9599e95a33d9833055bc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aenachescu/nbp_old/70eda61b598c4229d12c92020578da3fddd45015/samples/non_fatal_assert_type_operator/ulong.c",
"visit_date": "2023-02-02T15:48:26.355866"
} | stackv2 | /*
No Bugs in Production (NBP)
https://github.com/aenachescu/nbp
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
SPDX-License-Identifier: MIT
Copyright (c) 2019-2020 Alin Enachescu <https://github.com/aenachescu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <nbp.h>
#include "../sample_utils.h"
#include <limits.h>
unsigned long int get_ulong()
{
return 2UL;
}
volatile unsigned long int ulong_min = 0;
volatile unsigned long int ulong_max = ULONG_MAX;
volatile unsigned long int ulong_ = 2UL;
NBP_TEST(non_fatal_assert_ulong_eq)
{
SAMPLE_SLEEP();
NBP_ASSERT_ULONG_EQ(
get_ulong(),
ulong_
);
NBP_ASSERT_ULONG_EQ(
get_ulong(),
ulong_,
NBP_ASSERT_FAILURE_MESSAGE("non fatal assert failed")
);
NBP_ASSERT_ULONG_EQ(
get_ulong(),
ulong_,
NBP_ASSERT_SUCCESS_MESSAGE("non fatal assert passed")
);
NBP_ASSERT_ULONG_EQ(
get_ulong(),
ulong_,
NBP_ASSERT_FAILURE_MESSAGE("non fatal assert failed"),
NBP_ASSERT_SUCCESS_MESSAGE("non fatal assert passed")
);
}
NBP_TEST(non_fatal_assert_ulong_ne)
{
SAMPLE_SLEEP();
NBP_ASSERT_ULONG_NE(
get_ulong(),
ulong_min
);
NBP_ASSERT_ULONG_NE(
get_ulong(),
ulong_min,
NBP_ASSERT_FAILURE_MESSAGE("non fatal assert failed")
);
NBP_ASSERT_ULONG_NE(
get_ulong(),
ulong_min,
NBP_ASSERT_SUCCESS_MESSAGE("non fatal assert passed")
);
NBP_ASSERT_ULONG_NE(
get_ulong(),
ulong_min,
NBP_ASSERT_FAILURE_MESSAGE("non fatal assert failed"),
NBP_ASSERT_SUCCESS_MESSAGE("non fatal assert passed")
);
}
NBP_TEST(non_fatal_assert_ulong_gt)
{
SAMPLE_SLEEP();
NBP_ASSERT_ULONG_GT(
get_ulong(),
ulong_min
);
NBP_ASSERT_ULONG_GT(
get_ulong(),
ulong_min,
NBP_ASSERT_FAILURE_MESSAGE("non fatal assert failed")
);
NBP_ASSERT_ULONG_GT(
get_ulong(),
ulong_min,
NBP_ASSERT_SUCCESS_MESSAGE("non fatal assert passed")
);
NBP_ASSERT_ULONG_GT(
get_ulong(),
ulong_min,
NBP_ASSERT_FAILURE_MESSAGE("non fatal assert failed"),
NBP_ASSERT_SUCCESS_MESSAGE("non fatal assert passed")
);
}
NBP_TEST(non_fatal_assert_ulong_ge)
{
SAMPLE_SLEEP();
NBP_ASSERT_ULONG_GE(
get_ulong(),
ulong_min
);
NBP_ASSERT_ULONG_GE(
get_ulong(),
ulong_,
NBP_ASSERT_FAILURE_MESSAGE("non fatal assert failed")
);
NBP_ASSERT_ULONG_GE(
get_ulong(),
ulong_min,
NBP_ASSERT_SUCCESS_MESSAGE("non fatal assert passed")
);
NBP_ASSERT_ULONG_GE(
get_ulong(),
ulong_,
NBP_ASSERT_FAILURE_MESSAGE("non fatal assert failed"),
NBP_ASSERT_SUCCESS_MESSAGE("non fatal assert passed")
);
}
NBP_TEST(non_fatal_assert_ulong_lt)
{
SAMPLE_SLEEP();
NBP_ASSERT_ULONG_LT(
get_ulong(),
ulong_max
);
NBP_ASSERT_ULONG_LT(
get_ulong(),
ulong_max,
NBP_ASSERT_FAILURE_MESSAGE("non fatal assert failed")
);
NBP_ASSERT_ULONG_LT(
get_ulong(),
ulong_max,
NBP_ASSERT_SUCCESS_MESSAGE("non fatal assert passed")
);
NBP_ASSERT_ULONG_LT(
get_ulong(),
ulong_max,
NBP_ASSERT_FAILURE_MESSAGE("non fatal assert failed"),
NBP_ASSERT_SUCCESS_MESSAGE("non fatal assert passed")
);
}
NBP_TEST(non_fatal_assert_ulong_le)
{
SAMPLE_SLEEP();
NBP_ASSERT_ULONG_LE(
get_ulong(),
ulong_max
);
NBP_ASSERT_ULONG_LE(
get_ulong(),
ulong_,
NBP_ASSERT_FAILURE_MESSAGE("non fatal assert failed")
);
NBP_ASSERT_ULONG_LE(
get_ulong(),
ulong_max,
NBP_ASSERT_SUCCESS_MESSAGE("non fatal assert passed")
);
NBP_ASSERT_ULONG_LE(
get_ulong(),
ulong_,
NBP_ASSERT_FAILURE_MESSAGE("non fatal assert failed"),
NBP_ASSERT_SUCCESS_MESSAGE("non fatal assert passed")
);
}
NBP_MODULE(non_fatal_assert_ulong)
{
NBP_TEST_RUN(non_fatal_assert_ulong_eq);
NBP_TEST_RUN(non_fatal_assert_ulong_ne);
NBP_TEST_RUN(non_fatal_assert_ulong_gt);
NBP_TEST_RUN(non_fatal_assert_ulong_ge);
NBP_TEST_RUN(non_fatal_assert_ulong_lt);
NBP_TEST_RUN(non_fatal_assert_ulong_le);
}
| 2.078125 | 2 |
2024-11-18T18:09:47.525849+00:00 | 2019-03-01T05:16:46 | f5a8a0c1fc2d845384820ed93d74d518f7e044b6 | {
"blob_id": "f5a8a0c1fc2d845384820ed93d74d518f7e044b6",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-01T05:16:46",
"content_id": "5cfa1d3a02ad0a868f09856ee2c0e75364b6bf02",
"detected_licenses": [
"MIT"
],
"directory_id": "5a17a3d150c4773318d397a46878d2fd74c0671f",
"extension": "c",
"filename": "shenghuo-ling.c",
"fork_events_count": 0,
"gha_created_at": "2018-12-26T11:38:10",
"gha_event_created_at": "2018-12-26T11:38:10",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 163173406,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1304,
"license": "MIT",
"license_type": "permissive",
"path": "/nitan/clone/book/shenghuo-ling.c",
"provenance": "stackv2-0003.json.gz:314584",
"repo_name": "cantona/NT6",
"revision_date": "2019-03-01T05:16:46",
"revision_id": "073f4d491b3cfe6bfbe02fbad12db8983c1b9201",
"snapshot_id": "e9adc7308619b614990fa64456c294fad5f07d61",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cantona/NT6/073f4d491b3cfe6bfbe02fbad12db8983c1b9201/nitan/clone/book/shenghuo-ling.c",
"visit_date": "2020-04-15T21:16:28.817947"
} | stackv2 | // shenghuo-ling 聖火令
#include <weapon.h>
#include <ansi.h>
inherit SWORD;
void create()
{
set_name("聖火令",({ "shenghuo ling", "shenghuo", "ling" }) );
set_weight(1000);
if( clonep() )
set_default_object(__FILE__);
else
{
set("unit", "把");
set("value", 10000);
set("material", "steel");
set("no_drop", "1");
set("long", "這是一柄兩尺來長的黑牌,非金非鐵。質地堅硬無比,\n"
"似透明,令中隱隱似有火焰飛騰,實則是令質映光,顏\n"
"色變幻。令上刻得有不少波斯文字。 \n");
set("wield_msg", HIY "$N“唰”的一聲,從腰間抽出一片黑黝的鐵牌握在手中。\n");
set("unwield_msg", HIY "$N將聖火令插回腰間。\n" NOR);
}
set("skill", ([
"name" : "shenghuo-ling",
"exp_required": 50000,
"family_name" : "明教",
"jing_cost" : 40,
"difficulty" : 30,
"max_skill" : 200,
"min_skill" : 100
]) );
init_sword(50);
setup();
} | 2 | 2 |
2024-11-18T18:09:47.619618+00:00 | 2021-03-28T07:27:07 | 5fe71d831ffb33666eaaab8d13b589491f1df646 | {
"blob_id": "5fe71d831ffb33666eaaab8d13b589491f1df646",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-28T07:27:07",
"content_id": "d722dc4c9346a77b4aeae66daee9d1156d795c1c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8717b4036064ce0abb764958bea682e2f4d406d4",
"extension": "h",
"filename": "mem_heap.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 352254136,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1172,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/mem_heap.h",
"provenance": "stackv2-0003.json.gz:314712",
"repo_name": "meilanli/mem_heap",
"revision_date": "2021-03-28T07:27:07",
"revision_id": "b8307e1cc36c548a9d8ccbee327488b1e804d077",
"snapshot_id": "b0e4d09c6f4127bb68b4299b5057071e1dd99e75",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/meilanli/mem_heap/b8307e1cc36c548a9d8ccbee327488b1e804d077/mem_heap.h",
"visit_date": "2023-03-31T23:27:38.880065"
} | stackv2 | #ifndef __MEM_HEAP_H
#define __MEM_HEAP_H
#include "stdint.h"
//以下为了方便MDK环境下自动获取剩余RAM起始地址
//其它平台,自行定义MEM_HEAP_BEGIN,MEM_HEAP_END即可
#define RAM_SIZE 48 //RAM内存总KB
#define RAM_BEGIN 0x20000000 //内存起始地址
#if defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
#define __CLANG_ARM
#endif
#if defined(__CC_ARM) || defined(__CLANG_ARM)
extern int Image$$RW_IRAM1$$ZI$$Limit;
#define MEM_HEAP_BEGIN (&Image$$RW_IRAM1$$ZI$$Limit)
#elif __ICCARM__
#pragma section="HEAP"
#define MEM_HEAP_BEGIN (__segment_end("HEAP"))
#else
extern int __bss_end;
#define MEM_HEAP_BEGIN (&__bss_end)
#endif
#ifdef __ICCARM__
// Use *.icf ram symbal, to avoid hardcode.
extern char __ICFEDIT_region_RAM_end__;
#define MEM_SRAM_END &__ICFEDIT_region_RAM_end__
#else
#define MEM_HEAP_END (RAM_BEGIN + RAM_SIZE * 1024)
#endif
struct MemHeapInfo
{
uint32_t used_num;
uint32_t used_size;
uint32_t total_size;
};
void *heap_malloc(uint32_t size);
void heap_free(void *free);
struct MemHeapInfo *heap_get_info(void);
#endif
| 2.125 | 2 |
2024-11-18T18:09:48.101756+00:00 | 2015-01-05T12:31:35 | 99a65f88c44f2becc11b1b0860051af579a61a91 | {
"blob_id": "99a65f88c44f2becc11b1b0860051af579a61a91",
"branch_name": "refs/heads/master",
"committer_date": "2015-01-05T12:31:35",
"content_id": "67564ea993ba49e3516267f78b69258b71a23ccc",
"detected_licenses": [
"MIT"
],
"directory_id": "a8ccfc3047ae314995569ad06cc757dfa60c1ae1",
"extension": "c",
"filename": "alternate_cmd.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 13755007,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15848,
"license": "MIT",
"license_type": "permissive",
"path": "/src/cli/alternate_cmd.c",
"provenance": "stackv2-0003.json.gz:315228",
"repo_name": "bfontaine/Dazibao",
"revision_date": "2015-01-05T12:31:35",
"revision_id": "76dbf14474d213eb7437f0e7ca0b8d65d8e9bebd",
"snapshot_id": "e8201472e338f2943c2fa573a787f1f8f6c62e9b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bfontaine/Dazibao/76dbf14474d213eb7437f0e7ca0b8d65d8e9bebd/src/cli/alternate_cmd.c",
"visit_date": "2021-01-23T08:56:29.962703"
} | stackv2 | #include <limits.h>
#include <locale.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "utils.h"
#include "mdazibao.h"
#include "alternate_cmd.h"
/** @file */
/** buffer size used in various functions */
#define BUFFSIZE 512
int check_option_add(int argc, char **argv, int *date_idx, int *compound_idx,
int *dz_idx, int *type_idx, int *input_idx) {
int idx = 0,
args_count = 0;
for (int i = 0; i < argc; i++) {
if (!strcmp(argv[i], "--type")) {
*type_idx = idx;
} else if ((strcmp(argv[i], "--date") == 0)) {
if (*date_idx < 0) {
*date_idx = idx;
}
} else if (strcmp(argv[i], "--dazibao") == 0) {
if (*dz_idx < 0) {
*dz_idx = idx;
}
} else if (strcmp(argv[i], "--compound") == 0) {
if (*compound_idx < 0) {
*compound_idx = idx;
}
} else if (strcmp(argv[i], "-") == 0) {
if (*input_idx < 0) {
*input_idx = idx;
argv[idx] = argv[i];
idx++;
args_count++;
}
} else {
/* if the current parameter is not an option */
argv[idx] = argv[i];
idx++;
args_count++;
}
}
return args_count;
}
int check_type_args(int argc, char *type_args, char *op_type, int f_dz) {
char * delim = ",";
char *tmp = strtok(op_type, delim);
int i = 0;
while (tmp != NULL) {
int tmp_type = tlv_str2type(tmp);
if (tmp_type == (char) -1) {
printf("unrecognized type %s\n", tmp);
return -1;
} else {
type_args[i] = tmp_type;
}
tmp = strtok(NULL, delim);
i++;
}
if (i != (argc + (f_dz >= 0 ? -1 : 0))) {
printf("args to option type too large\n");
return -1;
}
return 0;
}
int check_args(int argc, char **argv, int *f_dz, int *f_co, int *f_d) {
int date_size = 0,
compound_size = 0,
tmp_size = 0,
i;
for (i = 0; i < argc; i++) {
if (strcmp(argv[i],"-") == 0) {
continue;
} else if ( i == *f_dz) {
if ((tmp_size = check_dz_path(argv[i], R_OK)) < 0) {
printf("check dz arg failed :%s\n", argv[i]);
return -1;
}
} else if ( i >= *f_co) {
if ((tmp_size = check_tlv_path(argv[i], R_OK)) < 0) {
printf("check path arg failed :%s\n", argv[i]);
return -1;
}
compound_size += tmp_size;
} else {
tmp_size = check_tlv_path(argv[i], R_OK);
if (tmp_size < 0) {
printf("check arg failed :%s\n", argv[i]);
return -1;
}
}
/* check size file for tlv */
if ((*f_d <= *f_co) && (i >= *f_co)) {
date_size += compound_size +
TLV_SIZEOF_HEADER + TLV_SIZEOF_DATE;
} else {
date_size += tmp_size;
}
if (tmp_size > TLV_MAX_VALUE_SIZE) {
printf("tlv too large, %s\n",argv[i]);
return -1;
} else if (date_size > TLV_MAX_VALUE_SIZE) {
printf("tlv date too large, %s\n",argv[i]);
return -1;
} else if (compound_size > TLV_MAX_VALUE_SIZE) {
printf("tlv compound too large, %s\n",argv[i]);
return -1;
}
tmp_size = 0;
date_size = 0;
}
return 0;
}
int cmd_add(int argc, char **argv, char * daz) {
int f_date = -1,
f_compound = -1,
f_dz = -1,
f_type = -1,
f_input = -1;
char *type_args = NULL;
if (argc < 0) {
printf("error no args for add\n");
return -1;
}
argc = check_option_add(argc, argv, &f_date, &f_compound, &f_dz,
&f_type, &f_input);
if (f_type >= 0) {
type_args = (char *) malloc(sizeof(*type_args)* argc);
char *tmp = argv[f_type];
if (f_type < (argc -1)) {
/* deleted type args in argv*/
int i;
for (i = (f_type + 1); i < (argc); i++) {
argv[i-1] = argv[i];
}
/* shift flag if it after type args */
f_date = (f_date > f_type ? f_date -1 : f_date);
f_compound = (f_compound > f_type ? f_compound-1 :
f_compound);
f_input = (f_input > f_type ? f_input-1 : f_input);
f_dz = (f_dz > f_type ? f_dz-1 : f_dz);
}
argc--;
if (check_type_args(argc, type_args, tmp, f_dz) < 0) {
printf("check_args_no_op failed\n");
free(type_args);
return -1;
}
} else if ( argc > (f_dz >= 0 ? 1:0) + (f_input >= 0 ? 1:0)) {
printf("check_type_args failed\n");
return -1;
}
if (check_args(argc, argv, &f_dz, &f_compound, &f_date)) {
printf("check path args failed\n");
return -1;
}
if (action_add(argc, argv, f_compound, f_dz, f_date, f_input,
type_args, daz) == -1) {
printf("error action add\n");
return -1;
}
if (f_type >= 0) {
free(type_args);
}
return 0;
}
int action_add(int argc, char **argv, int f_co, int f_dz, int f_d, int f_in,
char *type, char *daz) {
dz_t daz_buf;
unsigned int buff_size_co = 0;
tlv_t tlv = NULL;
tlv_t buff_co = NULL;
tlv_t buff_d = NULL;
int i,j = 0;
if (dz_open(&daz_buf, daz, O_RDWR) < 0) {
fprintf(stderr, "failed open the dazibao\n");
return -1;
}
f_d = (f_d == -1 ? argc : f_d);
f_co = (f_co == -1 ? argc : f_co);
for (i = 0; i < argc; i++) {
int tlv_size = 0;
/* inizialized tlv */
if (tlv_init(&tlv) < 0) {
printf("error to init tlv\n");
return -1;
}
/* different possibility to create a standard tlv*/
if (i == f_in) {
tlv_size = tlv_create_input(&tlv, &type[j]);
j++;
} else if (i == f_dz) {
tlv_size = dz2tlv(argv[i], &tlv);
} else {
tlv_size = tlv_create_path(argv[i], &tlv, &type[j]);
j++;
}
/* if not tlv as create error */
if (tlv_size < 0) {
printf("error to create tlv with path %s\n", argv[i]);
return -1;
}
/* other option who use tlv created */
if ( i >= f_co ) {
/* if tlv to insert to compound it type dated*/
if ((i >= f_d) && (f_d > f_co)) {
if (tlv_init(&buff_d) < 0) {
printf("error to init tlv compound");
return -1;
}
tlv_size = tlv_create_date(&buff_d, &tlv,
tlv_size);
if (tlv_size < 0) {
printf("error to create tlv dated"
"%s\n", argv[i]);
return -1;
}
tlv_destroy(&tlv);
tlv = buff_d;
buff_d = NULL;
}
unsigned int size_realloc = TLV_SIZEOF_HEADER;
if ((f_co == i) && (tlv_init(&buff_co) < 0)) {
printf("error to init tlv compound\n");
return -1;
}
size_realloc += buff_size_co + tlv_size;
buff_co = (tlv_t) safe_realloc(buff_co,
sizeof(*buff_co) * size_realloc);
if (buff_co == NULL) {
ERROR("realloc", -1);
}
memcpy(buff_co + buff_size_co, tlv, tlv_size);
buff_size_co += tlv_size;
tlv_destroy(&tlv);
/*when all tlv is insert, create tlv compound*/
if (i == argc -1) {
if (tlv_init(&tlv) < 0) {
printf(" error to init tlv");
return -1;
}
tlv_size = tlv_create_compound(&tlv, &buff_co,
buff_size_co);
if (tlv_size < 0) {
printf(" error to create compound"
" %s\n", argv[i]);
return -1;
}
tlv_destroy(&buff_co);
} else {
continue;
}
}
if ((i >= f_d) && (f_d <= f_co)) {
if (tlv_init(&buff_d) < 0) {
printf(" error to init tlv dated\n");
return -1;
}
tlv_size = tlv_create_date(&buff_d, &tlv, tlv_size);
if (tlv_size < 0) {
printf(" error to create tlv dated"
"%s\n", argv[i]);
return -1;
}
tlv_destroy(&tlv);
tlv = buff_d;
buff_d = NULL;
}
if (tlv_size > 0) {
if (dz_add_tlv(&daz_buf, &tlv) == -1) {
fprintf(stderr, "failed adding the tlv\n");
tlv_destroy(&tlv);
return -1;
}
tlv_destroy(&tlv);
}
}
if (dz_close(&daz_buf) < 0) {
fprintf(stderr, "failed closing the dazibao\n");
return -1;
}
return 0;
}
int choose_tlv_extract(dz_t *dz, tlv_t *tlv, long off) {
if (dz_tlv_at(dz, tlv, off) < 0) {
printf("error to read type and length tlv\n");
dz_close(dz);
tlv_destroy(tlv);
return -1;
}
if (tlv_get_type(tlv) == TLV_DATED) {
off = off + TLV_SIZEOF_HEADER + TLV_SIZEOF_DATE;
return choose_tlv_extract(dz,tlv,off);
}
if (dz_read_tlv(dz, tlv, off) < 0) {
printf("error to read value tlv\n");
dz_close(dz);
tlv_destroy(tlv);
return -1;
}
return 0;
}
int cmd_extract(int argc , char **argv, char *dz_path) {
dz_t dz;
tlv_t tlv;
long off;
int fd;
size_t real_size;
char *data;
char *path;
if (argc != 2) {
fprintf(stderr, "cmd extract : <offset> <path> <dazibao>\n");
return DZ_ARGS_ERROR;
}
/* If the offset doesn't start with a character between '0' and '9', it
* must be wrong.
*/
if (argv[0][0] < 48 || argv[0][0] > 57) {
fprintf(stderr,
"Usage:\n extract <offset> <file> <dazibao>\n");
return DZ_ARGS_ERROR;
}
off = str2dec_positive(argv[0]);
if (off < DAZIBAO_HEADER_SIZE) {
fprintf(stderr, "wrong offset\n");
return DZ_OFFSET_ERROR;
}
if (dz_open(&dz, dz_path, O_RDWR) < 0) {
fprintf(stderr, "Error while opening the dazibao\n");
return -1;
}
if (dz_check_tlv_at(&dz, off, -1,NULL) <= 0) {
fprintf(stderr, "no such TLV\n");
dz_close(&dz);
return DZ_OFFSET_ERROR;
}
if (tlv_init(&tlv) < 0) {
printf("error to init tlv\n");
dz_close(&dz);
return -1;
}
if (choose_tlv_extract(&dz,&tlv,off) < 0) {
printf("error to init tlv\n");
tlv_destroy(&tlv);
dz_close(&dz);
return -1;
}
if (dz_close(&dz) < 0) {
fprintf(stderr, "Error while closing the dazibao\n");
tlv_destroy(&tlv);
return -1;
}
if (tlv_get_type(&tlv) == TLV_COMPOUND) {
real_size = (size_t)tlv_get_length(&tlv) + DAZIBAO_HEADER_SIZE;
} else {
real_size = (size_t)tlv_get_length(&tlv);
}
path = argv[1];
fd = open(path, O_CREAT | O_TRUNC | O_RDWR, 0644);
if (fd == -1) {
tlv_destroy(&tlv);
ERROR("open", -1);
}
if (ftruncate(fd, real_size) < 0) {
fprintf(stderr, "Error while ftruncate path");
close(fd);
return -1;
}
data = (char*)mmap(NULL, real_size, PROT_WRITE, MAP_SHARED, fd, 0);
if (data == MAP_FAILED) {
fprintf(stderr, "Error while mmap ");
close(fd);
tlv_destroy(&tlv);
return -1;
}
if (tlv_get_type(&tlv) == TLV_COMPOUND) {
data[0] = MAGIC_NUMBER;
memset(data + 1, 0, DAZIBAO_HEADER_SIZE - 1);
real_size = real_size - DAZIBAO_HEADER_SIZE;
memcpy(data + DAZIBAO_HEADER_SIZE,
tlv_get_value_ptr(&tlv), real_size);
} else {
memcpy(data , tlv_get_value_ptr(&tlv), real_size);
}
tlv_destroy(&tlv);
close(fd);
return 0;
}
| 2.109375 | 2 |
2024-11-18T18:09:48.527688+00:00 | 2019-01-06T17:21:50 | 66fd6dc0db9cf6dc785f1888df5e4305b40786c1 | {
"blob_id": "66fd6dc0db9cf6dc785f1888df5e4305b40786c1",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-06T17:21:50",
"content_id": "9dc9f1773a0360e1b0d9f39f24dcd5c3ed1b78b2",
"detected_licenses": [
"NCSA"
],
"directory_id": "971c5ae1d87cdfbb97723485c3d76c17395b82b0",
"extension": "c",
"filename": "mzero5.c",
"fork_events_count": 0,
"gha_created_at": "2019-01-12T01:42:16",
"gha_event_created_at": "2019-01-12T01:42:16",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 165334058,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 507,
"license": "NCSA",
"license_type": "permissive",
"path": "/x86-semantics/tests/gcc.c-torture/ieee/src/mzero5.c",
"provenance": "stackv2-0003.json.gz:315740",
"repo_name": "mewbak/binary-decompilation",
"revision_date": "2019-01-06T17:21:50",
"revision_id": "f58da4c53cd823edc4bbbad6b647dbcefd7e64f8",
"snapshot_id": "7d0bf64d6cd01bfa5f5fc912d74a85ce81124959",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/mewbak/binary-decompilation/f58da4c53cd823edc4bbbad6b647dbcefd7e64f8/x86-semantics/tests/gcc.c-torture/ieee/src/mzero5.c",
"visit_date": "2020-04-16T06:08:14.983946"
} | stackv2 | #include "mini_string.h"
#include "mini_stdlib.h"
/* Test gcse handling of IEEE 0/-0 rules. */
static double zero = 0.0;
int
negzero_check (double d)
{
if (d == 0)
return !!memcmp ((void *)&zero, (void *)&d, sizeof (double));
return 0;
}
int
xsub (double d, double e)
{
if (d == 0.0 && e == 0.0
&& negzero_check (d) == 0 && negzero_check (e) == 0)
return 1;
else
return 0;
}
int
main (void)
{
double minus_zero = -0.0;
if (xsub (minus_zero, 0))
abort ();
return 0;
}
| 2.515625 | 3 |
2024-11-18T18:09:48.617710+00:00 | 2019-12-19T00:03:48 | c08b46a27c8f6b4162ae22faeecc1e59eb17d9b0 | {
"blob_id": "c08b46a27c8f6b4162ae22faeecc1e59eb17d9b0",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-19T00:03:48",
"content_id": "2f1b77bc2f2aadf6307e26eef2e4542c189572db",
"detected_licenses": [
"MIT"
],
"directory_id": "03ae399c214cdb071298ce680f05ff01028070d3",
"extension": "c",
"filename": "sender.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4903,
"license": "MIT",
"license_type": "permissive",
"path": "/csi-device-manager/src/sender.c",
"provenance": "stackv2-0003.json.gz:315868",
"repo_name": "Hive10/csi-monitor",
"revision_date": "2019-12-19T00:03:48",
"revision_id": "bb89cd50688f48d3f236d9654be7d845b8ba873c",
"snapshot_id": "7c110de31f44f1429eb995065c5ecbb670978d5c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Hive10/csi-monitor/bb89cd50688f48d3f236d9654be7d845b8ba873c/csi-device-manager/src/sender.c",
"visit_date": "2022-03-24T21:16:40.987766"
} | stackv2 | #include <arpa/inet.h>
#include <linux/if_packet.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <net/if.h>
#include <netinet/ether.h>
#include <unistd.h>
#include "sender.h"
int rawsock;
int start_send = FALSE;
int packets_per_second = 0;
int num_seconds = 0;
PACKET packet_to_send;
void *create_packets_sender(void *vargp) {
rawsock = create_raw_socket();
int wait_time, packets_sent, i;
while(TRUE) {
// Wait until start command
while(!start_send) sleep(1);
printf("Sending packets %d for %d seconds...\n", packets_per_second, num_seconds);
wait_time = 1000000/packets_per_second;
packets_sent = 0;
for(; num_seconds > 0; num_seconds--) {
// Cancel send if stop is called
if(!start_send) break;
for(i = 0; i < packets_per_second; i++) {
usleep(wait_time);
sendto(rawsock, packet_to_send.send_buffer, packet_to_send.len, 0,
(struct sockaddr*)&packet_to_send.socket_address, sizeof(struct sockaddr_ll));
packets_sent++;
}
}
printf("%d packets sent!\n", packets_sent);
start_send = FALSE;
num_seconds = 0;
packets_per_second = 0;
}
}
struct ifreq get_interface_index(int rawsock, char *if_name) {
struct ifreq if_idx;
memset(&if_idx, 0, sizeof(struct ifreq));
strncpy(if_idx.ifr_name, if_name, IFNAMSIZ-1);
if(ioctl(rawsock, SIOCGIFINDEX, &if_idx) < 0) {
printf("Could not get raw socket interface\n");
}
return if_idx;
}
struct ifreq get_interface_mac_address(int rawsock, char *if_name) {
struct ifreq if_mac;
memset(&if_mac, 0, sizeof(struct ifreq));
strncpy(if_mac.ifr_name, if_name, IFNAMSIZ-1);
if(ioctl(rawsock, SIOCGIFHWADDR, &if_mac) < 0) {
printf("Could not get raw socket source mac\n");
}
return if_mac;
}
int create_raw_socket() {
int rawsock;
/* Open RAW socket to send on */
if((rawsock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1) {
printf("Could not create raw socket\n");
return -1;
}
return rawsock;
}
PACKET create_packet(struct ifreq if_idx, struct ifreq if_mac, unsigned int dst_addr[6]) {
PACKET new_packet;
new_packet.len = 0;
new_packet.eh = (struct ether_header *) new_packet.send_buffer;
/* Construct the Ethernet header */
memset(new_packet.send_buffer, 0, BUF_SIZE);
/* Ethernet header */
new_packet.eh->ether_shost[0] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[0];
new_packet.eh->ether_shost[1] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[1];
new_packet.eh->ether_shost[2] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[2];
new_packet.eh->ether_shost[3] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[3];
new_packet.eh->ether_shost[4] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[4];
new_packet.eh->ether_shost[5] = ((uint8_t *)&if_mac.ifr_hwaddr.sa_data)[5];
new_packet.eh->ether_dhost[0] = dst_addr[0];
new_packet.eh->ether_dhost[1] = dst_addr[1];
new_packet.eh->ether_dhost[2] = dst_addr[2];
new_packet.eh->ether_dhost[3] = dst_addr[3];
new_packet.eh->ether_dhost[4] = dst_addr[4];
new_packet.eh->ether_dhost[5] = dst_addr[5];
new_packet.eh->ether_type = htons(ETH_P_IP);
new_packet.len += sizeof(struct ether_header);
/* Packet data
* We just set it to 0xaa you send arbitrary payload you like*/
int i;
for(i = 1; i <= 1000; i++) {
new_packet.send_buffer[new_packet.len++] = 0xaa;
}
new_packet.iph = (struct iphdr *) (new_packet.send_buffer + sizeof(struct ether_header));
new_packet.socket_address.sll_ifindex = if_idx.ifr_ifindex;
new_packet.socket_address.sll_family = PF_PACKET;
new_packet.socket_address.sll_protocol = htons(ETH_P_IP);
new_packet.socket_address.sll_hatype = ARPHRD_ETHER;
new_packet.socket_address.sll_pkttype = PACKET_OTHERHOST;
new_packet.socket_address.sll_halen = ETH_ALEN;
new_packet.socket_address.sll_addr[0] = dst_addr[0];
new_packet.socket_address.sll_addr[1] = dst_addr[1];
new_packet.socket_address.sll_addr[2] = dst_addr[2];
new_packet.socket_address.sll_addr[3] = dst_addr[3];
new_packet.socket_address.sll_addr[4] = dst_addr[4];
new_packet.socket_address.sll_addr[5] = dst_addr[5];
return new_packet;
}
void send_packets(unsigned int DstAddr[6], unsigned int quantity_of_packets, unsigned int until_seconds,
char ifName[IFNAMSIZ])
{
packet_to_send = create_packet(get_interface_index(rawsock, ifName),
get_interface_mac_address(rawsock, ifName),
DstAddr);
packets_per_second = quantity_of_packets;
num_seconds = until_seconds;
start_send = TRUE;
}
void stop_sending() {
printf("Stopping the sender...\n");
start_send = FALSE;
} | 2.390625 | 2 |
2024-11-18T18:09:48.880362+00:00 | 2020-08-06T16:53:36 | 6fb96f5908e8c9e31fb5ae5c23ef175a61d5bfae | {
"blob_id": "6fb96f5908e8c9e31fb5ae5c23ef175a61d5bfae",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-06T16:53:36",
"content_id": "3799b1cf0ead32c97152cdf63513472faec26369",
"detected_licenses": [
"MIT"
],
"directory_id": "8b7a272ae43c04ac490056635219be066aa6f2a1",
"extension": "c",
"filename": "write_mp_ack_frame.c",
"fork_events_count": 1,
"gha_created_at": "2020-08-10T07:59:28",
"gha_event_created_at": "2020-08-10T07:59:29",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 286412983,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6562,
"license": "MIT",
"license_type": "permissive",
"path": "/plugins/multipath/write_mp_ack_frame.c",
"provenance": "stackv2-0003.json.gz:316254",
"repo_name": "Ysurac/pquic",
"revision_date": "2020-08-06T16:53:36",
"revision_id": "2bd9737291f61f5f5286de6e758613f49237a0c6",
"snapshot_id": "b80c1649688a9a79c5430bffa0ac4d0022b52339",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Ysurac/pquic/2bd9737291f61f5f5286de6e758613f49237a0c6/plugins/multipath/write_mp_ack_frame.c",
"visit_date": "2022-11-28T17:10:29.023840"
} | stackv2 | #include "bpf.h"
/**
* See PROTOOP_PARAM_WRITE_FRAME
*/
protoop_arg_t write_mp_ack_frame(picoquic_cnx_t *cnx)
{
uint8_t* bytes = (uint8_t *) get_cnx(cnx, AK_CNX_INPUT, 0);
const uint8_t *bytes_max = (const uint8_t *) get_cnx(cnx, AK_CNX_INPUT, 1);
mp_ack_ctx_t *mac = (mp_ack_ctx_t *) get_cnx(cnx, AK_CNX_INPUT, 2);
size_t consumed = 0;
uint64_t current_time = picoquic_current_time();
picoquic_path_t *path_x = mac->path_x;
picoquic_packet_context_enum pc = mac->pc;
int ret = 0;
size_t byte_index = 0;
uint64_t num_block = 0;
size_t l_frame_id = 0;
size_t l_uniflow_id = 0;
size_t l_largest = 0;
size_t l_delay = 0;
size_t l_first_range = 0;
picoquic_packet_context_t * pkt_ctx = (picoquic_packet_context_t *) get_path(path_x, AK_PATH_PKT_CTX, pc);
picoquic_sack_item_t* first_sack = (picoquic_sack_item_t *) get_pkt_ctx(pkt_ctx, AK_PKTCTX_FIRST_SACK_ITEM);
picoquic_sack_item_t* next_sack = (picoquic_sack_item_t *) get_sack_item(first_sack, AK_SACKITEM_NEXT_SACK);
uint64_t ack_delay = 0;
uint64_t ack_range = 0;
uint64_t ack_gap = 0;
uint64_t lowest_acknowledged = 0;
size_t num_block_index = 0;
bpf_data *bpfd = get_bpf_data(cnx);
uniflow_data_t *ud = mp_get_receiving_uniflow_data(bpfd, path_x);
/* Check that there is enough room in the packet, and something to acknowledge */
uint64_t first_sack_start_range = (uint64_t) get_sack_item(first_sack, AK_SACKITEM_START_RANGE);
if (first_sack_start_range == (uint64_t)((int64_t)-1)) {
consumed = 0;
} else if (bytes_max - bytes < 14) {
/* A valid ACK, with our encoding, uses at least 13 bytes.
* If there is not enough space, don't attempt to encode it.
*/
consumed = 0;
ret = PICOQUIC_ERROR_FRAME_BUFFER_TOO_SMALL;
} else {
/* Encode the frame ID */
l_frame_id = picoquic_varint_encode(bytes + byte_index, (size_t) (bytes_max - bytes) - byte_index,
MP_ACK_TYPE);
byte_index += l_frame_id;
/* Encode the uniflow ID */
if (byte_index < bytes_max - bytes) {
l_uniflow_id = picoquic_varint_encode(bytes + byte_index, (size_t) (bytes_max - bytes) - byte_index,
ud->uniflow_id);
byte_index += l_uniflow_id;
}
/* Encode the largest seen */
uint64_t first_sack_end_range = (uint64_t) get_sack_item(first_sack, AK_SACKITEM_END_RANGE);
if (byte_index < bytes_max - bytes) {
l_largest = picoquic_varint_encode(bytes + byte_index, (size_t) (bytes_max - bytes) - byte_index,
first_sack_end_range);
byte_index += l_largest;
}
/* Encode the ack delay */
if (byte_index < bytes_max - bytes) {
uint64_t time_stamp_largest_received = (uint64_t) get_pkt_ctx(pkt_ctx, AK_PKTCTX_TIME_STAMP_LARGEST_RECEIVED);
if (current_time > time_stamp_largest_received) {
ack_delay = current_time - time_stamp_largest_received;
ack_delay >>= (uint8_t) get_cnx(cnx, AK_CNX_LOCAL_PARAMETER, TRANSPORT_PARAMETER_ACK_DELAY_EXPONENT);
}
l_delay = picoquic_varint_encode(bytes + byte_index, (size_t) (bytes_max - bytes) - byte_index,
ack_delay);
byte_index += l_delay;
}
if (ret == 0) {
/* Reserve one byte for the number of blocks */
num_block_index = byte_index;
byte_index++;
/* Encode the size of the first ack range */
if (byte_index < bytes_max - bytes) {
ack_range = first_sack_end_range - first_sack_start_range;
l_first_range = picoquic_varint_encode(bytes + byte_index, (size_t) (bytes_max - bytes) - byte_index,
ack_range);
byte_index += l_first_range;
}
}
if (l_uniflow_id == 0 || l_delay == 0 || l_largest == 0 || l_first_range == 0 || byte_index > (size_t) (bytes_max - bytes)) {
/* not enough space */
consumed = 0;
ret = PICOQUIC_ERROR_FRAME_BUFFER_TOO_SMALL;
} else if (ret == 0) {
/* Set the lowest acknowledged */
lowest_acknowledged = first_sack_start_range;
/* Encode the ack blocks that fit in the allocated space */
while (num_block < 63 && next_sack != NULL) {
size_t l_gap = 0;
size_t l_range = 0;
uint64_t next_sack_end_range = (uint64_t) get_sack_item(next_sack, AK_SACKITEM_END_RANGE);
uint64_t next_sack_start_range = (uint64_t) get_sack_item(next_sack, AK_SACKITEM_START_RANGE);
if (byte_index < (size_t) (bytes_max - bytes)) {
ack_gap = lowest_acknowledged - next_sack_end_range - 2; /* per spec */
l_gap = picoquic_varint_encode(bytes + byte_index,
(size_t) (bytes_max - bytes) - byte_index, ack_gap);
}
if (byte_index + l_gap < (size_t) (bytes_max - bytes)) {
ack_range = next_sack_end_range - next_sack_start_range;
l_range = picoquic_varint_encode(bytes + byte_index + l_gap,
(size_t) (bytes_max - bytes) - byte_index - l_gap, ack_range);
}
if (l_gap == 0 || l_range == 0) {
/* Not enough space to encode this gap. */
break;
} else {
byte_index += l_gap + l_range;
lowest_acknowledged = next_sack_start_range;
next_sack = (picoquic_sack_item_t *) get_sack_item(next_sack, AK_SACKITEM_NEXT_SACK);
num_block++;
}
}
/* When numbers are lower than 64, varint encoding fits on one byte */
my_memset(&bytes[num_block_index], (uint8_t)num_block, 1);
/* Remember the ACK value and time */
set_pkt_ctx(pkt_ctx, AK_PKTCTX_HIGHEST_ACK_SENT, first_sack_end_range);
set_pkt_ctx(pkt_ctx, AK_PKTCTX_HIGHEST_ACK_TIME, current_time);
consumed = byte_index;
}
}
if (ret == 0) {
set_pkt_ctx(pkt_ctx, AK_PKTCTX_ACK_NEEDED, 0);
}
my_free(cnx, mac);
//pd->doing_ack = false;
set_cnx(cnx, AK_CNX_OUTPUT, 0, (protoop_arg_t) consumed);
set_cnx(cnx, AK_CNX_OUTPUT, 1, (protoop_arg_t) 0);
return (protoop_arg_t) ret;
} | 2.140625 | 2 |
2024-11-18T18:09:48.959390+00:00 | 2015-11-24T09:35:17 | c1616d2aa3e3d966229b0a59177f98ec5faa2372 | {
"blob_id": "c1616d2aa3e3d966229b0a59177f98ec5faa2372",
"branch_name": "refs/heads/master",
"committer_date": "2015-11-24T09:35:17",
"content_id": "2a2b0438ef077231bf7b95c63864e0b9cd7d4fdb",
"detected_licenses": [
"MIT"
],
"directory_id": "d531386c1a6fb9be800161aae965b208740d4011",
"extension": "c",
"filename": "tm.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 46283440,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3129,
"license": "MIT",
"license_type": "permissive",
"path": "/src/kernel/tm.c",
"provenance": "stackv2-0003.json.gz:316382",
"repo_name": "shenchi/scos",
"revision_date": "2015-11-24T09:35:17",
"revision_id": "4109f5a4ce2a97efc0fdee69f9f97aed6df22dd0",
"snapshot_id": "baf2594a1d254cc3e899ec7c3326f8601639ea3e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/shenchi/scos/4109f5a4ce2a97efc0fdee69f9f97aed6df22dd0/src/kernel/tm.c",
"visit_date": "2021-01-10T04:19:16.499604"
} | stackv2 | //=======================================================
//Project Name: S.C. Operating System
//Version: 0.02
//Auther: Shen Chi
//=======================================================
#include "tm.h"
#include "kernel.h"
#include "task.h"
#include "fs.h"
#include "screen.h"
task_info ti[64];
unsigned long cur_task=0;
unsigned long cur_vbuf=0xb8000;
unsigned long cur_kbuf=0;
void init_tm(void){
unsigned long i;
for(i=0;i<=64;i++){
ti[i].kbuf_addr=0;
ti[i].vbuf_addr=-1;
}
cur_task=0;
}
void set_cur_task(unsigned long task_no){
cur_task=task_no;
cur_vbuf=ti[cur_task].vbuf_addr;
if(cur_vbuf==-1)cur_vbuf=0xb8000;
cur_kbuf=ti[cur_task].kbuf_addr;
}
void set_cur_task_without_task_no(void){
//puts("Set Task To ");puthex(current);puts("\n\r");
cur_task=current;
cur_vbuf=ti[cur_task].vbuf_addr;
if(cur_vbuf==-1)cur_vbuf=0xb8000;
cur_kbuf=ti[cur_task].kbuf_addr;
}
void set_cur_vbuf(unsigned long addr){
if(current==0)return;
unsigned long baseaddr=((current-1)*64+32)*1024*1024;
ti[current].vbuf_addr=baseaddr+addr;
cur_vbuf=ti[cur_task].vbuf_addr;
if(cur_vbuf==-1)cur_vbuf=0xb8000;
}
void set_cur_kbuf(unsigned long addr){
if(current==0)return;
unsigned long baseaddr=((current-1)*64+32)*1024*1024;
ti[current].kbuf_addr=baseaddr+addr;
cur_kbuf=ti[cur_task].kbuf_addr;
}
unsigned long read_file_for_ring3(unsigned long filenameaddr,unsigned long addr){
if(current==0)return 0;
unsigned long baseaddr=((current-1)*64+32)*1024*1024;
unsigned long tmpret;
tmpret=read_file((char*)(baseaddr+filenameaddr),baseaddr+addr);
return tmpret;
}
unsigned long create_file_for_ring3(unsigned long filenameaddr,unsigned long addr,unsigned long size){
if(current==0)return 0;
unsigned long baseaddr=((current-1)*64+32)*1024*1024;
unsigned long tmpret;
tmpret=create_file((char*)(baseaddr+filenameaddr), baseaddr+addr, size);
return tmpret;
}
unsigned long create_dir_for_ring3(unsigned long filenameaddr,unsigned long addr,unsigned long size){
if(current==0)return 0;
unsigned long baseaddr=((current-1)*64+32)*1024*1024;
unsigned long tmpret;
tmpret=create_dir((char*)(baseaddr+filenameaddr), baseaddr+addr, size);
return tmpret;
}
unsigned long delete_file_for_ring3(unsigned long filenameaddr){
if(current==0)return 0;
unsigned long baseaddr=((current-1)*64+32)*1024*1024;
unsigned long tmpret;
tmpret=delete_file((char*)(baseaddr+filenameaddr));
return tmpret;
}
unsigned long change_dir_for_ring3(unsigned long filenameaddr){
if(current==0)return 0;
unsigned long baseaddr=((current-1)*64+32)*1024*1024;
unsigned long tmpret;
tmpret=goto_dic((unsigned char*)(baseaddr+filenameaddr));
return tmpret;
}
void dir_for_ring3(unsigned long filenameaddr){
if(current==0)return;
unsigned long baseaddr=((current-1)*64+32)*1024*1024;
dir((unsigned char*)filenameaddr+baseaddr);
}
void task_list_for_ring3(unsigned long filenameaddr){
if(current==0)return;
unsigned long baseaddr=((current-1)*64+32)*1024*1024;
task_list((unsigned char*)filenameaddr+baseaddr);
}
| 2.53125 | 3 |
2024-11-18T18:09:49.108334+00:00 | 2019-01-06T17:21:50 | 457ff06cea5a7e661792f7576923c7c619b829fe | {
"blob_id": "457ff06cea5a7e661792f7576923c7c619b829fe",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-06T17:21:50",
"content_id": "df40c267a4f628aaa7fc4badc4b42d80e4d68f30",
"detected_licenses": [
"NCSA"
],
"directory_id": "971c5ae1d87cdfbb97723485c3d76c17395b82b0",
"extension": "c",
"filename": "test.c",
"fork_events_count": 0,
"gha_created_at": "2019-01-12T01:42:16",
"gha_event_created_at": "2019-01-12T01:42:16",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 165334058,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 349,
"license": "NCSA",
"license_type": "permissive",
"path": "/x86-semantics/tests/Programs/stdio_fflush/test.c",
"provenance": "stackv2-0003.json.gz:316510",
"repo_name": "mewbak/binary-decompilation",
"revision_date": "2019-01-06T17:21:50",
"revision_id": "f58da4c53cd823edc4bbbad6b647dbcefd7e64f8",
"snapshot_id": "7d0bf64d6cd01bfa5f5fc912d74a85ce81124959",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/mewbak/binary-decompilation/f58da4c53cd823edc4bbbad6b647dbcefd7e64f8/x86-semantics/tests/Programs/stdio_fflush/test.c",
"visit_date": "2020-04-16T06:08:14.983946"
} | stackv2 | #include <stdio.h>
int main()
{
char mybuffer[80];
FILE * pFile;
pFile = fopen ("example.txt","w");
fputs ("test",pFile);
fflush (pFile); // flushing or repositioning required
fclose (pFile);
pFile = fopen ("example.txt","r");
fgets (mybuffer,80,pFile);
puts (mybuffer);
fclose (pFile);
return 0;
}
| 2.171875 | 2 |
2024-11-18T18:09:50.965242+00:00 | 2018-02-10T00:29:26 | 5cfed590c7521c3a449a020ec9a6ad8a33f99701 | {
"blob_id": "5cfed590c7521c3a449a020ec9a6ad8a33f99701",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-10T00:29:26",
"content_id": "0af2ee6d97f7aa80f4647478eabf7def99a000d4",
"detected_licenses": [
"MIT"
],
"directory_id": "b7ff102f68c61fa3a4ab31c9a24008d60f709154",
"extension": "h",
"filename": "mouse.h",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1546,
"license": "MIT",
"license_type": "permissive",
"path": "/src/mouse.h",
"provenance": "stackv2-0003.json.gz:316770",
"repo_name": "Rockdell/2LCOM-MOsu",
"revision_date": "2018-02-10T00:29:26",
"revision_id": "e51c34cce164dcbea06bcde9f7e44604dead36bb",
"snapshot_id": "1f0da1c7bf914533d93c19515db45e6ccc9edce7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Rockdell/2LCOM-MOsu/e51c34cce164dcbea06bcde9f7e44604dead36bb/src/mouse.h",
"visit_date": "2021-04-18T18:35:33.364436"
} | stackv2 |
#ifndef __MOUSE_H
#define __MOUSE_H
#include <minix/syslib.h>
/** @defgroup mouse Mouse
* @{
*
* Mouse related functions
*/
/**
* @brief Subscribes mouse's interruptions.
* @return Returns an ID if successful and -1 otherwise.
*/
int mouse_subscribe_int(void );
/**
* @brief Unsubscribes mouse's interruptions.
* @return Returns 0 if successful and 1 otherwise.
*/
int mouse_unsubscribe_int();
/**
* @brief Mouse's interruption handler.
* @return Returns 0 if successful and 1 otherwise.
*/
int mouse_int_handler();
/**
* @brief Adds a processed byte to a packet.
* @return Returns 0 if successful and 1 otherwise.
*/
int addBytePacket(unsigned long byte);
/**
* @brief Gets the counter, which keeps track of the number of bytes processed (up to 3 per packet).
* @return Returns the counter of packets.
*/
int getCounter();
/**
* @brief Check if the right button is pressed (right click).
* @return Returns 1 if true and 0 otherwise.
*/
int getRB();
/**
* @brief Check if the left button is pressed (left click).
* @return Returns 1 if true and 0 otherwise.
*/
int getLB();
/**
* @brief Check X-axis' movement.
* @return Returns the X-axis' movement.
*/
int getX();
/**
* @brief Check Y-axis movement.
* @return Returns the Y-axis movement.
*/
int getY();
/**
* @brief Prints the last packet processed.
*/
void printPacket();
/**
* @brief Updates the static varibles with the last X-axis' movement and Y-axis' movement.
*/
void updateCoord();
/** @} end of mouse */
#endif
| 2.078125 | 2 |
2024-11-18T18:09:51.277499+00:00 | 2020-05-15T15:42:59 | 085647b3686ec55ecbbebc8c977a8a3373261eb0 | {
"blob_id": "085647b3686ec55ecbbebc8c977a8a3373261eb0",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-15T15:42:59",
"content_id": "9f287c7408c9cd16e86f57a63a969fea1aa4a85c",
"detected_licenses": [
"MIT"
],
"directory_id": "6ee3f3fa19120d7fba5316670aba623c9b9a83c0",
"extension": "h",
"filename": "Define.h",
"fork_events_count": 0,
"gha_created_at": "2020-05-01T13:01:39",
"gha_event_created_at": "2020-05-01T13:01:40",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 260460272,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 651,
"license": "MIT",
"license_type": "permissive",
"path": "/Tutorial/05/Define.h",
"provenance": "stackv2-0003.json.gz:317157",
"repo_name": "overworks/edu_cpp_IOCP",
"revision_date": "2020-05-15T15:42:59",
"revision_id": "9e272ee10cf6b425ec7ab13db1636143aa74e794",
"snapshot_id": "8af7c679d740e3692d5edab4f237d93077b66623",
"src_encoding": "UHC",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/overworks/edu_cpp_IOCP/9e272ee10cf6b425ec7ab13db1636143aa74e794/Tutorial/05/Define.h",
"visit_date": "2022-08-01T15:05:43.170338"
} | stackv2 | #pragma once
#include <winsock2.h>
#include <Ws2tcpip.h>
const UINT32 MAX_SOCKBUF = 256; // 소켓 버퍼의 크기
const UINT32 MAX_SOCK_SENDBUF = 4096; // 소켓 버퍼의 크기
const UINT32 MAX_WORKERTHREAD = 4; //쓰레드 풀에 넣을 쓰레드 수
enum class IOOperation
{
RECV,
SEND
};
//WSAOVERLAPPED구조체를 확장 시켜서 필요한 정보를 더 넣었다.
struct stOverlappedEx
{
WSAOVERLAPPED m_wsaOverlapped; //Overlapped I/O구조체
SOCKET m_socketClient; //클라이언트 소켓
WSABUF m_wsaBuf; //Overlapped I/O작업 버퍼
IOOperation m_eOperation; //작업 동작 종류
};
| 2.1875 | 2 |
2024-11-18T18:09:51.336161+00:00 | 2021-11-26T08:38:57 | 6dc5ed6cf730d410761448e61e38a6087e44cf04 | {
"blob_id": "6dc5ed6cf730d410761448e61e38a6087e44cf04",
"branch_name": "refs/heads/main",
"committer_date": "2021-11-26T08:38:57",
"content_id": "5ac2145c82d4c655efa0485ab2207978489a37ab",
"detected_licenses": [
"BSD-3-Clause",
"BSD-2-Clause"
],
"directory_id": "a77b595a482fc74260c7cccc50cafa77e0584c67",
"extension": "h",
"filename": "tinyspritebatch.h",
"fork_events_count": 1,
"gha_created_at": "2017-02-11T19:39:37",
"gha_event_created_at": "2021-11-01T08:16:12",
"gha_language": "C",
"gha_license_id": null,
"github_id": 81677344,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 58480,
"license": "BSD-3-Clause,BSD-2-Clause",
"license_type": "permissive",
"path": "/src/tinyheaders/tinyspritebatch.h",
"provenance": "stackv2-0003.json.gz:317285",
"repo_name": "meshula/LabRender",
"revision_date": "2021-11-26T08:38:57",
"revision_id": "690303a3364d726129d63c854e598061f04d1296",
"snapshot_id": "80486a10168a2982ef7daaf42b39c787cef1f540",
"src_encoding": "UTF-8",
"star_events_count": 15,
"url": "https://raw.githubusercontent.com/meshula/LabRender/690303a3364d726129d63c854e598061f04d1296/src/tinyheaders/tinyspritebatch.h",
"visit_date": "2021-12-24T18:32:04.573476"
} | stackv2 | /*
------------------------------------------------------------------------------
Licensing information can be found at the end of the file.
------------------------------------------------------------------------------
tinyspritebatch.h - v1.0
To create implementation (the function definitions)
#define SPRITEBATCH_IMPLEMENTATION
in *one* C/CPP file (translation unit) that includes this file
SUMMARY:
This header implements a 2D sprite batcher by tracking different textures within
a rolling atlas cache. Over time atlases are decayed and recreated when textures
stop being used. This header is useful for batching sprites at run-time. This avoids
the need to compile texture atlases as a pre-process step, letting the game load
images up individually, dramatically simplifying art pipelines.
MORE DETAILS:
`spritebatch_push` is used to push sprite instances into a buffer. Rendering sprites
works by calling `spritebatch_flush`. `spritebatch_flush` will use a user-supplied
callback to report sprite batches. This callback is of type `submit_batch_t`. The
batches are reported as an array of `spritebatch_sprite_t` sprites, and can be
further sorted by the user (for example to sort by depth). Sprites in a batch share
the same texture handle (either from the same base image, or from the same internal
atlas).
tinypsritebatch does not know anything about how to generate texture handles, or
destroy them. As such, the user must supply two callbacks for creating handles and
destroying them. These can be simple wrappers around, for example, `glGenTextures`
and `glDeleteTextures`.
Finally, tinyspritebatch will periodically need access to pixels from images. These
pixels are used to generate textures, or to build atlases (which in turn generate a
texture). tinyspritebatch does not need to know much about your images, other than
the pixel stride. The user supplies callback of type `get_pixels_t`, which lets
tinypsritebatch retreive the pixels associated with a particular image. The pixels
can be stored in RAM and handed to tinyspritebatch whenever requested, or the pixels
can be fetched directly from disk and handed to tinyspritebatch. It doesn't matter
to tinyspritebatch, and the pointer to the pixels are *not* stored anywhere after
the callback returns. Since `get_pixels_t` can be called from `spritebatch_flush` it
is recommended to avoid file i/o within the `get_pixels_t` callback, and instead try
to already have pixels ready in RAM.
The `spritebatch_defrag` function performs atlas creation and texture management. It
should be called periodically. It can be called once per game tick (once per render),
or optionally called at a different frequency (once ever N game ticks).
PROS AND CONS:
PROS
- Texture atlases are completely hidden behind an api. The api in this header can
easily be implemented with different backend sprite batchers. For example on
some platforms bindless textures can be utilized in order to avoid texture
atlases entirely! Code using this API can have the backend implementation swapped
without requiring any user code to change.
- Sprites are batched in an effective manner to dramatically reduce draw call counts.
- Supporting hotswapping or live-reloading of images can be trivialized due to
moving atlas creation out of the art-pipeline and into the run-time.
- Since atlases are built at run-time and continually maintained, images are
guaranteed to be drawn at the same time on-screen as their atlas neighbors. This is
typically not the case for atlas preprocessors, as a *guess* must be made to try
and organize images together in atlases that need to be drawn at roughly the same
time.
CONS
- Performance hits in the `spritebatch_defrag` function, and a little as well in
the `spritebatch_flush` function. Extra run-time memory usage for bookkeeping,
which implies a RAM hit as well as more things to clog the CPU cache.
- If each texture comes from a separate image on-disk, opening individual files on
disk can be very slow. For example on Windows just performing permissions and
related work to open a file is time-consuming.
- For large numbers of separate images, some file abstraction is necessary to avoid
a large performance hit on opening/closing many individual files. This problem is
*not* solved by tinyspritebatch.h, and instead should be solved by some separate
file abstraction system.
EXAMPLE USAGE:
spritebatch_config_t config;
spritebatch_set_default_config(&config);
config.batch_callback = my_report_batches_function;
config.get_pixels_callback = my_get_pixels_function;
config.generate_texture_callback = my_make_texture_handle_function;
config.delete_texture_callback = my_destroy_texture_handle_function;
spritebatch_t batcher;
spritebatch_init(&batcher, &config);
while (game_is_running)
{
for (int i = 0; i < sprite_count; ++i)
spritebatch_push(
&batcher,
sprites[i].image_id,
sprites[i].image_width_in_pixels,
sprites[i].image_height_in_pixels,
sprites[i].position_x,
sprites[i].poxition_y,
sprites[i].scale_x,
sprites[i].scale_y,
sprites[i].cos_rotation_angle,
sprites[i].sin_rotation_angle
);
spritebatch_tick(&batcher);
spritebatch_defrag(&batcher);
spritebatch_flush(&batcher);
}
CUSTOMIZATION:
The following macros can be defined before including this header with the
SPRITEBATCH_IMPLEMENTATION symbol defined, in order to customize the internal
behavior of tinyspritebatch.h. Search this header to find how each macro is
defined and used. Note that MALLOC/FREE functions can optionally take a context
parameter for custom allocation.
SPRITEBATCH_MALLOC
SPRITEBATCH_MEMCPY
SPRITEBATCH_MEMSET
SPRITEBATCH_ASSERT
SPRITEBATCH_ATLAS_FLIP_Y_AXIS_FOR_UV
SPRITEBATCH_ATLAS_EMPTY_COLOR
SPRITEBATCH_ALLOCA
SPRITEBATCH_LOG
Revision history:
0.01 (11/20/2017) experimental release
1.00 (04/14/2018) initial release
*/
#ifndef SPRITEBATCH_H
#ifndef SPRITEBATCH_U64
#define SPRITEBATCH_U64 unsigned long long
#endif SPRITEBATCH_U64
#ifndef EXTERNC
# ifdef __cplusplus
# define EXTERNC extern "C"
# else
# define EXTERNC
# endif
#endif
typedef struct spritebatch_t spritebatch_t;
typedef struct spritebatch_config_t spritebatch_config_t;
typedef struct spritebatch_sprite_t spritebatch_sprite_t;
//@dp
EXTERNC spritebatch_t* spritebatch_create();
EXTERNC void spritebatch_destroy(spritebatch_t* sb);
// Pushes a sprite onto an internal buffer. Does no other logic. `image_id` must be a unique
// identifier for the image a sprite references. `image_w` and image_h` are the width and height
// of the image referenced by `image_id`. `x` and `y` are the position of the sprite. `sx` and
// `sy` are the scale factors on the x and y axis for the sprite. `c` and `s` are the cosine and
// sine of the angle of the sprite, and represent a 2D rotation matrix.
EXTERNC int spritebatch_push(spritebatch_t* sb, SPRITEBATCH_U64 image_id, int image_w, int image_h, float x, float y, float sx, float sy, float c, float s, int sort_bits);
// Increments internal timestamps on all textures, for use in `spritebatch_defrag`.
EXTERNC void spritebatch_tick(spritebatch_t* sb);
// Sorts the internal sprites and flushes the buffer built by `spritebatch_push`. Will call
// the `submit_batch_t` function for each batch of sprites and return them as an array. Any `image_id`
// within the `spritebatch_push` buffer that do not yet have a texture handle will request pixels
// from the image via `get_pixels_t` and request a texture handle via `generate_texture_handle_t`.
EXTERNC int spritebatch_flush(spritebatch_t* sb);
// All textures created so far by `spritebatch_flush` will be considered as candidates for creating
// new internal texture atlases. Internal texture atlases compress images together inside of one
// texture to dramatically reduce draw calls. When an atlas is created, the most recently used `image_id`
// instances are prioritized, to ensure atlases are filled with images all drawn at the same time.
// As some textures cease to draw on screen, they "decay" over time. Once enough images in an atlas
// decay, the atlas is removed, and any "live" images in the atlas are used to create new atlases.
// Can be called every 1/N times `spritebatch_flush` is called.
EXTERNC int spritebatch_defrag(spritebatch_t* sb);
EXTERNC int spritebatch_init(spritebatch_t* sb, spritebatch_config_t* config);
EXTERNC void spritebatch_term(spritebatch_t* sb);
// Sprite batches are submit via synchronous callback back to the user. This function is called
// from inside `spritebatch_flush`. Each time `submit_batch_t` is called an array of sprites
// is handed to the user. The sprites are intended to be further sorted by the user as desired
// (for example, additional sorting based on depth).
typedef void (*submit_batch_t)(spritebatch_sprite_t* sprites, int count);
// tinyspritebatch.h needs to know how to get the pixels of an image, generate textures handles (for
// example glGenTextures for OpenGL), and destroy texture handles. These functions are all called
// from within the `spritebatch_defrag` function, and sometimes from `spritebatch_flush`.
typedef void* (*get_pixels_t)(SPRITEBATCH_U64 image_id);
typedef SPRITEBATCH_U64 (*generate_texture_handle_t)(void* pixels, int w, int h);
typedef void (*destroy_texture_handle_t)(SPRITEBATCH_U64 texture_id);
// Initializes a set of good default paramaters. The users must still set
// the four callbacks inside of `config`.
EXTERNC void spritebatch_set_default_config(spritebatch_config_t* config);
struct spritebatch_config_t
{
int pixel_stride;
int atlas_width_in_pixels;
int atlas_height_in_pixels;
int ticks_to_decay_texture; // number of ticks it takes for a texture handle to be destroyed via `destroy_texture_handle_t`
int lonely_buffer_count_till_flush; // number of unique textures until an atlas is constructed
float ratio_to_decay_atlas; // from 0 to 1, once ratio is less than `ratio_to_decay_atlas`, flush active textures in atlas to lonely buffer
float ratio_to_merge_atlases; // from 0 to 0.5, attempts to merge atlases with some ratio of empty space
submit_batch_t batch_callback;
get_pixels_t get_pixels_callback;
generate_texture_handle_t generate_texture_callback;
destroy_texture_handle_t delete_texture_callback;
void* allocator_context;
};
struct spritebatch_sprite_t
{
SPRITEBATCH_U64 texture_id;
// User-defined sorting key, see: http://realtimecollisiondetection.net/blog/?p=86
// The first 32-bits store the user's sort bits. The bottom 32-bits are for internal
// usage, and are not ever set by the user. Internally sprites are sorted first
// based on `sort_bits`, and to break ties they are sorted on `texture_id`. Feel free
// to change the sort predicate `spritebatch_internal_instance_pred` in the
// implementation section.
SPRITEBATCH_U64 sort_bits;
float x, y; // x and y position
float sx, sy; // scale on x and y axis
float c, s; // cosine and sine (represents cos(angle) and sin(angle))
float minx, miny; // u coordinate
float maxx, maxy; // v coordinate
};
#define SPRITEBATCH_H
#endif
#ifdef SPRITEBATCH_IMPLEMENTATION
#undef SPRITEBATCH_IMPLEMENTATION
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#ifndef _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE
#endif
#ifndef SPRITEBATCH_MALLOC
#include <stdlib.h>
#define SPRITEBATCH_MALLOC(size, ctx) malloc(size)
#define SPRITEBATCH_FREE(ptr, ctx) free(ptr)
#endif
#ifndef SPRITEBATCH_MEMCPY
#include <string.h>
#define SPRITEBATCH_MEMCPY(dst, src, n) memcpy(dst, src, n)
#endif
#ifndef SPRITEBATCH_MEMSET
#include <string.h>
#define SPRITEBATCH_MEMSET(ptr, val, n) memset(ptr, val, n)
#endif
#ifndef SPRITEBATCH_ASSERT
#include <assert.h>
#define SPRITEBATCH_ASSERT(condition) assert(condition)
#endif
// flips output uv coordinate's y. Can be useful to "flip image on load"
#ifndef SPRITEBATCH_ATLAS_FLIP_Y_AXIS_FOR_UV
#define SPRITEBATCH_ATLAS_FLIP_Y_AXIS_FOR_UV 1
#endif
// flips output uv coordinate's y. Can be useful to "flip image on load"
#ifndef SPRITEBATCH_LONELY_FLIP_Y_AXIS_FOR_UV
#define SPRITEBATCH_LONELY_FLIP_Y_AXIS_FOR_UV 1
#endif
#ifndef SPRITEBATCH_ATLAS_EMPTY_COLOR
#define SPRITEBATCH_ATLAS_EMPTY_COLOR 0x000000FF
#endif
#ifndef SPRITEBATCH_ALLOCA
#ifdef _WIN32
#include <malloc.h>
#else
#include <alloca.h>
#endif
#define SPRITEBATCH_ALLOCA(ctx, size) alloca(size)
#endif
#ifndef SPRITEBATCH_LOG
#if 0
#define SPRITEBATCH_LOG printf
#else
#define SPRITEBATCH_LOG(...)
#endif
#endif
#define HASHTABLE_MEMSET(ptr, val, n) SPRITEBATCH_MEMSET(ptr, val, n)
#define HASHTABLE_MEMCPY(dst, src, n) SPRITEBATCH_MEMCPY(dst, src, n)
#define HASHTABLE_MALLOC(ctx, size) SPRITEBATCH_MALLOC(size, ctx)
#define HASHTABLE_FREE(ctx, ptr) SPRITEBATCH_FREE(ptr, ctx)
// hashtable.h implementation by Mattias Gustavsson
// See: http://www.mattiasgustavsson.com/ and https://github.com/mattiasgustavsson/libs/blob/master/hashtable.h
// begin hashtable.h
#ifndef HASHTABLE_U64
#define HASHTABLE_U64 SPRITEBATCH_U64
#endif
#ifndef HASHTABLE_U32
#define HASHTABLE_U32 unsigned int
#endif
typedef struct hashtable_t hashtable_t;
void hashtable_init( hashtable_t* table, int item_size, int initial_capacity, void* memctx );
void hashtable_term( hashtable_t* table );
void* hashtable_insert( hashtable_t* table, HASHTABLE_U64 key, void const* item );
void hashtable_remove( hashtable_t* table, HASHTABLE_U64 key );
void hashtable_clear( hashtable_t* table );
void* hashtable_find( hashtable_t const* table, HASHTABLE_U64 key );
int hashtable_count( hashtable_t const* table );
void* hashtable_items( hashtable_t const* table );
HASHTABLE_U64 const* hashtable_keys( hashtable_t const* table );
void hashtable_swap( hashtable_t* table, int index_a, int index_b );
struct hashtable_internal_slot_t
{
HASHTABLE_U32 key_hash;
int item_index;
int base_count;
};
struct hashtable_t
{
void* memctx;
int count;
int item_size;
struct hashtable_internal_slot_t* slots;
int slot_capacity;
HASHTABLE_U64* items_key;
int* items_slot;
void* items_data;
int item_capacity;
void* swap_temp;
};
#ifndef HASHTABLE_SIZE_T
#include <stddef.h>
#define HASHTABLE_SIZE_T size_t
#endif
#ifndef HASHTABLE_ASSERT
#include <assert.h>
#define HASHTABLE_ASSERT( x ) assert( x )
#endif
static HASHTABLE_U32 hashtable_internal_pow2ceil( HASHTABLE_U32 v )
{
--v;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
++v;
v += ( v == 0 );
return v;
}
void hashtable_init( hashtable_t* table, int item_size, int initial_capacity, void* memctx )
{
initial_capacity = (int)hashtable_internal_pow2ceil( initial_capacity >=0 ? (HASHTABLE_U32) initial_capacity : 32U );
table->memctx = memctx;
table->count = 0;
table->item_size = item_size;
table->slot_capacity = (int) hashtable_internal_pow2ceil( (HASHTABLE_U32) ( initial_capacity + initial_capacity / 2 ) );
int slots_size = (int)( table->slot_capacity * sizeof( *table->slots ) );
table->slots = (struct hashtable_internal_slot_t*) HASHTABLE_MALLOC( table->memctx, (HASHTABLE_SIZE_T) slots_size );
HASHTABLE_ASSERT( table->slots );
HASHTABLE_MEMSET( table->slots, 0, (HASHTABLE_SIZE_T) slots_size );
table->item_capacity = (int) hashtable_internal_pow2ceil( (HASHTABLE_U32) initial_capacity );
table->items_key = (HASHTABLE_U64*) HASHTABLE_MALLOC( table->memctx,
table->item_capacity * ( sizeof( *table->items_key ) + sizeof( *table->items_slot ) + table->item_size ) + table->item_size );
HASHTABLE_ASSERT( table->items_key );
table->items_slot = (int*)( table->items_key + table->item_capacity );
table->items_data = (void*)( table->items_slot + table->item_capacity );
table->swap_temp = (void*)( ( (uintptr_t) table->items_data ) + table->item_size * table->item_capacity );
}
void hashtable_term( hashtable_t* table )
{
HASHTABLE_FREE( table->memctx, table->items_key );
HASHTABLE_FREE( table->memctx, table->slots );
}
// from https://gist.github.com/badboy/6267743
static HASHTABLE_U32 hashtable_internal_calculate_hash( HASHTABLE_U64 key )
{
key = ( ~key ) + ( key << 18 );
key = key ^ ( key >> 31 );
key = key * 21;
key = key ^ ( key >> 11 );
key = key + ( key << 6 );
key = key ^ ( key >> 22 );
HASHTABLE_ASSERT( key );
return (HASHTABLE_U32) key;
}
static int hashtable_internal_find_slot( hashtable_t const* table, HASHTABLE_U64 key )
{
int const slot_mask = table->slot_capacity - 1;
HASHTABLE_U32 const hash = hashtable_internal_calculate_hash( key );
int const base_slot = (int)( hash & (HASHTABLE_U32)slot_mask );
int base_count = table->slots[ base_slot ].base_count;
int slot = base_slot;
while( base_count > 0 )
{
HASHTABLE_U32 slot_hash = table->slots[ slot ].key_hash;
if( slot_hash )
{
int slot_base = (int)( slot_hash & (HASHTABLE_U32)slot_mask );
if( slot_base == base_slot )
{
HASHTABLE_ASSERT( base_count > 0 );
--base_count;
if( slot_hash == hash && table->items_key[ table->slots[ slot ].item_index ] == key )
return slot;
}
}
slot = ( slot + 1 ) & slot_mask;
}
return -1;
}
static void hashtable_internal_expand_slots( hashtable_t* table )
{
int const old_capacity = table->slot_capacity;
struct hashtable_internal_slot_t* old_slots = table->slots;
table->slot_capacity *= 2;
int const slot_mask = table->slot_capacity - 1;
int const size = (int)( table->slot_capacity * sizeof( *table->slots ) );
table->slots = (struct hashtable_internal_slot_t*) HASHTABLE_MALLOC( table->memctx, (HASHTABLE_SIZE_T) size );
HASHTABLE_ASSERT( table->slots );
HASHTABLE_MEMSET( table->slots, 0, (HASHTABLE_SIZE_T) size );
for( int i = 0; i < old_capacity; ++i )
{
HASHTABLE_U32 const hash = old_slots[ i ].key_hash;
if( hash )
{
int const base_slot = (int)( hash & (HASHTABLE_U32)slot_mask );
int slot = base_slot;
while( table->slots[ slot ].key_hash )
slot = ( slot + 1 ) & slot_mask;
table->slots[ slot ].key_hash = hash;
int item_index = old_slots[ i ].item_index;
table->slots[ slot ].item_index = item_index;
table->items_slot[ item_index ] = slot;
++table->slots[ base_slot ].base_count;
}
}
HASHTABLE_FREE( table->memctx, old_slots );
}
static void hashtable_internal_expand_items( hashtable_t* table )
{
table->item_capacity *= 2;
HASHTABLE_U64* const new_items_key = (HASHTABLE_U64*) HASHTABLE_MALLOC( table->memctx,
table->item_capacity * ( sizeof( *table->items_key ) + sizeof( *table->items_slot ) + table->item_size ) + table->item_size);
HASHTABLE_ASSERT( new_items_key );
int* const new_items_slot = (int*)( new_items_key + table->item_capacity );
void* const new_items_data = (void*)( new_items_slot + table->item_capacity );
void* const new_swap_temp = (void*)( ( (uintptr_t) new_items_data ) + table->item_size * table->item_capacity );
HASHTABLE_MEMCPY( new_items_key, table->items_key, table->count * sizeof( *table->items_key ) );
HASHTABLE_MEMCPY( new_items_slot, table->items_slot, table->count * sizeof( *table->items_key ) );
HASHTABLE_MEMCPY( new_items_data, table->items_data, (HASHTABLE_SIZE_T) table->count * table->item_size );
HASHTABLE_FREE( table->memctx, table->items_key );
table->items_key = new_items_key;
table->items_slot = new_items_slot;
table->items_data = new_items_data;
table->swap_temp = new_swap_temp;
}
void* hashtable_insert( hashtable_t* table, HASHTABLE_U64 key, void const* item )
{
HASHTABLE_ASSERT( hashtable_internal_find_slot( table, key ) < 0 );
if( table->count >= ( table->slot_capacity - table->slot_capacity / 3 ) )
hashtable_internal_expand_slots( table );
int const slot_mask = table->slot_capacity - 1;
HASHTABLE_U32 const hash = hashtable_internal_calculate_hash( key );
int const base_slot = (int)( hash & (HASHTABLE_U32)slot_mask );
int base_count = table->slots[ base_slot ].base_count;
int slot = base_slot;
int first_free = slot;
while( base_count )
{
HASHTABLE_U32 const slot_hash = table->slots[ slot ].key_hash;
if( slot_hash == 0 && table->slots[ first_free ].key_hash != 0 ) first_free = slot;
int slot_base = (int)( slot_hash & (HASHTABLE_U32)slot_mask );
if( slot_base == base_slot )
--base_count;
slot = ( slot + 1 ) & slot_mask;
}
slot = first_free;
while( table->slots[ slot ].key_hash )
slot = ( slot + 1 ) & slot_mask;
if( table->count >= table->item_capacity )
hashtable_internal_expand_items( table );
HASHTABLE_ASSERT( !table->slots[ slot ].key_hash && ( hash & (HASHTABLE_U32) slot_mask ) == (HASHTABLE_U32) base_slot );
HASHTABLE_ASSERT( hash );
table->slots[ slot ].key_hash = hash;
table->slots[ slot ].item_index = table->count;
++table->slots[ base_slot ].base_count;
void* dest_item = (void*)( ( (uintptr_t) table->items_data ) + table->count * table->item_size );
memcpy( dest_item, item, (HASHTABLE_SIZE_T) table->item_size );
table->items_key[ table->count ] = key;
table->items_slot[ table->count ] = slot;
++table->count;
return dest_item;
}
void hashtable_remove( hashtable_t* table, HASHTABLE_U64 key )
{
int const slot = hashtable_internal_find_slot( table, key );
HASHTABLE_ASSERT( slot >= 0 );
int const slot_mask = table->slot_capacity - 1;
HASHTABLE_U32 const hash = table->slots[ slot ].key_hash;
int const base_slot = (int)( hash & (HASHTABLE_U32) slot_mask );
HASHTABLE_ASSERT( hash );
--table->slots[ base_slot ].base_count;
table->slots[ slot ].key_hash = 0;
int index = table->slots[ slot ].item_index;
int last_index = table->count - 1;
if( index != last_index )
{
table->items_key[ index ] = table->items_key[ last_index ];
table->items_slot[ index ] = table->items_slot[ last_index ];
void* dst_item = (void*)( ( (uintptr_t) table->items_data ) + index * table->item_size );
void* src_item = (void*)( ( (uintptr_t) table->items_data ) + last_index * table->item_size );
HASHTABLE_MEMCPY( dst_item, src_item, (HASHTABLE_SIZE_T) table->item_size );
table->slots[ table->items_slot[ last_index ] ].item_index = index;
}
--table->count;
}
void* hashtable_find( hashtable_t const* table, HASHTABLE_U64 key )
{
int const slot = hashtable_internal_find_slot( table, key );
if( slot < 0 ) return 0;
int const index = table->slots[ slot ].item_index;
void* const item = (void*)( ( (uintptr_t) table->items_data ) + index * table->item_size );
return item;
}
void hashtable_clear( hashtable_t* table )
{
table->count = 0;
HASHTABLE_MEMSET( table->slots, 0, table->slot_capacity * sizeof( *table->slots ) );
}
int hashtable_count( hashtable_t const* table )
{
return table->count;
}
void* hashtable_items( hashtable_t const* table )
{
return table->items_data;
}
HASHTABLE_U64 const* hashtable_keys( hashtable_t const* table )
{
return table->items_key;
}
void hashtable_swap( hashtable_t* table, int index_a, int index_b )
{
if( index_a < 0 || index_a >= table->count || index_b < 0 || index_b >= table->count ) return;
int slot_a = table->items_slot[ index_a ];
int slot_b = table->items_slot[ index_b ];
table->items_slot[ index_a ] = slot_b;
table->items_slot[ index_b ] = slot_a;
HASHTABLE_U64 temp_key = table->items_key[ index_a ];
table->items_key[ index_a ] = table->items_key[ index_b ];
table->items_key[ index_b ] = temp_key;
void* item_a = (void*)( ( (uintptr_t) table->items_data ) + index_a * table->item_size );
void* item_b = (void*)( ( (uintptr_t) table->items_data ) + index_b * table->item_size );
HASHTABLE_MEMCPY( table->swap_temp, item_a, table->item_size );
HASHTABLE_MEMCPY( item_a, item_b, table->item_size );
HASHTABLE_MEMCPY( item_b, table->swap_temp, table->item_size );
table->slots[ slot_a ].item_index = index_b;
table->slots[ slot_b ].item_index = index_a;
}
// end of hashtable.h
typedef struct
{
SPRITEBATCH_U64 image_id;
SPRITEBATCH_U64 sort_bits;
int w;
int h;
float x, y;
float sx, sy;
float c, s;
} spritebatch_internal_sprite_t;
typedef struct
{
int timestamp;
int w, h;
float minx, miny;
float maxx, maxy;
SPRITEBATCH_U64 image_id;
} spritebatch_internal_texture_t;
typedef struct spritebatch_internal_atlas_t
{
SPRITEBATCH_U64 texture_id;
float volume_ratio;
hashtable_t sprites_to_textures;
struct spritebatch_internal_atlas_t* next;
struct spritebatch_internal_atlas_t* prev;
} spritebatch_internal_atlas_t;
typedef struct
{
int timestamp;
int w, h;
SPRITEBATCH_U64 image_id;
SPRITEBATCH_U64 texture_id;
} spritebatch_internal_lonely_texture_t;
struct spritebatch_t
{
int input_count;
int input_capacity;
spritebatch_internal_sprite_t* input_buffer;
int sprite_count;
int sprite_capacity;
spritebatch_sprite_t* sprites;
int key_buffer_count;
int key_buffer_capacity;
SPRITEBATCH_U64* key_buffer;
hashtable_t sprites_to_lonely_textures;
hashtable_t sprites_to_atlases;
spritebatch_internal_atlas_t* atlases;
int pixel_stride;
int atlas_width_in_pixels;
int atlas_height_in_pixels;
int ticks_to_decay_texture;
int lonely_buffer_count_till_flush;
int lonely_buffer_count_till_decay;
float ratio_to_decay_atlas;
float ratio_to_merge_atlases;
submit_batch_t batch_callback;
get_pixels_t get_pixels_callback;
generate_texture_handle_t generate_texture_callback;
destroy_texture_handle_t delete_texture_callback;
void* mem_ctx;
};
//@dp
spritebatch_t* spritebatch_create()
{
spritebatch_t* batch = (spritebatch_t*)malloc(sizeof(spritebatch_t));
memset(batch, 0, sizeof(spritebatch_t));
return batch;
}
//@dp
void spritebatch_destroy(spritebatch_t* sb)
{
if (sb)
free(sb);
}
int spritebatch_init(spritebatch_t* sb, spritebatch_config_t* config)
{
// read config params
if (!config | !sb) return 1;
sb->pixel_stride = config->pixel_stride;
sb->atlas_width_in_pixels = config->atlas_width_in_pixels;
sb->atlas_height_in_pixels = config->atlas_height_in_pixels;
sb->ticks_to_decay_texture = config->ticks_to_decay_texture;
sb->lonely_buffer_count_till_flush = config->lonely_buffer_count_till_flush;
sb->lonely_buffer_count_till_decay = sb->lonely_buffer_count_till_flush / 2;
if (sb->lonely_buffer_count_till_decay <= 0) sb->lonely_buffer_count_till_decay = 1;
sb->ratio_to_decay_atlas = config->ratio_to_decay_atlas;
sb->ratio_to_merge_atlases = config->ratio_to_merge_atlases;
sb->batch_callback = config->batch_callback;
sb->get_pixels_callback = config->get_pixels_callback;
sb->generate_texture_callback = config->generate_texture_callback;
sb->delete_texture_callback = config->delete_texture_callback;
sb->mem_ctx = config->allocator_context;
if (sb->atlas_width_in_pixels < 1 || sb->atlas_height_in_pixels < 1) return 1;
if (sb->ticks_to_decay_texture < 1) return 1;
if (sb->ratio_to_decay_atlas < 0 || sb->ratio_to_decay_atlas > 1.0f) return 1;
if (sb->ratio_to_merge_atlases < 0 || sb->ratio_to_merge_atlases > 0.5f) return 1;
if (!sb->batch_callback) return 1;
if (!sb->get_pixels_callback) return 1;
if (!sb->generate_texture_callback) return 1;
if (!sb->delete_texture_callback) return 1;
// initialize input buffer
sb->input_count = 0;
sb->input_capacity = 1024;
sb->input_buffer = (spritebatch_internal_sprite_t*)SPRITEBATCH_MALLOC(sizeof(spritebatch_internal_sprite_t) * sb->input_capacity, sb->mem_ctx);
if (!sb->input_buffer) return 1;
// initialize sprite buffer
sb->sprite_count = 0;
sb->sprite_capacity = 1024;
sb->sprites = (spritebatch_sprite_t*)SPRITEBATCH_MALLOC(sizeof(spritebatch_sprite_t) * sb->sprite_capacity, sb->mem_ctx);
if (!sb->sprites) return 1;
// initialize key buffer (for marking hash table entries for deletion)
sb->key_buffer_count = 0;
sb->key_buffer_capacity = 1024;
sb->key_buffer = (SPRITEBATCH_U64*)SPRITEBATCH_MALLOC(sizeof(SPRITEBATCH_U64) * sb->key_buffer_capacity, sb->mem_ctx);
// setup tables
hashtable_init(&sb->sprites_to_lonely_textures, sizeof(spritebatch_internal_lonely_texture_t), 1024, sb->mem_ctx);
hashtable_init(&sb->sprites_to_atlases, sizeof(spritebatch_internal_atlas_t*), 16, sb->mem_ctx);
sb->atlases = 0;
return 0;
}
void spritebatch_term(spritebatch_t* sb)
{
SPRITEBATCH_FREE(sb->input_buffer, sb->mem_ctx);
SPRITEBATCH_FREE(sb->sprites, sb->mem_ctx);
SPRITEBATCH_FREE(sb->key_buffer, sb->mem_ctx);
hashtable_term(&sb->sprites_to_lonely_textures);
hashtable_term(&sb->sprites_to_atlases);
if (sb->atlases)
{
spritebatch_internal_atlas_t* atlas = sb->atlases;
spritebatch_internal_atlas_t* sentinel = sb->atlases;
do
{
hashtable_term(&atlas->sprites_to_textures);
spritebatch_internal_atlas_t* next = atlas->next;
SPRITEBATCH_FREE(atlas, sb->mem_ctx);
atlas = next;
}
while (atlas != sentinel);
}
SPRITEBATCH_MEMSET(sb, 0, sizeof(spritebatch_t));
}
void spritebatch_set_default_config(spritebatch_config_t* config)
{
config->pixel_stride = sizeof(char) * 4;
config->atlas_width_in_pixels = 1024;
config->atlas_height_in_pixels = 1024;
config->ticks_to_decay_texture = 60 * 30;
config->lonely_buffer_count_till_flush = 64;
config->ratio_to_decay_atlas = 0.5f;
config->ratio_to_merge_atlases = 0.25f;
config->batch_callback = 0;
config->generate_texture_callback = 0;
config->delete_texture_callback = 0;
config->allocator_context = 0;
}
#define SPRITEBATCH_CHECK_BUFFER_GROW(ctx, count, capacity, data, type_size) \
do { \
if (ctx->count == ctx->capacity) \
{ \
int new_capacity = ctx->capacity * 2; \
void* new_data = SPRITEBATCH_MALLOC(new_capacity, ctx->mem_ctx); \
if (!new_data) return 0; \
SPRITEBATCH_MEMCPY(new_data, ctx->data, type_size * ctx->count); \
SPRITEBATCH_FREE(ctx->data, ctx->mem_ctx); \
ctx->data = new_data; \
ctx->capacity = new_capacity; \
} \
} while (0)
static SPRITEBATCH_U64 spritebatch_make_sort_key(int index, int sort_bits)
{
return (((SPRITEBATCH_U64)sort_bits) << 32) | ((SPRITEBATCH_U64)index);
}
int spritebatch_push(spritebatch_t* sb, SPRITEBATCH_U64 image_id, int w, int h, float x, float y, float sx, float sy, float c, float s, int sort_bits)
{
SPRITEBATCH_CHECK_BUFFER_GROW(sb, input_count, input_capacity, input_buffer, sizeof(spritebatch_internal_sprite_t));
spritebatch_internal_sprite_t sprite;
sprite.image_id = image_id;
sprite.sort_bits = spritebatch_make_sort_key(sb->input_count, sort_bits);
sprite.w = w;
sprite.h = h;
sprite.x = x;
sprite.y = y;
sprite.sx = sx;
sprite.sy = sy;
sprite.c = c;
sprite.s = s;
sb->input_buffer[sb->input_count++] = sprite;
return 1;
}
static int spritebatch_internal_instance_pred(spritebatch_sprite_t* a, spritebatch_sprite_t* b)
{
if (a->sort_bits < b->sort_bits) return 1;
else if(a->sort_bits == b->sort_bits) return a->texture_id < b->texture_id;
else return 0;
}
static void spritebatch_internal_qsort_sprites(spritebatch_sprite_t* items, int count)
{
if (count <= 1) return;
spritebatch_sprite_t pivot = items[count - 1];
int low = 0;
for (int i = 0; i < count - 1; ++i)
{
if (spritebatch_internal_instance_pred(items + i, &pivot))
{
spritebatch_sprite_t tmp = items[i];
items[i] = items[low];
items[low] = tmp;
low++;
}
}
items[count - 1] = items[low];
items[low] = pivot;
spritebatch_internal_qsort_sprites(items, low);
spritebatch_internal_qsort_sprites(items + low + 1, count - 1 - low);
}
spritebatch_internal_lonely_texture_t* spritebatch_internal_lonelybuffer_push(spritebatch_t* sb, SPRITEBATCH_U64 image_id, int w, int h, int make_tex)
{
spritebatch_internal_lonely_texture_t texture;
texture.timestamp = 0;
texture.w = w;
texture.h = h;
texture.image_id = image_id;
texture.texture_id = make_tex ? sb->generate_texture_callback(sb->get_pixels_callback(image_id), w, h) : ~0;
return (spritebatch_internal_lonely_texture_t*)hashtable_insert(&sb->sprites_to_lonely_textures, image_id, &texture);
}
int spritebatch_internal_lonely_sprite(spritebatch_t* sb, spritebatch_internal_sprite_t* s, spritebatch_sprite_t* sprite, int skip_missing_textures)
{
spritebatch_internal_lonely_texture_t* tex = (spritebatch_internal_lonely_texture_t*)hashtable_find(&sb->sprites_to_lonely_textures, s->image_id);
if (skip_missing_textures)
{
if (!tex) spritebatch_internal_lonelybuffer_push(sb, s->image_id, s->w, s->h, 0);
return 1;
}
else
{
if (!tex) tex = spritebatch_internal_lonelybuffer_push(sb, s->image_id, s->w, s->h, 1);
else if (tex->texture_id == ~0) tex->texture_id = sb->generate_texture_callback(sb->get_pixels_callback(s->image_id), s->w, s->h);
tex->timestamp = 0;
sprite->texture_id = tex->texture_id;
sprite->minx = sprite->miny = 0;
sprite->maxx = sprite->maxy = 1.0f;
if (SPRITEBATCH_LONELY_FLIP_Y_AXIS_FOR_UV)
{
float tmp = sprite->miny;
sprite->miny = sprite->maxy;
sprite->maxy = tmp;
}
return 0;
}
}
int spritebatch_internal_push_sprite(spritebatch_t* sb, spritebatch_internal_sprite_t* s, int skip_missing_textures)
{
int skipped_tex = 0;
spritebatch_sprite_t sprite;
sprite.sort_bits = s->sort_bits;
sprite.x = s->x;
sprite.y = s->y;
sprite.sx = s->sx;
sprite.sy = s->sy;
sprite.c = s->c;
sprite.s = s->s;
void* atlas_ptr = hashtable_find(&sb->sprites_to_atlases, s->image_id);
if (atlas_ptr)
{
spritebatch_internal_atlas_t* atlas = *(spritebatch_internal_atlas_t**)atlas_ptr;
sprite.texture_id = atlas->texture_id;
spritebatch_internal_texture_t* tex = (spritebatch_internal_texture_t*)hashtable_find(&atlas->sprites_to_textures, s->image_id);
SPRITEBATCH_ASSERT(tex);
tex->timestamp = 0;
tex->w = s->w;
tex->h = s->h;
sprite.minx = tex->minx;
sprite.miny = tex->miny;
sprite.maxx = tex->maxx;
sprite.maxy = tex->maxy;
}
else skipped_tex = spritebatch_internal_lonely_sprite(sb, s, &sprite, skip_missing_textures);
if (!skipped_tex)
{
SPRITEBATCH_CHECK_BUFFER_GROW(sb, sprite_count, sprite_capacity, sprites, sizeof(spritebatch_sprite_t));
sb->sprites[sb->sprite_count++] = sprite;
}
return skipped_tex;
}
void spritebatch_internal_process_input(spritebatch_t* sb, int skip_missing_textures)
{
int skipped_index = 0;
for (int i = 0; i < sb->input_count; ++i)
{
spritebatch_internal_sprite_t* s = sb->input_buffer + i;
int skipped = spritebatch_internal_push_sprite(sb, s, skip_missing_textures);
if (skip_missing_textures && skipped) sb->input_buffer[skipped_index++] = *s;
}
sb->input_count = skipped_index;
}
void spritebatch_tick(spritebatch_t* sb)
{
spritebatch_internal_atlas_t* atlas = sb->atlases;
if (atlas)
{
spritebatch_internal_atlas_t* sentinel = atlas;
do
{
int texture_count = hashtable_count(&atlas->sprites_to_textures);
spritebatch_internal_texture_t* textures = (spritebatch_internal_texture_t*)hashtable_items(&atlas->sprites_to_textures);
for (int i = 0; i < texture_count; ++i) textures[i].timestamp += 1;
atlas = atlas->next;
}
while (atlas != sentinel);
}
int texture_count = hashtable_count(&sb->sprites_to_lonely_textures);
spritebatch_internal_lonely_texture_t* lonely_textures = (spritebatch_internal_lonely_texture_t*)hashtable_items(&sb->sprites_to_lonely_textures);
for (int i = 0; i < texture_count; ++i) lonely_textures[i].timestamp += 1;
}
int spritebatch_flush(spritebatch_t* sb)
{
// process input buffer, make any necessary lonely textures
// convert user sprites to internal format
// lookup uv coordinates
spritebatch_internal_process_input(sb, 0);
// patchup any missing lonely textures that may have come from atlases decaying and whatnot
int texture_count = hashtable_count(&sb->sprites_to_lonely_textures);
spritebatch_internal_lonely_texture_t* lonely_textures = (spritebatch_internal_lonely_texture_t*)hashtable_items(&sb->sprites_to_lonely_textures);
for (int i = 0; i < texture_count; ++i)
{
spritebatch_internal_lonely_texture_t* lonely = lonely_textures + i;
if (lonely->texture_id == ~0) lonely->texture_id = sb->generate_texture_callback(sb->get_pixels_callback(lonely->image_id), lonely->w, lonely->h);
}
// sort internal sprite buffer and submit batches
spritebatch_internal_qsort_sprites(sb->sprites, sb->sprite_count);
int min = 0;
int max = 0;
int done = !sb->sprite_count;
int count = 0;
while (!done)
{
SPRITEBATCH_U64 id = sb->sprites[min].texture_id;
while (1)
{
if (max == sb->sprite_count)
{
done = 1;
break;
}
if (id != sb->sprites[max].texture_id)
break;
++max;
}
int batch_count = max - min;
if (batch_count)
{
sb->batch_callback(sb->sprites + min, batch_count);
++count;
}
min = max;
}
sb->sprite_count = 0;
return count;
}
typedef struct
{
int x;
int y;
} spritebatch_v2_t;
typedef struct
{
int img_index;
spritebatch_v2_t size;
spritebatch_v2_t min;
spritebatch_v2_t max;
int fit;
} spritebatch_internal_integer_image_t;
static spritebatch_v2_t spritebatch_v2(int x, int y)
{
spritebatch_v2_t v;
v.x = x;
v.y = y;
return v;
}
static spritebatch_v2_t spritebatch_sub(spritebatch_v2_t a, spritebatch_v2_t b)
{
spritebatch_v2_t v;
v.x = a.x - b.x;
v.y = a.y - b.y;
return v;
}
static spritebatch_v2_t spritebatch_add(spritebatch_v2_t a, spritebatch_v2_t b)
{
spritebatch_v2_t v;
v.x = a.x + b.x;
v.y = a.y + b.y;
return v;
}
typedef struct
{
spritebatch_v2_t size;
spritebatch_v2_t min;
spritebatch_v2_t max;
} spritebatch_internal_atlas_node_t;
static spritebatch_internal_atlas_node_t* spritebatch_best_fit(int sp, int w, int h, spritebatch_internal_atlas_node_t* nodes)
{
int best_volume = INT_MAX;
spritebatch_internal_atlas_node_t *best_node = 0;
int img_volume = w * h;
for ( int i = 0; i < sp; ++i )
{
spritebatch_internal_atlas_node_t *node = nodes + i;
int can_contain = node->size.x >= w && node->size.y >= h;
if ( can_contain )
{
int node_volume = node->size.x * node->size.y;
if ( node_volume == img_volume ) return node;
if ( node_volume < best_volume )
{
best_volume = node_volume;
best_node = node;
}
}
}
return best_node;
}
static int spritebatch_internal_perimeter_pred(spritebatch_internal_integer_image_t* a, spritebatch_internal_integer_image_t* b)
{
int perimeterA = 2 * (a->size.x + a->size.y);
int perimeterB = 2 * (b->size.x + b->size.y);
return perimeterB < perimeterA;
}
static void spritebatch_internal_image_sort(spritebatch_internal_integer_image_t* items, int count)
{
if (count <= 1) return;
spritebatch_internal_integer_image_t pivot = items[count - 1];
int low = 0;
for (int i = 0; i < count - 1; ++i)
{
if (spritebatch_internal_perimeter_pred(items + i, &pivot))
{
spritebatch_internal_integer_image_t tmp = items[i];
items[i] = items[low];
items[low] = tmp;
low++;
}
}
items[count - 1] = items[low];
items[low] = pivot;
spritebatch_internal_image_sort(items, low);
spritebatch_internal_image_sort(items + low + 1, count - 1 - low);
}
typedef struct
{
int img_index; // index into the `imgs` array
int w, h; // pixel w/h of original image
float minx, miny; // u coordinate
float maxx, maxy; // v coordinate
int fit; // non-zero if image fit and was placed into the atlas
} spritebatch_internal_atlas_image_t;
#define SPRITEBATCH_CHECK( X, Y ) do { if ( !(X) ) { SPRITEBATCH_LOG(Y); goto sb_err; } } while ( 0 )
void spritebatch_make_atlas(spritebatch_t* sb, spritebatch_internal_atlas_t* atlas_out, const spritebatch_internal_lonely_texture_t* imgs, int img_count)
{
float w0, h0, div, wTol, hTol;
int atlas_image_size, atlas_stride, sp;
void* atlas_pixels = 0;
int atlas_node_capacity = img_count * 2;
spritebatch_internal_integer_image_t* images = 0;
spritebatch_internal_atlas_node_t* nodes = 0;
int pixel_stride = sb->pixel_stride;
int atlas_width = sb->atlas_width_in_pixels;
int atlas_height = sb->atlas_height_in_pixels;
float volume_used = 0;
images = (spritebatch_internal_integer_image_t*)SPRITEBATCH_MALLOC(sizeof(spritebatch_internal_integer_image_t) * img_count, sb->mem_ctx);
nodes = (spritebatch_internal_atlas_node_t*)SPRITEBATCH_MALLOC(sizeof(spritebatch_internal_atlas_node_t) * atlas_node_capacity, sb->mem_ctx);
SPRITEBATCH_CHECK(images, "out of mem");
SPRITEBATCH_CHECK(nodes, "out of mem");
for (int i = 0; i < img_count; ++i)
{
const spritebatch_internal_lonely_texture_t* img = imgs + i;
spritebatch_internal_integer_image_t* image = images + i;
image->fit = 0;
image->size = spritebatch_v2(img->w, img->h);
image->img_index = i;
}
// Sort PNGs from largest to smallest
spritebatch_internal_image_sort(images, img_count);
// stack pointer, the stack is the nodes array which we will
// allocate nodes from as necessary.
sp = 1;
nodes[0].min = spritebatch_v2(0, 0 );
nodes[0].max = spritebatch_v2(atlas_width, atlas_height);
nodes[0].size = spritebatch_v2(atlas_width, atlas_height);
// Nodes represent empty space in the atlas. Placing a texture into the
// atlas involves splitting a node into two smaller pieces (or, if a
// perfect fit is found, deleting the node).
for (int i = 0; i < img_count; ++i)
{
spritebatch_internal_integer_image_t* image = images + i;
const spritebatch_internal_lonely_texture_t* img = imgs + image->img_index;
int width = img->w;
int height = img->h;
spritebatch_internal_atlas_node_t *best_fit = spritebatch_best_fit(sp, img->w, img->h, nodes);
image->min = best_fit->min;
image->max = spritebatch_add(image->min, image->size);
if (best_fit->size.x == width && best_fit->size.y == height)
{
spritebatch_internal_atlas_node_t* last_node = nodes + --sp;
*best_fit = *last_node;
image->fit = 1;
continue;
}
image->fit = 1;
if (sp == atlas_node_capacity)
{
int new_capacity = atlas_node_capacity * 2;
spritebatch_internal_atlas_node_t* new_nodes = (spritebatch_internal_atlas_node_t*)SPRITEBATCH_MALLOC(sizeof(spritebatch_internal_atlas_node_t) * new_capacity, mem_ctx);
SPRITEBATCH_CHECK(new_nodes, "out of mem");
memcpy(new_nodes, nodes, sizeof(spritebatch_internal_atlas_node_t) * sp);
SPRITEBATCH_FREE(nodes, mem_ctx);
nodes = new_nodes;
atlas_node_capacity = new_capacity;
}
spritebatch_internal_atlas_node_t* new_node = nodes + sp++;
new_node->min = best_fit->min;
// Split bestFit along x or y, whichever minimizes
// fragmentation of empty space
spritebatch_v2_t d = spritebatch_sub(best_fit->size, spritebatch_v2(width, height));
if (d.x < d.y)
{
new_node->size.x = d.x;
new_node->size.y = height;
new_node->min.x += width;
best_fit->size.y = d.y;
best_fit->min.y += height;
}
else
{
new_node->size.x = width;
new_node->size.y = d.y;
new_node->min.y += height;
best_fit->size.x = d.x;
best_fit->min.x += width;
}
new_node->max = spritebatch_add(new_node->min, new_node->size);
}
// Write the final atlas image, use SPRITEBATCH_ATLAS_EMPTY_COLOR as base color
atlas_stride = atlas_width * pixel_stride;
atlas_image_size = atlas_width * atlas_height * pixel_stride;
atlas_pixels = SPRITEBATCH_MALLOC(atlas_image_size, mem_ctx);
SPRITEBATCH_CHECK(atlas_image_size, "out of mem");
memset(atlas_pixels, SPRITEBATCH_ATLAS_EMPTY_COLOR, atlas_image_size);
for (int i = 0; i < img_count; ++i)
{
spritebatch_internal_integer_image_t* image = images + i;
if (image->fit)
{
const spritebatch_internal_lonely_texture_t* img = imgs + image->img_index;
char* pixels = (char*)sb->get_pixels_callback(img->image_id);
spritebatch_v2_t min = image->min;
spritebatch_v2_t max = image->max;
int atlas_offset = min.x * pixel_stride;
int tex_stride = img->w * pixel_stride;
for (int row = min.y, y = 0; row < max.y; ++row, ++y)
{
void* row_ptr = (char*)atlas_pixels + (row * atlas_stride + atlas_offset);
SPRITEBATCH_MEMCPY(row_ptr, pixels + y * tex_stride, tex_stride);
}
}
}
hashtable_init(&atlas_out->sprites_to_textures, sizeof(spritebatch_internal_texture_t), img_count, sb->mem_ctx);
atlas_out->texture_id = sb->generate_texture_callback(atlas_pixels, atlas_width, atlas_height);
// squeeze UVs inward by 128th of a pixel
// this prevents atlas bleeding. tune as necessary for good results.
w0 = 1.0f / (float)(atlas_width);
h0 = 1.0f / (float)(atlas_height);
div = 1.0f / 128.0f;
wTol = w0 * div;
hTol = h0 * div;
for (int i = 0; i < img_count; ++i)
{
spritebatch_internal_integer_image_t* img = images + i;
if (img->fit)
{
spritebatch_v2_t min = img->min;
spritebatch_v2_t max = img->max;
volume_used += img->size.x * img->size.y;
float min_x = (float)min.x * w0 + wTol;
float min_y = (float)min.y * h0 + hTol;
float max_x = (float)max.x * w0 - wTol;
float max_y = (float)max.y * h0 - hTol;
// flip image on y axis
if (SPRITEBATCH_ATLAS_FLIP_Y_AXIS_FOR_UV)
{
float tmp = min_y;
min_y = max_y;
max_y = tmp;
}
spritebatch_internal_texture_t texture;
texture.w = img->size.x;
texture.h = img->size.y;
texture.timestamp = 0;
texture.minx = min_x;
texture.miny = min_y;
texture.maxx = max_x;
texture.maxy = max_y;
SPRITEBATCH_ASSERT(!(img->size.x < 0));
SPRITEBATCH_ASSERT(!(img->size.y < 0));
SPRITEBATCH_ASSERT(!(min_x < 0));
SPRITEBATCH_ASSERT(!(max_x < 0));
SPRITEBATCH_ASSERT(!(min_y < 0));
SPRITEBATCH_ASSERT(!(max_y < 0));
texture.image_id = imgs[img->img_index].image_id;
hashtable_insert(&atlas_out->sprites_to_textures, texture.image_id, &texture);
}
}
// Need to adjust atlas_width and atlas_height in config params, as none of the images for this
// atlas actually fit inside of the atlas! Either adjust the config, or stop sending giant images
// to the sprite batcher.
SPRITEBATCH_ASSERT(volume_used > 0);
atlas_out->volume_ratio = volume_used / (atlas_width * atlas_height);
sb_err:
// no specific error handling needed here (yet)
SPRITEBATCH_FREE(atlas_pixels, mem_ctx);
SPRITEBATCH_FREE(nodes, mem_ctx);
SPRITEBATCH_FREE(images, mem_ctx);
return;
}
static int spritebatch_internal_lonely_pred(spritebatch_internal_lonely_texture_t* a, spritebatch_internal_lonely_texture_t* b)
{
return a->timestamp < b->timestamp;
}
static void spritebatch_internal_qsort_lonely(hashtable_t* lonely_table, spritebatch_internal_lonely_texture_t* items, int count)
{
if (count <= 1) return;
spritebatch_internal_lonely_texture_t pivot = items[count - 1];
int low = 0;
for (int i = 0; i < count - 1; ++i)
{
if (spritebatch_internal_lonely_pred(items + i, &pivot))
{
hashtable_swap(lonely_table, i, low);
low++;
}
}
hashtable_swap(lonely_table, low, count - 1);
spritebatch_internal_qsort_lonely(lonely_table, items, low);
spritebatch_internal_qsort_lonely(lonely_table, items + low + 1, count - 1 - low);
}
int spritebatch_internal_buffer_key(spritebatch_t* sb, SPRITEBATCH_U64 key)
{
SPRITEBATCH_CHECK_BUFFER_GROW(sb, key_buffer_count, key_buffer_capacity, key_buffer, sizeof(SPRITEBATCH_U64));
sb->key_buffer[sb->key_buffer_count++] = key;
return 0;
}
void spritebatch_internal_remove_table_entries(spritebatch_t* sb, hashtable_t* table)
{
for (int i = 0; i < sb->key_buffer_count; ++i) hashtable_remove(table, sb->key_buffer[i]);
sb->key_buffer_count = 0;
}
void spritebatch_internal_flush_atlas(spritebatch_t* sb, spritebatch_internal_atlas_t* atlas, spritebatch_internal_atlas_t** sentinel, spritebatch_internal_atlas_t** next)
{
int ticks_to_decay_texture = sb->ticks_to_decay_texture;
int texture_count = hashtable_count(&atlas->sprites_to_textures);
spritebatch_internal_texture_t* textures = (spritebatch_internal_texture_t*)hashtable_items(&atlas->sprites_to_textures);
for (int i = 0; i < texture_count; ++i)
{
spritebatch_internal_texture_t* atlas_texture = textures + i;
if (atlas_texture->timestamp < ticks_to_decay_texture)
{
spritebatch_internal_lonely_texture_t* lonely_texture = spritebatch_internal_lonelybuffer_push(sb, atlas_texture->image_id, atlas_texture->w, atlas_texture->h, 0);
lonely_texture->timestamp = atlas_texture->timestamp;
}
hashtable_remove(&sb->sprites_to_atlases, atlas_texture->image_id);
}
if (sb->atlases == atlas)
{
if (atlas->next == atlas) sb->atlases = 0;
else sb->atlases = atlas->prev;
}
// handle loop end conditions if sentinel was removed from the chain
if (sentinel && next)
{
if (*sentinel == atlas)
{
SPRITEBATCH_LOG("\t\tsentinel was also atlas: %p\n", *sentinel);
if ((*next)->next != *sentinel)
{
SPRITEBATCH_LOG("\t\t*next = (*next)->next : %p = (*next)->%p\n", *next, (*next)->next);
*next = (*next)->next;
}
SPRITEBATCH_LOG("\t\t*sentinel = *next : %p = %p\n", *sentinel, *next);
*sentinel = *next;
}
}
atlas->next->prev = atlas->prev;
atlas->prev->next = atlas->next;
hashtable_term(&atlas->sprites_to_textures);
sb->delete_texture_callback(atlas->texture_id);
SPRITEBATCH_FREE(atlas, sb->mem_ctx);
}
void spritebatch_internal_log_chain(spritebatch_internal_atlas_t* atlas)
{
if (atlas)
{
spritebatch_internal_atlas_t* sentinel = atlas;
SPRITEBATCH_LOG("sentinel: %p\n", sentinel);
do
{
spritebatch_internal_atlas_t* next = atlas->next;
SPRITEBATCH_LOG("\tatlas %p\n", atlas);
atlas = next;
}
while (atlas != sentinel);
}
}
int spritebatch_defrag(spritebatch_t* sb)
{
// remove decayed atlases and flush them to the lonely buffer
// only flush textures that are not decayed
int ticks_to_decay_texture = sb->ticks_to_decay_texture;
float ratio_to_decay_atlas = sb->ratio_to_decay_atlas;
spritebatch_internal_atlas_t* atlas = sb->atlases;
if (atlas)
{
spritebatch_internal_log_chain(atlas);
spritebatch_internal_atlas_t* sentinel = atlas;
do
{
spritebatch_internal_atlas_t* next = atlas->next;
int texture_count = hashtable_count(&atlas->sprites_to_textures);
spritebatch_internal_texture_t* textures = (spritebatch_internal_texture_t*)hashtable_items(&atlas->sprites_to_textures);
int decayed_texture_count = 0;
for (int i = 0; i < texture_count; ++i) if (textures[i].timestamp >= ticks_to_decay_texture) decayed_texture_count++;
float ratio;
if (!decayed_texture_count) ratio = 0;
else ratio = (float)texture_count / (float)decayed_texture_count;
if (ratio > ratio_to_decay_atlas)
{
SPRITEBATCH_LOG("flushed atlas %p\n", atlas);
spritebatch_internal_flush_atlas(sb, atlas, &sentinel, &next);
}
atlas = next;
}
while (atlas != sentinel);
}
// merge mostly empty atlases
float ratio_to_merge_atlases = sb->ratio_to_merge_atlases;
atlas = sb->atlases;
if (atlas)
{
int sp = 0;
spritebatch_internal_atlas_t* merge_stack[2];
spritebatch_internal_atlas_t* sentinel = atlas;
do
{
spritebatch_internal_atlas_t* next = atlas->next;
SPRITEBATCH_ASSERT(sp >= 0 && sp <= 2);
if (sp == 2)
{
SPRITEBATCH_LOG("merged 2 atlases\n");
spritebatch_internal_flush_atlas(sb, merge_stack[0], &sentinel, &next);
spritebatch_internal_flush_atlas(sb, merge_stack[1], &sentinel, &next);
sp = 0;
}
float ratio = atlas->volume_ratio;
if (ratio < ratio_to_merge_atlases) merge_stack[sp++] = atlas;
atlas = next;
}
while (atlas != sentinel);
if (sp == 2)
{
SPRITEBATCH_LOG("merged 2 atlases (out of loop)\n");
spritebatch_internal_flush_atlas(sb, merge_stack[0], 0, 0);
spritebatch_internal_flush_atlas(sb, merge_stack[1], 0, 0);
}
}
// remove decayed textures from the lonely buffer
int lonely_buffer_count_till_decay = sb->lonely_buffer_count_till_decay;
int lonely_count = hashtable_count(&sb->sprites_to_lonely_textures);
spritebatch_internal_lonely_texture_t* lonely_textures = (spritebatch_internal_lonely_texture_t*)hashtable_items(&sb->sprites_to_lonely_textures);
if (lonely_count >= lonely_buffer_count_till_decay)
{
spritebatch_internal_qsort_lonely(&sb->sprites_to_lonely_textures, lonely_textures, lonely_count);
int index = 0;
while (1)
{
if (index == lonely_count) break;
if (lonely_textures[index].timestamp >= ticks_to_decay_texture) break;
++index;
}
for (int i = index; i < lonely_count; ++i)
{
SPRITEBATCH_U64 texture_id = lonely_textures[i].texture_id;
if (texture_id != ~0) sb->delete_texture_callback(texture_id);
spritebatch_internal_buffer_key(sb, lonely_textures[i].image_id);
SPRITEBATCH_LOG("lonely texture decayed\n");
}
spritebatch_internal_remove_table_entries(sb, &sb->sprites_to_lonely_textures);
lonely_count -= lonely_count - index;
SPRITEBATCH_ASSERT(lonely_count == hashtable_count(&sb->sprites_to_lonely_textures));
}
// process input, but don't make textures just yet
spritebatch_internal_process_input(sb, 1);
lonely_count = hashtable_count(&sb->sprites_to_lonely_textures);
// while greater than lonely_buffer_count_till_flush elements in lonely buffer
// grab lonely_buffer_count_till_flush of them and make an atlas
int lonely_buffer_count_till_flush = sb->lonely_buffer_count_till_flush;
int stuck = 0;
while (lonely_count > lonely_buffer_count_till_flush && !stuck)
{
atlas = (spritebatch_internal_atlas_t*)SPRITEBATCH_MALLOC(sizeof(spritebatch_internal_atlas_t), sb->mem_ctx);
if (sb->atlases)
{
atlas->prev = sb->atlases;
atlas->next = sb->atlases->next;
sb->atlases->next->prev = atlas;
sb->atlases->next = atlas;
}
else
{
atlas->next = atlas;
atlas->prev = atlas;
sb->atlases = atlas;
}
spritebatch_make_atlas(sb, atlas, lonely_textures, lonely_count);
SPRITEBATCH_LOG("making atlas\n");
int tex_count_in_atlas = hashtable_count(&atlas->sprites_to_textures);
if (tex_count_in_atlas != lonely_count)
{
int hit_count = 0;
for (int i = 0; i < lonely_count; ++i)
{
SPRITEBATCH_U64 key = lonely_textures[i].image_id;
if (hashtable_find(&atlas->sprites_to_textures, key))
{
spritebatch_internal_buffer_key(sb, key);
SPRITEBATCH_U64 texture_id = lonely_textures[i].texture_id;
if (texture_id != ~0) sb->delete_texture_callback(texture_id);
hashtable_insert(&sb->sprites_to_atlases, key, &atlas);
SPRITEBATCH_LOG("removing lonely texture for atlas%s\n", texture_id != ~0 ? "" : " (tex was ~0)" );
}
else hit_count++;
}
spritebatch_internal_remove_table_entries(sb, &sb->sprites_to_lonely_textures);
if (!hit_count)
{
// TODO
// handle case where none fit in atlas
SPRITEBATCH_ASSERT(0);
}
}
else
{
for (int i = 0; i < lonely_count; ++i)
{
SPRITEBATCH_U64 key = lonely_textures[i].image_id;
SPRITEBATCH_U64 texture_id = lonely_textures[i].texture_id;
if (texture_id != ~0) sb->delete_texture_callback(texture_id);
hashtable_insert(&sb->sprites_to_atlases, key, &atlas);
SPRITEBATCH_LOG("(fast path) removing lonely texture for atlas%s\n", texture_id != ~0 ? "" : " (tex was ~0)" );
}
hashtable_clear(&sb->sprites_to_lonely_textures);
lonely_count = 0;
break;
}
}
return 1;
}
#endif SPRITEBATCH_IMPLEMENTATION
/*
------------------------------------------------------------------------------
This software is available under 2 licenses - you may choose the one you like.
------------------------------------------------------------------------------
ALTERNATIVE A - zlib license
Copyright (c) 2017 Randy Gaul http://www.randygaul.net
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not
be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
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 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.
------------------------------------------------------------------------------
*/
| 2.34375 | 2 |
2024-11-18T18:09:51.443283+00:00 | 2015-07-31T19:33:31 | 8b09a54421274823a44ae2bfba9813fd720d82f1 | {
"blob_id": "8b09a54421274823a44ae2bfba9813fd720d82f1",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-31T19:33:31",
"content_id": "7ec7c2bb46c45518a5f4ba98aec47a9c74ef64e4",
"detected_licenses": [
"MIT"
],
"directory_id": "2a5268a09ddc1bd8afe53032b3cfabf0f3b2b0a0",
"extension": "c",
"filename": "main.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 24499299,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 6303,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/el_example_03.X/main.c",
"provenance": "stackv2-0003.json.gz:317413",
"repo_name": "jianingchen/epucklib",
"revision_date": "2015-07-31T19:33:31",
"revision_id": "7020fb11af88926cbafb34d7a60dc964a1e62933",
"snapshot_id": "bcb7ca54edb5da08df41fff4d3a90e7e814ab1f6",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/jianingchen/epucklib/7020fb11af88926cbafb34d7a60dc964a1e62933/examples/el_example_03.X/main.c",
"visit_date": "2016-09-06T12:33:19.281929"
} | stackv2 | /*
embedded system library for e-puck - example 3
--------------------------------------------------------------------------------
code distribution:
https://github.com/jianingchen/epucklib
online documentation:
http://jianingchen.github.io/epucklib/html/
--------------------------------------------------------------------------------
This file is released under the terms of the MIT license (see "el.h").
*/
#include <el.h>
#include <elu.h>
void BootingProcedure01_SelectorBarrier();
void TimerCallback_MotionAutoStop(void*arg);
void TimerCallback_MeasureCameraFPS(void*arg);
void Process_ConsoleLoop(void*arg);
el_ir_proximity_data ProximitySensor[8];
volatile el_uint32 CameraFrameCounter;
volatile el_int16 CameraFrameRate;
el_handle CameraFrameRateTimer;
el_handle MotionTimer;
int main(void){
el_initialization();
el_calibrate_sensors();
el_uart_use_reset_code(true,128);
/*
* Put the robot in silence when the selector is in 0~3.
*/
BootingProcedure01_SelectorBarrier();
/*
* The values below are same as the default configurations; they are placed
* here just for demonstration. Note, when the automatic mode is used, the
* frame rate will be varied depending on the lighting condition of the
* environment.
*/
el_camera_options()->ExposureMode = EL_AUTOMATIC;
el_camera_options()->AutoWhiteBalance = true;
el_camera_options()->AutoDigitalGain = true;
el_camera_options_apply();
el_launch_process(Process_ConsoleLoop,NULL);
el_main_loop();
return 0;
}
void BootingProcedure01_SelectorBarrier(){
while(el_get_selector_value()<4){
el_led_set(EL_LED_RING_5,1);
el_sleep(125);
el_led_set(EL_LED_RING_5,0);
el_sleep(875);
}
}
void Process_ConsoleLoop(void*arg){
const int MOTION_TIME = 600;
char c;
int i;
elu_printf("EL_EXAMPLE_03\n");
el_stepper_motor_options()->UseAcceleration = true;
el_stepper_motor_options()->AccelerationRate = 2000;
el_config_stepper_motor(el_stepper_motor_options());
el_enable_camera();
el_enable_ir_proximity();
el_enable_stepper_motor();
el_process_wait(500);// wait for 500 ms
// setup a timer to measure framerate of the camera
CameraFrameRateTimer = el_create_timer();
el_timer_set_callback(CameraFrameRateTimer,TimerCallback_MeasureCameraFPS,NULL);
el_timer_start(CameraFrameRateTimer,1000);// 1000 milliseconds
// setup a timer to stop moving automatically after last motion command
MotionTimer = el_create_timer();
el_timer_set_periodic(MotionTimer,false);
el_timer_set_callback(MotionTimer,TimerCallback_MotionAutoStop,NULL);
el_uart_flush_char(EL_UART_1);
el_led_set(EL_LED_BODY,EL_ON);
while(1){
do{
el_process_cooperate();
}while(el_uart_get_char_counter(EL_UART_1)==0);
c = el_uart_get_char(EL_UART_1);
switch(c){
case 'H':
case 'h':// list available commands
elu_println("<HELP>");
elu_println("Key\tAction");
elu_println("'1'\ttoggle front led");
elu_println("'2'\ttoggle body led");
elu_println("'r'\treport ir proximity sensor outputs");
elu_println("'y'\treport camera framerate");
elu_println("'t'\ttransmit camera image");
elu_println("'w'\tmove forward");
elu_println("'a'\tspin left");
elu_println("'s'\tmove backward");
elu_println("'d'\tspin right");
elu_println("'q'\tturn left");
elu_println("'e'\tturn right");
elu_println("' '\tstop");
break;
case 'f':
case '1':
el_led_set(EL_LED_FRONT,EL_TOGGLE);
break;
case '2':
el_led_set(EL_LED_BODY,EL_TOGGLE);
break;
case 'r':// report ir proximity sensor outputs
elu_println("<IR>");
el_ir_proximity_get(EL_IR_PROXIMITY_SENSOR_ALL,EL_IR_ALL_3V,(el_int16*)ProximitySensor);
elu_printf("AMB:");
for(i=0;i<8;i++){
elu_printf("\t%d",ProximitySensor[i].Ambient);
}
elu_putchar('\n');
elu_printf("REF:");
for(i=0;i<8;i++){
elu_printf("\t%d",ProximitySensor[i].Reflection);
}
elu_putchar('\n');
break;
case 'y':// report camera framerate
elu_println("[CAM]\nFPS:\t%d\tNUM:\t%lu",CameraFrameRate,CameraFrameCounter);
break;
case 't':
el_camera_lock_frame();
elu_print_camera_image(el_camera_frame(),el_camera_get_frame_counter());
el_camera_unlock_frame();
elu_putchar('\n');
break;
case 'w':
el_set_wheel_speed(800,800);
el_timer_start(MotionTimer,MOTION_TIME);
break;
case 'a':
el_set_wheel_speed(-200,200);
el_timer_start(MotionTimer,MOTION_TIME);
break;
case 's':
el_set_wheel_speed(-500,-500);
el_timer_start(MotionTimer,MOTION_TIME);
break;
case 'd':
el_set_wheel_speed(200,-200);
el_timer_start(MotionTimer,MOTION_TIME);
break;
case 'q':
el_set_wheel_speed(500,800);
el_timer_start(MotionTimer,MOTION_TIME);
break;
case 'e':
el_set_wheel_speed(800,500);
el_timer_start(MotionTimer,MOTION_TIME);
break;
case ' ':
el_set_wheel_speed(0,0);
el_timer_start(MotionTimer,MOTION_TIME);
break;
}
}
}
void TimerCallback_MotionAutoStop(void*arg){
el_set_wheel_speed(0,0);
}
void TimerCallback_MeasureCameraFPS(void*args){
el_uint32 c = el_camera_get_frame_counter();
el_int16 d = c - CameraFrameCounter;
CameraFrameCounter = c;
CameraFrameRate = d;
}
| 2.609375 | 3 |
2024-11-18T18:09:51.672491+00:00 | 2023-08-22T19:06:25 | 42c15a6eda8c965ba1b20608d5841e481c9de1d4 | {
"blob_id": "42c15a6eda8c965ba1b20608d5841e481c9de1d4",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-22T19:06:25",
"content_id": "12f7e8e9ecc0e5353d2c6395b72c521910614efa",
"detected_licenses": [
"MIT"
],
"directory_id": "d153de2407f635bbd2667a6b266354d532e80e85",
"extension": "c",
"filename": "TestPairedData3.c",
"fork_events_count": 13,
"gha_created_at": "2021-03-08T16:45:37",
"gha_event_created_at": "2023-09-13T23:01:51",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 345726079,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3218,
"license": "MIT",
"license_type": "permissive",
"path": "/test/Dss-C/source/TestPairedData3.c",
"provenance": "stackv2-0003.json.gz:317671",
"repo_name": "HydrologicEngineeringCenter/hec-dss",
"revision_date": "2023-08-22T19:06:25",
"revision_id": "8587bd5339ee9aa8519d1d0d17f3625419a63122",
"snapshot_id": "195845c6312f2d9fc508032b39179f457849ede1",
"src_encoding": "UTF-8",
"star_events_count": 26,
"url": "https://raw.githubusercontent.com/HydrologicEngineeringCenter/hec-dss/8587bd5339ee9aa8519d1d0d17f3625419a63122/test/Dss-C/source/TestPairedData3.c",
"visit_date": "2023-08-30T11:56:27.416514"
} | stackv2 | #include <stdio.h>
#include <string.h>
#include "heclib.h"
#include "TestDssC.h"
int TestPairedData3(long long *ifltab)
{
zStructPairedData *pds1, *pds2, *pds3, *pds4, *pds5;
float fordinates[500], fvalues[10][500];
float *temp;
char label[20], labels[100];
int labelLength;
char pathname[100];
int numberValues;
int status, i, j;
// This function tests features not supported in DSS-6
if (zgetVersion(ifltab) == 6) {
return 0;
}
// Gen up some data
for (j=0; j<500; j++) {
fordinates[j] = (float)(j + 1) * (float)10;
for (i=0; i<10; i++) {
fvalues[i][j] = ((float)(j + 1) * (float)100.0) + (float)(i + 1);
}
}
stringCopy(pathname, sizeof(pathname), "/Basin/Location/Stage-Damage///PD 3/", _TRUNCATE);
pds1 = zstructPdNewFloats(pathname, fordinates, (float *)fvalues, 500, 10,
"feet", "linear", "dollars", "linear");
status = zpdStore(ifltab, pds1, 0);
if (status != STATUS_OKAY) return status;
//zset("mlvl", "", 15);
// Now retrieve the data
pds2 = zstructPdNew(pathname);
status = zpdRetrieve(ifltab, pds2, 0);
if (status) return status;
// compare
status = comparePDs (ifltab, pds1, pds2, "TestPairedData3, Loc 1, floats");
if (status != STATUS_OKAY) return status;
// Lets change a block of data within the curves
// It's easiest (not effiecent) to retrieve the data,
// change and store back. Let's do that for row 5-10, columns 2-5:
pds3 = zstructPdNew(pathname);
pds3->startingOrdinate = 4;
pds3->endingOrdinate = 10;
pds3->startingCurve = 2;
pds3->endingCurve = 5;
status = zpdRetrieve(ifltab, pds3, 1);
// We'll just use this as a single array for simplicity,
// instead of the doubly dimensioned array, which it really is.
numberValues = pds3->numberCurvesInStruct * pds3->numberOrdinatesInStruct;
// Let's make the values negative
for (i=0; i<numberValues; i++) {
pds3->floatValues[i] = -(pds3->floatValues[i]);
}
status = zpdStore(ifltab, pds3, 0);
if (status != STATUS_OKAY) return status;
// Now read and print the earlier block
pds4 = zstructPdNew(pathname);
pds4->startingOrdinate = pds3->startingOrdinate;
pds4->endingOrdinate = pds3->endingOrdinate;
pds4->startingCurve = pds3->startingCurve;
pds4->endingCurve = pds3->endingCurve;
status = zpdRetrieve(ifltab, pds4, 0);
status = comparePDs (ifltab, pds3, pds4, "TestPairedData3, Loc 10, A segment");
if (status != STATUS_OKAY) return status;
// Compare the full data set now
// pds2 should be the original pds1, but not what is on disk
// Change pds2 to be what should be on disk, read, and compare
for (j=pds4->startingOrdinate; j<=pds4->endingOrdinate ; j++) {
for (i=pds4->startingCurve; i<=pds4->endingCurve ; i++) {
fvalues[i-1][j-1] = -fvalues[i-1][j-1];
}
}
temp = pds2->floatValues;
pds2->floatValues = (float *)fvalues;
pds5 = zstructPdNew(pathname);
status = zpdRetrieve(ifltab, pds5, 0);
// compare
status = comparePDs (ifltab, pds2, pds5, "TestPairedData3, Loc 11, floats");
if (status) return status;
pds2->floatValues = temp;
zstructFree(pds1);
zstructFree(pds2);
zstructFree(pds3);
zstructFree(pds4);
zstructFree(pds5);
printf("Completed testPairedData3 test successfully!\n");
return 0;
}
| 2.296875 | 2 |
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 797