hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
77426e33b46ceacff27804b24e23fe4d8959c520
11,994
c
C
src/lang.c
re-Isearch/re-Isearch
f2a2012c1814b0940a6004b6186a5e6896c1135a
[ "BSD-4-Clause-UC", "Apache-2.0" ]
2
2022-02-05T17:48:29.000Z
2022-02-06T15:25:04.000Z
src/lang.c
re-Isearch/re-Isearch
f2a2012c1814b0940a6004b6186a5e6896c1135a
[ "BSD-4-Clause-UC", "Apache-2.0" ]
null
null
null
src/lang.c
re-Isearch/re-Isearch
f2a2012c1814b0940a6004b6186a5e6896c1135a
[ "BSD-4-Clause-UC", "Apache-2.0" ]
1
2022-03-30T20:14:00.000Z
2022-03-30T20:14:00.000Z
{"ab", "Abkhazian"}, {"abk", "Abkhazian"}, {"ace", "Achinese"}, {"ach", "Acoli"}, {"ada", "Adangme"}, {"om", "Afan Oromo"}, {"aa", "Afar"}, {"aar", "Afar"}, {"afr", "Africaans"}, {"afh", "Afrihili"}, {"af", "Afrikaans"}, {"afa", "Afro-Asiatic (Other)"}, {"aka", "Akan"}, {"akk", "Akkadian"}, {"alb", "Albanian"}, {"sqi", "Albanian"}, {"sq", "Albanian"}, {"ale", "Aleut"}, {"alg", "Algonquian languages"}, {"ajm", "Aljamia"}, {"tut", "Altaic (Other)"}, {"am", "Amharic"}, {"amh", "Amharic"}, {"apa", "Apache languages"}, {"ar", "Arabic"}, {"ara", "Arabic"}, {"arc", "Aramaic"}, {"arp", "Arapaho"}, {"arn", "Araucanian"}, {"arw", "Arawak"}, {"arm", "Armenian"}, {"hy", "Armenian"}, {"hye", "Armenian"}, {"art", "Artificial (Other)"}, {"as", "Assamese"}, {"asm", "Assamese"}, {"ath", "Athapascan languages"}, {"map", "Austronesian (Other)"}, {"ava", "Avaric"}, {"ave", "Avestan"}, {"awa", "Awandhi"}, {"ay", "Aymara"}, {"aym", "Aymara"}, {"az", "Azerbaijani"}, {"aze", "Azerbaijani"}, {"nah", "Aztec"}, {"ban", "Balinese"}, {"bat", "Baltic (Other)"}, {"bal", "Baluchi"}, {"bam", "Bambara"}, {"bai", "Bamileke languages"}, {"bad", "Banda"}, {"bas", "Basa"}, {"ba", "Bashkir"}, {"bak", "Bashkir"}, {"baq", "Basque"}, {"eu", "Basque"}, {"eus", "Basque"}, {"bej", "Beja"}, {"bem", "Bemba"}, {"ben", "Bengali"}, {"bn", "Bengali; Bangla"}, {"ber", "Berber languages"}, {"bho", "Bhojpuri"}, {"dz", "Bhutani"}, {"bh", "Bihari"}, {"bih", "Bihari"}, {"bik", "Bikol"}, {"bin", "Bini"}, {"bi", "Bislama"}, {"bis", "Bislama"}, {"bra", "Braj"}, {"br", "Breton"}, {"bre", "Breton"}, {"bug", "Buginese"}, {"bg", "Bulgarian"}, {"bul", "Bulgarian"}, {"bur", "Burmese"}, {"my", "Burmese"}, {"mya", "Burmese"}, {"be", "Byelorussian"}, {"bel", "Byelorussian"}, {"cad", "Caddo"}, {"km", "Cambodian"}, {"car", "Carib"}, {"ca", "Catalan"}, {"cat", "Catalan"}, {"cau", "Caucasian (Other)"}, {"ceb", "Cebuano"}, {"cel", "Celtic (Other)"}, {"cai", "Central American Indian (Other)"}, {"chg", "Chagatai"}, {"cha", "Chamorro"}, {"che", "Chechen"}, {"chr", "Cherokee"}, {"chy", "Cheyenne"}, {"chb", "Chibcha"}, {"chi", "Chinese"}, {"zh", "Chinese"}, {"zho", "Chinese"}, {"chn", "Chinook jargon"}, {"cho", "Choctaw"}, {"chu", "Church Slavic"}, {"chv", "Chuvash"}, {"cop", "Coptic"}, {"cor", "Cornish"}, {"co", "Corsican"}, {"cos", "Corsican"}, {"cre", "Cree"}, {"mus", "Creek"}, {"crp", "Creoles and pidgins (Other)"}, {"cpe", "Creoles and pidgins, English-based (Other)"}, {"cpf", "Creoles and pidgins, French-based (Other)"}, {"cpp", "Creoles and pidgins, Portuguese-based (Other)"}, {"hr", "Croatian"}, {"cus", "Cushitic (Other)"}, {"cs", "Czech"}, {"cze", "Czech"}, {"ces", "Czeck"}, {"dak", "Dakota"}, {"da", "Danish"}, {"dan", "Danish"}, {"del", "Delaware"}, {"din", "Dinka"}, {"doi", "Dogri"}, {"dra", "Dravidian (Other)"}, {"dua", "Duala"}, {"dut", "Dutch"}, {"nl", "Dutch"}, {"nld", "Dutch"}, {"dum", "Dutch, Middle (ca. 1050-1350)"}, {"dyu", "Dyula"}, {"dzo", "Dzongkha"}, {"efi", "Efik"}, {"egy", "Egyptian (Ancient)"}, {"eka", "Ekajuk"}, {"elx", "Elamite"}, {"en", "English"}, {"eng", "English"}, {"enm", "English, Middle (1100-1500)"}, {"ang", "English, Old (ca. 450-1100)"}, {"esk", "Eskimo (Other)"}, {"eo", "Esperanto"}, {"epo", "Esperanto"}, {"est", "Estonian"}, {"et", "Estonian"}, {"eth", "Ethiopic"}, {"ewe", "Ewe"}, {"ewo", "Ewondo"}, {"fo", "Faeroese"}, {"fan", "Fang"}, {"fat", "Fanti"}, {"fao", "Faroese"}, {"fj", "Fiji"}, {"fij", "Fijian"}, {"fi", "Finnish"}, {"fin", "Finnish"}, {"fiu", "Finno-Ugrian (Other)"}, {"fon", "Fon"}, {"fr", "French"}, {"fra", "French"}, {"fre", "French"}, {"frm", "French, Middel (ca. 1400-1600)"}, {"fro", "French, Old (ca. 842-1400)"}, {"fry", "Friesian"}, {"fy", "Frisian"}, {"ful", "Fulah"}, {"gaa", "Ga"}, {"gae", "Gaelic (Scots)"}, {"gdh", "Gaelic (Scots)"}, {"gl", "Galician"}, {"glg", "Gallegan"}, {"lug", "Ganda"}, {"gay", "Gayo"}, {"geo", "Georgian"}, {"ka", "Georgian"}, {"kat", "Georgian"}, {"de", "German"}, {"deu", "German"}, {"ger", "German"}, {"gmh", "German, Middle High (ca. 1050-1500)"}, {"goh", "German, Old High (ca. 750-1050)"}, {"gem", "Germanic (Other)"}, {"gil", "Gilbertese"}, {"gon", "Gondi"}, {"got", "Gothic"}, {"kl", "Greaenlandic"}, {"grb", "Grebo"}, {"el", "Greek"}, {"grc", "Greek, Ancient (to 1453)"}, {"ell", "Greek, Modern (1453- )"}, {"gre", "Greek, Modern (1453- )"}, {"kal", "Greenlandic"}, {"gn", "Guamni"}, {"grn", "Guarani"}, {"gu", "Gujarati"}, {"guj", "Gujarati"}, {"hai", "Haida"}, {"ha", "Hausa"}, {"hau", "Hausa"}, {"haw", "Hawaiian"}, {"he", "Hebrew"}, {"heb", "Hebrew"}, {"iw", "Hebrew, to be removed, see he"}, {"her", "Herero"}, {"hil", "Hiligaynon"}, {"him", "Himachali"}, {"hi", "Hindi"}, {"hin", "Hindi"}, {"hmo", "Hiri Motu"}, {"hu", "Hungarian"}, {"hun", "Hungarian"}, {"hup", "Hupa"}, {"iba", "Iban"}, {"ice", "Icelandic"}, {"is", "Icelandic"}, {"isl", "Icelandic"}, {"ibo", "Igbo"}, {"ijo", "Ijo"}, {"ilo", "Iloko"}, {"inc", "Indic (Other)"}, {"ine", "Indo-European (Other)"}, {"id", "Indonesian"}, {"ind", "Indonesian"}, {"in", "Indonesian, to be removed, see id"}, {"ia", "Interlingua"}, {"ina", "Interlingua (International Auxilary Language Association)"}, {"ile", "Interlingue"}, {"iku", "Inuktitut"}, {"iu", "Inuktitut (Eskimo)"}, {"ipk", "Inupiak"}, {"ira", "Iranian (Other)"}, {"ga", "Irish"}, {"gai", "Irish"}, {"iri", "Irish"}, {"iro", "Iroquoian languages"}, {"it", "Italian"}, {"ita", "Italian"}, {"ja", "Japanese"}, {"jpn", "Japanese"}, {"jav", "Javanese"}, {"jaw", "Javanese"}, {"jw", "Javanese"}, {"jrb", "Judeo-Arabic"}, {"jpr", "Judeo-Persian"}, {"kab", "Kabyle"}, {"kac", "Kachin"}, {"kam", "Kamba"}, {"kan", "Kannada"}, {"kn", "Kannada"}, {"kau", "Kanuri"}, {"kaa", "Kara-Kalpak"}, {"kar", "Karen"}, {"kas", "Kashmiri"}, {"ks", "Kashmiri"}, {"kaw", "Kawi"}, {"kaz", "Kazakh"}, {"kk", "Kazakh"}, {"kha", "Khasi"}, {"khm", "Khmer"}, {"khi", "Khoisan (Other)"}, {"kho", "Khotanese"}, {"kik", "Kikuyu"}, {"rw", "Kinya, Rwanda"}, {"kin", "Kinyarwanda"}, {"kir", "Kirghiz"}, {"ky", "Kirghiz"}, {"rn", "Kirundi"}, {"ik", "Knupiak"}, {"kon", "Kongo"}, {"kok", "Konkani"}, {"ko", "Korean"}, {"kor", "Korean"}, {"kpe", "Kpelle"}, {"kro", "Kru"}, {"kua", "Kuanyama"}, {"ku", "Kurdish"}, {"kur", "Kurdish"}, {"kru", "Kurukh"}, {"kus", "Kusaie"}, {"kut", "Kutenai"}, {"lad", "Ladino"}, {"lah", "Lahnda"}, {"lam", "Lamba"}, {"oci", "Langue d'oc (post 1500)"}, {"lao", "Lao"}, {"lo", "Laothian"}, {"lap", "Lapp languages"}, {"la", "Latin"}, {"lat", "Latin"}, {"lav", "Latvian"}, {"lv", "Latvian, Lettish"}, {"lin", "Lingala"}, {"ln", "Lingala"}, {"lt", "Lithuainnian"}, {"lit", "Lithuanian"}, {"ie", "lnteriingue"}, {"loz", "Lozi"}, {"lub", "Luba-Katanga"}, {"lui", "Luiseno"}, {"lun", "Lunda"}, {"luo", "Luo (Kenya and Tanzania)"}, {"mac", "Macedonian"}, {"mk", "Macedonian"}, {"mke", "Macedonian"}, {"mad", "Madurese"}, {"mag", "Magahi"}, {"mai", "Maithili"}, {"mak", "Makasar"}, {"mg", "Malagasy"}, {"mlg", "Malagasy"}, {"may", "Malay"}, {"ms", "Malay"}, {"msa", "Malay"}, {"mal", "Malayalam"}, {"ml", "Malayalam"}, {"mlt", "Maltese"}, {"mt", "Maltese"}, {"man", "Mandingo"}, {"mni", "Manipuri"}, {"mno", "Manobo languages"}, {"max", "Manx"}, {"mao", "Maori"}, {"mi", "Maori"}, {"mri", "Maori"}, {"mar", "Marathi"}, {"mr", "Marathi"}, {"mah", "Marshall"}, {"mwr", "Marwari"}, {"mas", "Masai"}, {"myn", "Mayan languages"}, {"men", "Mende"}, {"mic", "Micmac"}, {"min", "Minangkabau"}, {"mis", "Miscellaneous (Other)"}, {"moh", "Mohawk"}, {"mo", "Moldavian"}, {"mol", "Moldavian"}, {"mkh", "Mon-Khmer (Other)"}, {"lol", "Mongo"}, {"mn", "Mongolian"}, {"mon", "Mongolian"}, {"mos", "Mossi"}, {"mul", "Multiple languages"}, {"mun", "Munda (Other)"}, {"na", "Nauru"}, {"nau", "Nauru"}, {"nav", "Navajo"}, {"nde", "Ndebele (Zimbabwe)"}, {"ndo", "Ndonga"}, {"ne", "Nepali"}, {"nep", "Nepali"}, {"new", "Newari"}, {"nic", "Niger-Kordofanian (Other)"}, {"ssa", "Nilo-Saharan (Other)"}, {"niu", "Niuean"}, {"nai", "North American Indian (Other)"}, {"nso", "Northern Sohto"}, {"no", "Norwegian"}, {"nor", "Norwegian"}, {"nub", "Nubian languages"}, {"nym", "Nyamwezi"}, {"nya", "Nyanja"}, {"nyn", "Nyankole"}, {"nyo", "Nyoro"}, {"nzi", "Nzima"}, {"oc", "Occitan"}, {"oji", "Ojibwa"}, {"non", "Old Norse"}, {"peo", "Old Persian (ca. 600-400 B.C.)"}, {"or", "Oriya"}, {"ori", "Oriya"}, {"orm", "Oromo"}, {"osa", "Osage"}, {"oss", "Ossetic"}, {"oto", "Otomian languages"}, {"qu", "Ouechua"}, {"pal", "Pahlavi"}, {"pau", "Palauan"}, {"pli", "Pali"}, {"pam", "Pampanga"}, {"pag", "Pangasinan"}, {"pan", "Panjabi"}, {"pap", "Papiamento"}, {"paa", "Papuan-Australian (Other)"}, {"ps", "Pashto, Pushto"}, {"fa", "Persian"}, {"fas", "Persian"}, {"per", "Persian"}, {"pl", "Polish"}, {"pol", "Polish"}, {"pon", "Ponape"}, {"por", "Portuguese"}, {"pt", "Portuguese"}, {"pra", "Prakrit languages"}, {"pro", "Provencal, Old (to 1500)"}, {"pa", "Punjabi"}, {"pus", "Pushto"}, {"que", "Quechua"}, {"roh", "Raeto-Romance"}, {"raj", "Rajasthani"}, {"rar", "Rarotongan"}, {"rm", "Rhaeto-Romance"}, {"roa", "Romance (Other)"}, {"ro", "Romanian"}, {"ron", "Romanian"}, {"rum", "Romanian"}, {"rom", "Romany"}, {"run", "Rundi"}, {"ru", "Russian"}, {"rus", "Russian"}, {"sal", "Salishan languages"}, {"sam", "Samaritan Aramaic"}, {"sm", "Samoan"}, {"smo", "Samoan"}, {"sad", "Sandawe"}, {"sag", "Sango"}, {"sg", "Sangro"}, {"sa", "Sanskrit"}, {"san", "Sanskrit"}, {"sco", "Scots"}, {"gd", "Scots Gaelic"}, {"sel", "Selkup"}, {"sem", "Semitic (Other)"}, {"sr", "Serbian"}, {"scr", "Serbo-Croatian"}, {"sh", "Serbo-Croatian"}, {"srr", "Serer"}, {"st", "Sesotho"}, {"tn", "Setswana"}, {"shn", "Shan"}, {"sn", "Shona"}, {"sna", "Shona"}, {"sid", "Sidamo"}, {"bla", "Siksika"}, {"sd", "Sindhi"}, {"snd", "Sindhi"}, {"si", "Singhalese"}, {"sin", "Sinhalese"}, {"sit", "Sino-Tibetan (Other)"}, {"sio", "Siouan languages"}, {"ss", "Siswati"}, {"sla", "Slavic (Other)"}, {"sk", "Slovak"}, {"slk", "Slovak"}, {"slo", "Slovak"}, {"sl", "Slovenian"}, {"slv", "Slovenian"}, {"sog", "Sogdian"}, {"so", "Somali"}, {"som", "Somali"}, {"son", "Songhai"}, {"wen", "Sorbian languages"}, {"sot", "Sotho"}, {"sai", "South American Indian (Other)"}, {"es", "Spanish"}, {"esl", "Spanish"}, {"spa", "Spanish"}, {"suk", "Sukuma"}, {"sux", "Sumerian"}, {"su", "Sundanese"}, {"sun", "Sundanese"}, {"sus", "Susu"}, {"sw", "Swahili"}, {"swa", "Swahili"}, {"ssw", "Swazi"}, {"sv", "Swedish"}, {"sve", "Swedish"}, {"swe", "Swedish"}, {"syr", "Syriac"}, {"tgl", "Tagalog"}, {"tl", "Tagalog"}, {"tah", "Tahitian"}, {"tg", "Tajik"}, {"tgk", "Tajik"}, {"ta", "Tamil"}, {"tam", "Tamil"}, {"tat", "Tatar"}, {"tt", "Tatar"}, {"te", "Tegulu"}, {"tel", "Telugu"}, {"ter", "Tereno"}, {"th", "Thai"}, {"tha", "Thai"}, {"bo", "Tibetan"}, {"bod", "Tibetan"}, {"tib", "Tibetan"}, {"tig", "Tigre"}, {"ti", "Tigrinya"}, {"tir", "Tigrinya"}, {"tem", "Timne"}, {"tiv", "Tivi"}, {"tli", "Tlingit"}, {"to", "Tonga"}, {"tog", "Tonga (Nyasa)"}, {"ton", "Tonga (Tonga Islands)"}, {"tru", "Truk"}, {"tsi", "Tsimshian"}, {"ts", "Tsonga"}, {"tso", "Tsonga"}, {"tsn", "Tswana"}, {"tum", "Tumbuka"}, {"tr", "Turkish"}, {"tur", "Turkish"}, {"ota", "Turkish, Ottoman"}, {"tk", "Turkmen"}, {"tuk", "Turkmen"}, {"tw", "Twi"}, {"twi", "Twi"}, {"uga", "Ugaritic"}, {"uig", "Uighur"}, {"ug", "Uigur"}, {"uk", "Ukrainian"}, {"ukr", "Ukrainian"}, {"umb", "Umbundu"}, {"und", "Undetermined"}, {"ur", "Urdu"}, {"urd", "Urdu"}, {"uz", "Uzbek"}, {"uzb", "Uzbek"}, {"vai", "Vai"}, {"ven", "Venda"}, {"vi", "Vietnamese"}, {"vie", "Vietnamese"}, {"vol", "Volapuk"}, {"vo", "Volapük"}, {"vot", "Votic"}, {"wak", "Wakashan languages"}, {"wal", "Walamo"}, {"war", "Waray"}, {"was", "Washo"}, {"cy", "Welsh"}, {"cym", "Welsh"}, {"we", "Welsh"}, {"wo", "Wolof"}, {"wo", "Wolof"}, {"wol", "Wolof"}, {"xh", "Xhosa"}, {"xh", "Xhosa"}, {"xho", "Xhosa"}, {"yao", "Yao"}, {"yap", "Yap"}, {"yi", "Yiddish"}, {"yid", "Yiddish"}, {"ji", "Yiddish"}, {"yo", "Yoruba"}, {"yo", "Yoruba"}, {"yor", "Yoruba"}, {"zap", "Zapotec"}, {"zen", "Zenaga"}, {"za", "Zhuang"}, {"zha", "Zhuang"}, {"zu", "Zulu"}, {"zul", "Zulu"}, {"zun", "Zuni"},
21.571942
69
0.510589
[ "cad" ]
774ed3fc9c97140400eba133562eac4e551115c4
17,635
c
C
vm/Ddm.c
mcoughli/platform-dalvik
b26a7c3077286f6f63d19adb7aee216cf1a22a00
[ "Apache-2.0" ]
1
2018-03-07T04:33:50.000Z
2018-03-07T04:33:50.000Z
vm/Ddm.c
mcoughli/platform-dalvik
b26a7c3077286f6f63d19adb7aee216cf1a22a00
[ "Apache-2.0" ]
null
null
null
vm/Ddm.c
mcoughli/platform-dalvik
b26a7c3077286f6f63d19adb7aee216cf1a22a00
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Handle Dalvik Debug Monitor requests and events. * * Remember that all DDM traffic is big-endian since it travels over the * JDWP connection. */ #include "Dalvik.h" #include <fcntl.h> #include <errno.h> /* * "buf" contains a full JDWP packet, possibly with multiple chunks. We * need to process each, accumulate the replies, and ship the whole thing * back. * * Returns "true" if we have a reply. The reply buffer is newly allocated, * and includes the chunk type/length, followed by the data. * * TODO: we currently assume that the request and reply include a single * chunk. If this becomes inconvenient we will need to adapt. */ bool dvmDdmHandlePacket(const u1* buf, int dataLen, u1** pReplyBuf, int* pReplyLen) { Thread* self = dvmThreadSelf(); const int kChunkHdrLen = 8; ArrayObject* dataArray = NULL; bool result = false; assert(dataLen >= 0); /* * Prep DdmServer. We could throw this in gDvm. */ ClassObject* ddmServerClass; Method* dispatch; ddmServerClass = dvmFindClass("Lorg/apache/harmony/dalvik/ddmc/DdmServer;", NULL); if (ddmServerClass == NULL) { LOGW("Unable to find org.apache.harmony.dalvik.ddmc.DdmServer\n"); goto bail; } dispatch = dvmFindDirectMethodByDescriptor(ddmServerClass, "dispatch", "(I[BII)Lorg/apache/harmony/dalvik/ddmc/Chunk;"); if (dispatch == NULL) { LOGW("Unable to find DdmServer.dispatch\n"); goto bail; } /* * Prep Chunk. */ int chunkTypeOff, chunkDataOff, chunkOffsetOff, chunkLengthOff; ClassObject* chunkClass; chunkClass = dvmFindClass("Lorg/apache/harmony/dalvik/ddmc/Chunk;", NULL); if (chunkClass == NULL) { LOGW("Unable to find org.apache.harmony.dalvik.ddmc.Chunk\n"); goto bail; } chunkTypeOff = dvmFindFieldOffset(chunkClass, "type", "I"); chunkDataOff = dvmFindFieldOffset(chunkClass, "data", "[B"); chunkOffsetOff = dvmFindFieldOffset(chunkClass, "offset", "I"); chunkLengthOff = dvmFindFieldOffset(chunkClass, "length", "I"); if (chunkTypeOff < 0 || chunkDataOff < 0 || chunkOffsetOff < 0 || chunkLengthOff < 0) { LOGW("Unable to find all chunk fields\n"); goto bail; } /* * The chunk handlers are written in the Java programming language, so * we need to convert the buffer to a byte array. */ dataArray = dvmAllocPrimitiveArray('B', dataLen, ALLOC_DEFAULT); if (dataArray == NULL) { LOGW("array alloc failed (%d)\n", dataLen); dvmClearException(self); goto bail; } memcpy(dataArray->contents, buf, dataLen); /* * Run through and find all chunks. [Currently just find the first.] */ unsigned int offset, length, type; type = get4BE((u1*)dataArray->contents + 0); length = get4BE((u1*)dataArray->contents + 4); offset = kChunkHdrLen; if (offset+length > (unsigned int) dataLen) { LOGW("WARNING: bad chunk found (len=%u pktLen=%d)\n", length, dataLen); goto bail; } /* * Call the handler. */ JValue callRes; dvmCallMethod(self, dispatch, NULL, &callRes, type, dataArray, offset, length); if (dvmCheckException(self)) { LOGI("Exception thrown by dispatcher for 0x%08x\n", type); dvmLogExceptionStackTrace(); dvmClearException(self); goto bail; } Object* chunk; ArrayObject* replyData; chunk = (Object*) callRes.l; if (chunk == NULL) goto bail; /* * Pull the pieces out of the chunk. We copy the results into a * newly-allocated buffer that the caller can free. We don't want to * continue using the Chunk object because nothing has a reference to it. * (If we do an alloc in here, we need to dvmAddTrackedAlloc it.) * * We could avoid this by returning type/data/offset/length and having * the caller be aware of the object lifetime issues, but that * integrates the JDWP code more tightly into the VM, and doesn't work * if we have responses for multiple chunks. * * So we're pretty much stuck with copying data around multiple times. */ type = dvmGetFieldInt(chunk, chunkTypeOff); replyData = (ArrayObject*) dvmGetFieldObject(chunk, chunkDataOff); offset = dvmGetFieldInt(chunk, chunkOffsetOff); length = dvmGetFieldInt(chunk, chunkLengthOff); LOGV("DDM reply: type=0x%08x data=%p offset=%d length=%d\n", type, replyData, offset, length); if (length == 0 || replyData == NULL) goto bail; if (offset + length > replyData->length) { LOGW("WARNING: chunk off=%d len=%d exceeds reply array len %d\n", offset, length, replyData->length); goto bail; } u1* reply; reply = (u1*) malloc(length + kChunkHdrLen); if (reply == NULL) { LOGW("malloc %d failed\n", length+kChunkHdrLen); goto bail; } set4BE(reply + 0, type); set4BE(reply + 4, length); memcpy(reply+kChunkHdrLen, (const u1*)replyData->contents + offset, length); *pReplyBuf = reply; *pReplyLen = length + kChunkHdrLen; result = true; LOGV("dvmHandleDdm returning type=%.4s buf=%p len=%d\n", (char*) reply, reply, length); bail: dvmReleaseTrackedAlloc((Object*) dataArray, NULL); return result; } /* defined in org.apache.harmony.dalvik.ddmc.DdmServer */ #define CONNECTED 1 #define DISCONNECTED 2 /* * Broadcast an event to all handlers. */ static void broadcast(int event) { ClassObject* ddmServerClass; Method* bcast; ddmServerClass = dvmFindClass("Lorg/apache/harmony/dalvik/ddmc/DdmServer;", NULL); if (ddmServerClass == NULL) { LOGW("Unable to find org.apache.harmony.dalvik.ddmc.DdmServer\n"); goto bail; } bcast = dvmFindDirectMethodByDescriptor(ddmServerClass, "broadcast", "(I)V"); if (bcast == NULL) { LOGW("Unable to find DdmServer.broadcast\n"); goto bail; } Thread* self = dvmThreadSelf(); if (self->status != THREAD_RUNNING) { LOGE("ERROR: DDM broadcast with thread status=%d\n", self->status); /* try anyway? */ } JValue unused; dvmCallMethod(self, bcast, NULL, &unused, event); if (dvmCheckException(self)) { LOGI("Exception thrown by broadcast(%d)\n", event); dvmLogExceptionStackTrace(); dvmClearException(self); goto bail; } bail: ; } /* * First DDM packet has arrived over JDWP. Notify the press. * * We can do some initialization here too. */ void dvmDdmConnected(void) { // TODO: any init LOGV("Broadcasting DDM connect\n"); broadcast(CONNECTED); } /* * JDWP connection has dropped. * * Do some cleanup. */ void dvmDdmDisconnected(void) { LOGV("Broadcasting DDM disconnect\n"); broadcast(DISCONNECTED); gDvm.ddmThreadNotification = false; } /* * Turn thread notification on or off. */ void dvmDdmSetThreadNotification(bool enable) { /* * We lock the thread list to avoid sending duplicate events or missing * a thread change. We should be okay holding this lock while sending * the messages out. (We have to hold it while accessing a live thread.) */ dvmLockThreadList(NULL); gDvm.ddmThreadNotification = enable; if (enable) { Thread* thread; for (thread = gDvm.threadList; thread != NULL; thread = thread->next) { //LOGW("notify %d\n", thread->threadId); dvmDdmSendThreadNotification(thread, true); } } dvmUnlockThreadList(); } /* * Send a notification when a thread starts or stops. * * Because we broadcast the full set of threads when the notifications are * first enabled, it's possible for "thread" to be actively executing. */ void dvmDdmSendThreadNotification(Thread* thread, bool started) { if (!gDvm.ddmThreadNotification) return; StringObject* nameObj = NULL; Object* threadObj = thread->threadObj; if (threadObj != NULL) { nameObj = (StringObject*) dvmGetFieldObject(threadObj, gDvm.offJavaLangThread_name); } int type, len; u1 buf[256]; if (started) { const u2* chars; u2* outChars; size_t stringLen; type = CHUNK_TYPE("THCR"); if (nameObj != NULL) { stringLen = dvmStringLen(nameObj); chars = dvmStringChars(nameObj); } else { stringLen = 0; chars = NULL; } /* leave room for the two integer fields */ if (stringLen > (sizeof(buf) - sizeof(u4)*2) / 2) stringLen = (sizeof(buf) - sizeof(u4)*2) / 2; len = stringLen*2 + sizeof(u4)*2; set4BE(&buf[0x00], thread->threadId); set4BE(&buf[0x04], stringLen); /* copy the UTF-16 string, transforming to big-endian */ outChars = (u2*) &buf[0x08]; while (stringLen--) set2BE((u1*) (outChars++), *chars++); } else { type = CHUNK_TYPE("THDE"); len = 4; set4BE(&buf[0x00], thread->threadId); } dvmDbgDdmSendChunk(type, len, buf); } /* * Send a notification when a thread's name changes. */ void dvmDdmSendThreadNameChange(int threadId, StringObject* newName) { if (!gDvm.ddmThreadNotification) return; size_t stringLen = dvmStringLen(newName); const u2* chars = dvmStringChars(newName); /* * Output format: * (4b) thread ID * (4b) stringLen * (xb) string chars */ int bufLen = 4 + 4 + (stringLen * 2); u1 buf[bufLen]; set4BE(&buf[0x00], threadId); set4BE(&buf[0x04], stringLen); u2* outChars = (u2*) &buf[0x08]; while (stringLen--) set2BE((u1*) (outChars++), *chars++); dvmDbgDdmSendChunk(CHUNK_TYPE("THNM"), bufLen, buf); } /* * Get some per-thread stats. * * This is currently generated by opening the appropriate "stat" file * in /proc and reading the pile of stuff that comes out. */ static bool getThreadStats(pid_t pid, pid_t tid, unsigned long* pUtime, unsigned long* pStime) { /* int pid; char comm[128]; char state; int ppid, pgrp, session, tty_nr, tpgid; unsigned long flags, minflt, cminflt, majflt, cmajflt, utime, stime; long cutime, cstime, priority, nice, zero, itrealvalue; unsigned long starttime, vsize; long rss; unsigned long rlim, startcode, endcode, startstack, kstkesp, kstkeip; unsigned long signal, blocked, sigignore, sigcatch, wchan, nswap, cnswap; int exit_signal, processor; unsigned long rt_priority, policy; scanf("%d %s %c %d %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %ld %ld %ld " "%ld %ld %ld %lu %lu %ld %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu " "%lu %lu %lu %d %d %lu %lu", &pid, comm, &state, &ppid, &pgrp, &session, &tty_nr, &tpgid, &flags, &minflt, &cminflt, &majflt, &cmajflt, &utime, &stime, &cutime, &cstime, &priority, &nice, &zero, &itrealvalue, &starttime, &vsize, &rss, &rlim, &startcode, &endcode, &startstack, &kstkesp, &kstkeip, &signal, &blocked, &sigignore, &sigcatch, &wchan, &nswap, &cnswap, &exit_signal, &processor, &rt_priority, &policy); */ char nameBuf[64]; int i, fd; /* * Open and read the appropriate file. This is expected to work on * Linux but will fail on other platforms (e.g. Mac sim). */ sprintf(nameBuf, "/proc/%d/task/%d/stat", (int) pid, (int) tid); fd = open(nameBuf, O_RDONLY); if (fd < 0) { LOGV("Unable to open '%s': %s\n", nameBuf, strerror(errno)); return false; } char lineBuf[512]; // > 2x typical int cc; cc = read(fd, lineBuf, sizeof(lineBuf)-1); if (cc <= 0) { const char* msg = (cc == 0) ? "unexpected EOF" : strerror(errno); LOGI("Unable to read '%s': %s\n", nameBuf, msg); close(fd); return false; } lineBuf[cc] = '\0'; /* * Skip whitespace-separated tokens. */ static const char* kWhitespace = " "; char* cp = lineBuf; for (i = 0; i < 13; i++) { cp += strcspn(cp, kWhitespace); // skip token cp += strspn(cp, kWhitespace); // skip whitespace } /* * Grab the values we want. */ char* endp; *pUtime = strtoul(cp, &endp, 10); if (endp == cp) LOGI("Warning: strtoul failed on utime ('%.30s...')\n", cp); cp += strcspn(cp, kWhitespace); cp += strspn(cp, kWhitespace); *pStime = strtoul(cp, &endp, 10); if (endp == cp) LOGI("Warning: strtoul failed on stime ('%.30s...')\n", cp); close(fd); return true; } /* * Generate the contents of a THST chunk. The data encompasses all known * threads. * * Response has: * (1b) header len * (1b) bytes per entry * (2b) thread count * Then, for each thread: * (4b) threadId * (1b) thread status * (4b) tid * (4b) utime * (4b) stime * (1b) is daemon? * * The length fields exist in anticipation of adding additional fields * without wanting to break ddms or bump the full protocol version. I don't * think it warrants full versioning. They might be extraneous and could * be removed from a future version. * * Returns a new byte[] with the data inside, or NULL on failure. The * caller must call dvmReleaseTrackedAlloc() on the array. */ ArrayObject* dvmDdmGenerateThreadStats(void) { const int kHeaderLen = 4; const int kBytesPerEntry = 18; dvmLockThreadList(NULL); Thread* thread; int threadCount = 0; for (thread = gDvm.threadList; thread != NULL; thread = thread->next) threadCount++; /* * Create a temporary buffer. We can't perform heap allocation with * the thread list lock held (could cause a GC). The output is small * enough to sit on the stack. */ int bufLen = kHeaderLen + threadCount * kBytesPerEntry; u1 tmpBuf[bufLen]; u1* buf = tmpBuf; set1(buf+0, kHeaderLen); set1(buf+1, kBytesPerEntry); set2BE(buf+2, (u2) threadCount); buf += kHeaderLen; pid_t pid = getpid(); for (thread = gDvm.threadList; thread != NULL; thread = thread->next) { unsigned long utime, stime; bool isDaemon = false; if (!getThreadStats(pid, thread->systemTid, &utime, &stime)) { // failed; drop in empty values utime = stime = 0; } Object* threadObj = thread->threadObj; if (threadObj != NULL) { isDaemon = dvmGetFieldBoolean(threadObj, gDvm.offJavaLangThread_daemon); } set4BE(buf+0, thread->threadId); set1(buf+4, thread->status); set4BE(buf+5, thread->systemTid); set4BE(buf+9, utime); set4BE(buf+13, stime); set1(buf+17, isDaemon); buf += kBytesPerEntry; } dvmUnlockThreadList(); /* * Create a byte array to hold the data. */ ArrayObject* arrayObj = dvmAllocPrimitiveArray('B', bufLen, ALLOC_DEFAULT); if (arrayObj != NULL) memcpy(arrayObj->contents, tmpBuf, bufLen); return arrayObj; } /* * Find the specified thread and return its stack trace as an array of * StackTraceElement objects. */ ArrayObject* dvmDdmGetStackTraceById(u4 threadId) { Thread* self = dvmThreadSelf(); Thread* thread; int* traceBuf; dvmLockThreadList(self); for (thread = gDvm.threadList; thread != NULL; thread = thread->next) { if (thread->threadId == threadId) break; } if (thread == NULL) { LOGI("dvmDdmGetStackTraceById: threadid=%d not found\n", threadId); dvmUnlockThreadList(); return NULL; } /* * Suspend the thread, pull out the stack trace, then resume the thread * and release the thread list lock. If we're being asked to examine * our own stack trace, skip the suspend/resume. */ int stackDepth = -1; if (thread != self) dvmSuspendThread(thread); traceBuf = dvmFillInStackTraceRaw(thread, &stackDepth); if (thread != self) dvmResumeThread(thread); dvmUnlockThreadList(); /* * Convert the raw buffer into an array of StackTraceElement. */ ArrayObject* trace = dvmGetStackTraceRaw(traceBuf, stackDepth); free(traceBuf); return trace; } /* * Gather up the allocation data and copy it into a byte[]. * * Returns NULL on failure with an exception raised. */ ArrayObject* dvmDdmGetRecentAllocations(void) { u1* data; size_t len; if (!dvmGenerateTrackedAllocationReport(&data, &len)) { /* assume OOM */ dvmThrowException("Ljava/lang/OutOfMemoryError;","recent alloc native"); return NULL; } ArrayObject* arrayObj = dvmAllocPrimitiveArray('B', len, ALLOC_DEFAULT); if (arrayObj != NULL) memcpy(arrayObj->contents, data, len); return arrayObj; }
29.052718
81
0.622739
[ "object" ]
77586d0561f5a53985ee0c05ce4770b9322688fb
600
h
C
src/renderer/sky.h
ani003/c-ray
d8d5385138b2e032729c22fde280b1d32cdf8716
[ "MIT" ]
null
null
null
src/renderer/sky.h
ani003/c-ray
d8d5385138b2e032729c22fde280b1d32cdf8716
[ "MIT" ]
null
null
null
src/renderer/sky.h
ani003/c-ray
d8d5385138b2e032729c22fde280b1d32cdf8716
[ "MIT" ]
1
2022-01-19T10:26:46.000Z
2022-01-19T10:26:46.000Z
// // sky.h // C-Ray // // Created by Valtteri Koskivuori on 16/06/2020. // Copyright © 2015-2020 Valtteri Koskivuori. All rights reserved. // #pragma once struct color; struct lightRay; // This models atmospheric rayleigh scattering to produce // a realistic looking sky up in the +Y direction. // This is not very useful at the moment, since our // path tracer does not do any kind of direct sampling, // meaning our render will have a ton of noise. // A lot of the physical parameters are tweakable in the // start of the implementation file. struct color sky(struct lightRay incidentRay);
27.272727
67
0.738333
[ "render" ]
81c28cce24a5e027888facfd70555ea74d23676e
2,915
h
C
include/BC/OSC.h
CommanderAsdasd/bcplayer
bf3481c9f08fb810660367b083392304479daaef
[ "MIT" ]
null
null
null
include/BC/OSC.h
CommanderAsdasd/bcplayer
bf3481c9f08fb810660367b083392304479daaef
[ "MIT" ]
null
null
null
include/BC/OSC.h
CommanderAsdasd/bcplayer
bf3481c9f08fb810660367b083392304479daaef
[ "MIT" ]
null
null
null
// OSC.h ///////////////////////////////////////////// // OSC class - definition //////////////////////////// #ifndef OSC_H #define OSC_H class Astro; class LFO; #include <vector> #include "Astro.h" #include "LFO.h" #include "Fall.h" using namespace std; class OSC { static const int OSC_TABLE_SIZE; static const int ENV_TABLE_SIZE; static const double OSC_SAMPLE_RATE; static const float TWO_PI; static const int OSC_HISTORY_SIZE = 64; public: vector<float> table; int tableType; float yFlip; double phase; double dblPhaseIntPart; int intPhase; int intPhaseNext; float deviation; double increment; double freq; double adjustedFreq; double detune; float gain; bool resting; bool forceSilenceAtBeginning; int nEnvFrames; int nAttackFrames; int nPeakFrames; int nDecayFrames; int decayStartPos; float peakLevel; float decayAmount; float sustainLevel; int envPos; bool envADfinished; int nReleaseFrames; int releasePos; bool envRfinished; Astro astro; bool astroEnabled; LFO lfo; bool lfoEnabled; Fall fall; bool fallActive; Rise rise; bool riseActive; bool beefUp; float beefUpFactor; float compRatio; float compThreshold; int popGuardCount; float lastAmp; float history[OSC_HISTORY_SIZE]; int historyWriteWait; int historyWriteIndex; OSC(); ~OSC(); void setTable(int type); void advance(); void setToRest(); void confirmFirstNoteIsRest(); void setNewNote(double newFreq); void setFrequency(double noteFreq); void setIncrement(double noteFreq); void initializePhase(); void refreshForSongBeginning(); float getOutput(); float compress(float in); float popGuard(float in); void enableBeefUp(); void disableBeefUp(); void setBeefUpFactor(float factor); void advanceEnvelope(); void refreshEnvelope(); float getEnvelopeOutput(); void setGain(float g); float getGain(); void enableAstro(); void disableAstro(); void setAstroSpeed(int nCyclesPerSecond); void enableLFO(); void disableLFO(); void initializeLFO(); void setLFOwaitTime(int milliseconds); void setLFOrange(int cents); void setLFOspeed(double cyclePerSeconds); void startFall(); void stopFall(); void setFallSpeed(double fallSpeed); void setFallWait(double waitTimeMS); void setFallToDefault(); void startRise(); void stopRise(); void setRiseSpeed(double riseSpeed); void setRiseRange(double riseRange); void setRiseToDefault(); void setAttackTime(int attackTimeMS); void setPeakTime(int peakTimeMS); void setDecayTime(int decayTimeMS); void setReleaseTime(int releaseTimeMS); void setPeakLevel(float peakLV); void setSustainLevel(float sustainLV); void setEnvelope(int attackTimeMS, int peakTimeMS, int decayTimeMS, int releaseTimeMS, float peakLV, float sustainLV); void readjustEnvParams(); void pushHistory(float g); float getHistoricalAverage(); void clearHistory(); void flipYAxis(); void resetYFlip(); }; #endif
20.384615
87
0.741338
[ "vector" ]
81ca1eba2fa5b3cd2c670c242a721f2459129a35
10,173
h
C
NaoTHSoccer/Source/Cognition/Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
NaoTHSoccer/Source/Cognition/Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
NaoTHSoccer/Source/Cognition/Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** * @file MonteCarloSelfLocator.h * * @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a> * Declaration of class MonteCarloSelfLocator */ #ifndef _MonteCarloSelfLocator_h_ #define _MonteCarloSelfLocator_h_ #include <ModuleFramework/Module.h> #include "Tools/Math/Geometry.h" #include "Tools/CameraGeometry.h" #include <Tools/DataStructures/ParameterList.h> #include "Tools/Debug/DebugParameterList.h" #include "Tools/Math/Probabilistics.h" // representations // basic info #include "Representations/Infrastructure/FieldInfo.h" #include "Representations/Infrastructure/FrameInfo.h" #include "Representations/Infrastructure/GameData.h" #include "Representations/Modeling/PlayerInfo.h" // motion / kinematics #include "Representations/Modeling/OdometryData.h" #include "Representations/Perception/CameraMatrix.h" // situation #include "Representations/Motion/MotionStatus.h" #include "Representations/Modeling/BodyState.h" #include "Representations/Modeling/SituationStatus.h" #include "Representations/Modeling/SituationPrior.h" // sensor percepts #include "Representations/Perception/GoalPercept.h" #include "Representations/Perception/LinePercept.h" // local models #include "Representations/Modeling/ProbabilisticQuadCompas.h" #include "Representations/Perception/LineGraphPercept.h" // this are the results :) #include "Representations/Modeling/RobotPose.h" #include "Representations/Modeling/GoalModel.h" // debug #include "Tools/Debug/DebugPlot.h" #include "Tools/Debug/DebugRequest.h" #include "Tools/Debug/DebugModify.h" #include "Tools/Debug/DebugDrawings.h" // basic tools #include "SampleSet.h" #include "CanopyClustering.h" //////////////////// BEGIN MODULE INTERFACE DECLARATION //////////////////// BEGIN_DECLARE_MODULE(MonteCarloSelfLocator) PROVIDE(DebugRequest) PROVIDE(DebugPlot) PROVIDE(DebugModify) PROVIDE(DebugDrawings) PROVIDE(DebugParameterList) REQUIRE(FieldInfo) REQUIRE(FrameInfo) REQUIRE(PlayerInfo) REQUIRE(GameData) REQUIRE(OdometryData) REQUIRE(CameraMatrix) REQUIRE(CameraMatrixTop) REQUIRE(MotionStatus) REQUIRE(BodyState) REQUIRE(SituationStatus) REQUIRE(SituationPrior) REQUIRE(GoalPercept) REQUIRE(GoalPerceptTop) REQUIRE(SensingGoalModel) REQUIRE(ProbabilisticQuadCompas) REQUIRE(LineGraphPercept) REQUIRE(LinePercept) REQUIRE(RansacCirclePercept) PROVIDE(RobotPose) PROVIDE(SelfLocGoalModel) END_DECLARE_MODULE(MonteCarloSelfLocator) //////////////////// END MODULE INTERFACE DECLARATION ////////////////////// class MonteCarloSelfLocator : private MonteCarloSelfLocatorBase { public: MonteCarloSelfLocator(); virtual ~MonteCarloSelfLocator(); void execute(); private: // local types enum State { BLIND, // no sensory information is processed but the state is monitored KIDNAPPED, // robot is lifted up LOCALIZE, TRACKING } state, lastState; // NOTE: indecates whether the robot is localized bool islocalized; class Parameters: public ParameterList { public: Parameters(): ParameterList("MCSLParameters") { PARAMETER_REGISTER(thresholdCanopy) = 900; PARAMETER_REGISTER(resamplingThreshhold) = 0.01; PARAMETER_REGISTER(processNoiseDistance) = 70; PARAMETER_REGISTER(processNoiseAngle) = 0.1; PARAMETER_REGISTER(motionNoise) = false; PARAMETER_REGISTER(motionNoiseDistance) = 5.0; PARAMETER_REGISTER(motionNoiseAngle) = 0.01; PARAMETER_REGISTER(updateByGoalPostTracking) = false; PARAMETER_REGISTER(updateByGoalPostLocalize) = true; PARAMETER_REGISTER(goalPostSigmaDistance) = 0.1; PARAMETER_REGISTER(goalPostSigmaAngle) = 0.1; PARAMETER_REGISTER(updateByLinePoints) = true; PARAMETER_REGISTER(linePointsSigmaDistance) = 0.1; PARAMETER_REGISTER(linePointsSigmaAngle) = 0.1; PARAMETER_REGISTER(linePointsMaxNumber) = 10; PARAMETER_REGISTER(updateByLinePercept) = true; PARAMETER_REGISTER(updateByShortLinePercept) = false; PARAMETER_REGISTER(sensorResetByMiddleCircle) = true; PARAMETER_REGISTER(updateByMiddleCircle) = true; PARAMETER_REGISTER(updateByLinePerceptCircle) = true; PARAMETER_REGISTER(updateByRansacCircle) = true; PARAMETER_REGISTER(sigmaDistanceCenterCircle) = 0.2; PARAMETER_REGISTER(sigmaAngleCenterCircle) = 0.1; PARAMETER_REGISTER(updateByOldPose) = false; PARAMETER_REGISTER(oldPoseSigmaDistance) = 0.1; PARAMETER_REGISTER(updateByCompas) = true; PARAMETER_REGISTER(treatLiftUp) = true; PARAMETER_REGISTER(treatInitState) = true; PARAMETER_REGISTER(resetOwnHalf) = false; PARAMETER_REGISTER(downWeightFactorOwnHalf) = 0.01; PARAMETER_REGISTER(maxTimeForLiftUp) = 500; PARAMETER_REGISTER(updateBySituation) = true; PARAMETER_REGISTER(startPositionsSigmaDistance) = 500; PARAMETER_REGISTER(startPositionsSigmaAngle) = 0.5; PARAMETER_REGISTER(resampleSUS) = false; PARAMETER_REGISTER(resampleGT07) = true; PARAMETER_REGISTER(maxAcceptedGoalErrorWhileTracking) = 0; PARAMETER_REGISTER(updateByOdometryWhenBlind) = true; // load from the file after registering all parameters syncWithConfig(); } double thresholdCanopy; double resamplingThreshhold; double processNoiseDistance; double processNoiseAngle; bool motionNoise; double motionNoiseDistance; double motionNoiseAngle; bool updateByGoalPostTracking; bool updateByGoalPostLocalize; double goalPostSigmaDistance; double goalPostSigmaAngle; bool updateByLinePoints; double linePointsSigmaDistance; double linePointsSigmaAngle; int linePointsMaxNumber; bool updateByLinePercept; bool updateByShortLinePercept; bool sensorResetByMiddleCircle; bool updateByMiddleCircle; bool updateByLinePerceptCircle; bool updateByRansacCircle; double sigmaDistanceCenterCircle; double sigmaAngleCenterCircle; bool updateByOldPose; double oldPoseSigmaDistance; bool updateByCompas; bool treatLiftUp; bool treatInitState; bool resetOwnHalf; double downWeightFactorOwnHalf; double maxTimeForLiftUp; bool updateBySituation; double startPositionsSigmaDistance; double startPositionsSigmaAngle; bool resampleSUS; bool resampleGT07; double maxAcceptedGoalErrorWhileTracking; bool updateByOdometryWhenBlind; } parameters; class LineDensity { private: Math::LineSegment segment; double angle; double distDeviation; double angleDeviation; public: LineDensity() { } LineDensity( const Vector2d& start, const Vector2d& end, double angle, double distDeviation, double angleDeviation) : segment(start, end), angle(angle), distDeviation(distDeviation), angleDeviation(angleDeviation) { } double update(const Sample& sample) const { double distDiff = segment.minDistance(sample.translation); double angleDiff = Math::normalize(angle - sample.rotation); return Math::gaussianProbability(distDiff, distDeviation) * Math::gaussianProbability(angleDiff, angleDeviation); } void draw(DrawingCanvas2D& canvas) { canvas.pen("000000", 10); canvas.drawLine(segment.begin().x, segment.begin().y, segment.end().x, segment.end().y); canvas.drawArrow( segment.begin().x, segment.begin().y, segment.begin().x + 100*cos(angle), segment.begin().y + 100*sin(angle)); canvas.drawArrow( segment.end().x, segment.end().y, segment.end().x + 100*cos(angle), segment.end().y + 100*sin(angle)); } }; private: // goal posts bool updatedByGoalPosts; private: // data members OdometryData lastRobotOdometry; SampleSet theSampleSet; SampleSet mhBackendSet; // used ONLY by resampleMH //SampleSet setBeforeResampling; // sort of 'double buffering' CanopyClustering<SampleSet> canopyClustering; // statistics: // augmentation trends double slowWeighting; double fastWeighting; // double effective_number_of_samples; private: // workers void updateByOdometry(SampleSet& sampleSet, bool noise, bool onlyRotation) const; bool updateBySensors(SampleSet& sampleSet) const; void updateByGoalPosts(const GoalPercept& goalPercept, SampleSet& sampleSet) const; void updateBySingleGoalPost(const GoalPercept::GoalPost& goalPost, SampleSet& sampleSet) const; void updateByCompas(SampleSet& sampleSet) const; void updateByLinePoints(const LineGraphPercept& linePercept, SampleSet& sampleSet) const; void updateByLines(const LinePercept& linePercept, SampleSet& sampleSet) const; void updateByShortLines(const LinePercept& linePercept, SampleSet& sampleSet) const; void updateByMiddleCircle(const Vector2d& middleCircleCenter, SampleSet& sampleSet) const; // A-Priori knowledge based on the game state void updateBySidePositions(SampleSet& sampleSet) const; void updateByStartPositions(SampleSet& sampleSet) const; void updateByOwnHalfLookingForward(SampleSet& sampleSet) const; void updateByOwnHalf(SampleSet& sampleSet) const; void updateByOppHalf(SampleSet& sampleSet) const; void updateByGoalBox(SampleSet& sampleSet) const; void updateBySituation(); void updateByOldPose(SampleSet& sampleSet) const; void updateByPose(SampleSet& sampleSet, Pose2D pose, double sigmaDistance, double /*sigmaAngle*/) const; void updateStatistics(SampleSet& sampleSet); void resetLocator(); void resampleSimple(SampleSet& sampleSet, int number) const; void resampleMH(SampleSet& sampleSet); void resampleGT07(SampleSet& sampleSet, bool noise) const; int resampleSUS(SampleSet& sampleSet, int n) const; int sensorResetBySensingGoalModel(SampleSet& sampleSet, int n) const; void sensorResetByMiddleCircle(SampleSet& sampleSet, const Vector2d& middleCircleCenter) const; void calculatePose(SampleSet& sampleSet); private: //debug void draw_sensor_belief() const; void drawPosition() const; }; #endif //_MonteCarloSelfLocator_h_
29.920588
106
0.748353
[ "geometry" ]
81dcffbb2d575597d3215cae4cde278ba5930a02
7,500
c
C
src/ezcu_mem.c
issamsaid/ezCU
8be3703c2eb5112978854f3e95bda44fdf6a506a
[ "BSD-3-Clause" ]
2
2017-05-23T03:23:39.000Z
2017-09-08T13:12:53.000Z
src/ezcu_mem.c
issamsaid/ezCU
8be3703c2eb5112978854f3e95bda44fdf6a506a
[ "BSD-3-Clause" ]
null
null
null
src/ezcu_mem.c
issamsaid/ezCU
8be3703c2eb5112978854f3e95bda44fdf6a506a
[ "BSD-3-Clause" ]
null
null
null
/// /// @copyright Copyright (c) 2016-, Issam SAID <said.issam@gmail.com> /// All rights reserved. /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions /// are met: /// /// 1. Redistributions of source code must retain the above copyright /// notice, this list of conditions and the following disclaimer. /// 2. Redistributions in binary form must reproduce the above copyright /// notice, this list of conditions and the following disclaimer in the /// documentation and/or other materials provided with the distribution. /// 3. Neither the name of the copyright holder nor the names of its /// contributors may be used to endorse or promote products derived /// from this software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, /// INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY AND FITNESS /// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT /// HOLDER OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, /// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, /// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR /// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF /// LIABILITY, WETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING /// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS /// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /// /// @file ezcu_mem.c /// @author Issam SAID /// @brief The implementation of the ezcu memory objects manipulation routines. /// #include <stdio.h> #include <ezcu/mem.h> #include <__ezcu/config/mem.h> #include <__ezcu/config/dev.h> #include <__ezcu/config/util.h> #include <__ezcu/types-inl.h> #include <__ezcu/mem-inl.h> #include <__ezcu/dev-inl.h> #include <__ezcu/util-inl.h> ezcu_mem_t ezcu_mem_wrap(ezcu_dev_t d, void *h, size_t size, ezcu_flags_t flags) { EZCU_EXIT_IF(d == NULL, "invalid device"); EZCU_EXIT_IF(size == 0, "invalid memory size"); EZCU_EXIT_IF(h == NULL, "invalid memory pointer"); urb_t *n; size_t bytes; if ((n=urb_tree_find(&ezcu->mems, h, __ezcu_ptr_cmp)) != &urb_sentinel) { #ifdef __DEBUG char __tmp[__EZCU_STR_SIZE]; ezcu_mem_t m = n->value; ezcu_flags_mem_to_str(m->flags, __tmp); EZCU_DEBUG("reuse mem wrap: flags=%s, found existing object", __tmp); EZCU_DEBUG("end mem wrap: {h=%p, id=%llu} " "(size= %12.5f MB, refs= %d)", m->h, m->id, (double)m->size*m->unit_size/1024./1024., m->refs); EZCU_DEBUG(""); #endif return n->value; } else { int tmp; ezcu_mem_t m = (ezcu_mem_t) malloc(sizeof(struct __ezcu_mem_t)); ezcu_flags_check_mem(flags); m->flags = ((flags & (~(DEFAULT))) | __EZCU_MEM_HOST_ALLOCATED); if ((flags & EZCU_FLAGS_MEM_LOCS_MASK)==0) m->flags |= HWA; if ((flags & EZCU_FLAGS_MEM_ACCESS_MODES_MASK)==0) m->flags |= READ_WRITE; if ((flags & EZCU_FLAGS_MEM_TYPES_MASK)==0) m->flags |= FLOAT; __EZCU_MEM_CLEAR_HOST(m->flags); __EZCU_MEM_CLEAR_HWA(m->flags); m->id = -1; m->size = size; m->unit_size = ezcu_flags_to_mem_unit_size(m->flags); m->stream = d->streams[__EZCU_DEV_MEM_STREAM]; bytes = m->unit_size*m->size; #ifdef __DEBUG char __tmp[__EZCU_STR_SIZE]; ezcu_flags_mem_to_str(m->flags, __tmp); EZCU_DEBUG("start mem wrap: flags=%s", __tmp); #endif EZCU_CHECK(cuCtxPushCurrent(d->ctx), "failed to push the context"); if (EZCU_FLAGS_HAVE(m->flags, ZERO_COPY)) { __EZCU_DEV_GET(d->id, CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY, tmp); EZCU_EXIT_IF(!tmp, "the device cannot map host zero-copy buffers"); /// wrap zero-copy buffers in the CPU memory. if (EZCU_FLAGS_HAVE(m->flags, HOST)) { EZCU_CHECK(cuMemHostRegister((void*)h, m->size*m->unit_size, CU_MEMHOSTREGISTER_DEVICEMAP), "failed to regiter pre-allocated host memory"); /// needed to map the memory on the device memory EZCU_CHECK(cuMemHostGetDevicePointer(&m->id, h, 0), "failed to map memory region to device"); /// wrap zero-copy buffers in the HWA memory. } else if (EZCU_FLAGS_HAVE(m->flags, HWA)) { EZCU_EXIT("device zero-copy buffers are not wrappable yet"); } else { EZCU_EXIT("invalid flags for wrapping zero-copy buffers"); } m->h = h; } else { /// regular CPU buffers. if (EZCU_FLAGS_HAVE(m->flags, HOST)) { m->h = (void*)h; /// regular HWA buffers. } else if (EZCU_FLAGS_HAVE(m->flags, HWA)) { if (EZCU_FLAGS_HAVE(m->flags, PINNED)) { EZCU_CHECK(cuMemHostRegister((void*)h, m->size*m->unit_size, CU_MEMHOSTREGISTER_PORTABLE), "failed to page-lock preallocated memory"); m->h = (void*)h; } else { m->h = (void*)h; } EZCU_CHECK(cuMemAlloc(&m->id, m->size*m->unit_size), "failed to allocate device memory object"); __ezcu_mem_htod((void*)h, m->id, bytes, m->stream, true); } else { EZCU_EXIT("invalid flags combination for wrapping buffers"); } } urb_tree_put(&ezcu->mems, urb_tree_create(h, m), __ezcu_ptr_cmp); m->refs = 1; EZCU_DEBUG("end mem wrap: {h=%p, id=%llu} " "(size= %12.5f MB, refs= %d)", m->h, m->id, (double)m->size*m->unit_size/1024./1024., m->refs); EZCU_DEBUG(""); EZCU_CHECK(cuCtxPopCurrent(&d->ctx), "failed to pop the context"); return m; } } void ezcu_mem_release(void *h) { urb_t * n = urb_tree_find(&ezcu->mems, h, __ezcu_ptr_cmp); if (n != &urb_sentinel) { //((ezcu_mem_t)n->value)->refs = 1; /// force deletion on the device. __ezcu_mem_release(n->value); urb_tree_delete(&n, NULL, __ezcu_mem_release); } } void ezcu_mem_update(void* h, ezcu_flags_t f) { ezcu_mem_t m = (ezcu_mem_t)urb_tree_find(&ezcu->mems, h, __ezcu_ptr_cmp)->value; #ifdef __DEBUG char __tmp[__EZCU_STR_SIZE]; ezcu_flags_mem_to_str(f, __tmp); EZCU_DEBUG("start mem update {h=%p, id=%llu}, : flags=%s " "host-dirty: %s, hwa-dirty: %s", m->h, m->id, __tmp, __EZCU_MEM_HOST_IS_DIRTY(m->flags) ? "Yes" : "No", __EZCU_MEM_HWA_IS_DIRTY(m->flags) ? "Yes" : "No"); #endif if (EZCU_FLAGS_HAVE(m->flags, ZERO_COPY)) { if (__EZCU_MEM_HWA_IS_DIRTY(m->flags)) { __EZCU_MEM_CLEAR_HWA(m->flags); } } else { if (__EZCU_MEM_HWA_IS_DIRTY(m->flags)) { // if ((!EZCU_FLAGS_HAVE(f, WRITE_ONLY)) && // (!EZCU_FLAGS_HAVE(m->flags, WRITE_ONLY))) { __ezcu_mem_dtoh(m->h, m->id, m->size*m->unit_size, m->stream, true); __EZCU_MEM_CLEAR_HWA(m->flags); //} } } if (EZCU_FLAGS_HAVE(f, READ_WRITE) || EZCU_FLAGS_HAVE(f, WRITE_ONLY)) __EZCU_MEM_TOUCH_HOST(m->flags); EZCU_DEBUG("end mem update: {h=%p, id=%llu}, " "host-dirty: %s, hwa-dirty: %s", m->h, m->id, __EZCU_MEM_HOST_IS_DIRTY(m->flags) ? "Yes" : "No", __EZCU_MEM_HWA_IS_DIRTY(m->flags) ? "Yes" : "No"); EZCU_DEBUG(""); }
41.899441
80
0.628267
[ "object" ]
81e6db25b47acf55080ce7cc927db18fedbeba92
2,973
h
C
pmem-mariadb/storage/tokudb/PerconaFT/locktree/tests/lock_request_unit_test.h
wc222/pmdk-examples
64aadc3a70471c469ac8e214eb1e04ff47cf18ff
[ "BSD-3-Clause" ]
11
2017-10-28T08:41:08.000Z
2021-06-24T07:24:21.000Z
pmem-mariadb/storage/tokudb/PerconaFT/locktree/tests/lock_request_unit_test.h
WSCWDA/pmdk-examples
c3d079e52cd18b0e14836ef42bad9a995336bf90
[ "BSD-3-Clause" ]
1
2021-02-24T05:26:44.000Z
2021-02-24T05:26:44.000Z
pmem-mariadb/storage/tokudb/PerconaFT/locktree/tests/lock_request_unit_test.h
isabella232/pmdk-examples
be7a5a18ba7bb8931e512f6d552eadf820fa2235
[ "BSD-3-Clause" ]
4
2017-09-07T09:33:26.000Z
2021-02-19T07:45:08.000Z
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" /*====== This file is part of PerconaFT. Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved. PerconaFT is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. PerconaFT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PerconaFT. If not, see <http://www.gnu.org/licenses/>. ---------------------------------------- PerconaFT is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. PerconaFT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with PerconaFT. If not, see <http://www.gnu.org/licenses/>. ======= */ #ident "Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved." #pragma once #include "test.h" #include "locktree_unit_test.h" #include "lock_request.h" namespace toku { class lock_request_unit_test { public: // create and set the object's internals, destroy should not crash. void test_create_destroy(void); // make setting keys and getting them back works properly. // at a high level, we want to make sure keys are copied // when appropriate and plays nice with +/- infinity. void test_get_set_keys(void); // starting a lock request without immediate success should get // stored in the lock request set as pending. void test_start_pending(void); // make sure deadlocks are detected when a lock request starts void test_start_deadlock(void); // test that the get_wait_time callback works void test_wait_time_callback(void); private: // releases a single range lock and retries all lock requests. // this is kind of like what the ydb layer does, except that // the ydb layer releases all of a txn's locks at once using // lt->release_locks(), not individually using lt->remove_overlapping_locks_for_txnid). void release_lock_and_retry_requests(locktree *lt, TXNID txnid, const DBT *left_key, const DBT * right_key) { locktree_unit_test::locktree_test_release_lock(lt, txnid, left_key, right_key); lock_request::retry_all_lock_requests(lt); } }; }
36.703704
91
0.713757
[ "object" ]
81ed02b6ae0de2459ffbbb6d44860d7b309d21fd
858
h
C
libless/include/less/value/FunctionLibrary.h
Ti-R/clessc
c822dedd077ff82395890d6c58f213d9a574d96c
[ "MIT" ]
66
2015-02-07T09:08:30.000Z
2021-12-06T17:07:45.000Z
libless/include/less/value/FunctionLibrary.h
Ti-R/clessc
c822dedd077ff82395890d6c58f213d9a574d96c
[ "MIT" ]
30
2015-01-18T07:05:48.000Z
2020-10-08T12:44:21.000Z
libless/include/less/value/FunctionLibrary.h
Ti-R/clessc
c822dedd077ff82395890d6c58f213d9a574d96c
[ "MIT" ]
19
2015-10-19T12:59:19.000Z
2021-12-06T17:07:49.000Z
#ifndef __less_value_FunctionLibrary_h__ #define __less_value_FunctionLibrary_h__ #include <cstring> #include <map> #include <vector> #include "less/value/Value.h" typedef struct FuncInfo { const char* parameterTypes; Value* (*func)(const vector<const Value*>& arguments); } FuncInfo; class FunctionLibrary { private: std::map<std::string, FuncInfo*> map; public: const FuncInfo* getFunction(const char* functionName) const; void push(string name, const char* parameterTypes, Value* (*func)(const vector<const Value*>& arguments)); bool checkArguments(const FuncInfo* fi, const vector<const Value*>& arguments) const; const char* functionDefToString(const char* functionName, const FuncInfo* fi = NULL) const; }; #endif // __less_value_FunctionLibrary_h__
26.8125
67
0.691142
[ "vector" ]
81f55de9c256672584422244dba7e975ccc412bf
5,901
h
C
include/cpp-sort/probes/exc.h
sehe/cpp-sort
ddcadeb2d8a3dec220f5e23cc17e0b05e555d665
[ "MIT" ]
null
null
null
include/cpp-sort/probes/exc.h
sehe/cpp-sort
ddcadeb2d8a3dec220f5e23cc17e0b05e555d665
[ "MIT" ]
null
null
null
include/cpp-sort/probes/exc.h
sehe/cpp-sort
ddcadeb2d8a3dec220f5e23cc17e0b05e555d665
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016-2021 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_PROBES_EXC_H_ #define CPPSORT_PROBES_EXC_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <functional> #include <iterator> #include <type_traits> #include <utility> #include <vector> #include <cpp-sort/sorter_facade.h> #include <cpp-sort/sorter_traits.h> #include <cpp-sort/utility/as_function.h> #include <cpp-sort/utility/functional.h> #include <cpp-sort/utility/size.h> #include <cpp-sort/utility/static_const.h> #include "../detail/functional.h" #include "../detail/iterator_traits.h" #include "../detail/pdqsort.h" namespace cppsort { namespace probe { namespace detail { template<typename ForwardIterator, typename Compare, typename Projection> auto exc_probe_algo(ForwardIterator first, ForwardIterator last, cppsort::detail::difference_type_t<ForwardIterator> size, Compare compare, Projection projection) -> ::cppsort::detail::difference_type_t<ForwardIterator> { using difference_type = ::cppsort::detail::difference_type_t<ForwardIterator>; auto&& comp = utility::as_function(compare); auto&& proj = utility::as_function(projection); if (size < 2) { return 0; } //////////////////////////////////////////////////////////// // Indirectly sort the iterators // Copy the iterators in a vector std::vector<ForwardIterator> iterators; iterators.reserve(size); for (auto it = first ; it != last ; ++it) { iterators.push_back(it); } // Sort the iterators on pointed values cppsort::detail::pdqsort( iterators.begin(), iterators.end(), compare, cppsort::detail::indirect(projection) ); //////////////////////////////////////////////////////////// // Count the number of cycles std::vector<bool> sorted(size, false); // Element where the current cycle starts auto start = first; difference_type cycles = 0; while (start != last) { // Find the element to put in current's place auto current = start; auto next_pos = std::distance(first, current); auto next = iterators[next_pos]; sorted[next_pos] = true; // Process the current cycle if (next != current) { while (next != start) { // If an element is in the place of another element that compares // equivalent, it means that this element was actually already in // a suitable place, so we count one more cycle as if it was an // already suitably placed element, this handles collections with // several elements which compare equivalent if (not comp(proj(*next), proj(*current)) && not comp(proj(*current), proj(*next))) { ++cycles; } // Locate the next element of the cycle current = next; auto next_pos = std::distance(first, next); next = iterators[next_pos]; sorted[next_pos] = true; } } ++cycles; // Find the next cycle auto&& sorted_it = sorted.begin() + std::distance(first, start); do { ++start; ++sorted_it; } while (start != last && *sorted_it); } return size - cycles; } struct exc_impl { template< typename ForwardIterable, typename Compare = std::less<>, typename Projection = utility::identity, typename = std::enable_if_t< is_projection_v<Projection, ForwardIterable, Compare> > > auto operator()(ForwardIterable&& iterable, Compare compare={}, Projection projection={}) const -> decltype(auto) { return exc_probe_algo(std::begin(iterable), std::end(iterable), utility::size(iterable), std::move(compare), std::move(projection)); } template< typename ForwardIterator, typename Compare = std::less<>, typename Projection = utility::identity, typename = std::enable_if_t< is_projection_iterator_v<Projection, ForwardIterator, Compare> > > auto operator()(ForwardIterator first, ForwardIterator last, Compare compare={}, Projection projection={}) const -> decltype(auto) { return exc_probe_algo(first, last, std::distance(first, last), std::move(compare), std::move(projection)); } template<typename Integer> static constexpr auto max_for_size(Integer n) -> Integer { return n == 0 ? 0 : n - 1; } }; } namespace { constexpr auto&& exc = utility::static_const< sorter_facade<detail::exc_impl> >::value; } }} #endif // CPPSORT_PROBES_EXC_H_
36.202454
90
0.486697
[ "vector" ]
81fdb18a7c17ba17a8ddccffef2b3f5aef206b64
1,523
h
C
include/igl/combine.h
rushmash/libwetcloth
24f16481c68952c3d2a91acd6e3b74eb091b66bc
[ "BSD-3-Clause-Clear" ]
28
2017-03-01T04:09:18.000Z
2022-02-01T13:33:50.000Z
include/igl/combine.h
rushmash/libwetcloth
24f16481c68952c3d2a91acd6e3b74eb091b66bc
[ "BSD-3-Clause-Clear" ]
3
2017-03-09T05:22:49.000Z
2017-08-02T18:38:05.000Z
include/igl/combine.h
rushmash/libwetcloth
24f16481c68952c3d2a91acd6e3b74eb091b66bc
[ "BSD-3-Clause-Clear" ]
17
2017-03-01T14:00:01.000Z
2022-02-08T06:36:54.000Z
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2016 Alec Jacobson <alecjacobson@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #ifndef IGL_COMBINE_H #define IGL_COMBINE_H #include "igl_inline.h" #include <Eigen/Core> #include <vector> namespace igl { // Combine k meshes into a single >=k connected component mesh with a single // vertex list and face list. Similar to Maya's Combine operation. // // Inputs: // VV k-long list of lists of mesh vertex positions // FF k-long list of lists of mesh face indices so that FF[i] indexes // VV[i] // Outputs: // V VV[0].rows()+...+VV[k-1].rows() by VV[0].cols() list of mesh // vertex positions // F FF[0].rows()+...+FF[k-1].rows() by FF[0].cols() list of mesh faces // indices into V // Example: // // Suppose you have mesh A (VA,FA) and mesh B (VB,FB) // igl::combine<Eigen::MatrixXd,Eigen::MatrixXi>({VA,VB},{FA,FB},V,F); // template < typename DerivedVV, typename DerivedFF, typename DerivedV, typename DerivedF> IGL_INLINE void combine( const std::vector<DerivedVV> & VV, const std::vector<DerivedFF> & FF, Eigen::PlainObjectBase<DerivedV> & V, Eigen::PlainObjectBase<DerivedF> & F); } #ifndef IGL_STATIC_LIBRARY # include "combine.cpp" #endif #endif
31.081633
79
0.658569
[ "mesh", "geometry", "vector" ]
c309d74fe7fcf7a43624b48614a65f87726b2b45
2,692
h
C
src/project.h
andrasigneczi/DarknetProjectManager
e4fe20346b3244f529edef1e2aa6c15163ef6671
[ "Apache-2.0" ]
null
null
null
src/project.h
andrasigneczi/DarknetProjectManager
e4fe20346b3244f529edef1e2aa6c15163ef6671
[ "Apache-2.0" ]
null
null
null
src/project.h
andrasigneczi/DarknetProjectManager
e4fe20346b3244f529edef1e2aa6c15163ef6671
[ "Apache-2.0" ]
null
null
null
#ifndef __PROJECT_H__ #define __PROJECT_H__ #include <string> #include <vector> #include <map> #include <QRect> using namespace std; class Project { public: struct NormRect { double mCenterX; double mCenterY; double mWidth; double mHeight; }; struct RectAndLabel { string mLabel; NormRect mNormRect; //int mLabelId; //QRect mRect; //int mImageWidth; //int mImageHeight; }; enum LoadType { LT_TRAIN, LT_TEST, LT_BOTH }; // load the datafile and the others listed in the data void openProject(string path, LoadType loadType = LT_BOTH); void saveProject(string path); // returns with the imagelist of the training files const vector<string>& getTrainAndTestFileList() const { return mTrainAndTestFiles; } // returns with the bounding rect vector of the selected image const vector<RectAndLabel>& getLabelsAndRects(size_t labelId) const { return mRectsAndLabels[labelId]; }; // The MainWindow calls this function if anything was modified and saving necessary void updateLabelAndRect(size_t labelId, const vector<RectAndLabel>& updatedLabelsAndRects); const vector<string>& getNames() { return mNames; } private: // main/project file loading void loadDataFile(string path); // Names file contains the labels void loadNamesFile(); // train.txt and test.txt file contain a list of image paths void loadTrainAndTestTxt(LoadType loadType); void loadTrainAndTestTxt(ifstream& file); // load all the txt file which contains one or more label id and bounding rect // description void loadBoundingRecFiles(); // parse a line of the data file void parseDataFileLine(string line); // the program loads the whole content of a label file // this function parses this string line by line and fills the mRectsAndLabels void parseLabelFileString(string content); // Txt path contains the bounding rects' descriptions and the label id string getTxtPath(string imgPath); // Saving the labels void saveNames(); // Labels file path string mNamesFilePath; // Data dir file path string mDataFilePath; // Every relative path compared to this folder string mProjectFolder; // .data file's content map<string, string> mDataMap; // Labels, the index is the id vector<string> mNames; // File names from the training and test file list vector<string> mTrainAndTestFiles; // The txt files' content in structures vector<vector<RectAndLabel>> mRectsAndLabels; }; #endif // __PROJECT_H__
31.670588
109
0.686478
[ "vector" ]
c30d1ce45a0963bc011e393d86e3ef3e06a2ff5c
233
h
C
test/unit-tests/main/poseidonos_mock.h
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
38
2021-04-06T03:20:55.000Z
2022-03-02T09:33:28.000Z
test/unit-tests/main/poseidonos_mock.h
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
19
2021-04-08T02:27:44.000Z
2022-03-23T00:59:04.000Z
test/unit-tests/main/poseidonos_mock.h
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
28
2021-04-08T04:39:18.000Z
2022-03-24T05:56:00.000Z
#include <gmock/gmock.h> #include <list> #include <string> #include <vector> #include "src/main/poseidonos.h" namespace pos { class MockIbofos : public Poseidonos { public: using Poseidonos::Poseidonos; }; } // namespace pos
12.944444
36
0.712446
[ "vector" ]
c31557b0740285680f84ed95efa09adeef5769c9
19,079
h
C
src/d3d11/exports.h
bobmoretti/bmsdedi
fa9188f5911403a219204a9438d32badb70a6585
[ "Zlib" ]
2
2020-12-28T11:32:28.000Z
2021-07-06T16:15:04.000Z
src/d3d11/exports.h
bobmoretti/bmsdedi
fa9188f5911403a219204a9438d32badb70a6585
[ "Zlib" ]
null
null
null
src/d3d11/exports.h
bobmoretti/bmsdedi
fa9188f5911403a219204a9438d32badb70a6585
[ "Zlib" ]
null
null
null
/* CONTRIBUTORS: Sean Pesce Undocumented function prototypes were determined using IDA Pro and the following references: https://github.com/doitsujin/dxvk/blob/master/src/d3d11/d3d11_main.cpp https://github.com/bo3b/3Dmigoto/blob/master/DirectX11/D3D11Wrapper.cpp https://chromium.googlesource.com/external/p3/regal/+/cass/src/apitrace/wrappers/d3d11stubs.cpp */ #pragma once #ifndef SP_D3D11_DLL_EXPORTS_H_ #define SP_D3D11_DLL_EXPORTS_H_ #include "d3d11_wrapper.h" // Creates an instance of IDirect3DDevice from an IDXGIDevice. // https://msdn.microsoft.com/en-us/library/windows/apps/dn895087.aspx typedef HRESULT (WINAPI *CreateDirect3D11DeviceFromDXGIDevice_t)(IDXGIDevice*, IInspectable**); HRESULT WINAPI CreateDirect3D11DeviceFromDXGIDevice_(_In_ IDXGIDevice* dxgiDevice, _Out_ IInspectable** graphicsDevice); // Creates an instance of IDirect3DSurface from an IDXGISurface. // https://msdn.microsoft.com/en-us/library/windows/apps/dn895088.aspx typedef HRESULT (WINAPI *CreateDirect3D11SurfaceFromDXGISurface_t)(IDXGISurface*, IInspectable**); HRESULT WINAPI CreateDirect3D11SurfaceFromDXGISurface_(_In_ IDXGISurface* dxgiSurface, _Out_ IInspectable** graphicsSurface); typedef HRESULT (WINAPI *D3D11CoreCreateDevice_t)( IDXGIFactory*, IDXGIAdapter*, UINT, const D3D_FEATURE_LEVEL*, UINT, ID3D11Device** ); HRESULT WINAPI D3D11CoreCreateDevice_( IDXGIFactory* pFactory, IDXGIAdapter* pAdapter, UINT Flags, const D3D_FEATURE_LEVEL* pFeatureLevels, UINT FeatureLevels, ID3D11Device** ppDevice ); typedef HRESULT (WINAPI *D3D11CoreCreateLayeredDevice_t)( const void*, DWORD, const void*, REFIID, void** ); HRESULT WINAPI D3D11CoreCreateLayeredDevice_( const void* unknown0, DWORD unknown1, const void* unknown2, REFIID riid, void** ppvObj ); typedef SIZE_T (WINAPI *D3D11CoreGetLayeredDeviceSize_t)(const void*, DWORD); SIZE_T WINAPI D3D11CoreGetLayeredDeviceSize_(const void* unknown0, DWORD unknown1); typedef HRESULT (WINAPI *D3D11CoreRegisterLayers_t)(const void*, DWORD); HRESULT WINAPI D3D11CoreRegisterLayers_(const void* unknown0, DWORD unknown1); // Creates a device that represents the display adapter. // https://msdn.microsoft.com/en-us/library/windows/desktop/ff476082%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 typedef HRESULT (WINAPI *D3D11CreateDevice_t)( _In_opt_ IDXGIAdapter*, D3D_DRIVER_TYPE, HMODULE, UINT, _In_opt_ const D3D_FEATURE_LEVEL*, UINT, UINT, _Out_opt_ ID3D11Device**, _Out_opt_ D3D_FEATURE_LEVEL*, _Out_opt_ ID3D11DeviceContext** ); HRESULT WINAPI D3D11CreateDevice_( _In_opt_ IDXGIAdapter* pAdapter, D3D_DRIVER_TYPE DriverType, HMODULE Software, UINT Flags, _In_opt_ const D3D_FEATURE_LEVEL* pFeatureLevels, UINT FeatureLevels, UINT SDKVersion, _Out_opt_ ID3D11Device** ppDevice, _Out_opt_ D3D_FEATURE_LEVEL* pFeatureLevel, _Out_opt_ ID3D11DeviceContext** ppImmediateContext ); // Creates a device that represents the display adapter and a swap chain used for rendering. // https://msdn.microsoft.com/en-us/library/windows/desktop/ff476083(v=vs.85).aspx typedef HRESULT (WINAPI *D3D11CreateDeviceAndSwapChain_t)( _In_opt_ IDXGIAdapter*, D3D_DRIVER_TYPE, HMODULE, UINT, _In_opt_ const D3D_FEATURE_LEVEL*, UINT, UINT, _In_opt_ const DXGI_SWAP_CHAIN_DESC*, _Out_opt_ IDXGISwapChain**, _Out_opt_ ID3D11Device**, _Out_opt_ D3D_FEATURE_LEVEL*, _Out_opt_ ID3D11DeviceContext** ); HRESULT WINAPI D3D11CreateDeviceAndSwapChain_( _In_opt_ IDXGIAdapter* pAdapter, D3D_DRIVER_TYPE DriverType, HMODULE Software, UINT Flags, _In_opt_ const D3D_FEATURE_LEVEL* pFeatureLevels, UINT FeatureLevels, UINT SDKVersion, _In_opt_ const DXGI_SWAP_CHAIN_DESC* pSwapChainDesc, _Out_opt_ IDXGISwapChain** ppSwapChain, _Out_opt_ ID3D11Device** ppDevice, _Out_opt_ D3D_FEATURE_LEVEL* pFeatureLevel, _Out_opt_ ID3D11DeviceContext** ppImmediateContext ); typedef HRESULT (WINAPI *D3D11CreateDeviceForD3D12_t)( IUnknown*, UINT, const D3D_FEATURE_LEVEL*, UINT, UINT, UINT, ID3D11Device**, ID3D11DeviceContext**, D3D_FEATURE_LEVEL* ); HRESULT WINAPI D3D11CreateDeviceForD3D12_( IUnknown* pDevice, UINT Flags, const D3D_FEATURE_LEVEL* pFeatureLevels, UINT FeatureLevels, UINT NumQueues, // ? SDKVersion ? UINT NodeMask, // ? NumQueues ? ID3D11Device** ppDevice, ID3D11DeviceContext** ppImmediateContext, D3D_FEATURE_LEVEL* pChosenFeatureLevel ); typedef HRESULT (WINAPI *D3D11On12CreateDevice_t)( _In_ IUnknown*, UINT, _In_opt_ const D3D_FEATURE_LEVEL*, UINT, _In_opt_ IUnknown*, UINT, UINT, _Out_opt_ ID3D11Device**, _Out_opt_ ID3D11DeviceContext**, _Out_opt_ D3D_FEATURE_LEVEL* ); HRESULT WINAPI D3D11On12CreateDevice_( _In_ IUnknown* pDevice, UINT Flags, _In_opt_ const D3D_FEATURE_LEVEL* pFeatureLevels, UINT FeatureLevels, _In_opt_ IUnknown* ppCommandQueues, UINT NumQueues, UINT NodeMask, _Out_opt_ ID3D11Device** ppDevice, _Out_opt_ ID3D11DeviceContext** ppImmediateContext, _Out_opt_ D3D_FEATURE_LEVEL* pChosenFeatureLevel ); // Closes a graphics adapter that was previously opened by using the D3DKMTOpenAdapterFromHdc function. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtcloseadapter //NTSTATUS APIENTRY D3DKMTCloseAdapter(const D3DKMT_CLOSEADAPTER* pAdapter); typedef HRESULT (WINAPI *D3DKMTCloseAdapter_t)(); HRESULT WINAPI D3DKMTCloseAdapter_(); // Creates allocations of system or video memory. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtcreateallocation //NTSTATUS APIENTRY D3DKMTCreateAllocation(D3DKMT_CREATEALLOCATION* Arg1); typedef HRESULT (WINAPI *D3DKMTCreateAllocation_t)(); HRESULT WINAPI D3DKMTCreateAllocation_(); // Creates a kernel-mode device context. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtcreatecontext //NTSTATUS APIENTRY D3DKMTCreateContext(D3DKMT_CREATECONTEXT* Arg1); typedef HRESULT (WINAPI *D3DKMTCreateContext_t)(); HRESULT WINAPI D3DKMTCreateContext_(); // Creates a kernel-mode device context. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtcreatedevice //NTSTATUS APIENTRY D3DKMTCreateDevice(D3DKMT_CREATEDEVICE* Arg1); typedef HRESULT (WINAPI *D3DKMTCreateDevice_t)(); HRESULT WINAPI D3DKMTCreateDevice_(); // Creates a kernel-mode synchronization object. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtcreatesynchronizationobject //NTSTATUS APIENTRY D3DKMTCreateSynchronizationObject(D3DKMT_CREATESYNCHRONIZATIONOBJECT* Arg1); typedef HRESULT (WINAPI *D3DKMTCreateSynchronizationObject_t)(); HRESULT WINAPI D3DKMTCreateSynchronizationObject_(); // Releases a resource, a list of allocations, or both. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtdestroyallocation //NTSTATUS APIENTRY D3DKMTDestroyAllocation(const D3DKMT_DESTROYALLOCATION* Arg1); typedef HRESULT (WINAPI *D3DKMTDestroyAllocation_t)(); HRESULT WINAPI D3DKMTDestroyAllocation_(); // Releases a kernel-mode device context. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtdestroycontext //NTSTATUS APIENTRY D3DKMTDestroyContext(const D3DKMT_DESTROYCONTEXT* Arg1); typedef HRESULT (WINAPI *D3DKMTDestroyContext_t)(); HRESULT WINAPI D3DKMTDestroyContext_(); // Releases a kernel-mode device context. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtdestroydevice //NTSTATUS APIENTRY D3DKMTDestroyDevice(const D3DKMT_DESTROYDEVICE* Arg1); typedef HRESULT (WINAPI *D3DKMTDestroyDevice_t)(); HRESULT WINAPI D3DKMTDestroyDevice_(); // Destroys a kernel-mode synchronization object. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtdestroysynchronizationobject //NTSTATUS APIENTRY D3DKMTDestroySynchronizationObject(const D3DKMT_DESTROYSYNCHRONIZATIONOBJECT* Arg1); typedef HRESULT (WINAPI *D3DKMTDestroySynchronizationObject_t)(); HRESULT WINAPI D3DKMTDestroySynchronizationObject_(); // Exchanges information with the display miniport driver. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtescape //NTSTATUS APIENTRY D3DKMTEscape(const D3DKMT_ESCAPE* Arg1); typedef HRESULT (WINAPI *D3DKMTEscape_t)(); HRESULT WINAPI D3DKMTEscape_(); // Retrieves the scheduling priority for a device context. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtgetcontextschedulingpriority //NTSTATUS APIENTRY D3DKMTGetContextSchedulingPriority(D3DKMT_GETCONTEXTSCHEDULINGPRIORITY* Arg1); typedef HRESULT (WINAPI *D3DKMTGetContextSchedulingPriority_t)(); HRESULT WINAPI D3DKMTGetContextSchedulingPriority_(); // Retrieves the state of a device. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtgetdevicestate //NTSTATUS APIENTRY D3DKMTGetDeviceState(D3DKMT_GETDEVICESTATE* Arg1); typedef HRESULT (WINAPI *D3DKMTGetDeviceState_t)(); HRESULT WINAPI D3DKMTGetDeviceState_(); // Retrieves a list of available display modes, including modes with extended format. // https://msdn.microsoft.com/en-us/windows/hardware/ff546967(v=vs.100) //NTSTATUS APIENTRY D3DKMTGetDisplayModeList(_Inout_ D3DKMT_GETDISPLAYMODELIST* pData); typedef HRESULT (WINAPI *D3DKMTGetDisplayModeList_t)(); HRESULT WINAPI D3DKMTGetDisplayModeList_(); // Retrieves a list of multiple-sample methods that are used for an allocation. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtgetmultisamplemethodlist //NTSTATUS APIENTRY D3DKMTGetMultisampleMethodList(D3DKMT_GETMULTISAMPLEMETHODLIST* Arg1); typedef HRESULT (WINAPI *D3DKMTGetMultisampleMethodList_t)(); HRESULT WINAPI D3DKMTGetMultisampleMethodList_(); // For system use only. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtgetruntimedata //NTSTATUS APIENTRY D3DKMTGetRuntimeData(const D3DKMT_GETRUNTIMEDATA* Arg1); typedef HRESULT (WINAPI *D3DKMTGetRuntimeData_t)(); HRESULT WINAPI D3DKMTGetRuntimeData_(); // Retrieves the global shared handle for the primary surface. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtgetsharedprimaryhandle //NTSTATUS APIENTRY D3DKMTGetSharedPrimaryHandle(D3DKMT_GETSHAREDPRIMARYHANDLE* Arg1); typedef HRESULT (WINAPI *D3DKMTGetSharedPrimaryHandle_t)(); HRESULT WINAPI D3DKMTGetSharedPrimaryHandle_(); // Locks an entire allocation or specific pages within an allocation. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtlock //NTSTATUS APIENTRY D3DKMTLock(D3DKMT_LOCK* Arg1); typedef HRESULT (WINAPI *D3DKMTLock_t)(); HRESULT WINAPI D3DKMTLock_(); // Maps a device context handle (HDC) to a graphics adapter handle and, if the adapter contains multiple monitor outputs, to one of those outputs. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtopenadapterfromhdc //NTSTATUS APIENTRY D3DKMTOpenAdapterFromHdc(D3DKMT_OPENADAPTERFROMHDC* Arg1); typedef HRESULT (WINAPI *D3DKMTOpenAdapterFromHdc_t)(); HRESULT WINAPI D3DKMTOpenAdapterFromHdc_(); // Opens a shared resource. // https://technet.microsoft.com/en-us/windows/ff547065%28v=vs.80%29?f=255&MSPPError=-2147217396 //NTSTATUS APIENTRY D3DKMTOpenResource(_Inout_ D3DKMT_OPENRESOURCE* pData); typedef HRESULT (WINAPI *D3DKMTOpenResource_t)(); HRESULT WINAPI D3DKMTOpenResource_(); // Submits a present command to the Microsoft DirectX graphics kernel subsystem (Dxgkrnl.sys). // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtpresent //NTSTATUS APIENTRY D3DKMTPresent(D3DKMT_PRESENT* Arg1); typedef HRESULT (WINAPI *D3DKMTPresent_t)(); HRESULT WINAPI D3DKMTPresent_(); // Retrieves graphics adapter information. // https://msdn.microsoft.com/en-us/windows/ff547100(v=vs.80) //NTSTATUS APIENTRY D3DKMTQueryAdapterInfo(_Inout_ const D3DKMT_QUERYADAPTERINFO* pData); typedef HRESULT (WINAPI *D3DKMTQueryAdapterInfo_t)(); HRESULT WINAPI D3DKMTQueryAdapterInfo_(); // Retrieves the residency status of a resource or list of allocations. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtqueryallocationresidency //NTSTATUS APIENTRY D3DKMTQueryAllocationResidency(const D3DKMT_QUERYALLOCATIONRESIDENCY* Arg1); typedef HRESULT (WINAPI *D3DKMTQueryAllocationResidency_t)(); HRESULT WINAPI D3DKMTQueryAllocationResidency_(); // Retrieves information about a shared resource. // https://technet.microsoft.com/en-us/windows/ff547124(v=vs.60) //NTSTATUS APIENTRY D3DKMTQueryResourceInfo(_Inout_ D3DKMT_QUERYRESOURCEINFO* pData); typedef HRESULT (WINAPI *D3DKMTQueryResourceInfo_t)(); HRESULT WINAPI D3DKMTQueryResourceInfo_(); // Submits the current command buffer to the Microsoft DirectX graphics kernel subsystem (Dxgkrnl.sys). // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtrender //NTSTATUS APIENTRY D3DKMTRender(D3DKMT_RENDER* Arg1); typedef HRESULT (WINAPI *D3DKMTRender_t)(); HRESULT WINAPI D3DKMTRender_(); // Sets the priority level of a resource or list of allocations. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtsetallocationpriority //NTSTATUS APIENTRY D3DKMTSetAllocationPriority(const D3DKMT_SETALLOCATIONPRIORITY* Arg1); typedef HRESULT (WINAPI *D3DKMTSetAllocationPriority_t)(); HRESULT WINAPI D3DKMTSetAllocationPriority_(); // Sets the scheduling priority for a device context. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtsetcontextschedulingpriority //NTSTATUS APIENTRY D3DKMTSetContextSchedulingPriority(const D3DKMT_SETCONTEXTSCHEDULINGPRIORITY* Arg1); typedef HRESULT (WINAPI *D3DKMTSetContextSchedulingPriority_t)(); HRESULT WINAPI D3DKMTSetContextSchedulingPriority_(); // Sets the allocation that is used to scan out to the display. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtsetdisplaymode //NTSTATUS APIENTRY D3DKMTSetDisplayMode(const D3DKMT_SETDISPLAYMODE* Arg1); typedef HRESULT (WINAPI *D3DKMTSetDisplayMode_t)(); HRESULT WINAPI D3DKMTSetDisplayMode_(); // Changes the private-format attribute of a video present source. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtsetdisplayprivatedriverformat //NTSTATUS APIENTRY D3DKMTSetDisplayPrivateDriverFormat(const D3DKMT_SETDISPLAYPRIVATEDRIVERFORMAT* Arg1); typedef HRESULT (WINAPI *D3DKMTSetDisplayPrivateDriverFormat_t)(); HRESULT WINAPI D3DKMTSetDisplayPrivateDriverFormat_(); // Sets the gamma ramp. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtsetgammaramp //NTSTATUS APIENTRY D3DKMTSetGammaRamp(const D3DKMT_SETGAMMARAMP* Arg1); typedef HRESULT (WINAPI *D3DKMTSetGammaRamp_t)(); HRESULT WINAPI D3DKMTSetGammaRamp_(); // Sets and releases the video present source in the path of a video present network (VidPN) topology that owns the VidPN. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtsetvidpnsourceowner //NTSTATUS APIENTRY D3DKMTSetVidPnSourceOwner(const D3DKMT_SETVIDPNSOURCEOWNER* Arg1); typedef HRESULT (WINAPI *D3DKMTSetVidPnSourceOwner_t)(); HRESULT WINAPI D3DKMTSetVidPnSourceOwner_(); // Inserts a signal for the specified synchronization objects in the specified context stream. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtsignalsynchronizationobject //NTSTATUS APIENTRY D3DKMTSignalSynchronizationObject(const D3DKMT_SIGNALSYNCHRONIZATIONOBJECT* Arg1); typedef HRESULT (WINAPI *D3DKMTSignalSynchronizationObject_t)(); HRESULT WINAPI D3DKMTSignalSynchronizationObject_(); // Unlocks a list of allocations. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtunlock //NTSTATUS APIENTRY D3DKMTUnlock(const D3DKMT_UNLOCK* Arg1); typedef HRESULT (WINAPI *D3DKMTUnlock_t)(); HRESULT WINAPI D3DKMTUnlock_(); // Inserts a wait for the specified synchronization objects in the specified context stream. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtwaitforsynchronizationobject //NTSTATUS APIENTRY D3DKMTWaitForSynchronizationObject(const D3DKMT_WAITFORSYNCHRONIZATIONOBJECT* Arg1); typedef HRESULT (WINAPI *D3DKMTWaitForSynchronizationObject_t)(); HRESULT WINAPI D3DKMTWaitForSynchronizationObject_(); // Waits for the vertical blanking interval to occur and then returns. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3dkmthk/nf-d3dkmthk-d3dkmtwaitforverticalblankevent //NTSTATUS APIENTRY D3DKMTWaitForVerticalBlankEvent(const D3DKMT_WAITFORVERTICALBLANKEVENT* Arg1); typedef HRESULT (WINAPI *D3DKMTWaitForVerticalBlankEvent_t)(); HRESULT WINAPI D3DKMTWaitForVerticalBlankEvent_(); //////////////////// UNDOCUMENTED FUNCTIONS //////////////////// typedef void* (*D3DPerformance_BeginEvent_t)(void*, void*); void* D3DPerformance_BeginEvent_(void* unknown0, void* unknown1); // ? D3DPerformance_BeginEvent_(void* unknown0) ? typedef void* (*D3DPerformance_EndEvent_t)(void**); void* D3DPerformance_EndEvent_(void** unknown0); typedef void* (*D3DPerformance_GetStatus_t)(void**); void* D3DPerformance_GetStatus_(void** unknown0); typedef UINT (*D3DPerformance_SetMarker_t)(void*, void*); UINT D3DPerformance_SetMarker_(void* unknown0, void* unknown1); typedef void* (WINAPI *EnableFeatureLevelUpgrade_t)(); void* WINAPI EnableFeatureLevelUpgrade_(); //////////////////////////////////////////////////////////////// // Creates a graphics adapter object that is referenced in subsequent calls. // https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/d3d10umddi/nc-d3d10umddi-pfnd3d10ddi_openadapter //HRESULT APIENTRY OpenAdapter10(D3D10DDIARG_OPENADAPTER* pOpenData); typedef HRESULT (WINAPI *OpenAdapter10_t)(void*); HRESULT WINAPI OpenAdapter10_(void* pOpenData); // Creates a graphics adapter object that is referenced in subsequent calls. // https://msdn.microsoft.com/en-us/library/windows/hardware/ff568603%28v=vs.85%29.aspx //HRESULT APIENTRY OpenAdapter10_2(_Inout_ D3D10DDIARG_OPENADAPTER* pOpenData); typedef HRESULT (WINAPI *OpenAdapter10_2_t)(void*); HRESULT WINAPI OpenAdapter10_2_(_Inout_ void* pOpenData); #endif // SP_D3D11_DLL_EXPORTS_H_
42.024229
146
0.800566
[ "object" ]
c318db11692d9889a662ac732784b2977c9f76d0
1,219
h
C
ICC_Golf_Balls_Project/ICC_Golf_Balls_Project/ids_camera.h
ArminPCM/GolfBall-Logo-Recognition
b03896c5b0d0f54dbdd06896b741509968ba02f3
[ "Unlicense" ]
null
null
null
ICC_Golf_Balls_Project/ICC_Golf_Balls_Project/ids_camera.h
ArminPCM/GolfBall-Logo-Recognition
b03896c5b0d0f54dbdd06896b741509968ba02f3
[ "Unlicense" ]
null
null
null
ICC_Golf_Balls_Project/ICC_Golf_Balls_Project/ids_camera.h
ArminPCM/GolfBall-Logo-Recognition
b03896c5b0d0f54dbdd06896b741509968ba02f3
[ "Unlicense" ]
null
null
null
#pragma once //#define NO_UEYE #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> typedef unsigned long HIDS; class IDS_Camera { public: // Public Data Members HIDS m_hCam; //IDS camera handle void* newFrame; int m_nRenderMode; // render mode int m_nColorMode; // Y8/RGB16/RGB24/REG32 int m_nBitsPerPixel; // number of bits needed store one pixel int m_nMaxSizeX; // width of video int m_nMaxSizeY; // height of video int m_nSizeX; // width of video int m_nSizeY; // height of video int m_lMemoryId; // grabber memory - buffer ID char* m_pcImageMemory; // grabber memory - pointer to buffer int nMemID; // memory ID const char* m_filename; int m_filecount; int m_frameindex; // Constructor & Destructor IDS_Camera(void); ~IDS_Camera(void); void setCaptureFiles(const char* name, int number); int setROI(int x, int y, int width, int height); int resetROI(); bool initiCamera(HIDS, char SerNo[16]); bool lockImage(cv::Mat&); void unlockImage(cv::Mat&); void unlockImage(char*); void setinifile(char* file); char* freezeFrame(); void startCapture(); void Cleanup(); };
26.5
66
0.670221
[ "render" ]
c320fb3f6ba18e012fd6a8dd1c5ede670f6cef9c
698
h
C
app/src/main/cpp/nbbook/tools/font/FontManager.h
kartikhimself/NBReader
e423b13915578ab95c1683bfa7a70e59f19f2eab
[ "Apache-2.0" ]
29
2020-02-21T16:11:59.000Z
2022-02-09T08:49:29.000Z
app/src/main/cpp/nbbook/tools/font/FontManager.h
kartikhimself/NBReader
e423b13915578ab95c1683bfa7a70e59f19f2eab
[ "Apache-2.0" ]
5
2020-03-12T02:55:40.000Z
2021-06-30T10:50:08.000Z
app/src/main/cpp/nbbook/tools/font/FontManager.h
newbiechen1024/NBReader
e423b13915578ab95c1683bfa7a70e59f19f2eab
[ "Apache-2.0" ]
6
2020-03-18T12:07:07.000Z
2021-12-14T03:51:27.000Z
// author : newbiechen // date : 2019-10-06 16:56 // description : 字体管理器 // #ifndef NBREADER_FONTMANAGER_H #define NBREADER_FONTMANAGER_H #include <string> #include <vector> #include "FontMap.h" class FontManager { public: std::string put(const std::string &family, std::shared_ptr<FontEntry> entry); int familyListIndex(const std::vector<std::string> &familyList); const std::map<std::string,std::shared_ptr<FontEntry> > &entries() const; // const std::vector<std::vector<std::string> > &familyLists() const; private: std::map<std::string,std::shared_ptr<FontEntry> > mEntries; std::vector<std::vector<std::string> > mFamilyLists; }; #endif //NBREADER_FONTMANAGER_H
24.928571
81
0.712034
[ "vector" ]
dc912600a5d8addb807fd4daf3de9e023e21a5d8
823
h
C
app/out_html5/out/h3d/shader/ColorKey.h
Lerg/hashlink-emscripten
8f5c28a879c78f275fcbc482e1c5f86c08dbe72e
[ "MIT" ]
1
2021-10-03T16:34:38.000Z
2021-10-03T16:34:38.000Z
app/out_html5/out/h3d/shader/ColorKey.h
Lerg/hashlink-emscripten
8f5c28a879c78f275fcbc482e1c5f86c08dbe72e
[ "MIT" ]
null
null
null
app/out_html5/out/h3d/shader/ColorKey.h
Lerg/hashlink-emscripten
8f5c28a879c78f275fcbc482e1c5f86c08dbe72e
[ "MIT" ]
null
null
null
// Generated by HLC 4.2.1 (HL v4) #ifndef INC_h3d__shader__ColorKey #define INC_h3d__shader__ColorKey typedef struct _h3d__shader__$ColorKey *h3d__shader__$ColorKey; typedef struct _h3d__shader__ColorKey *h3d__shader__ColorKey; #include <hl/Class.h> #include <hl/BaseType.h> #include <_std/String.h> #include <hxsl/SharedShader.h> #include <hxsl/Shader.h> #include <hxsl/ShaderInstance.h> #include <h3d/Vector.h> struct _h3d__shader__$ColorKey { hl_type *$type; hl_type* __type__; vdynamic* __meta__; varray* __implementedBy__; String __name__; vdynamic* __constructor__; String SRC; hxsl__SharedShader _SHADER; }; struct _h3d__shader__ColorKey { hl_type *$type; int priority; hxsl__SharedShader shader; hxsl__ShaderInstance instance; int constBits; bool constModified; h3d__Vector colorKey__; }; #endif
22.861111
63
0.792224
[ "vector" ]
dc985cc1246f5209937939466462fb1e5609b198
8,740
h
C
datasets/linux-4.11-rc3/drivers/staging/fsl-mc/include/dprc.h
yijunyu/demo-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
1
2019-05-03T19:27:45.000Z
2019-05-03T19:27:45.000Z
datasets/linux-4.11-rc3/drivers/staging/fsl-mc/include/dprc.h
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
datasets/linux-4.11-rc3/drivers/staging/fsl-mc/include/dprc.h
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2013-2016 Freescale Semiconductor Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the above-listed copyright holders nor the * names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * * ALTERNATIVELY, this software may be distributed under the terms of the * GNU General Public License ("GPL") as published by the Free Software * Foundation, either version 2 of that License or (at your option) any * later version. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _FSL_DPRC_H #define _FSL_DPRC_H #include "mc-cmd.h" /* * Data Path Resource Container API * Contains DPRC API for managing and querying DPAA resources */ struct fsl_mc_io; int dprc_open(struct fsl_mc_io *mc_io, u32 cmd_flags, int container_id, u16 *token); int dprc_close(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token); /* IRQ */ /* IRQ index */ #define DPRC_IRQ_INDEX 0 /* Number of dprc's IRQs */ #define DPRC_NUM_OF_IRQS 1 /* DPRC IRQ events */ /* IRQ event - Indicates that a new object added to the container */ #define DPRC_IRQ_EVENT_OBJ_ADDED 0x00000001 /* IRQ event - Indicates that an object was removed from the container */ #define DPRC_IRQ_EVENT_OBJ_REMOVED 0x00000002 /* IRQ event - Indicates that resources added to the container */ #define DPRC_IRQ_EVENT_RES_ADDED 0x00000004 /* IRQ event - Indicates that resources removed from the container */ #define DPRC_IRQ_EVENT_RES_REMOVED 0x00000008 /* * IRQ event - Indicates that one of the descendant containers that opened by * this container is destroyed */ #define DPRC_IRQ_EVENT_CONTAINER_DESTROYED 0x00000010 /* * IRQ event - Indicates that on one of the container's opened object is * destroyed */ #define DPRC_IRQ_EVENT_OBJ_DESTROYED 0x00000020 /* Irq event - Indicates that object is created at the container */ #define DPRC_IRQ_EVENT_OBJ_CREATED 0x00000040 /** * struct dprc_irq_cfg - IRQ configuration * @paddr: Address that must be written to signal a message-based interrupt * @val: Value to write into irq_addr address * @irq_num: A user defined number associated with this IRQ */ struct dprc_irq_cfg { phys_addr_t paddr; u32 val; int irq_num; }; int dprc_set_irq(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, u8 irq_index, struct dprc_irq_cfg *irq_cfg); int dprc_get_irq(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, u8 irq_index, int *type, struct dprc_irq_cfg *irq_cfg); int dprc_set_irq_enable(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, u8 irq_index, u8 en); int dprc_get_irq_enable(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, u8 irq_index, u8 *en); int dprc_set_irq_mask(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, u8 irq_index, u32 mask); int dprc_get_irq_mask(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, u8 irq_index, u32 *mask); int dprc_get_irq_status(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, u8 irq_index, u32 *status); int dprc_clear_irq_status(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, u8 irq_index, u32 status); /** * struct dprc_attributes - Container attributes * @container_id: Container's ID * @icid: Container's ICID * @portal_id: Container's portal ID * @options: Container's options as set at container's creation */ struct dprc_attributes { int container_id; u16 icid; int portal_id; u64 options; }; int dprc_get_attributes(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, struct dprc_attributes *attributes); int dprc_get_obj_count(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, int *obj_count); /* Objects Attributes Flags */ /* Opened state - Indicates that an object is open by at least one owner */ #define DPRC_OBJ_STATE_OPEN 0x00000001 /* Plugged state - Indicates that the object is plugged */ #define DPRC_OBJ_STATE_PLUGGED 0x00000002 /** * Shareability flag - Object flag indicating no memory shareability. * the object generates memory accesses that are non coherent with other * masters; * user is responsible for proper memory handling through IOMMU configuration. */ #define DPRC_OBJ_FLAG_NO_MEM_SHAREABILITY 0x0001 /** * struct dprc_obj_desc - Object descriptor, returned from dprc_get_obj() * @type: Type of object: NULL terminated string * @id: ID of logical object resource * @vendor: Object vendor identifier * @ver_major: Major version number * @ver_minor: Minor version number * @irq_count: Number of interrupts supported by the object * @region_count: Number of mappable regions supported by the object * @state: Object state: combination of DPRC_OBJ_STATE_ states * @label: Object label * @flags: Object's flags */ struct dprc_obj_desc { char type[16]; int id; u16 vendor; u16 ver_major; u16 ver_minor; u8 irq_count; u8 region_count; u32 state; char label[16]; u16 flags; }; int dprc_get_obj(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, int obj_index, struct dprc_obj_desc *obj_desc); int dprc_get_obj_desc(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, char *obj_type, int obj_id, struct dprc_obj_desc *obj_desc); int dprc_set_obj_irq(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, char *obj_type, int obj_id, u8 irq_index, struct dprc_irq_cfg *irq_cfg); int dprc_get_obj_irq(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, char *obj_type, int obj_id, u8 irq_index, int *type, struct dprc_irq_cfg *irq_cfg); int dprc_get_res_count(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, char *type, int *res_count); /** * enum dprc_iter_status - Iteration status * @DPRC_ITER_STATUS_FIRST: Perform first iteration * @DPRC_ITER_STATUS_MORE: Indicates more/next iteration is needed * @DPRC_ITER_STATUS_LAST: Indicates last iteration */ enum dprc_iter_status { DPRC_ITER_STATUS_FIRST = 0, DPRC_ITER_STATUS_MORE = 1, DPRC_ITER_STATUS_LAST = 2 }; /* Region flags */ /* Cacheable - Indicates that region should be mapped as cacheable */ #define DPRC_REGION_CACHEABLE 0x00000001 /** * enum dprc_region_type - Region type * @DPRC_REGION_TYPE_MC_PORTAL: MC portal region * @DPRC_REGION_TYPE_QBMAN_PORTAL: Qbman portal region */ enum dprc_region_type { DPRC_REGION_TYPE_MC_PORTAL, DPRC_REGION_TYPE_QBMAN_PORTAL }; /** * struct dprc_region_desc - Mappable region descriptor * @base_offset: Region offset from region's base address. * For DPMCP and DPRC objects, region base is offset from SoC MC portals * base address; For DPIO, region base is offset from SoC QMan portals * base address * @size: Region size (in bytes) * @flags: Region attributes * @type: Portal region type */ struct dprc_region_desc { u32 base_offset; u32 size; u32 flags; enum dprc_region_type type; }; int dprc_get_obj_region(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 token, char *obj_type, int obj_id, u8 region_index, struct dprc_region_desc *region_desc); int dprc_get_api_version(struct fsl_mc_io *mc_io, u32 cmd_flags, u16 *major_ver, u16 *minor_ver); int dprc_get_container_id(struct fsl_mc_io *mc_io, u32 cmd_flags, int *container_id); #endif /* _FSL_DPRC_H */
28.012821
78
0.730435
[ "object" ]
dc9f1fe1d594fbcc60dcbcbc635e0cd844bda156
1,578
h
C
config_backend/inc/configuration_backend.h
mnyrenius/awesome-fxd
b643cea47a92aa465d24194e23a10e4ff34e0de1
[ "MIT" ]
null
null
null
config_backend/inc/configuration_backend.h
mnyrenius/awesome-fxd
b643cea47a92aa465d24194e23a10e4ff34e0de1
[ "MIT" ]
null
null
null
config_backend/inc/configuration_backend.h
mnyrenius/awesome-fxd
b643cea47a92aa465d24194e23a10e4ff34e0de1
[ "MIT" ]
null
null
null
#ifndef CONFIGURATION_BACKEND_H #define CONFIGURATION_BACKEND_H #include <fx_chain_configuration.h> #include <global_settings.h> #include <functional> #include <cstdint> #include <memory> namespace awesomefx { class ConfigurationBackend { public: using Ptr = std::unique_ptr<ConfigurationBackend>; using OnGetPluginsCallback = std::function<AvailablePlugins()>; using OnApplyConfigCallback = std::function<void(const FxChainConfiguration&)>; using OnGetConfigCallback = std::function<FxChainConfiguration()>; using OnSetParametersCallback = std::function<void(std::uint32_t, const std::vector<ParameterValue>&)>; using OnReloadCallback = std::function<void()>; using OnApplyGlobalSettingsCallback = std::function<void(const GlobalSettings&)>; using OnGetGlobalSettingsCallback = std::function<GlobalSettings()>; virtual ~ConfigurationBackend() {} virtual void registerOnGetPlugins(const OnGetPluginsCallback& callback) = 0; virtual void registerOnApplyConfig(const OnApplyConfigCallback& callback) = 0; virtual void registerOnGetConfig(const OnGetConfigCallback& callback) = 0; virtual void registerOnSetParameters(const OnSetParametersCallback& callback) = 0; virtual void registerOnReload(const OnReloadCallback& callback) = 0; virtual void registerOnApplyGlobalSettings(const OnApplyGlobalSettingsCallback& callback) = 0; virtual void registerOnGetGlobalSettings(const OnGetGlobalSettingsCallback& callback) = 0; virtual void start(std::uint32_t port) = 0; }; } #endif /* CONFIGURATION_BACKEND_H */
40.461538
107
0.781369
[ "vector" ]
dca4b2c51304ada0e0848f6caa44d355c9882363
671
h
C
Example/Pods/LZDependencyToolkit/LZDependencyToolkit/Classes/Category/NSObject+LZRuntime.h
liLeiBest/LZPhotoBrowser
1673caca95eb3e07c01abf3579c241830e935fcd
[ "MIT" ]
3
2017-11-29T17:13:48.000Z
2021-12-10T04:09:45.000Z
Example/Pods/LZDependencyToolkit/LZDependencyToolkit/Classes/Category/NSObject+LZRuntime.h
liLeiBest/LZPhotoBrowser
1673caca95eb3e07c01abf3579c241830e935fcd
[ "MIT" ]
null
null
null
Example/Pods/LZDependencyToolkit/LZDependencyToolkit/Classes/Category/NSObject+LZRuntime.h
liLeiBest/LZPhotoBrowser
1673caca95eb3e07c01abf3579c241830e935fcd
[ "MIT" ]
1
2021-12-10T04:09:48.000Z
2021-12-10T04:09:48.000Z
// // NSObject+LZRuntime.h // Pods // // Created by Dear.Q on 2017/12/9. // // #import <Foundation/Foundation.h> @interface NSObject (LZRuntime) /** * 类交换方法 */ void LZ_exchangeClassMethod(Class destClass, SEL originSelector, SEL swizzleSelector); /** * 对象交换方法 */ void LZ_exchangeInstanceMethod(Class destClass, SEL originSelector, SEL swizzleSelector); /** * 添加属性 */ void LZ_setAssociatedObject(id object, const void *key, id value); /** * 添加属性 copy */ void LZ_setAssociatedCopyObject(id object, const void *key, id value); /** * 获取属性 */ id LZ_getAssociatedObject(id object, const void *key); /** * 获取对象属性列表 */ - (NSArray *)properties; @end
15.25
89
0.685544
[ "object" ]
dca733ef67503845267c0a4f4f616190908d1af7
5,423
h
C
samples/include/linux/assoc_array_priv.h
yehudahs/silver-leaves
c3945f36466455dd1c54594f45d15026587b701b
[ "MIT" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
src/linux/include/linux/assoc_array_priv.h
lukedsmalley/oo-kernel-hacking
57161ae3e8a780a72b475b3c27fec8deef83b8e1
[ "MIT" ]
13
2021-07-10T04:36:17.000Z
2022-03-03T10:50:05.000Z
src/linux/include/linux/assoc_array_priv.h
lukedsmalley/oo-kernel-hacking
57161ae3e8a780a72b475b3c27fec8deef83b8e1
[ "MIT" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* Private definitions for the generic associative array implementation. * * See Documentation/core-api/assoc_array.rst for information. * * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) */ #ifndef _LINUX_ASSOC_ARRAY_PRIV_H #define _LINUX_ASSOC_ARRAY_PRIV_H #ifdef CONFIG_ASSOCIATIVE_ARRAY #include <linux/assoc_array.h> #define ASSOC_ARRAY_FAN_OUT 16 /* Number of slots per node */ #define ASSOC_ARRAY_FAN_MASK (ASSOC_ARRAY_FAN_OUT - 1) #define ASSOC_ARRAY_LEVEL_STEP (ilog2(ASSOC_ARRAY_FAN_OUT)) #define ASSOC_ARRAY_LEVEL_STEP_MASK (ASSOC_ARRAY_LEVEL_STEP - 1) #define ASSOC_ARRAY_KEY_CHUNK_MASK (ASSOC_ARRAY_KEY_CHUNK_SIZE - 1) #define ASSOC_ARRAY_KEY_CHUNK_SHIFT (ilog2(BITS_PER_LONG)) /* * Undefined type representing a pointer with type information in the bottom * two bits. */ struct assoc_array_ptr; /* * An N-way node in the tree. * * Each slot contains one of four things: * * (1) Nothing (NULL). * * (2) A leaf object (pointer types 0). * * (3) A next-level node (pointer type 1, subtype 0). * * (4) A shortcut (pointer type 1, subtype 1). * * The tree is optimised for search-by-ID, but permits reasonable iteration * also. * * The tree is navigated by constructing an index key consisting of an array of * segments, where each segment is ilog2(ASSOC_ARRAY_FAN_OUT) bits in size. * * The segments correspond to levels of the tree (the first segment is used at * level 0, the second at level 1, etc.). */ struct assoc_array_node { struct assoc_array_ptr *back_pointer; u8 parent_slot; struct assoc_array_ptr *slots[ASSOC_ARRAY_FAN_OUT]; unsigned long nr_leaves_on_branch; }; /* * A shortcut through the index space out to where a collection of nodes/leaves * with the same IDs live. */ struct assoc_array_shortcut { struct assoc_array_ptr *back_pointer; int parent_slot; int skip_to_level; struct assoc_array_ptr *next_node; unsigned long index_key[]; }; /* * Preallocation cache. */ struct assoc_array_edit { struct rcu_head rcu; struct assoc_array *array; const struct assoc_array_ops *ops; const struct assoc_array_ops *ops_for_excised_subtree; struct assoc_array_ptr *leaf; struct assoc_array_ptr **leaf_p; struct assoc_array_ptr *dead_leaf; struct assoc_array_ptr *new_meta[3]; struct assoc_array_ptr *excised_meta[1]; struct assoc_array_ptr *excised_subtree; struct assoc_array_ptr **set_backpointers[ASSOC_ARRAY_FAN_OUT]; struct assoc_array_ptr *set_backpointers_to; struct assoc_array_node *adjust_count_on; long adjust_count_by; struct { struct assoc_array_ptr **ptr; struct assoc_array_ptr *to; } set[2]; struct { u8 *p; u8 to; } set_parent_slot[1]; u8 segment_cache[ASSOC_ARRAY_FAN_OUT + 1]; }; /* * Internal tree member pointers are marked in the bottom one or two bits to * indicate what type they are so that we don't have to look behind every * pointer to see what it points to. * * We provide functions to test type annotations and to create and translate * the annotated pointers. */ #define ASSOC_ARRAY_PTR_TYPE_MASK 0x1UL #define ASSOC_ARRAY_PTR_LEAF_TYPE 0x0UL /* Points to leaf (or nowhere) */ #define ASSOC_ARRAY_PTR_META_TYPE 0x1UL /* Points to node or shortcut */ #define ASSOC_ARRAY_PTR_SUBTYPE_MASK 0x2UL #define ASSOC_ARRAY_PTR_NODE_SUBTYPE 0x0UL #define ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE 0x2UL static inline bool assoc_array_ptr_is_meta(const struct assoc_array_ptr *x) { return (unsigned long)x & ASSOC_ARRAY_PTR_TYPE_MASK; } static inline bool assoc_array_ptr_is_leaf(const struct assoc_array_ptr *x) { return !assoc_array_ptr_is_meta(x); } static inline bool assoc_array_ptr_is_shortcut(const struct assoc_array_ptr *x) { return (unsigned long)x & ASSOC_ARRAY_PTR_SUBTYPE_MASK; } static inline bool assoc_array_ptr_is_node(const struct assoc_array_ptr *x) { return !assoc_array_ptr_is_shortcut(x); } static inline void *assoc_array_ptr_to_leaf(const struct assoc_array_ptr *x) { return (void *)((unsigned long)x & ~ASSOC_ARRAY_PTR_TYPE_MASK); } static inline unsigned long __assoc_array_ptr_to_meta(const struct assoc_array_ptr *x) { return (unsigned long)x & ~(ASSOC_ARRAY_PTR_SUBTYPE_MASK | ASSOC_ARRAY_PTR_TYPE_MASK); } static inline struct assoc_array_node *assoc_array_ptr_to_node(const struct assoc_array_ptr *x) { return (struct assoc_array_node *)__assoc_array_ptr_to_meta(x); } static inline struct assoc_array_shortcut *assoc_array_ptr_to_shortcut(const struct assoc_array_ptr *x) { return (struct assoc_array_shortcut *)__assoc_array_ptr_to_meta(x); } static inline struct assoc_array_ptr *__assoc_array_x_to_ptr(const void *p, unsigned long t) { return (struct assoc_array_ptr *)((unsigned long)p | t); } static inline struct assoc_array_ptr *assoc_array_leaf_to_ptr(const void *p) { return __assoc_array_x_to_ptr(p, ASSOC_ARRAY_PTR_LEAF_TYPE); } static inline struct assoc_array_ptr *assoc_array_node_to_ptr(const struct assoc_array_node *p) { return __assoc_array_x_to_ptr( p, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_NODE_SUBTYPE); } static inline struct assoc_array_ptr *assoc_array_shortcut_to_ptr(const struct assoc_array_shortcut *p) { return __assoc_array_x_to_ptr( p, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE); } #endif /* CONFIG_ASSOCIATIVE_ARRAY */ #endif /* _LINUX_ASSOC_ARRAY_PRIV_H */
30.296089
89
0.784437
[ "object" ]
dcb8178f9ee59c70c65bf49650d14a2edf85bef2
5,071
c
C
python-ios/src/scipy_files/scipy/patches/linalg/src/id_dist/src/iddr_rsvd_subr_0.c
ktraunmueller/Computable
5a6a872c4c0f5e122c24c321cd877a949877dcf7
[ "MIT" ]
26
2018-02-14T23:52:58.000Z
2021-08-16T13:50:03.000Z
scipy_build_2.0/linalg/src/id_dist/src/iddr_rsvd_subr_0.c
wtbh/scipy_arm64
00f8f9ca06cc941a854601546ab4bfb259ef6bda
[ "Apache-2.0" ]
3
2019-09-03T05:50:32.000Z
2020-05-10T05:35:11.000Z
scipy_build_2.0/linalg/src/id_dist/src/iddr_rsvd_subr_0.c
wtbh/scipy_arm64
00f8f9ca06cc941a854601546ab4bfb259ef6bda
[ "Apache-2.0" ]
10
2018-08-13T19:38:39.000Z
2020-04-19T03:02:00.000Z
/* iddr_rsvd_subr_0.f -- translated by f2c (version 20100827). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "f2c.h" /* Subroutine */ int iddr_rsvd_(integer *m, integer *n, U_fp matvect, doublereal *p1t, doublereal *p2t, doublereal *p3t, doublereal *p4t, U_fp matvec, doublereal *p1, doublereal *p2, doublereal *p3, doublereal *p4, integer *krank, doublereal *u, doublereal *v, doublereal *s, integer *ier, doublereal *w) { /* System generated locals */ integer u_dim1, u_offset, v_dim1, v_offset, i__1; /* Local variables */ extern /* Subroutine */ int iddr_rsvd0_(integer *, integer *, U_fp, doublereal *, doublereal *, doublereal *, doublereal *, U_fp, doublereal *, doublereal *, doublereal *, doublereal *, integer *, doublereal *, doublereal *, doublereal *, integer *, doublereal * , doublereal *, doublereal *, doublereal *); static integer lw, icol, lcol, iproj, ilist, lproj, llist, iwork, lwork; /* constructs a rank-krank SVD u diag(s) v^T approximating a, */ /* where matvect is a routine which applies a^T */ /* to an arbitrary vector, and matvec is a routine */ /* which applies a to an arbitrary vector; */ /* u is an m x krank matrix whose columns are orthonormal, */ /* v is an n x krank matrix whose columns are orthonormal, */ /* and diag(s) is a diagonal krank x krank matrix whose entries */ /* are all nonnegative. This routine uses a randomized algorithm. */ /* input: */ /* m -- number of rows in a */ /* n -- number of columns in a */ /* matvect -- routine which applies the transpose */ /* of the matrix to be SVD'd */ /* to an arbitrary vector; this routine must have */ /* a calling sequence of the form */ /* matvect(m,x,n,y,p1t,p2t,p3t,p4t), */ /* where m is the length of x, */ /* x is the vector to which the transpose */ /* of the matrix is to be applied, */ /* n is the length of y, */ /* y is the product of the transposed matrix and x, */ /* and p1t, p2t, p3t, and p4t are user-specified */ /* parameters */ /* p1t -- parameter to be passed to routine matvect */ /* p2t -- parameter to be passed to routine matvect */ /* p3t -- parameter to be passed to routine matvect */ /* p4t -- parameter to be passed to routine matvect */ /* matvec -- routine which applies the matrix to be SVD'd */ /* to an arbitrary vector; this routine must have */ /* a calling sequence of the form */ /* matvec(n,x,m,y,p1,p2,p3,p4), */ /* where n is the length of x, */ /* x is the vector to which the matrix is to be applied, */ /* m is the length of y, */ /* y is the product of the matrix and x, */ /* and p1, p2, p3, and p4 are user-specified parameters */ /* p1 -- parameter to be passed to routine matvec */ /* p2 -- parameter to be passed to routine matvec */ /* p3 -- parameter to be passed to routine matvec */ /* p4 -- parameter to be passed to routine matvec */ /* krank -- rank of the SVD being constructed */ /* output: */ /* u -- matrix of orthonormal left singular vectors of a */ /* v -- matrix of orthonormal right singular vectors of a */ /* s -- array of singular values of a */ /* ier -- 0 when the routine terminates successfully; */ /* nonzero otherwise */ /* work: */ /* w -- must be at least (krank+1)*(2*m+4*n)+25*krank**2 */ /* real*8 elements long */ /* _N.B._: The algorithm used by this routine is randomized. */ /* Allocate memory in w. */ /* Computing 2nd power */ i__1 = *krank; /* Parameter adjustments */ --w; --s; v_dim1 = *n; v_offset = 1 + v_dim1; v -= v_offset; u_dim1 = *m; u_offset = 1 + u_dim1; u -= u_offset; /* Function Body */ lw = 0; ilist = lw + 1; llist = *n; lw += llist; iproj = lw + 1; lproj = *krank * (*n - *krank); lw += lproj; icol = lw + 1; lcol = *m * *krank; lw += lcol; iwork = lw + 1; /* Computing 2nd power */ i__1 = *krank; lwork = (*krank + 1) * (*m + *n * 3) + i__1 * i__1 * 26; lw += lwork; iddr_rsvd0_(m, n, (U_fp)matvect, p1t, p2t, p3t, p4t, (U_fp)matvec, p1, p2, p3, p4, krank, &u[u_offset], &v[v_offset], &s[1], ier, &w[ ilist], &w[iproj], &w[icol], &w[iwork]); return 0; } /* iddr_rsvd__ */
36.482014
76
0.568133
[ "object", "vector" ]
dcbca2baa6bf8654a94f25be3e1637ee1e0e89de
7,037
h
C
tigcc/game.h
joeyadams/nukesnake
49dcb2f412d6b665057529981bf81d6cab1dc256
[ "MIT" ]
null
null
null
tigcc/game.h
joeyadams/nukesnake
49dcb2f412d6b665057529981bf81d6cab1dc256
[ "MIT" ]
null
null
null
tigcc/game.h
joeyadams/nukesnake
49dcb2f412d6b665057529981bf81d6cab1dc256
[ "MIT" ]
null
null
null
/* * Nuke Snake - A game where you control a nuclear-powered snake. Your goal is * to destroy your opponent(s) while avoiding obstacles such as mines and rocks. * * Copyright (c) 2016 David Riggle, Joey Adams * * 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. */ #ifndef GAME_H #define GAME_H #ifdef __cplusplus extern "C" { #endif #define MAX_FRAMEDROP 10 struct NS; struct NS_Settings; struct NS_Player; struct NS_Bullet; struct NS_Effect; typedef struct NS NS; typedef struct NS_Settings NS_Settings; typedef struct NS_Player NS_Player; typedef struct NS_Bullet NS_Bullet; typedef struct NS_Effect NS_Effect; #include "ai.h" #include "glue.h" #include "menu.h" void NS_init(void); void NS_uninit(void); void NS_newgame(unsigned short width,unsigned short height, short gametype); void NS_newround(unsigned short width,unsigned short height); short NS_frame(void); //returns one of FrameStatus void NS_schedule_redraw(void); short NS_draw(void); NS_Player *NS_find_player_by_type(short type, const NS_Player *dont_pick); //the argument is 'dont_pick' instead of 'not' because 'not' is a C++ keyword static inline void NS_redraw(void) { NS_schedule_redraw(); NS_draw(); } //None of the max values should be zero #define PLAYER_MAX 2 #define BULLET_MAX 256 #define EFFECT_MAX 256 struct NS { signed char *board; //board==NULL means there is no game open right now //The board's data consists of two parts, each width*height bytes //The current half is the cells the game engine will write to in order to request draws of cells //The actual half is what is drawn to the screen at the last redraw //Both board halves are used in NS_draw in order to bring the actual half up to date unsigned short width; unsigned short height; signed char *overlay; //This is where explosions and respawn animations are drawn struct NS_Settings { unsigned short sound:1, mines:1, mine_detonators:1, clusters:1, bullets:1, bullet_ammo:1, rockets:1, rocket_ammo:1, nukes:1, nuke_ammo:1, linear_terrain:1, fractal_terrain:1, stop_at_water:1, diagonals:1, walls:1, rubber_walls:1; unsigned short tails:1, explosion_blocks:1, total_war:1; //total_war means there are no new rounds; players simply respawn unsigned char game_speed; //undefined units unsigned char bullet_speed; //speed in relation to player (should be 2...6) } settings; unsigned short phase; //counts down unsigned short paused:1, player_dying:1, reset_scheduled:1; struct NS_Player { char type; //Any of PlayerTypes or 0 for hole char direction; unsigned short x,y; signed char covering; //The tile this object replaced to be drawn at (x,y). It will restore this tile when it moves char phase; signed char icon; //Any of TileTypes char alive; char has_tail; signed char fire_phase; //counts down, <=0 means the player can fire right now (minimum is -bullet_maxphase, after-fire is +bullet_maxphase) char trudge; //number of updates to wait before player can move unsigned short bullet_count; //only matters if settings.bullet_ammo==1 unsigned short rocket_count; //only matters if settings.rocket_ammo==1 unsigned short nuke_count; //only matters if settings.nuke_ammo==1 unsigned short deaths; union { //PT_Right and PT_Left (players controlled by the keyboard) have no controller state information NS_AI ai; //defined in ai.h NS_Net net; //defined in glue.h } cs; //controller state } players[PLAYER_MAX]; struct NS_Bullet { char type; //Any of BulletTypes or 0 for hole char direction; unsigned short x,y; signed char covering; //see description in NS_Player::covering char phase; //counts down } bullets[BULLET_MAX]; struct NS_Effect { char type; //Any of EffectTypes or 0 for hole char frame; //counts down unsigned short x,y; char unused; char phase; //counts down short respawn; //players[respawn] will respawn at the end of this effect if type == ET_Respawn //a respawn effect will be generated at the end of this effect if type == ET_Explosion and respawn>=0 } effects[EFFECT_MAX]; }; extern NS ns; #define dir_vec(dir) (_dir_vec[(int)(dir)]) extern const signed char _dir_vec[][2]; #define vec_dir(x,y) (_vec_dir[(y)+1][(x)+1]); extern const char _vec_dir[3][3]; static inline short average_dir(short a, short b) { short ret=vec_dir((dir_vec(a)[0]+dir_vec(b)[0])/2, (dir_vec(a)[1]+dir_vec(b)[1])/2); if (ret<0 || ret>=8) { Bug("vec_dir returned an invalid direction %d.",ret); ret=0; } return ret; } #define bullet_icon(type,direction) (BulletH + ((type)-1)*4 + dir_hvfb[(int)(direction)]) extern const char dir_hvfb[9]; extern const char dir_opposite[9]; extern const char dir_xflip[9]; extern const char dir_yflip[9]; //evaluates 'dir' twice #define dir_isdiagonal(dir) (dir ? ~dir&1 : 0) enum TileTypes { Floor=0, BluePiece, RedPiece, BulletH, BulletV, BulletF, BulletB, RocketH, RocketV, RocketF, RocketB, NukeH, NukeV, NukeF, NukeB, Explode1, Explode2, AmmoPack, RocketPack, NukePack, Mine, MineDetonator, Coal, Tree, Wall, Water, Swamp, BlueTail, RedTail, TILE_TYPE_COUNT, NullTile }; extern const char tile_class[TILE_TYPE_COUNT]; enum TileClasses { TC_Floor=0, TC_Player, TC_Bullet, //includes rockets TC_Explosion, TC_Tail, TC_Other }; enum PlayerTypes { PT_Right=1, PT_Left=2, PT_AI=3, PT_Network=4 }; enum BulletTypes { BT_Bullet=1, BT_Rocket=2, BT_Nuke=3 }; enum EffectTypes { ET_Explosion=1, ET_Respawn=2 }; enum Directions { NoDirection=0, Right, DownRight, Down, DownLeft, Left, UpLeft, Up, UpRight }; enum FrameStatus { NSF_NORMAL=0, NSF_SOMEONEDIED=1 }; enum EventTypes { EV_Explosion, EV_PlayerKilled, EV_BulletFired, EV_RocketFired, EV_NukeFired, EV_AmmoPickedUp, EV_RocketPickedUp, EV_NukePickedUp, EV_PlayerLost }; enum MeansOfDeath { MOD_Player, MOD_Bullet, MOD_Rocket, MOD_Nuke, MOD_Explosion, MOD_NukeRadius, MOD_Mine, MOD_Coal, MOD_Wall, MOD_Tail, MOD_ShotHimself, MOD_MineDetonator }; #ifdef __cplusplus } #endif #endif //ifndef GAME_H
29.817797
152
0.74833
[ "object" ]
dcc8624c3910a27e99266eeec9d67bb723e18a79
1,809
h
C
Base/include/FasTC/IPixel.h
kyapp69/FasTC
47c67a16ba4dca4ea71b889cc8a9cd95a18e7dc6
[ "Apache-2.0" ]
189
2016-02-15T15:37:26.000Z
2022-03-02T03:29:49.000Z
Base/include/FasTC/IPixel.h
kyapp69/FasTC
47c67a16ba4dca4ea71b889cc8a9cd95a18e7dc6
[ "Apache-2.0" ]
20
2016-02-17T09:27:04.000Z
2021-06-04T16:28:16.000Z
Base/include/FasTC/IPixel.h
kyapp69/FasTC
47c67a16ba4dca4ea71b889cc8a9cd95a18e7dc6
[ "Apache-2.0" ]
32
2016-02-15T15:50:38.000Z
2022-01-22T07:28:38.000Z
// Copyright 2016 The University of North Carolina at Chapel Hill // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Please send all BUG REPORTS to <pavel@cs.unc.edu>. // <http://gamma.cs.unc.edu/FasTC/> #ifndef BASE_INCLUDE_IPIXEL_H_ #define BASE_INCLUDE_IPIXEL_H_ #include "TexCompTypes.h" #include "VectorBase.h" namespace FasTC { class IPixel : public VectorBase<float, 1> { public: IPixel() : VectorBase<float, 1>() { vec[0] = 0.0f; } IPixel(float f) : VectorBase<float, 1>(&f) { } operator float() const { return vec[0]; } IPixel operator=(const float &f) { return vec[0] = f; } // Take all of the components, transform them to their 8-bit variants, // and then pack each channel into an R8G8B8A8 32-bit integer. We assume // that the architecture is little-endian, so the alpha channel will end // up in the most-significant byte. uint32 Pack() const; void Unpack(uint32 rgba); void MakeOpaque() { /* Do nothing.. */ } bool operator==(const IPixel &other) const { return static_cast<float>(*this) == static_cast<float>(other); } bool operator!=(const IPixel &other) const { return static_cast<float>(*this) != static_cast<float>(other); } }; REGISTER_VECTOR_TYPE(IPixel); } // namespace FasTC #endif // BASE_INCLUDE_PIXEL_H_
29.655738
75
0.704809
[ "transform" ]
dccfe3e6510493d9d95704293ae8e0f710c9e7be
10,105
h
C
src/RankingTool.h
xzf89718/bbtautau-hists
3f20c9d9cf82149df12aef155c6dd148a367aece
[ "MIT" ]
1
2022-01-21T18:45:47.000Z
2022-01-21T18:45:47.000Z
src/RankingTool.h
xzf89718/bbtautau-hists
3f20c9d9cf82149df12aef155c6dd148a367aece
[ "MIT" ]
4
2021-01-27T21:51:49.000Z
2021-04-17T14:47:50.000Z
src/RankingTool.h
xzf89718/bbtautau-hists
3f20c9d9cf82149df12aef155c6dd148a367aece
[ "MIT" ]
1
2021-01-28T13:09:24.000Z
2021-01-28T13:09:24.000Z
/** * @brief: make this tool as a child of WorkSpace */ #ifndef RANKING_H #define RANKING_H #include "StatisticTool.h" #include "WorkSpace.h" #include <fstream> using std::ofstream; class RankingEngine : public StatisticTool { public: RankingEngine(const WorkspaceInfo* info, const string& name="RankingEngine") : StatisticTool(name), m_cInfo(info) { Tools::println("Initializing [%]", this->sToolName); RooMsgService::instance().setGlobalKillBelow(ERROR); } virtual ~RankingEngine() override { for (auto& p : m_fits) { if (!p.second) { delete p.second; } } m_fits.clear(); } RankingEngine(RankingEngine& old) = delete; RankingEngine& operator=(RankingEngine& old) = delete; public: virtual void Execute() override { auto run = [this](const string& sNP, const double nMode) { string sPostFix = nMode > 0 ? "_Hi" : "_Lo"; m_fits[sNP + sPostFix] = new WorkSpace(m_cInfo); m_fits[sNP + sPostFix]->FitWithFixedPara(sNP, m_fits["base"]->GetFittedNPs(), nMode); // m_fits[sNP + sPostFix]->Check(); m_mapAltPOIs[sNP + sPostFix] = m_fits[sNP + sPostFix]->GetCache(m_fits[sNP + sPostFix]->NameOfPOI()); if (!m_bCache) { delete m_fits[sNP + sPostFix]; } }; m_fits["base"] = new WorkSpace(m_cInfo); Tools::println(">> All: "); m_fits["base"]->FitAll(); m_nPOI = m_fits["base"]->GetCache(m_fits["base"]->NameOfPOI()); m_fits["base"]->Check(); Tools::println(">> Fixed NP: "); for (const auto& sNP: m_fits["base"]->GetNPs()) { for (double nMode : {1.0f, -1.0f}) { run(sNP, nMode); } } if (!m_bCache) { delete m_fits["base"]; } } map<WorkSpace::ePOI, double> GetFittedPOI() { return m_nPOI; } map<string, map<WorkSpace::ePOI, double>> GetFittedPOIWithFixedNPs() { return m_mapAltPOIs; } public: void WriteToTxt(const std::string& outname) { /// @todo fix the copying auto val = GetFittedPOI(); auto res = GetFittedPOIWithFixedNPs(); ofstream output(outname); output << OUTPUT_TABLE_4("FIXED NP", "POI_VALUE", "POI_ERROR_UP", "POI_ERROR_DOWN"); Tools::println("% -> VALUE % ERROR_UP % ERROR_DOWN %", "No fixed NP", val[WorkSpace::ePOI::VALUE], val[WorkSpace::ePOI::ERRORUP], val[WorkSpace::ePOI::ERRORDOWN]); output << OUTPUT_TABLE_4("None", val[WorkSpace::ePOI::VALUE], val[WorkSpace::ePOI::ERRORUP], val[WorkSpace::ePOI::ERRORDOWN]) for (auto& p : res) { Tools::println("% Fixed -> VALUE % ERROR_UP % ERROR_DOWN %", p.first, p.second[WorkSpace::ePOI::VALUE], p.second[WorkSpace::ePOI::ERRORUP], p.second[WorkSpace::ePOI::ERRORDOWN]); output << OUTPUT_TABLE_4( p.first, p.second[WorkSpace::ePOI::VALUE], p.second[WorkSpace::ePOI::ERRORUP], p.second[WorkSpace::ePOI::ERRORDOWN]); } } public: void CacheWorkSpaces() { m_bCache = true; } protected: bool m_bCache = false; const WorkspaceInfo* m_cInfo; map<string, WorkSpace*> m_fits; map<WorkSpace::ePOI, double> m_nPOI; map<string, map<WorkSpace::ePOI, double>> m_mapAltPOIs; }; struct RankingData { RankingData(const string& np, double hi, double lo) : fixedNP(np), deltaMuByHi(hi), deltaMuByLo(lo) {} string fixedNP; double deltaMuByHi; double deltaMuByLo; }; class RankingPlotter : public StatisticTool { public: RankingPlotter(const string& name="RankingPlotter") : StatisticTool(name) { } void LoadFromTxt(const std::string& sFileName) { ifstream input(sFileName, std::ios::in); if (input.is_open()) { string sLine; unsigned nRow = 0; while (getline(input, sLine)) { istringstream iss(sLine); string tmp; if (nRow == 0) { Tools::println("Starting!"); } else if (nRow == 1) { iss >> tmp >> m_nPOI[WorkSpace::ePOI::VALUE] >> m_nPOI[WorkSpace::ePOI::ERRORUP] >> m_nPOI[WorkSpace::ePOI::ERRORDOWN]; // symmetric of up due to Hesse } else { iss >> tmp >> m_mapAltPOIs[tmp][WorkSpace::ePOI::VALUE] >> m_mapAltPOIs[tmp][WorkSpace::ePOI::ERRORUP] >> m_mapAltPOIs[tmp][WorkSpace::ePOI::ERRORDOWN]; // symmetric of up due to Hesse } nRow++; } } for (auto& p : m_mapAltPOIs) { string sNameOfNP = p.first.substr(0, p.first.length()-3); string sDirection = p.first.substr(p.first.length()-2); if (m_mapLookUp.find(sNameOfNP) == m_mapLookUp.end()) { m_mapLookUp[sNameOfNP] = m_vData.size(); if (sDirection == "Hi") { m_vData.emplace_back(sNameOfNP, p.second[WorkSpace::ePOI::VALUE]-m_nPOI[WorkSpace::ePOI::VALUE], -999); } else { m_vData.emplace_back(sNameOfNP, -999, p.second[WorkSpace::ePOI::VALUE]-m_nPOI[WorkSpace::ePOI::VALUE]); } } else { if (sDirection == "Hi") { m_vData[m_mapLookUp[sNameOfNP]].deltaMuByHi = p.second[WorkSpace::ePOI::VALUE]-m_nPOI[WorkSpace::ePOI::VALUE]; } else { m_vData[m_mapLookUp[sNameOfNP]].deltaMuByLo = p.second[WorkSpace::ePOI::VALUE]-m_nPOI[WorkSpace::ePOI::VALUE]; } } } double fSumSQ = 0.; for (const RankingData& data : m_vData) { fSumSQ += 0.25 * (std::fabs(data.deltaMuByHi - data.deltaMuByLo) * std::fabs(data.deltaMuByHi - data.deltaMuByLo)); } fSumSQ = std::sqrt(fSumSQ); std::sort(m_vData.begin(), m_vData.end(), [&fSumSQ](RankingData& a, RankingData& b) { return std::fabs(a.deltaMuByHi - a.deltaMuByLo) > std::fabs(b.deltaMuByHi - b.deltaMuByLo); }); unsigned i = 1; for (auto& info : m_vData) { Tools::println("% % % %", i++, info.fixedNP, info.deltaMuByHi, info.deltaMuByLo); } Tools::println("Sum in quadrature = %", fSumSQ); } void Draw(const string output, uint8_t nNPs=15) { gROOT->SetStyle("ATLAS"); gStyle->SetErrorX(0.5); TCanvas* c1 = new TCanvas("c", "", 900, 1200); c1->SetLeftMargin(0.20); c1->SetBottomMargin(0.50); TH1* h_one = new TH1D("one", "", nNPs, 0, nNPs); TH1* h_hi = new TH1D("hi", "", nNPs, 0, nNPs); TH1* h_lo = new TH1D("lo", "", nNPs, 0, nNPs); for (std::size_t i = 1; i <= nNPs; i++) { h_hi->GetXaxis()->SetBinLabel(i, Utils::systStringShort(m_vData[i-1].fixedNP).c_str()); h_hi->SetBinContent(i, m_vData[i-1].deltaMuByHi); h_lo->SetBinContent(i, m_vData[i-1].deltaMuByLo); h_one->SetBinContent(i, 0); } h_hi->SetBarWidth(0.90); h_lo->SetBarWidth(0.90); h_hi->SetLineColor(kRed); h_hi->SetLineWidth(1); h_hi->SetFillColor(kRed); h_hi->SetFillStyle(3245); h_hi->SetMarkerSize(0); h_hi->GetXaxis()->SetLabelSize(0.036); h_hi->GetXaxis()->SetTitleSize(0.036); h_hi->GetXaxis()->LabelsOption("v"); double max_of_hist = std::max(std::abs(h_hi->GetMaximum()), std::abs(h_lo->GetMaximum())); h_hi->GetYaxis()->SetRangeUser(-1.6*max_of_hist, 1.6*max_of_hist); // h_hi->GetYaxis()->SetRangeUser(-0.5, 0.5); h_hi->GetYaxis()->SetLabelSize(0.036); h_hi->GetYaxis()->SetTitleSize(0.036); h_hi->GetYaxis()->SetTitleOffset(2); h_hi->GetYaxis()->SetTitle("#Delta#mu"); h_lo->SetLineColor(kBlue); h_lo->SetLineWidth(1); h_lo->SetFillColor(kBlue); h_lo->SetFillStyle(3254); h_lo->SetMarkerSize(0); h_one->SetLineColor(kRed+1); h_one->SetLineWidth(3); h_hi->Draw("hist b"); h_lo->Draw("hist b same"); h_one->Draw("hist same"); TLegend* legend = new TLegend(0.50, 0.85, 0.80, 0.93); legend->SetTextFont(42); legend->SetFillStyle(0); legend->SetBorderSize(0); legend->SetTextSize(0.035); legend->SetTextAlign(12); legend->AddEntry(h_hi, "+1#sigma post-fit impact on #mu", "f"); legend->AddEntry(h_lo, "-1#sigma post-fit impact on #mu", "f"); legend->Draw("same"); TLatex *text = new TLatex(); text->SetNDC(); text->SetTextFont(72); text->SetTextSize(0.050); text->DrawLatex(0.50, 0.52, "ATLAS"); text->SetTextFont(42); text->DrawLatex(0.50 + 0.18, 0.52, "Internal"); text->SetTextSize(0.045); text->SetTextSize(0.040); text->DrawLatex(0.60, 0.96, "Fit to Data"); c1->SaveAs(output.c_str()); delete h_hi; delete h_lo; delete legend; delete text; delete c1; } private: map<WorkSpace::ePOI, double> m_nPOI; map<string, map<WorkSpace::ePOI, double>> m_mapAltPOIs; vector<RankingData> m_vData; map<string, std::size_t> m_mapLookUp; }; #endif
32.181529
130
0.524691
[ "vector" ]
dcd1f46b249f00a8315beb6d59153e83643ed9b3
2,405
h
C
Test/UnitTest/UnitTest1/Test/LogServer/UnitTest_Kafka.h
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
1
2020-06-20T07:35:25.000Z
2020-06-20T07:35:25.000Z
Test/UnitTest/UnitTest1/Test/LogServer/UnitTest_Kafka.h
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
null
null
null
Test/UnitTest/UnitTest1/Test/LogServer/UnitTest_Kafka.h
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // CopyRight (c) 2019 StormForge // // Author : KyungKun Ko // // Description : AVL tree test // // //////////////////////////////////////////////////////////////////////////////// #include <gtest/gtest.h> #include "Multithread/SFThread.h" #include "MemoryManager/SFMemoryManager.h" #include "Util/SFToString.h" #include "../SFTestBase.h" #include "json/json.h" // common setting class class KafkaTest : public MyTestBase { protected: #ifdef DEBUG const int MAX_TEST_VALUE = 100; #else const int MAX_TEST_VALUE = 1100000; #endif // Heap for test SF::Heap m_Heap; // Thread module test std::vector<SF::Thread*> m_Threads; SF::SpinLock m_LockObject; unsigned m_NumberOfTest; int *m_TestValues; const char* m_StreamServerAddress[2] = { "192.168.0.84:19130", // Broker address "192.168.0.84:19130" // stream directory server address }; public: KafkaTest() : m_Heap("KafkaTest", SF::GetSystemHeap()) , m_NumberOfTest(0) , m_TestValues(nullptr) { } // Heap interface SF::IHeap& GetHeap() { return m_Heap; } void SetupRandomTestValue() { m_NumberOfTest = MAX_TEST_VALUE; m_TestValues = new(GetHeap()) int[MAX_TEST_VALUE]; for (int iTest = 0; iTest < MAX_TEST_VALUE; iTest++) { m_TestValues[iTest] = rand() % MAX_TEST_VALUE; } } void SetupReverseSequencialTestValue() { m_NumberOfTest = MAX_TEST_VALUE; m_TestValues = new(GetHeap()) int[MAX_TEST_VALUE]; for (int iTest = 0; iTest < MAX_TEST_VALUE; iTest++) { m_TestValues[iTest] = MAX_TEST_VALUE - iTest; } } void SetupSequencialTestValue() { m_NumberOfTest = MAX_TEST_VALUE; m_TestValues = new(GetHeap()) int[MAX_TEST_VALUE]; for (int iTest = 0; iTest < MAX_TEST_VALUE; iTest++) { m_TestValues[iTest] = iTest+1; } } // Stop all thread void StopAllThread() { std::for_each( m_Threads.begin(), m_Threads.end(), []( SF::Thread* pThread ) { if( pThread ) pThread->Stop( true ); SF::IHeap::Delete(pThread); }); m_Threads.clear(); } // Remember that SetUp() is run immediately before a test starts. virtual void SetUp() { MyTestBase::SetUp(); } // TearDown() is invoked immediately after a test finishes. Here we virtual void TearDown() { MyTestBase::TearDown(); StopAllThread(); SF::IHeap::Delete(m_TestValues); m_TestValues = nullptr; } };
19.395161
80
0.635343
[ "vector" ]
dcdc530338d9759f2caed43b7ab1e84710771a48
3,195
h
C
clusters/SparseLikelihood.h
mlebeur/merlin
71a595a414c30fdfa067a2633d8768ab1c2eb722
[ "BSD-3-Clause" ]
4
2017-01-11T13:24:50.000Z
2022-01-18T21:37:50.000Z
cstatgen/src/umich/clusters/SparseLikelihood.h
changebio/rvnpl
22053ca4e24e5486e1179a5e85aaf316a218391f
[ "MIT" ]
8
2020-03-18T02:39:45.000Z
2020-12-12T08:05:24.000Z
cstatgen/src/umich/clusters/SparseLikelihood.h
changebio/rvnpl
22053ca4e24e5486e1179a5e85aaf316a218391f
[ "MIT" ]
3
2021-01-26T03:22:59.000Z
2021-11-15T14:27:51.000Z
////////////////////////////////////////////////////////////////////// // clusters/SparseLikelihood.h // (c) 2000-2007 Goncalo Abecasis // // This file is distributed as part of the MERLIN source code package // and may not be redistributed in any form, without prior written // permission from the author. Permission is granted for you to // modify this file for your own personal use, but modified versions // must retain this copyright notice and must not be distributed. // // Permission is granted for you to use this file to compile MERLIN. // // All computer programs have bugs. Use this file at your own risk. // // Tuesday December 18, 2007 // #ifndef __SPARSELIKELIHOOD_H__ #define __SPARSELIKELIHOOD_H__ #include "HaploGraph.h" #include "HaploSet.h" #include "MathMatrix.h" #include "HaploTree.h" class SparseLikelihood { public: int markers; int haplos; Vector frequencies; SparseLikelihood() { trees = NULL; index = NULL; tol = 1e-7; ztol = 1e-10; secondPass = false; } ~SparseLikelihood() { if (index != NULL) delete [] index; if (trees != NULL) delete [] trees; } void Initialize(const IntArray & alleleCounts); void Initialize(const IntArray & allelicCounts, const IntArray & haplos, const Vector & freqs); void RandomEM(HaplotypeSets * sets); void EM(HaplotypeSets * sets, bool quiet = false); void Print(double minfreq, HaplotypeSets * sets = NULL); void PrintExtras(double minfreq); void RetrieveHaplotypes(IntArray & haplos, Vector & freqs, double minFreq); double SetLikelihood(HaplotypeSet * set); double GraphLikelihood(HaplotypeGraph * graph); double GraphLikelihood(HaplotypeGraph * graph, int tree, int i); double CurrentLikelihood(HaplotypeGraph * graph, int tree); // Returns log of constant that has been used to scale likelihoods // for all component graphs in a haplotype set. double GetLogOffset(HaplotypeSet * set); void ArgMax(HaplotypeGraph * graph, int i = 0); void ExtractConfiguration(HaplotypeGraph * graph, IntArray & configuration, bool sample); void ExtractConfiguration(HaplotypeGraph * graph, bool sample, int index = 0); void SelectState(HaplotypeGraph * graph); void SampleState(HaplotypeGraph * graph); double best_llk; double tol, ztol; private: IntArray * index; IntArray last; IntArray new_index; IntArray selectedState; Vector marginals; bool secondPass; double setLikelihood; Vector new_frequencies; bool UpdateIndex(HaplotypeGraph * graph, int tree, int i); bool ExpandIndex(HaplotypeGraph * graph, int tree, int i); bool SelectAllele(int tree, int i, int allele); void CoreEM(HaplotypeSets * sets, bool quiet = false); // Each tree has up to (2^treeBits) markers int treeBits; // Number of trees int treeCount; // Array of trees HaploTree * trees; // Likelihood factors within each graph Matrix factorMatrix; Vector * factors; }; #endif
31.323529
103
0.653208
[ "vector" ]
dcdede9bcf94eeed5a5d10a5c2bac8bfe0af60f0
3,703
h
C
ios/PolyvCloudClassModule/PolyvCloudClassUICode/Watch/Modules/Chatroom/PLVChatroomController.h
polyv/polyv-rn-cloudclass-sdk-demo
852f44438e497ea7fa6d9c5b46b13c8e6718d4f1
[ "MIT" ]
1
2020-07-27T15:44:51.000Z
2020-07-27T15:44:51.000Z
ios/PolyvCloudClassModule/PolyvCloudClassUICode/Watch/Modules/Chatroom/PLVChatroomController.h
polyv/polyv-rn-cloudclass-sdk-demo
852f44438e497ea7fa6d9c5b46b13c8e6718d4f1
[ "MIT" ]
3
2020-08-06T07:02:37.000Z
2021-05-10T13:09:52.000Z
ios/PolyvCloudClassModule/PolyvCloudClassUICode/Watch/Modules/Chatroom/PLVChatroomController.h
polyv/polyv-rn-cloudclass-sdk-demo
852f44438e497ea7fa6d9c5b46b13c8e6718d4f1
[ "MIT" ]
1
2020-10-19T06:22:44.000Z
2020-10-19T06:22:44.000Z
// // PLVChatroomController.h // PolyvCloudClassDemo // // Created by ftao on 23/08/2018. // Copyright © 2018 polyv. All rights reserved. // #import <UIKit/UIKit.h> #import <PolyvCloudClassSDK/PLVLiveVideoAPI.h> #import <PolyvBusinessSDK/PLVSocketObject.h> #import "PLVTextInputView.h" extern NSString *PLVChatroomSendTextMsgNotification; extern NSString *PLVChatroomSendImageMsgNotification; extern NSString *PLVChatroomSendCustomMsgNotification; /// 聊天室错误码 typedef NS_ENUM(NSInteger, PLVChatroomErrorCode) { /// 无访问权限 PLVChatroomErrorCodeBeKicked = -100, /// 房间关闭 PLVChatroomErrorCodeRoomClose = -111, /// 被禁言 PLVChatroomErrorCodeBanned = -122, }; @class PLVChatroomController; @protocol PLVChatroomDelegate <NSObject> @required /// 授权失败的回调 - (void)chatroom:(PLVChatroomController *)chatroom didOpenError:(PLVChatroomErrorCode)code; /// 聊天室消息回调 - (void)chatroom:(PLVChatroomController *)chatroom emitSocketObject:(PLVSocketChatRoomObject *)object; /// 从外层获取当前频道的SessionId - (NSString *)currentChannelSessionId:(PLVChatroomController *)chatroom; /// 登录成功后,返回登录消息里的user信息,调用PLVPPTViewController里的setUser - (void)chatroom:(PLVChatroomController *)chatroom userInfo:(NSDictionary *)userInfo; @optional /// 输入键盘弹出弹入回调,由外层实现相关逻辑 - (void)chatroom:(PLVChatroomController *)chatroom followKeyboardAnimation:(BOOL)flag; /// 发言回调,可用于弹幕显示 - (void)chatroom:(PLVChatroomController *)chatroom didSendSpeakContent:(NSString *)content; /// 自定义消息回调 - (void)chatroom:(PLVChatroomController *)chatroom emitCustomEvent:(NSString *)event emitMode:(int)emitMode data:(NSDictionary *)data tip:(NSString *)tip; /// 回调HUD消息 - (void)chatroom:(PLVChatroomController *)chatroom showMessage:(NSString *)message; /// 查看公告 - (void)readBulletin:(PLVChatroomController *)chatroom; /// 当前userId已在别处登录,确认后自动退出直播间(废弃, from 0.12.0) //- (void)reLogin:(PLVChatroomController *)chatroom; /// 刷新连麦窗口的当前聊天室在线人数 - (void)refreshLinkMicOnlineCount:(PLVChatroomController *)chatroom number:(NSUInteger)number; @end @interface PLVChatroomController : UIViewController /// 当前频道号 @property (nonatomic, readonly) NSUInteger roomId; /// 输入键盘的类型 @property (nonatomic, readonly) PLVTextInputViewType type; /// 聊天室在线人数(实时) @property (nonatomic, readonly) NSUInteger onlineCount; /// 是否关闭 @property (nonatomic, getter=isClosed, readonly) BOOL closed; /// delegate @property (nonatomic, weak) id<PLVChatroomDelegate> delegate; /// 直播间开关信息 @property (nonatomic, strong) NSDictionary *switchInfo; /// 只看讲师模式下是否允许发言、点赞、送花等操作,默认 YES(公聊模式属性) @property (nonatomic, assign) BOOL allowToSpeakInTeacherMode; /** 聊天室初始化方法 @param type 聊天室类型 @param roomId 房间号 @param frame frame @return PLVChatroomController */ - (instancetype)initChatroomWithType:(PLVTextInputViewType)type roomId:(NSUInteger)roomId frame:(CGRect)frame; /** 聊天室便利初始化方法 @param type 聊天室类型 @param roomId 房间号 @param frame frame @return PLVChatroomController */ + (instancetype)chatroomWithType:(PLVTextInputViewType)type roomId:(NSUInteger)roomId frame:(CGRect)frame; /** 加载子视图 */ - (void)loadSubViews:(UIView *)tapSuperView; /** 准备退出时,必须清空定时器资源 */ - (void)clearResource; /** 还原聊天室状态 */ - (void)recoverChatroomStatus; /** 添加新事件 @param object PLVSocketChatRoomObject */ - (void)addNewChatroomObject:(PLVSocketChatRoomObject *)object; /** 添加自定义事件 @param customeMessage 自定义消息内容 @param mine 自己消息类型 @param msgId 消息id */ - (void)addCustomMessage:(NSDictionary *)customeMessage mine:(BOOL)mine msgId:(NSString *)msgId; /** 发送一条自己文字评论 @param text 自己文本消息 */ - (void)sendTextMessage:(NSString *)text; /// 取消键盘的输入 - (void)tapChatInputView; /// 在连麦时需要调整聊天室的窗口大小 - (void)resetChatroomFrame:(CGRect)rect; @end
23.737179
154
0.763705
[ "object" ]
dce0b4d91d91407a46b7b37f7fc394d1b1fa1f87
16,036
h
C
pdb/src/lambdas/headers/Lambda.h
dimitrijejankov/pdb
395b5ebd48c2c1b14a56bf24aeea726b36559074
[ "Apache-2.0" ]
29
2018-06-14T03:19:32.000Z
2021-04-27T02:45:12.000Z
pdb/src/lambdas/headers/Lambda.h
dimitrijejankov/pdb
395b5ebd48c2c1b14a56bf24aeea726b36559074
[ "Apache-2.0" ]
4
2018-07-03T21:50:14.000Z
2018-11-01T15:36:07.000Z
pdb/src/lambdas/headers/Lambda.h
dimitrijejankov/pdb
395b5ebd48c2c1b14a56bf24aeea726b36559074
[ "Apache-2.0" ]
13
2018-06-14T03:39:14.000Z
2020-08-03T00:58:24.000Z
/***************************************************************************** * * * Copyright 2018 Rice University * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * *****************************************************************************/ #ifndef LAMBDA_H #define LAMBDA_H #include <memory> #include <vector> #include <functional> #include "Object.h" #include "Handle.h" #include "Ptr.h" #include "TupleSpec.h" #include "ComputeExecutor.h" #include "GenericLambdaObject.h" #include "DereferenceLambda.h" #include "MultiInputsBase.h" namespace pdb { /** * * @tparam ReturnType */ template<class ReturnType> class Lambda { public: /** * create a lambda tree that returns a pointer * this is an implicit * @param treeWithPointer */ Lambda(LambdaTree<Ptr<ReturnType>> treeWithPointer) { // a problem is that consumers of this lambda will not be able to deal with a // Ptr<ReturnType>... // so we need to add an additional operation that dereferences the pointer std::shared_ptr<DereferenceLambda<ReturnType>> newRoot = std::make_shared<DereferenceLambda<ReturnType>>(treeWithPointer); tree = newRoot; } /** * create a lambda tree that returns a non-pointer * @param tree */ Lambda(LambdaTree<ReturnType> tree) : tree(tree.getPtr()) {} unsigned int getInputIndex() { return tree->getInputIndex(); } /** * convert one of these guys to a map * @param returnVal * @param suffix */ void toMap(std::map<std::string, GenericLambdaObjectPtr> &returnVal, int &suffix) { traverse(returnVal, tree, suffix); } std::vector<std::string> getAllInputs(MultiInputsBase *multiInputsBase) { std::vector<std::string> ret; this->getInputs(ret, tree, multiInputsBase); return ret; } /** * This is to get the TCAPString for this lambda tree * @param inputTupleSetName * @param inputColumnNames * @param inputColumnsToApply * @param childrenLambdaNames * @param lambdaLabel * @param computationName * @param computationLabel * @param outputTupleSetName * @param outputColumnNames * @param addedOutputColumnName * @param myLambdaName * @param whetherToRemoveUnusedOutputColumns * @param multiInputsComp * @param amIPartOfJoinPredicate * @return */ std::string toTCAPString(std::string inputTupleSetName, std::vector<std::string> &inputColumnNames, std::vector<std::string> &inputColumnsToApply, std::vector<std::string> &childrenLambdaNames, int &lambdaLabel, std::string computationName, int computationLabel, std::string &outputTupleSetName, std::vector<std::string> &outputColumnNames, std::string &addedOutputColumnName, std::string &myLambdaName, bool whetherToRemoveUnusedOutputColumns, MultiInputsBase *multiInputsComp = nullptr, bool amIPartOfJoinPredicate = false) { std::vector<std::string> tcapStrings; std::string outputTCAPString; std::vector<std::string> inputTupleSetNames; inputTupleSetNames.push_back(inputTupleSetName); std::vector<std::string> columnNames; for (const auto &inputColumnName : inputColumnNames) { columnNames.push_back(inputColumnName); } std::vector<std::string> columnsToApply; for (const auto &i : inputColumnsToApply) { columnsToApply.push_back(i); } std::vector<std::string> childrenLambdas; for (const auto &childrenLambdaName : childrenLambdaNames) { childrenLambdas.push_back(childrenLambdaName); } getTCAPString(tcapStrings, inputTupleSetNames, columnNames, columnsToApply, childrenLambdas, tree, lambdaLabel, computationName, computationLabel, addedOutputColumnName, myLambdaName, outputTupleSetName, multiInputsComp, amIPartOfJoinPredicate); PDB_COUT << "Lambda: lambdaLabel=" << lambdaLabel << std::endl; bool isOutputInInput = false; outputColumnNames.clear(); if (!whetherToRemoveUnusedOutputColumns) { for (const auto &columnName : columnNames) { outputColumnNames.push_back(columnName); if (addedOutputColumnName == columnName) { isOutputInInput = true; } } if (!isOutputInInput) { outputColumnNames.push_back(addedOutputColumnName); } } else { outputColumnNames.push_back(addedOutputColumnName); } // TODO this is very dirty and should not be done like that! For now I'm going to patch it! if (whetherToRemoveUnusedOutputColumns) { // get the last tcap string unsigned long last = tcapStrings.size() - 1; PDB_COUT << "tcapStrings[" << last << "]=" << tcapStrings[last] << std::endl; std::string right = tcapStrings[last].substr(tcapStrings[last].find("<=")); // by default the end is an empty string std::string end; // check if we have an info dictionary if we have chop off the end and store it in the end variable if (right.find('[') != std::string::npos) { end = right.substr(right.find('[')); right = right.substr(0, right.find('[')); } // find the positions of the last brackets () unsigned long pos1 = right.find_last_of('('); unsigned long pos2 = right.rfind("),"); // empty out anything between the brackets right.replace(pos1 + 1, pos2 - 1 - (pos1 + 1) + 1, ""); // combine the string and replace it tcapStrings[last] = outputTupleSetName + " (" + addedOutputColumnName + ") " + right + end; } // combine all the tcap strings for (const auto &tcapString : tcapStrings) { outputTCAPString.append(tcapString); } return outputTCAPString; } private: /** * in case we wrap up a non-pointer type */ std::shared_ptr<TypedLambdaObject<ReturnType>> tree; /** * does the actual tree traversal * JiaNote: I changed below method from pre-order traversing to post-order traversing, so that it follows * the lambda execution ordering * @param fillMe * @param root * @param startLabel */ static void traverse(std::map<std::string, GenericLambdaObjectPtr> &fillMe, GenericLambdaObjectPtr root, int &startLabel) { for (int i = 0; i < root->getNumChildren(); i++) { GenericLambdaObjectPtr child = root->getChild(i); traverse(fillMe, child, startLabel); } std::string myName = root->getTypeOfLambda(); myName = myName + "_" + std::to_string(startLabel); startLabel++; fillMe[myName] = root; } /** * * @param allInputs * @param root * @param multiInputsBase */ void getInputs(std::vector<std::string> &allInputs, GenericLambdaObjectPtr root, MultiInputsBase *multiInputsBase) { for (int i = 0; i < root->getNumChildren(); i++) { GenericLambdaObjectPtr child = root->getChild(i); getInputs(allInputs, child, multiInputsBase); } if (root->getNumChildren() == 0) { for (int i = 0; i < root->getNumInputs(); i++) { std::string myName = multiInputsBase->getNameForIthInput(root->getInputIndex(i)); auto iter = std::find(allInputs.begin(), allInputs.end(), myName); if (iter == allInputs.end()) { allInputs.push_back(myName); } } } } /** * JiaNote: below function is to generate a sequence of TCAP Strings for this Lambda tree * @param tcapStrings * @param inputTupleSetNames * @param inputColumnNames * @param inputColumnsToApply * @param childrenLambdaNames * @param root * @param lambdaLabel * @param computationName * @param computationLabel * @param addedOutputColumnName * @param myLambdaName * @param outputTupleSetName * @param multiInputsComp * @param amIPartOfJoinPredicate * @param amILeftChildOfEqualLambda * @param amIRightChildOfEqualLambda * @param parentLambdaName * @param isSelfJoin */ static void getTCAPString(std::vector<std::string> &tcapStrings, std::vector<std::string> &inputTupleSetNames, std::vector<std::string> &inputColumnNames, std::vector<std::string> &inputColumnsToApply, std::vector<std::string> &childrenLambdaNames, GenericLambdaObjectPtr root, int &lambdaLabel, std::string computationName, int computationLabel, std::string &addedOutputColumnName, std::string &myLambdaName, std::string &outputTupleSetName, MultiInputsBase *multiInputsComp = nullptr, bool amIPartOfJoinPredicate = false, bool amILeftChildOfEqualLambda = false, bool amIRightChildOfEqualLambda = false, std::string parentLambdaName = "", bool isSelfJoin = false) { std::vector<std::string> columnsToApply; std::vector<std::string> childrenLambdas; std::vector<std::string> inputNames; std::vector<std::string> inputColumns; if (root->getNumChildren() > 0) { for (const auto &i : inputColumnsToApply) { columnsToApply.push_back(i); } inputColumnsToApply.clear(); for (const auto &childrenLambdaName : childrenLambdaNames) { childrenLambdas.push_back(childrenLambdaName); } childrenLambdaNames.clear(); for (const auto &inputTupleSetName : inputTupleSetNames) { auto iter = std::find(inputNames.begin(), inputNames.end(), inputTupleSetName); if (iter == inputNames.end()) { inputNames.push_back(inputTupleSetName); } } inputTupleSetNames.clear(); for (const auto &inputColumnName : inputColumnNames) { inputColumns.push_back(inputColumnName); } inputColumnNames.clear(); } std::string myTypeName = root->getTypeOfLambda(); PDB_COUT << "\tExtracted lambda named: " << myTypeName << "\n"; std::string myName = myTypeName + "_" + std::to_string(lambdaLabel + root->getNumChildren()); bool isLeftChildOfEqualLambda = false; bool isRightChildOfEqualLambda = false; bool isChildSelfJoin = false; GenericLambdaObjectPtr nextChild = nullptr; for (int i = 0; i < root->getNumChildren(); i++) { GenericLambdaObjectPtr child = root->getChild(i); if ((i + 1) < root->getNumChildren()) { nextChild = root->getChild(i + 1); } if (myTypeName == "==") { if (i == 0) { isLeftChildOfEqualLambda = true; } if (i == 1) { isRightChildOfEqualLambda = true; } } if ((isLeftChildOfEqualLambda || isRightChildOfEqualLambda) && (multiInputsComp != nullptr)) { std::string nextInputName; if (nextChild != nullptr) { nextInputName = multiInputsComp->getNameForIthInput(nextChild->getInputIndex(0)); } std::string myInputName = multiInputsComp->getNameForIthInput(child->getInputIndex(0)); if (nextInputName == myInputName) { isChildSelfJoin = true; } } getTCAPString(tcapStrings, inputNames, inputColumns, columnsToApply, childrenLambdas, child, lambdaLabel, computationName, computationLabel, addedOutputColumnName, myLambdaName, outputTupleSetName, multiInputsComp, amIPartOfJoinPredicate, isLeftChildOfEqualLambda, isRightChildOfEqualLambda, myName, isChildSelfJoin); inputColumnsToApply.push_back(addedOutputColumnName); childrenLambdaNames.push_back(myLambdaName); if (multiInputsComp != nullptr) { auto iter = std::find(inputTupleSetNames.begin(), inputTupleSetNames.end(), outputTupleSetName); if (iter == inputTupleSetNames.end()) { inputTupleSetNames.push_back(outputTupleSetName); } } else { inputTupleSetNames.clear(); inputTupleSetNames.push_back(outputTupleSetName); inputColumnNames.clear(); } for (const auto &inputColumn : inputColumns) { auto iter = std::find(inputColumnNames.begin(), inputColumnNames.end(), inputColumn); if (iter == inputColumnNames.end()) { inputColumnNames.push_back(inputColumn); } } isLeftChildOfEqualLambda = false; isRightChildOfEqualLambda = false; isChildSelfJoin = false; nextChild = nullptr; } std::vector<std::string> outputColumns; std::string tcapString = root->toTCAPString(inputTupleSetNames, inputColumnNames, inputColumnsToApply, childrenLambdaNames, lambdaLabel, computationName, computationLabel, outputTupleSetName, outputColumns, addedOutputColumnName, myLambdaName, multiInputsComp, amIPartOfJoinPredicate, amILeftChildOfEqualLambda, amIRightChildOfEqualLambda, parentLambdaName, isSelfJoin); tcapStrings.push_back(tcapString); lambdaLabel++; if (multiInputsComp == nullptr) { inputTupleSetNames.clear(); inputTupleSetNames.push_back(outputTupleSetName); } inputColumnNames.clear(); for (const auto &outputColumn : outputColumns) { inputColumnNames.push_back(outputColumn); } } }; } #endif
34.264957
126
0.560489
[ "object", "vector" ]
dce38e8925d3f4949264e6b24314b4e65d062eba
713
h
C
ClearScript/V8/ClearScriptV8/V8ScriptImpl.h
grumpydev/ClearScript
3fb8b8f38eedeed164d471bafabba63486d5976a
[ "MIT" ]
null
null
null
ClearScript/V8/ClearScriptV8/V8ScriptImpl.h
grumpydev/ClearScript
3fb8b8f38eedeed164d471bafabba63486d5976a
[ "MIT" ]
null
null
null
ClearScript/V8/ClearScriptV8/V8ScriptImpl.h
grumpydev/ClearScript
3fb8b8f38eedeed164d471bafabba63486d5976a
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once namespace Microsoft { namespace ClearScript { namespace V8 { //------------------------------------------------------------------------- // V8ScriptImpl //------------------------------------------------------------------------- private ref class V8ScriptImpl sealed : V8Script { public: V8ScriptImpl(ClearScript::DocumentInfo documentInfo, V8ScriptHolder* pHolder); SharedPtr<V8ScriptHolder> GetHolder(); ~V8ScriptImpl(); !V8ScriptImpl(); private: Object^ m_gcLock; SharedPtr<V8ScriptHolder>* m_pspHolder; }; }}}
22.28125
86
0.518934
[ "object" ]
dce4f290cb7cb39ebbc90a5b345ad7a5ffd01a6c
5,806
h
C
Code/Engine/Foundation/IO/Implementation/DeduplicationReadContext_inl.h
asheraryam/ezEngine
bfe6d109b72d8fd6f13d043b11980796625c648e
[ "MIT" ]
null
null
null
Code/Engine/Foundation/IO/Implementation/DeduplicationReadContext_inl.h
asheraryam/ezEngine
bfe6d109b72d8fd6f13d043b11980796625c648e
[ "MIT" ]
null
null
null
Code/Engine/Foundation/IO/Implementation/DeduplicationReadContext_inl.h
asheraryam/ezEngine
bfe6d109b72d8fd6f13d043b11980796625c648e
[ "MIT" ]
null
null
null
#include <Foundation/IO/Stream.h> template <typename T> EZ_ALWAYS_INLINE ezResult ezDeduplicationReadContext::ReadObjectInplace(ezStreamReader& stream, T& obj) { return ReadObject(stream, obj, nullptr); } template <typename T> ezResult ezDeduplicationReadContext::ReadObject(ezStreamReader& stream, T& obj, ezAllocatorBase* pAllocator) { bool bIsRealObject; stream >> bIsRealObject; EZ_ASSERT_DEV(bIsRealObject, "Reading an object inplace only works for the first occurrence"); EZ_SUCCEED_OR_RETURN(ezStreamReaderUtil::Deserialize<T>(stream, obj)); m_Objects.PushBack(&obj); return EZ_SUCCESS; } template <typename T> ezResult ezDeduplicationReadContext::ReadObject(ezStreamReader& stream, T*& pObject, ezAllocatorBase* pAllocator) { bool bIsRealObject; stream >> bIsRealObject; if (bIsRealObject) { pObject = EZ_NEW(pAllocator, T); EZ_SUCCEED_OR_RETURN(ezStreamReaderUtil::Deserialize<T>(stream, *pObject)); m_Objects.PushBack(pObject); } else { ezUInt32 uiIndex; stream >> uiIndex; if (uiIndex < m_Objects.GetCount()) { pObject = static_cast<T*>(m_Objects[uiIndex]); } else if (uiIndex == ezInvalidIndex) { pObject = nullptr; } else { return EZ_FAILURE; } } return EZ_SUCCESS; } template <typename T> ezResult ezDeduplicationReadContext::ReadObject(ezStreamReader& stream, ezSharedPtr<T>& pObject, ezAllocatorBase* pAllocator) { T* ptr = nullptr; if (ReadObject(stream, ptr, pAllocator).Succeeded()) { pObject = ezSharedPtr<T>(ptr, pAllocator); return EZ_SUCCESS; } return EZ_FAILURE; } template <typename T> ezResult ezDeduplicationReadContext::ReadObject(ezStreamReader& stream, ezUniquePtr<T>& pObject, ezAllocatorBase* pAllocator) { T* ptr = nullptr; if (ReadObject(stream, ptr, pAllocator).Succeeded()) { pObject = std::move(ezUniquePtr<T>(ptr, pAllocator)); return EZ_SUCCESS; } return EZ_FAILURE; } template <typename ArrayType, typename ValueType> ezResult ezDeduplicationReadContext::ReadArray(ezStreamReader& stream, ezArrayBase<ValueType, ArrayType>& Array, ezAllocatorBase* pAllocator) { ezUInt64 uiCount = 0; stream.ReadQWordValue(&uiCount); EZ_ASSERT_DEV( uiCount < std::numeric_limits<ezUInt32>::max(), "Containers currently use 32 bit for counts internally. Value from file is too large."); Array.Clear(); if (uiCount > 0) { static_cast<ArrayType&>(Array).Reserve(static_cast<ezUInt32>(uiCount)); for (ezUInt32 i = 0; i < static_cast<ezUInt32>(uiCount); ++i) { EZ_SUCCEED_OR_RETURN(ReadObject(stream, Array.ExpandAndGetRef(), pAllocator)); } } return EZ_SUCCESS; } template <typename KeyType, typename Comparer> ezResult ezDeduplicationReadContext::ReadSet(ezStreamReader& stream, ezSetBase<KeyType, Comparer>& Set, ezAllocatorBase* pAllocator) { ezUInt64 uiCount = 0; stream.ReadQWordValue(&uiCount); EZ_ASSERT_DEV( uiCount < std::numeric_limits<ezUInt32>::max(), "Containers currently use 32 bit for counts internally. Value from file is too large."); Set.Clear(); for (ezUInt32 i = 0; i < static_cast<ezUInt32>(uiCount); ++i) { KeyType key; EZ_SUCCEED_OR_RETURN(ReadObject(stream, key, pAllocator)); Set.Insert(std::move(key)); } return EZ_SUCCESS; } namespace ezInternal { // Internal helper to prevent the compiler from trying to find a de-serialization method for pointer types or other types which don't have // one. struct DeserializeHelper { template <typename T> static auto Deserialize(ezStreamReader& stream, T& obj, int) -> decltype(ezStreamReaderUtil::Deserialize(stream, obj)) { return ezStreamReaderUtil::Deserialize(stream, obj); } template <typename T> static ezResult Deserialize(ezStreamReader& stream, T& obj, float) { EZ_REPORT_FAILURE("No deserialize method available"); return EZ_FAILURE; } }; } // namespace ezInternal template <typename KeyType, typename ValueType, typename Comparer> ezResult ezDeduplicationReadContext::ReadMap(ezStreamReader& stream, ezMapBase<KeyType, ValueType, Comparer>& Map, ReadMapMode mode, ezAllocatorBase* pKeyAllocator, ezAllocatorBase* pValueAllocator) { ezUInt64 uiCount = 0; stream.ReadQWordValue(&uiCount); EZ_ASSERT_DEV( uiCount < std::numeric_limits<ezUInt32>::max(), "Containers currently use 32 bit for counts internally. Value from file is too large."); Map.Clear(); if (mode == ReadMapMode::DedupKey) { for (ezUInt32 i = 0; i < static_cast<ezUInt32>(uiCount); ++i) { KeyType key; ValueType value; EZ_SUCCEED_OR_RETURN(ReadObject(stream, key, pKeyAllocator)); EZ_SUCCEED_OR_RETURN(ezInternal::DeserializeHelper::Deserialize<ValueType>(stream, value, 0)); Map.Insert(std::move(key), std::move(value)); } } else if (mode == ReadMapMode::DedupValue) { for (ezUInt32 i = 0; i < static_cast<ezUInt32>(uiCount); ++i) { KeyType key; ValueType value; EZ_SUCCEED_OR_RETURN(ezInternal::DeserializeHelper::Deserialize<KeyType>(stream, key, 0)); EZ_SUCCEED_OR_RETURN(ReadObject(stream, value, pValueAllocator)); Map.Insert(std::move(key), std::move(value)); } } else { for (ezUInt32 i = 0; i < static_cast<ezUInt32>(uiCount); ++i) { KeyType key; ValueType value; EZ_SUCCEED_OR_RETURN(ReadObject(stream, key, pKeyAllocator)); EZ_SUCCEED_OR_RETURN(ReadObject(stream, value, pValueAllocator)); Map.Insert(std::move(key), std::move(value)); } } return EZ_SUCCESS; }
28.742574
142
0.687048
[ "object" ]
dcfec5be5375ae476a520ea15d32ba8492af2d8b
19,723
c
C
third_party/libSBML-5.11.0-Source/src/sbml/xml/test/TestXMLNamespaces.c
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
third_party/libSBML-5.11.0-Source/src/sbml/xml/test/TestXMLNamespaces.c
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
third_party/libSBML-5.11.0-Source/src/sbml/xml/test/TestXMLNamespaces.c
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
/** * \file TestXMLNamespaces.c * \brief XMLNamespaces unit tests * \author Michael Hucka <mhucka@caltech.edu> * * <!-------------------------------------------------------------------------- * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. * * Copyright (C) 2013-2014 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * 3. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2009-2013 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * * Copyright (C) 2006-2008 by the California Institute of Technology, * Pasadena, CA, USA * * Copyright (C) 2002-2005 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. Japan Science and Technology Agency, Japan * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution * and also available online as http://sbml.org/software/libsbml/license.html * ---------------------------------------------------------------------- -->*/ #include <sbml/common/common.h> #include <sbml/xml/XMLNamespaces.h> #include <check.h> #if defined(__cplusplus) LIBSBML_CPP_NAMESPACE_USE CK_CPPSTART #endif static XMLNamespaces_t *NS; void XMLNamespacesTest_setup (void) { NS = XMLNamespaces_create(); if (NS == NULL) { fail("XMLNamespacesTest_setup() failed to create a XMLNamespaces object."); } } void XMLNamespacesTest_teardown (void) { XMLNamespaces_free(NS); } START_TEST (test_XMLNamespaces_baseline) { fail_unless( XMLNamespaces_getLength(NS) == 0 ); fail_unless( XMLNamespaces_isEmpty(NS) == 1 ); } END_TEST START_TEST (test_XMLNamespaces_add) { fail_unless( XMLNamespaces_getLength(NS) == 0 ); fail_unless( XMLNamespaces_isEmpty(NS) == 1 ); XMLNamespaces_add(NS, "http://test1.org/", "test1"); fail_unless( XMLNamespaces_getLength(NS) == 1 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); XMLNamespaces_add(NS, "http://test2.org/", "test2"); fail_unless( XMLNamespaces_getLength(NS) == 2 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); XMLNamespaces_add(NS, "http://test1.org/", "test1a"); fail_unless( XMLNamespaces_getLength(NS) == 3 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); XMLNamespaces_add(NS, "http://test1.org/", "test1a"); fail_unless( XMLNamespaces_getLength(NS) == 3 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); fail_if( XMLNamespaces_getIndex(NS, "http://test1.org/") == -1); } END_TEST START_TEST (test_XMLNamespaces_add1) { char * test; fail_unless( XMLNamespaces_getLength(NS) == 0 ); fail_unless( XMLNamespaces_isEmpty(NS) == 1 ); int i = XMLNamespaces_add(NS, "http://test1.org/", "test1"); fail_unless( i == LIBSBML_OPERATION_SUCCESS); fail_unless( XMLNamespaces_getLength(NS) == 1 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); test = XMLNamespaces_getPrefix(NS, 0); fail_unless( strcmp(test, "test1") == 0 ); free(test); test = XMLNamespaces_getPrefixByURI(NS, "http://test1.org/"); fail_unless( strcmp(test, "test1") == 0 ); free(test); test = XMLNamespaces_getURI(NS, 0); fail_unless( strcmp(test, "http://test1.org/") == 0 ); free(test); test = XMLNamespaces_getURIByPrefix(NS, "test1"); fail_unless( strcmp(test, "http://test1.org/") == 0 ); free(test); // add with existing prefix i = XMLNamespaces_add(NS, "http://test2.org/", "test1"); fail_unless( i == LIBSBML_OPERATION_SUCCESS); fail_unless( XMLNamespaces_getLength(NS) == 1 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); test = XMLNamespaces_getPrefix(NS, 0); fail_unless( strcmp(test, "test1") == 0 ); free(test); test = XMLNamespaces_getPrefixByURI(NS, "http://test2.org/"); fail_unless( strcmp(test, "test1") == 0 ); free(test); test = XMLNamespaces_getURI(NS, 0); fail_unless( strcmp(test, "http://test2.org/") == 0 ); free(test); test = XMLNamespaces_getURIByPrefix(NS, "test1"); fail_unless( strcmp(test, "http://test2.org/") == 0 ); free(test); // add i = XMLNamespaces_add(NS, "http://test.org/", ""); fail_unless( i == LIBSBML_OPERATION_SUCCESS); fail_unless( XMLNamespaces_getLength(NS) == 2 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); fail_unless( XMLNamespaces_getPrefix(NS, 1) == NULL ); fail_unless( XMLNamespaces_getPrefixByURI(NS, "http://test.org/") == NULL); test = XMLNamespaces_getURI(NS, 1); fail_unless( strcmp(test, "http://test.org/") == 0 ); free(test); // add repeat with empty prefix i = XMLNamespaces_add(NS, "http://test3.org/", ""); fail_unless( i == LIBSBML_OPERATION_SUCCESS); fail_unless( XMLNamespaces_getLength(NS) == 2 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); fail_unless( XMLNamespaces_getPrefix(NS, 1) == NULL ); fail_unless( XMLNamespaces_getPrefixByURI(NS, "http://test3.org/") == NULL); test = XMLNamespaces_getURI(NS, 1); fail_unless( strcmp(test, "http://test3.org/") == 0 ); free(test); // add sbml ns i = XMLNamespaces_add(NS, "http://www.sbml.org/sbml/level1", ""); fail_unless( i == LIBSBML_OPERATION_SUCCESS); fail_unless( XMLNamespaces_getLength(NS) == 2 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); fail_unless( XMLNamespaces_getPrefix(NS, 1) == NULL ); fail_unless( XMLNamespaces_getPrefixByURI(NS, "http://www.sbml.org/sbml/level1") == NULL); test = XMLNamespaces_getURI(NS, 1); fail_unless( strcmp(test, "http://www.sbml.org/sbml/level1") == 0 ); free(test); // add a repeat of the sbml prefix ns i = XMLNamespaces_add(NS, "http://test_sbml_prefix/", ""); fail_unless( i == LIBSBML_OPERATION_FAILED); fail_unless( XMLNamespaces_getLength(NS) == 2 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); fail_unless( XMLNamespaces_getPrefix(NS, 1) == NULL ); fail_unless( XMLNamespaces_getPrefixByURI(NS, "http://www.sbml.org/sbml/level1") == NULL); test = XMLNamespaces_getURI(NS, 1); fail_unless( strcmp(test, "http://www.sbml.org/sbml/level1") == 0 ); free(test); // add repeat sbml ns uri i = XMLNamespaces_add(NS, "http://www.sbml.org/sbml/level1", "newprefix"); fail_unless( i == LIBSBML_OPERATION_SUCCESS); fail_unless( XMLNamespaces_getLength(NS) == 3 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); test = XMLNamespaces_getPrefix(NS, 2); fail_unless( strcmp(test, "newprefix") == 0 ); free(test); // this fails because the search finds the uri with the empty prefix first fail_unless( XMLNamespaces_getPrefixByURI(NS, "http://www.sbml.org/sbml/level1") == NULL); test = XMLNamespaces_getURI(NS, 2); fail_unless( strcmp(test, "http://www.sbml.org/sbml/level1") == 0 ); free(test); // add repeat prefix i = XMLNamespaces_add(NS, "http://www.foo", "newprefix"); fail_unless( i == LIBSBML_OPERATION_FAILED); fail_unless( XMLNamespaces_getLength(NS) == 3 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); test = XMLNamespaces_getPrefix(NS, 2); fail_unless( strcmp(test, "newprefix") == 0 ); free(test); test = XMLNamespaces_getURI(NS, 2); fail_unless( strcmp(test, "http://www.sbml.org/sbml/level1") == 0 ); free(test); // change sbml ns uri - it will not do this i = XMLNamespaces_add(NS, "http://www.sbml.org/sbml/level2", "newprefix"); fail_unless( i == LIBSBML_OPERATION_FAILED); fail_unless( XMLNamespaces_getLength(NS) == 3 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); test = XMLNamespaces_getPrefix(NS, 2); fail_unless( strcmp(test, "newprefix") == 0 ); free(test); test = XMLNamespaces_getURI(NS, 2); fail_unless( strcmp(test, "http://www.sbml.org/sbml/level1") == 0 ); free(test); } END_TEST START_TEST (test_XMLNamespaces_add2) { fail_unless( XMLNamespaces_getLength(NS) == 0 ); fail_unless( XMLNamespaces_isEmpty(NS) == 1 ); XMLNamespaces_add(NS, "http://test1.org/", "test1"); fail_unless( XMLNamespaces_getLength(NS) == 1 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); XMLNamespaces_add(NS, "http://test2.org/", "test2"); fail_unless( XMLNamespaces_getLength(NS) == 2 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); XMLNamespaces_add(NS, "http://test1.org/", "test1a"); fail_unless( XMLNamespaces_getLength(NS) == 3 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); XMLNamespaces_add(NS, "http://test1.org/", "test1a"); fail_unless( XMLNamespaces_getLength(NS) == 3 ); fail_unless( XMLNamespaces_isEmpty(NS) == 0 ); fail_if( XMLNamespaces_getIndex(NS, "http://test1.org/") == -1); } END_TEST START_TEST (test_XMLNamespaces_get) { char* test; XMLNamespaces_add(NS, "http://test1.org/", "test1"); /* index 0 */ XMLNamespaces_add(NS, "http://test2.org/", "test2"); /* index 1 */ XMLNamespaces_add(NS, "http://test3.org/", "test3"); /* index 2 */ XMLNamespaces_add(NS, "http://test4.org/", "test4"); /* index 3 */ XMLNamespaces_add(NS, "http://test5.org/", "test5"); /* index 4 */ XMLNamespaces_add(NS, "http://test6.org/", "test6"); /* index 5 */ XMLNamespaces_add(NS, "http://test7.org/", "test7"); /* index 6 */ XMLNamespaces_add(NS, "http://test8.org/", "test8"); /* index 7 */ XMLNamespaces_add(NS, "http://test9.org/", "test9"); /* index 8 */ fail_unless( XMLNamespaces_getLength(NS) == 9 ); fail_unless( XMLNamespaces_getNumNamespaces(NS) == 9 ); fail_unless( XMLNamespaces_getIndex(NS, "http://test1.org/") == 0 ); test = XMLNamespaces_getPrefix(NS, 1); fail_unless( strcmp(test, "test2") == 0 ); free(test); test = XMLNamespaces_getPrefixByURI(NS, "http://test1.org/"); fail_unless( strcmp(test, "test1") == 0 ); free(test); test = XMLNamespaces_getURI(NS, 1); fail_unless( strcmp(test, "http://test2.org/") == 0 ); free(test); test = XMLNamespaces_getURIByPrefix(NS, "test2"); fail_unless( strcmp(test, "http://test2.org/") == 0 ); free(test); fail_unless( XMLNamespaces_getIndex(NS, "http://test1.org/") == 0 ); fail_unless( XMLNamespaces_getIndex(NS, "http://test2.org/") == 1 ); fail_unless( XMLNamespaces_getIndex(NS, "http://test5.org/") == 4 ); fail_unless( XMLNamespaces_getIndex(NS, "http://test9.org/") == 8 ); fail_unless( XMLNamespaces_getIndex(NS, "http://testX.org/") == -1 ); fail_unless( XMLNamespaces_hasURI(NS, "http://test1.org/") != 0 ); fail_unless( XMLNamespaces_hasURI(NS, "http://test2.org/") != 0 ); fail_unless( XMLNamespaces_hasURI(NS, "http://test5.org/") != 0 ); fail_unless( XMLNamespaces_hasURI(NS, "http://test9.org/") != 0 ); fail_unless( XMLNamespaces_hasURI(NS, "http://testX.org/") == 0 ); fail_unless( XMLNamespaces_getIndexByPrefix(NS, "test1") == 0 ); fail_unless( XMLNamespaces_getIndexByPrefix(NS, "test5") == 4 ); fail_unless( XMLNamespaces_getIndexByPrefix(NS, "test9") == 8 ); fail_unless( XMLNamespaces_getIndexByPrefix(NS, "testX") == -1 ); fail_unless( XMLNamespaces_hasPrefix(NS, "test1") != 0 ); fail_unless( XMLNamespaces_hasPrefix(NS, "test5") != 0 ); fail_unless( XMLNamespaces_hasPrefix(NS, "test9") != 0 ); fail_unless( XMLNamespaces_hasPrefix(NS, "testX") == 0 ); fail_unless( XMLNamespaces_hasNS(NS, "http://test1.org/", "test1") != 0 ); fail_unless( XMLNamespaces_hasNS(NS, "http://test5.org/", "test5") != 0 ); fail_unless( XMLNamespaces_hasNS(NS, "http://test9.org/", "test9") != 0 ); fail_unless( XMLNamespaces_hasNS(NS, "http://testX.org/", "testX") == 0 ); } END_TEST START_TEST (test_XMLNamespaces_remove) { XMLNamespaces_add(NS, "http://test1.org/", "test1"); XMLNamespaces_add(NS, "http://test2.org/", "test2"); XMLNamespaces_add(NS, "http://test3.org/", "test3"); XMLNamespaces_add(NS, "http://test4.org/", "test4"); XMLNamespaces_add(NS, "http://test5.org/", "test5"); fail_unless( XMLNamespaces_getLength(NS) == 5 ); fail_unless( XMLNamespaces_getNumNamespaces(NS) == 5 ); XMLNamespaces_remove(NS, 4); fail_unless( XMLNamespaces_getLength(NS) == 4 ); XMLNamespaces_remove(NS, 3); fail_unless( XMLNamespaces_getLength(NS) == 3 ); XMLNamespaces_remove(NS, 2); fail_unless( XMLNamespaces_getLength(NS) == 2 ); XMLNamespaces_remove(NS, 1); fail_unless( XMLNamespaces_getLength(NS) == 1 ); XMLNamespaces_remove(NS, 0); fail_unless( XMLNamespaces_getLength(NS) == 0 ); fail_unless( XMLNamespaces_getNumNamespaces(NS) == 0 ); XMLNamespaces_add(NS, "http://test1.org/", "test1"); XMLNamespaces_add(NS, "http://test2.org/", "test2"); XMLNamespaces_add(NS, "http://test3.org/", "test3"); XMLNamespaces_add(NS, "http://test4.org/", "test4"); XMLNamespaces_add(NS, "http://test5.org/", "test5"); fail_unless( XMLNamespaces_getLength(NS) == 5 ); fail_unless( XMLNamespaces_getNumNamespaces(NS) == 5 ); XMLNamespaces_remove(NS, 0); fail_unless( XMLNamespaces_getLength(NS) == 4 ); XMLNamespaces_remove(NS, 0); fail_unless( XMLNamespaces_getLength(NS) == 3 ); XMLNamespaces_remove(NS, 0); fail_unless( XMLNamespaces_getLength(NS) == 2 ); fail_unless( XMLNamespaces_getNumNamespaces(NS) == 2 ); XMLNamespaces_remove(NS, 0); fail_unless( XMLNamespaces_getLength(NS) == 1 ); XMLNamespaces_remove(NS, 0); fail_unless( XMLNamespaces_getLength(NS) == 0 ); fail_unless( XMLNamespaces_getNumNamespaces(NS) == 0 ); } END_TEST START_TEST (test_XMLNamespaces_remove_by_prefix) { XMLNamespaces_add(NS, "http://test1.org/", "test1"); XMLNamespaces_add(NS, "http://test2.org/", "test2"); XMLNamespaces_add(NS, "http://test3.org/", "test3"); XMLNamespaces_add(NS, "http://test4.org/", "test4"); XMLNamespaces_add(NS, "http://test5.org/", "test5"); fail_unless( XMLNamespaces_getLength(NS) == 5 ); XMLNamespaces_removeByPrefix(NS, "test1"); fail_unless( XMLNamespaces_getLength(NS) == 4 ); XMLNamespaces_removeByPrefix(NS, "test2"); fail_unless( XMLNamespaces_getLength(NS) == 3 ); XMLNamespaces_removeByPrefix(NS, "test3"); fail_unless( XMLNamespaces_getLength(NS) == 2 ); XMLNamespaces_removeByPrefix(NS, "test4"); fail_unless( XMLNamespaces_getLength(NS) == 1 ); XMLNamespaces_removeByPrefix(NS, "test5"); fail_unless( XMLNamespaces_getLength(NS) == 0 ); XMLNamespaces_add(NS, "http://test1.org/", "test1"); XMLNamespaces_add(NS, "http://test2.org/", "test2"); XMLNamespaces_add(NS, "http://test3.org/", "test3"); XMLNamespaces_add(NS, "http://test4.org/", "test4"); XMLNamespaces_add(NS, "http://test5.org/", "test5"); fail_unless( XMLNamespaces_getLength(NS) == 5 ); XMLNamespaces_removeByPrefix(NS, "test5"); fail_unless( XMLNamespaces_getLength(NS) == 4 ); XMLNamespaces_removeByPrefix(NS, "test4"); fail_unless( XMLNamespaces_getLength(NS) == 3 ); XMLNamespaces_removeByPrefix(NS, "test3"); fail_unless( XMLNamespaces_getLength(NS) == 2 ); XMLNamespaces_removeByPrefix(NS, "test2"); fail_unless( XMLNamespaces_getLength(NS) == 1 ); XMLNamespaces_removeByPrefix(NS, "test1"); fail_unless( XMLNamespaces_getLength(NS) == 0 ); XMLNamespaces_add(NS, "http://test1.org/", "test1"); XMLNamespaces_add(NS, "http://test2.org/", "test2"); XMLNamespaces_add(NS, "http://test3.org/", "test3"); XMLNamespaces_add(NS, "http://test4.org/", "test4"); XMLNamespaces_add(NS, "http://test5.org/", "test5"); fail_unless( XMLNamespaces_getLength(NS) == 5 ); XMLNamespaces_removeByPrefix(NS, "test3"); fail_unless( XMLNamespaces_getLength(NS) == 4 ); XMLNamespaces_removeByPrefix(NS, "test1"); fail_unless( XMLNamespaces_getLength(NS) == 3 ); XMLNamespaces_removeByPrefix(NS, "test4"); fail_unless( XMLNamespaces_getLength(NS) == 2 ); XMLNamespaces_removeByPrefix(NS, "test5"); fail_unless( XMLNamespaces_getLength(NS) == 1 ); XMLNamespaces_removeByPrefix(NS, "test2"); fail_unless( XMLNamespaces_getLength(NS) == 0 ); } END_TEST START_TEST (test_XMLNamespaces_remove1) { XMLNamespaces_add(NS, "http://test1.org/", "test1"); XMLNamespaces_add(NS, "http://test2.org/", "test2"); fail_unless( XMLNamespaces_getLength(NS) == 2 ); int i = XMLNamespaces_remove(NS, 4); fail_unless (i == LIBSBML_INDEX_EXCEEDS_SIZE ); fail_unless( XMLNamespaces_getLength(NS) == 2 ); i = XMLNamespaces_removeByPrefix(NS, "test4"); fail_unless (i == LIBSBML_INDEX_EXCEEDS_SIZE ); fail_unless( XMLNamespaces_getLength(NS) == 2 ); i = XMLNamespaces_remove(NS, 1); fail_unless (i == LIBSBML_OPERATION_SUCCESS ); fail_unless( XMLNamespaces_getLength(NS) == 1 ); i = XMLNamespaces_removeByPrefix(NS, "test1"); fail_unless (i == LIBSBML_OPERATION_SUCCESS ); fail_unless( XMLNamespaces_getLength(NS) == 0 ); } END_TEST START_TEST (test_XMLNamespaces_clear) { XMLNamespaces_add(NS, "http://test1.org/", "test1"); XMLNamespaces_add(NS, "http://test2.org/", "test2"); XMLNamespaces_add(NS, "http://test3.org/", "test3"); XMLNamespaces_add(NS, "http://test4.org/", "test4"); XMLNamespaces_add(NS, "http://test5.org/", "test5"); fail_unless( XMLNamespaces_getLength(NS) == 5 ); int i = XMLNamespaces_clear(NS); fail_unless( i == LIBSBML_OPERATION_SUCCESS); fail_unless( XMLNamespaces_getLength(NS) == 0 ); } END_TEST START_TEST (test_XMLNamespaces_accessWithNULL) { fail_unless( XMLNamespaces_add(NULL, NULL, NULL) == LIBSBML_INVALID_OBJECT); fail_unless( XMLNamespaces_clear(NULL) == LIBSBML_OPERATION_FAILED); fail_unless( XMLNamespaces_clone(NULL) == NULL); XMLNamespaces_free(NULL); fail_unless( XMLNamespaces_getIndex(NULL, NULL) == -1); fail_unless( XMLNamespaces_getIndexByPrefix(NULL, NULL) == -1); fail_unless( XMLNamespaces_getLength(NULL) == 0); fail_unless( XMLNamespaces_getPrefix(NULL, 0) == NULL); fail_unless( XMLNamespaces_getPrefixByURI(NULL, NULL) == NULL); fail_unless( XMLNamespaces_getURI(NULL, 0) == NULL); fail_unless( XMLNamespaces_getURIByPrefix(NULL, NULL) == NULL); fail_unless( XMLNamespaces_hasNS(NULL, NULL, NULL) == 0); fail_unless( XMLNamespaces_hasPrefix(NULL, NULL) == 0); fail_unless( XMLNamespaces_hasURI(NULL, NULL) == 0); fail_unless( XMLNamespaces_isEmpty(NULL) == 1); fail_unless( XMLNamespaces_remove(NULL, 0) == LIBSBML_INVALID_OBJECT); fail_unless( XMLNamespaces_removeByPrefix(NULL, NULL) == LIBSBML_INVALID_OBJECT); } END_TEST Suite * create_suite_XMLNamespaces (void) { Suite *suite = suite_create("XMLNamespaces"); TCase *tcase = tcase_create("XMLNamespaces"); tcase_add_checked_fixture( tcase, XMLNamespacesTest_setup, XMLNamespacesTest_teardown ); tcase_add_test( tcase, test_XMLNamespaces_baseline ); tcase_add_test( tcase, test_XMLNamespaces_add ); tcase_add_test( tcase, test_XMLNamespaces_add1 ); tcase_add_test( tcase, test_XMLNamespaces_add2 ); tcase_add_test( tcase, test_XMLNamespaces_get ); tcase_add_test( tcase, test_XMLNamespaces_remove ); tcase_add_test( tcase, test_XMLNamespaces_remove_by_prefix ); tcase_add_test( tcase, test_XMLNamespaces_remove1 ); tcase_add_test( tcase, test_XMLNamespaces_clear ); tcase_add_test( tcase, test_XMLNamespaces_accessWithNULL ); suite_add_tcase(suite, tcase); return suite; } #if defined(__cplusplus) CK_CPPEND #endif
34.969858
83
0.688688
[ "object" ]
0d005f46fdb7f0f8b502b0fcb173be1f3cf2d976
3,422
c
C
unit-test/test_ezsigntemplatepackagesigner_create_object_v1_response_all_of.c
ezmaxinc/eZmax-SDK-c
725eab79d6311127a2d5bd731b978bce94142d69
[ "curl", "MIT" ]
null
null
null
unit-test/test_ezsigntemplatepackagesigner_create_object_v1_response_all_of.c
ezmaxinc/eZmax-SDK-c
725eab79d6311127a2d5bd731b978bce94142d69
[ "curl", "MIT" ]
null
null
null
unit-test/test_ezsigntemplatepackagesigner_create_object_v1_response_all_of.c
ezmaxinc/eZmax-SDK-c
725eab79d6311127a2d5bd731b978bce94142d69
[ "curl", "MIT" ]
null
null
null
#ifndef ezsigntemplatepackagesigner_create_object_v1_response_all_of_TEST #define ezsigntemplatepackagesigner_create_object_v1_response_all_of_TEST // the following is to include only the main from the first c file #ifndef TEST_MAIN #define TEST_MAIN #define ezsigntemplatepackagesigner_create_object_v1_response_all_of_MAIN #endif // TEST_MAIN #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdbool.h> #include "../external/cJSON.h" #include "../model/ezsigntemplatepackagesigner_create_object_v1_response_all_of.h" ezsigntemplatepackagesigner_create_object_v1_response_all_of_t* instantiate_ezsigntemplatepackagesigner_create_object_v1_response_all_of(int include_optional); #include "test_ezsigntemplatepackagesigner_create_object_v1_response_m_payload.c" ezsigntemplatepackagesigner_create_object_v1_response_all_of_t* instantiate_ezsigntemplatepackagesigner_create_object_v1_response_all_of(int include_optional) { ezsigntemplatepackagesigner_create_object_v1_response_all_of_t* ezsigntemplatepackagesigner_create_object_v1_response_all_of = NULL; if (include_optional) { ezsigntemplatepackagesigner_create_object_v1_response_all_of = ezsigntemplatepackagesigner_create_object_v1_response_all_of_create( // false, not to have infinite recursion instantiate_ezsigntemplatepackagesigner_create_object_v1_response_m_payload(0) ); } else { ezsigntemplatepackagesigner_create_object_v1_response_all_of = ezsigntemplatepackagesigner_create_object_v1_response_all_of_create( NULL ); } return ezsigntemplatepackagesigner_create_object_v1_response_all_of; } #ifdef ezsigntemplatepackagesigner_create_object_v1_response_all_of_MAIN void test_ezsigntemplatepackagesigner_create_object_v1_response_all_of(int include_optional) { ezsigntemplatepackagesigner_create_object_v1_response_all_of_t* ezsigntemplatepackagesigner_create_object_v1_response_all_of_1 = instantiate_ezsigntemplatepackagesigner_create_object_v1_response_all_of(include_optional); cJSON* jsonezsigntemplatepackagesigner_create_object_v1_response_all_of_1 = ezsigntemplatepackagesigner_create_object_v1_response_all_of_convertToJSON(ezsigntemplatepackagesigner_create_object_v1_response_all_of_1); printf("ezsigntemplatepackagesigner_create_object_v1_response_all_of :\n%s\n", cJSON_Print(jsonezsigntemplatepackagesigner_create_object_v1_response_all_of_1)); ezsigntemplatepackagesigner_create_object_v1_response_all_of_t* ezsigntemplatepackagesigner_create_object_v1_response_all_of_2 = ezsigntemplatepackagesigner_create_object_v1_response_all_of_parseFromJSON(jsonezsigntemplatepackagesigner_create_object_v1_response_all_of_1); cJSON* jsonezsigntemplatepackagesigner_create_object_v1_response_all_of_2 = ezsigntemplatepackagesigner_create_object_v1_response_all_of_convertToJSON(ezsigntemplatepackagesigner_create_object_v1_response_all_of_2); printf("repeating ezsigntemplatepackagesigner_create_object_v1_response_all_of:\n%s\n", cJSON_Print(jsonezsigntemplatepackagesigner_create_object_v1_response_all_of_2)); } int main() { test_ezsigntemplatepackagesigner_create_object_v1_response_all_of(1); test_ezsigntemplatepackagesigner_create_object_v1_response_all_of(0); printf("Hello world \n"); return 0; } #endif // ezsigntemplatepackagesigner_create_object_v1_response_all_of_MAIN #endif // ezsigntemplatepackagesigner_create_object_v1_response_all_of_TEST
56.098361
273
0.897428
[ "model" ]
0d01e4842a08636aba7f83781ee8147e8d2a96d3
11,920
h
C
src/cpp/main/id.h
akzare/Pipeline_Processing
4b5c4c304659c567b1b397cd61931861b1f6af79
[ "MIT" ]
1
2020-09-03T06:39:33.000Z
2020-09-03T06:39:33.000Z
src/cpp/main/id.h
akzare/Pipeline_Processing
4b5c4c304659c567b1b397cd61931861b1f6af79
[ "MIT" ]
null
null
null
src/cpp/main/id.h
akzare/Pipeline_Processing
4b5c4c304659c567b1b397cd61931861b1f6af79
[ "MIT" ]
null
null
null
/** * @file id.h * * Copyright 2017 The Ray Authors. https://github.com/ray-project/ray * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * It has been modified & adapted to the Pipeline Processing Framework by: * Armin Zare Zadeh ali.a.zarezadeh@gmail.com * Eric J. Mayo eric@pozicom.net * * @brief id.h includes the implementation for the ID generator class */ #ifndef PL_ID_H_ #define PL_ID_H_ #include "util.h" #include <inttypes.h> #include <limits.h> #include <chrono> #include <cstring> #include <mutex> #include <random> #include <string> namespace pl_proc { class ObjectID; class UniqueID; class JobRunID; /// The type of thes processor object. enum class ModuleType : uint8_t { ADDER_MODULE = 0x00, BER_BF_MODULE = 0x01, CHUNKS2SYMB_MODULE = 0x02, ENCODER_TRELLIS_MODULE = 0x03, DECODER_LAZY_VITERBI_MODULE = 0x04, METRICS_MODULE = 0x05, SRC_NOISE_MODULE = 0x06, SRC_VEC_MODULE = 0x07, SINK_VEC_MODULE = 0x08, PACK_MODULE = 0x09, UNPACK_MODULE = 0x0A, }; using JobRunIDType = uint16_t; using ObjectIDModuleType = uint8_t; using ObjectIDModuleIndexType = uint8_t; using ObjectIDPaketIndexType = uint32_t; /// Length of FEC full-length IDs in bytes. constexpr size_t kObjectIDSize = 8; /// An ObjectID's bytes are split into the task ID itself and the index of the /// object's creation. This is the maximum width of the object index in bits. constexpr int kObjectIdModuleIndexSize = 8; static_assert(kObjectIdModuleIndexSize % CHAR_BIT == 0, "ObjectIDModuleIndex prefix not a multiple of bytes"); constexpr int kObjectIdPaketIndexSize = 32; static_assert(kObjectIdPaketIndexSize % CHAR_BIT == 0, "ObjectIDPaketIndex prefix not a multiple of bytes"); // Declaration. uint64_t MurmurHash64A(const void *key, int len, unsigned int seed); // Change the compiler alignment to 1 byte (default is 8). #pragma pack(push, 1) template <typename T> class BaseID { public: BaseID(); // Warning: this can duplicate IDs after a fork() call. We assume this never happens. static T FromRandom(); static T FromBinary(const std::string &binary); static const T &Nil(); static size_t Size() { return T::Size(); } size_t Hash() const; bool IsNil() const; bool operator==(const BaseID &rhs) const; bool operator!=(const BaseID &rhs) const; const uint8_t *Data() const; std::string Binary() const; std::string Hex() const; protected: BaseID(const std::string &binary) { CHECK(binary.size() == Size() || binary.size() == 0) << "expected size is " << Size() << ", but got " << binary.size(); std::memcpy(const_cast<uint8_t *>(this->Data()), binary.data(), binary.size()); } // All IDs are immutable for hash evaluations. MutableData is only allow to use // in construction time, so this function is protected. uint8_t *MutableData(); // For lazy evaluation, be careful to have one Id contained in another. // This hash code will be duplicated. mutable size_t hash_ = 0; }; class UniqueID : public BaseID<UniqueID> { public: static size_t Size() { return kObjectIDSize; } UniqueID() : BaseID() {} protected: UniqueID(const std::string &binary); protected: uint8_t id_[kObjectIDSize]; }; class JobRunID : public BaseID<JobRunID> { public: static constexpr int64_t kLength = 2; static JobRunID FromInt(uint16_t value); static JobRunID FromUniqueBytes(const JobRunID &job_id, const ObjectID &parent_task_id, const size_t parent_task_counter); static size_t Size() { return kLength; } // Warning: this can duplicate IDs after a fork() call. We assume this never happens. // static JobRunID FromRandom() = delete; JobRunID() : BaseID() {} // conversion operator: return float value of fraction operator std::stringstream() const { std::stringstream os; for (int i: id_) os << i; return os; } static JobRunID* getInstance() { if (instance_ == nullptr) { static JobRunID t = FromRandom(); instance_ = &t; } return instance_; } private: uint8_t id_[kLength]; static JobRunID *instance_; }; class ObjectID : public BaseID<ObjectID> { private: static constexpr size_t kModuleTypeBytesLength = sizeof(ObjectIDModuleType); static constexpr size_t kModuleIndexBytesLength = sizeof(ObjectIDModuleIndexType); static constexpr size_t kPaketIndexBytesLength = sizeof(ObjectIDPaketIndexType); public: /// The maximum number of modules that can be returned or put by a task. static constexpr int64_t kMaxModuleIndex = ((int64_t)1 << kObjectIdModuleIndexSize) - 1; /// The maximum number of pakets that can be returned or put by a task. static constexpr int64_t kMaxPaketIndex = ((int64_t)1 << kObjectIdPaketIndexSize) - 1; /// The length of ObjectID in bytes. static constexpr size_t kLength = kModuleIndexBytesLength + kPaketIndexBytesLength + kModuleTypeBytesLength + JobRunID::kLength; ObjectID() : BaseID() {} /// The maximum index of object. /// /// It also means the max number of objects created (put or return) by one task. /// /// \return The maximum index of object. static uint64_t MaxModuleIndex() { return kMaxModuleIndex; } static uint64_t MaxPaketIndex() { return kMaxPaketIndex; } static size_t Size() { return kLength; } /// Get the index of this object in the task that created it. /// /// \return The index of object creation according to the task that created /// this object. ObjectIDModuleIndexType GetModuleIndex() const; ObjectIDPaketIndexType GetPaketIndex() const; JobRunIDType GetRunID() const; /// Compute the task ID of the job that created the object. /// /// \return The task ID of the task that created this object. JobRunID JobRunId() const; /// Return if this is a direct actor call object. /// /// \return True if this is a direct actor object return. bool IsUnpackModuleType() const { return GetModuleType() == static_cast<uint8_t>(ModuleType::UNPACK_MODULE); } /// Get the moduleType out of this object id. ObjectIDModuleType GetModuleType() const; /// Compute the object ID of an object put by the task. /// /// \param task_id The task ID of the task that created the object. /// \param index What index of the object put in the task. /// \param transport_type Which type of the transport that is used to /// transfer this object. /// /// \return The computed object ID. static ObjectID ForModuleIndex(const JobRunID &run_id, ObjectIDModuleType module_type, ObjectIDModuleIndexType module_index, ObjectIDPaketIndexType paket_index); private: /// A helper method to generate an ObjectID. static ObjectID GenerateObjectId(const std::string &run_id_binary, ObjectIDModuleType module_type, ObjectIDModuleIndexType module_index, ObjectIDPaketIndexType paket_index); private: uint8_t id_[kLength]; }; //static_assert(sizeof(JobRunID) == JobRunID::kLength + sizeof(size_t) + sizeof(JobRunID*), // "JobRunID size is not as expected"); static_assert(sizeof(ObjectID) == ObjectID::kLength + sizeof(size_t), "ObjectID size is not as expected"); std::ostream &operator<<(std::ostream &os, const UniqueID &id); std::ostream &operator<<(std::ostream &os, const JobRunID &id); std::ostream &operator<<(std::ostream &os, const ObjectID &id); #define DEFINE_UNIQUE_ID(type) \ class type : public UniqueID { \ public: \ explicit type(const UniqueID &from) { \ std::memcpy(&id_, from.Data(), kObjectIDSize); \ } \ type() : UniqueID() {} \ static type FromRandom() { return type(UniqueID::FromRandom()); } \ static type FromBinary(const std::string &binary) { return type(binary); } \ static type Nil() { return type(UniqueID::Nil()); } \ static size_t Size() { return kObjectIDSize; } \ \ private: \ explicit type(const std::string &binary) { \ FEC_CHECK(binary.size() == Size() || binary.size() == 0) \ << "expected size is " << Size() << ", but got " << binary.size(); \ std::memcpy(&id_, binary.data(), binary.size()); \ } \ }; //DEFINE_UNIQUE_ID(FunctionID) #undef DEFINE_UNIQUE_ID // Restore the compiler alignment to default (8 bytes). #pragma pack(pop) template <typename T> BaseID<T>::BaseID() { // Using const_cast to directly change data is dangerous. The cached // hash may not be changed. This is used in construction time. std::fill_n(this->MutableData(), T::Size(), 0xff); } template <typename T> T BaseID<T>::FromRandom() { std::string data(T::Size(), 0); FillRandom(&data); return T::FromBinary(data); } template <typename T> T BaseID<T>::FromBinary(const std::string &binary) { CHECK(binary.size() == T::Size() || binary.size() == 0) << "expected size is " << T::Size() << ", but got " << binary.size(); T t = T::Nil(); std::memcpy(t.MutableData(), binary.data(), binary.size()); return t; } template <typename T> const T &BaseID<T>::Nil() { static const T nil_id; return nil_id; } template <typename T> bool BaseID<T>::IsNil() const { static T nil_id = T::Nil(); return *this == nil_id; } template <typename T> size_t BaseID<T>::Hash() const { // Note(ashione): hash code lazy calculation(it's invoked every time if hash code is // default value 0) if (!hash_) { hash_ = MurmurHash64A(Data(), T::Size(), 0); } return hash_; } template <typename T> bool BaseID<T>::operator==(const BaseID &rhs) const { return std::memcmp(Data(), rhs.Data(), T::Size()) == 0; } template <typename T> bool BaseID<T>::operator!=(const BaseID &rhs) const { return !(*this == rhs); } template <typename T> uint8_t *BaseID<T>::MutableData() { return reinterpret_cast<uint8_t *>(this) + sizeof(hash_); } template <typename T> const uint8_t *BaseID<T>::Data() const { return reinterpret_cast<const uint8_t *>(this) + sizeof(hash_); } template <typename T> std::string BaseID<T>::Binary() const { return std::string(reinterpret_cast<const char *>(Data()), T::Size()); } template <typename T> std::string BaseID<T>::Hex() const { constexpr char hex[] = "0123456789abcdef"; const uint8_t *id = Data(); std::string result; for (int i = 0; i < T::Size(); i++) { unsigned int val = id[i]; result.push_back(hex[val >> 4]); result.push_back(hex[val & 0xf]); } return result; } } // namespace pl_proc #endif // PL_ID_H_
32.043011
100
0.632886
[ "object" ]
0d05da8f07767cdced87fc4cc9465334113e9523
1,542
h
C
components/cloud/baidu/iotcore_client/src/iotcore_param_util.h
flyghost/OneOS-V2.1.0
6fedab0558c07fe679d63ba1eb8ee9992c044d86
[ "Apache-2.0" ]
null
null
null
components/cloud/baidu/iotcore_client/src/iotcore_param_util.h
flyghost/OneOS-V2.1.0
6fedab0558c07fe679d63ba1eb8ee9992c044d86
[ "Apache-2.0" ]
null
null
null
components/cloud/baidu/iotcore_client/src/iotcore_param_util.h
flyghost/OneOS-V2.1.0
6fedab0558c07fe679d63ba1eb8ee9992c044d86
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017 Baidu, Inc. All Rights Reserved. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef IOTCORE_PARAM_UTIL_H #define IOTCORE_PARAM_UTIL_H #include "iotcore_param.h" #ifdef __cplusplus extern "C" { #endif typedef struct _IOTCORE_CONNECT_MQTT_PARAM { char *broker_addr; char *user_name; char *passwd; char *client_id; } IOTCORE_CONNECT_MQTT_PARAM; // construct IOTCORE_CONNECT_MQTT_PARAM struct from IOTCORE_INFO struct int iotcore_construct_connect_mqtt_param(const IOTCORE_INFO* info, IOTCORE_CONNECT_MQTT_PARAM* param); // free IOTCORE_CONNECT_MQTT_PARAM object members // not free IOTCORE_CONNECT_MQTT_PARAM object self void iotcore_clear_connect_mqtt_param(IOTCORE_CONNECT_MQTT_PARAM* param); #ifdef __cplusplus } #endif #endif // IOTCORE_PARAM_UTIL_H
30.235294
102
0.789235
[ "object" ]
0d0b77c1ea68777712ae6c892069dbec98a28abd
1,829
h
C
bcos-pbft/bcos-pbft/pbft/interfaces/PBFTProposalInterface.h
xueying4402/FISCO-BCOS
737e08752e8904c7c24e3737f8f46bf5327ef792
[ "Apache-2.0" ]
10
2021-08-10T03:36:58.000Z
2022-03-18T08:50:21.000Z
bcos-pbft/bcos-pbft/pbft/interfaces/PBFTProposalInterface.h
xueying4402/FISCO-BCOS
737e08752e8904c7c24e3737f8f46bf5327ef792
[ "Apache-2.0" ]
96
2021-04-08T08:51:07.000Z
2021-12-15T02:53:18.000Z
bcos-pbft/bcos-pbft/pbft/interfaces/PBFTProposalInterface.h
xueying4402/FISCO-BCOS
737e08752e8904c7c24e3737f8f46bf5327ef792
[ "Apache-2.0" ]
7
2021-02-22T07:37:43.000Z
2021-11-03T02:53:50.000Z
/** * Copyright (C) 2021 FISCO BCOS. * SPDX-License-Identifier: Apache-2.0 * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @brief interface for PBFTProposal * @file PBFTProposalInterfaces.h * @author: yujiechen * @date 2021-04-15 */ #pragma once #include "../../framework/ProposalInterface.h" #include "../utilities/Common.h" namespace bcos { namespace consensus { class PBFTProposalInterface : virtual public ProposalInterface { public: using Ptr = std::shared_ptr<PBFTProposalInterface>; PBFTProposalInterface() = default; ~PBFTProposalInterface() override {} virtual size_t signatureProofSize() const = 0; virtual std::pair<int64_t, bytesConstRef> signatureProof(size_t _index) const = 0; virtual void appendSignatureProof(int64_t _nodeIdx, bytesConstRef _signatureData) = 0; virtual void clearSignatureProof() = 0; }; using PBFTProposalList = std::vector<PBFTProposalInterface::Ptr>; using PBFTProposalListPtr = std::shared_ptr<PBFTProposalList>; template <typename T> inline std::string printPBFTProposal(T _proposal) { std::ostringstream stringstream; stringstream << LOG_KV("propHash", _proposal->hash().abridged()) << LOG_KV("propIndex", _proposal->index()); return stringstream.str(); } } // namespace consensus } // namespace bcos
34.509434
90
0.732641
[ "vector" ]
0d152554464fb98eef3152f452ba669dfa5eedfd
64,798
c
C
src/dxf_attract.c
gexiangying/CadZinho
aaed69b5aa5a0c86bf32d763fe0fba005a04655f
[ "MIT" ]
null
null
null
src/dxf_attract.c
gexiangying/CadZinho
aaed69b5aa5a0c86bf32d763fe0fba005a04655f
[ "MIT" ]
null
null
null
src/dxf_attract.c
gexiangying/CadZinho
aaed69b5aa5a0c86bf32d763fe0fba005a04655f
[ "MIT" ]
1
2021-06-25T06:10:33.000Z
2021-06-25T06:10:33.000Z
#include "dxf_attract.h" #include "list.h" #define IN_BOUNDS(x,y,p1x,p1y,p2x,p2y) ((((x <= p1x) && (x >= p2x))||((x <= p2x) && (x >= p1x))) && (((y <= p1y) && (y >= p2y))||((y <= p2y) && (y >= p1y)))) #define TOL 1e-6 #define NEAR_LN(x,y,p1x,p1y,p2x,p2y,s) (((fabs(p1x-p2x)<TOL) && (fabs(p1x - x) < s) && (((y <= p1y) && (y >= p2y))||((y <= p2y) && (y >= p1y)))) || ((fabs(p1y-p2y)<TOL) && (fabs(p1y - y) < s) && (((x <= p1x) && (x >= p2x))||((x <= p2x) && (x >= p1x))))) #define MAX_CAND 50 #define SIG(x) (x >= 0) ? 1 : -1 int point_lies_seg(double p1x, double p1y, double p2x, double p2y, double x, double y){ if(fabs(p1x - p2x) < TOL){ if ((fabs(x - p2x) < TOL) && (((y >= p1y) && (y <= p2y)) || ((y <= p1y) && (y >= p2y)))){ return 1; } } else if(fabs(p1y - p2y) < TOL){ if ((fabs(y - p2y) < TOL) && (((x >= p1x) && (x <= p2x)) || ((x <= p1x) && (x >= p2x)))){ return 1; } } else if ((((x >= p1x) && (x <= p2x)) || ((x <= p1x) && (x >= p2x))) && (((y >= p1y) && (y <= p2y)) || ((y <= p1y) && (y >= p2y)))){ return 1; } return 0; } #if(0) int axis_transform(double *x, double *y, double *z, double normal[3]){ if ((x != NULL) && (y != NULL) && (z != NULL)){ double x0, y0, z0; double x_axis[3], y_axis[3], z_axis[3], point[3]; double wy_axis[3] = {0.0, 1.0, 0.0}; double wz_axis[3] = {0.0, 0.0, 1.0}; /* axis tranform */ /* choose absolute world axis, according DXF spec, and obtain x axis */ if ((fabs(normal[0] < 0.015625)) && (fabs(normal[1] < 0.015625))){ cross_product(wy_axis, normal, x_axis); } else{ cross_product(wz_axis, normal, x_axis); } unit_vector(x_axis); /* normalize axis */ cross_product(normal, x_axis, y_axis); /*obtain y axis */ unit_vector(y_axis); /* normalize axis */ /* z_axis is the same normal, but normalized*/ z_axis[0] = normal[0]; z_axis[1] = normal[1]; z_axis[2] = normal[2]; unit_vector(z_axis); /* normalize axis */ /*obtain result point */ point[0] = *x; point[1] = *y; point[2] = *z; *x = dot_product(point, x_axis); *y = dot_product(point, y_axis); *z = dot_product(point, z_axis); return 1; } return 0; } #endif int transform(double *x, double *y, struct ins_space space){ if ((x != NULL) && (y != NULL)){ double x0, y0; /* rotation constants */ double cosine = cos(space.rot * M_PI/180); double sine = sin(space.rot * M_PI/180); /* scale and translation transformations */ *x = *x * space.scale_x + space.ofs_x; *y = *y * space.scale_y + space.ofs_y; /* rotation transform */ x0 = cosine*(*x - space.ofs_x) - sine*(*y - space.ofs_y) + space.ofs_x; y0 = sine*(*x - space.ofs_x) + cosine*(*y - space.ofs_y) + space.ofs_y; /* update return values*/ *x = x0; *y = y0; return 1; } return 0; } int ellipse_transf(double *center_x, double *center_y, double *center_z, double *axis, double *ratio, double *rot, double normal[3]){ int ok = 0; if ((center_x != NULL) && (center_y != NULL) && (center_z != NULL) && (axis != NULL) && (ratio != NULL) && (rot != NULL) && (normal != NULL)){ double pt[3]; /* convert OCS to WCS */ pt[0] = *center_x; pt[1] = *center_y; pt[2] = *center_z; //axis_transform(center_x, center_y, center_z, normal); mod_axis(pt, normal, 0.0); *center_x = pt[0]; *center_y = pt[1]; *center_z = pt[2]; /* transform the circle in ellipse, by the OCS */ pt[0] = 1.0; pt[1] = 1.0; pt[2] = 0.0; //axis_transform(&pt[0], &pt[1], &pt[2], normal); mod_axis(pt, normal, 0.0); *axis *= fabs(pt[0]); *ratio *= fabs(pt[1] / pt[0]); *rot += atan2(normal[0], normal[1]); ok = 1; } return ok; } int in_ellip_bound(double pos_x, double pos_y, double sensi, double center_x, double center_y, double axis, double ratio, double rot){ /* rotation constants */ double cosine = cos(rot); double sine = sin(rot); /* calc the half width and height of rectangle of ellipse bounds */ /*https://math.stackexchange.com/questions/91132/how-to-get-the-limits-of-rotated-ellipse xa = Sqrt[a^2 Cos[th]^2 + b^2 Sin[th]^2] ya = Sqrt[a^2 Sin[th]^2 + b^2 Cos[th]^2]*/ double x = sqrt(pow(axis, 2)*pow(cosine, 2) + pow(axis*ratio, 2)*pow(sine, 2)); double y = sqrt(pow(axis, 2)*pow(sine, 2) + pow(axis*ratio, 2)*pow(cosine, 2)); /*determine the rectangle coordinates, considering the sensibility */ double tr_x = center_x + x + sensi; double tr_y = center_y + y + sensi; double bl_x = center_x - x - sensi; double bl_y = center_y - y - sensi; /* verify if point is in bounds */ if((pos_x >= bl_x) && (pos_x <= tr_x) && (pos_y >= bl_y) && (pos_y <= tr_y)){ return 1; } return 0; } int arc_near(double axis, double ratio, double rot, double ang_start, double ang_end, double center_x, double center_y, double pos_x, double pos_y, double *ret_x, double *ret_y){ /* elliptical arc */ int ret = ATRC_NONE; double curr_dist; double test, start, end; /* rotation constants */ double cosine = cos(rot); double sine = sin(rot); /*ellipse's parameters */ double a = axis, b = axis * ratio; /* find the angle of point, referenced to arc center */ double ang_pt = atan2(pos_y - center_y, pos_x - center_x); angle_range(&rot); /* set angle range to 0-2*pi */ /* update by rotation */ ang_pt = ang_pt - rot; angle_range(&ang_pt); /* set angle range to 0-2*pi */ /* find the ellipse polar parameter (t) for point*/ double t = ellipse_par(ang_pt, a, b); /* verify if arc is a full circle */ if ((fabs(ang_end - ang_start) < 1e-6) || (fabs(ang_end - ang_start) >= (2*M_PI - 1e-6))){ ang_start = 0.0; ang_end = 2*M_PI; start = ang_start; end = ang_end; test = 0.0; } else{ angle_range(&ang_start); /* set angle range to 0-2*pi */ angle_range(&ang_end); /* set angle range to 0-2*pi */ /* verify if point angle is between start and end of arc */ test = t - ang_start; if (test < 0 ) test += 2*M_PI; end = ang_end - ang_start; if (end < 0 ) end += 2*M_PI; } if (test <= end){ /* point in ellipse near current position */ *ret_x = center_x + a*cos(t)*cosine - b*sin(t)*sine; *ret_y = center_y + a*cos(t)*sine + b*sin(t)*cosine; return 1; } return 0; } #if (0) double dxf_text_width(shape *font, char *text){ if ((text!= NULL) && (font!=NULL)) { graph_obj *curr_graph = shx_font_parse(font, ONE_TIME, text, NULL); if (curr_graph){ double txt_w; txt_w = fabs(curr_graph->ext_max_x - curr_graph->ext_min_x); return txt_w; } graph_mem_pool(ZERO_GRAPH, ONE_TIME); graph_mem_pool(ZERO_LINE, ONE_TIME); } return 0; } #endif int dxf_line_get (dxf_drawing *drawing, dxf_node * obj, double *pt1_x, double *pt1_y, double *pt1_z, double *pt2_x, double *pt2_y, double *pt2_z){ dxf_node *current = NULL; /*flags*/ int pt1 = 0, pt2 = 0, ok = 0; if (obj){ if (obj->type == DXF_ENT){ if (obj->obj.content){ current = obj->obj.content->next; *pt1_x = 0, *pt1_y = 0, *pt1_z = 0; *pt2_x = 0, *pt2_y = 0, *pt2_z = 0; } } } while (current){ if (current->type == DXF_ATTR){ /* DXF attibute */ switch (current->value.group){ case 10: *pt1_x = current->value.d_data; pt1 = 1; /* set flag */ break; case 11: *pt2_x = current->value.d_data; pt2 = 1; /* set flag */ break; case 20: *pt1_y = current->value.d_data; pt1 = 1; /* set flag */ break; case 21: *pt2_y = current->value.d_data; pt2 = 1; /* set flag */ break; case 30: *pt1_z = current->value.d_data; pt1 = 1; /* set flag */ break; case 31: *pt2_z = current->value.d_data; pt2 = 1; /* set flag */ break; } } current = current->next; /* go to the next in the list */ } if((pt1 !=0) && (pt2 !=0)) ok = 1; return ok; } int dxf_circle_get(dxf_drawing *drawing, dxf_node * obj, double *center_x, double *center_y, double *center_z, double *axis, double *ratio, double *rot){ int ok = 0; if(obj){ dxf_node *current = NULL; double pt1_x = 0, pt1_y = 0, pt1_z = 0, radius = 0; double elev = 0; double extru_x = 0.0, extru_y = 0.0, extru_z = 1.0, normal[3]; /*flags*/ int pt1 = 0; if (obj->type == DXF_ENT){ if (obj->obj.content){ current = obj->obj.content->next; } } while (current){ if (current->type == DXF_ATTR){ /* DXF attibute */ switch (current->value.group){ case 10: pt1_x = current->value.d_data; pt1 = 1; /* set flag */ break; case 20: pt1_y = current->value.d_data; pt1 = 1; /* set flag */ break; case 30: pt1_z = current->value.d_data; pt1 = 1; /* set flag */ break; case 40: radius = current->value.d_data; break; case 38: elev = current->value.d_data; break; case 210: extru_x = current->value.d_data; break; case 220: extru_y = current->value.d_data; break; case 230: extru_z = current->value.d_data; break; } } current = current->next; /* go to the next in the list */ } /* convert OCS to WCS, transform the circle in ellipse */ normal[0] = extru_x; normal[1] = extru_y; normal[2] = extru_z; *center_x = pt1_x; *center_y = pt1_y; *center_z = pt1_z; *axis = radius; *ratio = 1.0; *rot = 0.0; ok = ellipse_transf(center_x, center_y, center_z, axis, ratio, rot, normal); } return ok; } int dxf_arc_get(dxf_drawing *drawing, dxf_node * obj, double *center_x, double *center_y, double *center_z, double *axis, double *ratio, double *rot, double *start_ang, double *end_ang){ int ok = 0; if(obj){ dxf_node *current = NULL; double pt1_x = 0, pt1_y = 0, pt1_z = 0, radius; double elev = 0; double extru_x = 0.0, extru_y = 0.0, extru_z = 1.0, normal[3]; /*flags*/ int pt1 = 0; if (obj->type == DXF_ENT){ if (obj->obj.content){ current = obj->obj.content->next; } } while (current){ if (current->type == DXF_ATTR){ /* DXF attibute */ switch (current->value.group){ case 10: pt1_x = current->value.d_data; pt1 = 1; /* set flag */ break; case 20: pt1_y = current->value.d_data; pt1 = 1; /* set flag */ break; case 30: pt1_z = current->value.d_data; pt1 = 1; /* set flag */ break; case 40: radius = current->value.d_data; break; case 50: *start_ang = current->value.d_data; break; case 51: *end_ang = current->value.d_data; break; case 38: elev = current->value.d_data; break; case 210: extru_x = current->value.d_data; break; case 220: extru_y = current->value.d_data; break; case 230: extru_z = current->value.d_data; break; } } current = current->next; /* go to the next in the list */ } /* convert OCS to WCS, transform the circle in ellipse */ normal[0] = extru_x; normal[1] = extru_y; normal[2] = extru_z; *center_x = pt1_x; *center_y = pt1_y; *center_z = pt1_z; *axis = radius; *ratio = 1.0; *rot = 0.0; ok = ellipse_transf(center_x, center_y, center_z, axis, ratio, rot, normal); /*convert to radians */ *start_ang *= M_PI/180; *end_ang *= M_PI/180; } return ok; } int dxf_ellipse_get(dxf_drawing *drawing, dxf_node * obj, double *center_x, double *center_y, double *center_z, double *axis, double *ratio, double *rot, double *start_ang, double *end_ang){ int ok = 0; if(obj){ dxf_node *current = NULL; double pt1_x = 0, pt1_y = 0, pt1_z = 0; double pt2_x = 0, pt2_y = 0, pt2_z = 0; double elev = 0; double extru_x = 0.0, extru_y = 0.0, extru_z = 1.0, normal[3]; /*flags*/ int pt1 = 0, pt2 = 0; if (obj->type == DXF_ENT){ if (obj->obj.content){ current = obj->obj.content->next; } } while (current){ if (current->type == DXF_ATTR){ /* DXF attibute */ switch (current->value.group){ case 10: pt1_x = current->value.d_data; pt1 = 1; /* set flag */ break; case 11: pt2_x = current->value.d_data; pt2 = 1; /* set flag */ break; case 20: pt1_y = current->value.d_data; pt1 = 1; /* set flag */ break; case 21: pt2_y = current->value.d_data; pt2 = 1; /* set flag */ break; case 30: pt1_z = current->value.d_data; pt1 = 1; /* set flag */ break; case 31: pt2_z = current->value.d_data; pt2 = 1; /* set flag */ break; case 40: *ratio = current->value.d_data; break; case 41: *start_ang = current->value.d_data; break; case 42: *end_ang = current->value.d_data; break; case 38: elev = current->value.d_data; break; case 210: extru_x = current->value.d_data; break; case 220: extru_y = current->value.d_data; break; case 230: extru_z = current->value.d_data; break; } } current = current->next; /* go to the next in the list */ } /* convert OCS to WCS */ normal[0] = extru_x; normal[1] = extru_y; normal[2] = extru_z; *center_x = pt1_x; *center_y = pt1_y; *center_z = pt1_z; *axis = sqrt(pow(pt2_x, 2) + pow(pt2_y, 2)); *rot = atan2(pt2_y, pt2_x); ok = ellipse_transf(center_x, center_y, center_z, axis, ratio, rot, normal); /*convert to radians */ //*start_ang *= M_PI/180; //*end_ang *= M_PI/180; } return ok; } int dxf_text_get(dxf_drawing *drawing, dxf_node * obj, char *text, int *fnt_idx, double *above, double *below, double *ins_x, double *ins_y, double *ins_z, double *alin_x, double *alin_y, double *alin_z, double *w, double *h, double *rot, int *alin_v, int *alin_h){ int ok = 0; #if(0) if(obj){ dxf_node *current = NULL; double pt1_x = 0, pt1_y = 0, pt1_z = 0; double pt2_x = 0, pt2_y = 0, pt2_z = 0; double elev = 0, size = 0, scale_x = 1.0; double extru_x = 0.0, extru_y = 0.0, extru_z = 1.0, normal[3]; char t_style[DXF_MAX_CHARS]; char tmp_str[DXF_MAX_CHARS]; char *pos_st, *pos_curr, *pos_tmp, special; int under_l, over_l; double fnt_size, txt_size; shape *shx_font = NULL; t_style[0] = 0; tmp_str[0] = 0; /*flags*/ int pt1 = 0, pt2 = 0; if (obj->type == DXF_ENT){ if (obj->obj.content){ current = obj->obj.content->next; } } while (current){ if (current->type == DXF_ATTR){ /* DXF attibute */ switch (current->value.group){ case 1: strcpy(text, current->value.s_data); break; case 7: strcpy(t_style, current->value.s_data); break; case 10: pt1_x = current->value.d_data; pt1 = 1; /* set flag */ break; case 11: pt2_x = current->value.d_data; pt2 = 1; /* set flag */ break; case 20: pt1_y = current->value.d_data; pt1 = 1; /* set flag */ break; case 21: pt2_y = current->value.d_data; pt2 = 1; /* set flag */ break; case 30: pt1_z = current->value.d_data; pt1 = 1; /* set flag */ break; case 31: pt2_z = current->value.d_data; pt2 = 1; /* set flag */ break; case 40: size = current->value.d_data; break; case 41: scale_x = current->value.d_data; break; case 50: *rot = current->value.d_data; break; case 38: elev = current->value.d_data; break; case 72: *alin_h = current->value.i_data; break; case 73: *alin_v = current->value.i_data; break; case 210: extru_x = current->value.d_data; break; case 220: extru_y = current->value.d_data; break; case 230: extru_z = current->value.d_data; break; } } current = current->next; /* go to the next in the list */ } /* find the tstyle index and font*/ *fnt_idx = dxf_tstyle_idx(drawing, t_style); shx_font = drawing->text_styles[*fnt_idx].shx_font; if(shx_font == NULL){ /* if font not loaded*/ /* use the deafault font*/ shx_font = drawing->text_styles[0].shx_font; } /* find the dimentions of SHX font */ if(shx_font){ /* if the font exists */ if(shx_font->next){ /* the font descriptor is stored in first iten of list */ if(shx_font->next->cmd_size > 1){ /* check if the font is valid */ *above = shx_font->next->cmds[0]; /* size above the base line of text */ *below = shx_font->next->cmds[1]; /* size below the base line of text */ if((*above + *below) > 0){ fnt_size = *above + *below; ok = 1; } } } } /* find and replace special symbols in the text*/ under_l = 0; /* under line flag*/ over_l = 0; /* over line flag*/ pos_curr = strstr(text, "%%"); pos_st = text; pos_tmp = tmp_str; while (pos_curr){ /* copy the part of text until the control string */ strncpy(pos_tmp, pos_st, pos_curr - pos_st); /*control string is stripped in new string */ pos_tmp += pos_curr - pos_st; /*get the control character */ special = *(pos_curr + 2); /* verify the action to do */ switch (special){ /* put the diameter simbol (unicode D8 Hex) in text*/ case 'c': pos_tmp += wctomb(pos_tmp, L'\xd8'); break; case 'C': pos_tmp += wctomb(pos_tmp, L'\xd8'); break; /* put the degrees simbol in text*/ case 'd': pos_tmp += wctomb(pos_tmp, L'\xb0'); break; case 'D': pos_tmp += wctomb(pos_tmp, L'\xb0'); break; /* put the plus/minus tolerance simbol in text*/ case 'p': pos_tmp += wctomb(pos_tmp, L'\xb1'); break; case 'P': pos_tmp += wctomb(pos_tmp, L'\xb1'); break; /* under line */ case 'u': under_l = 1; break; case 'U': under_l = 1; break; /* over line */ case 'o': over_l = 1; break; case 'O': over_l = 1; break; } /*try to find new control sequences in the rest of text*/ pos_curr += 3; pos_st = pos_curr; pos_curr = strstr(pos_curr, "%%"); } /* copy the rest of text after the last control string */ strcpy(pos_tmp, pos_st); /* find the dimentions of text */ txt_size = size/(*above); /* convert OCS to WCS */ normal[0] = extru_x; normal[1] = extru_y; normal[2] = extru_z; *ins_x = pt1_x; *ins_y = pt1_y; *ins_z = pt1_z; *alin_x = pt2_x; *alin_y = pt2_y; *alin_z = pt2_z; axis_transform(ins_x, ins_y, ins_z, normal); axis_transform(alin_x, alin_y, alin_z, normal); pt1_x = 1.0; pt1_y = 1.0; pt1_z = 0.0; axis_transform(&pt1_x, &pt1_y, &pt1_z, normal); scale_x *= fabs(pt1_x); txt_size *= fabs(pt1_y / pt1_x); *rot += atan2(normal[0], normal[1]); *w = dxf_text_width(shx_font, tmp_str) * txt_size * scale_x; *h = size * fabs(pt1_y / pt1_x); *above *= txt_size; *below *= txt_size; } #endif return ok; } int dxf_line_attract(double pt1_x, double pt1_y, double pt2_x, double pt2_y, enum attract_type type, double pos_x, double pos_y, double ref_x, double ref_y, double sensi, double *ret_x, double *ret_y, int *init_dist, double *min_dist){ int ret = ATRC_NONE; double curr_dist; if(type & ATRC_END){ /* if type of attractor is flaged as endpoint */ /* check if points of the line pass on distance criteria */ curr_dist = sqrt(pow(pt1_x - pos_x, 2) + pow(pt1_y - pos_y, 2)); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = pt1_x; *ret_y = pt1_y; ret = ATRC_END; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = pt1_x; *ret_y = pt1_y; ret = ATRC_END; } } curr_dist = sqrt(pow(pt2_x - pos_x, 2) + pow(pt2_y - pos_y, 2)); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = pt2_x; *ret_y = pt2_y; ret = ATRC_END; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = pt2_x; *ret_y = pt2_y; ret = ATRC_END; } } } if(type & ATRC_MID){ /* if type of attractor is flaged as midpoint */ double mid_x = (pt1_x + pt2_x)/2; double mid_y = (pt1_y + pt2_y)/2; curr_dist = sqrt(pow(mid_x - pos_x, 2) + pow(mid_y - pos_y, 2)); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = mid_x; *ret_y = mid_y; ret = ATRC_MID; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = mid_x; *ret_y = mid_y; ret = ATRC_MID; } } } if(type & ATRC_PERP){ /* if type of attractor is flaged as perpenticular */ double perp_x, perp_y; double a1, b1, c1, a2, b2, c2; /* parameters of line in general form ax+by = c */ a1 = pt1_y - pt2_y; b1 = pt2_x - pt1_x; c1 = (pt2_x - pt1_x)*pt1_y + (pt1_y - pt2_y)*pt1_x; /* parameters of perpenticular line passing through the reference point */ a2 = -b1; b2 = a1; c2 = a1*ref_y - b1*ref_x; /* find the intersection */ if (line_inter(a1, b1, c1, a2, b2, c2, &perp_x, &perp_y)){ /* check if pass on distance criteria */ curr_dist = sqrt(pow(perp_x - pos_x, 2) + pow(perp_y - pos_y, 2)); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = perp_x; *ret_y = perp_y; ret = ATRC_PERP; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = perp_x; *ret_y = perp_y; ret = ATRC_PERP; } } } } if(type & ATRC_ANY){ /* if type of attractor is flaged as any point */ /*consider line equation ax + by + c = 0 */ double a = pt2_y - pt1_y; double b = -(pt2_x - pt1_x); double c = pt2_x * pt1_y - pt2_y * pt1_x; if ((a != 0) || (b != 0)){ /* calcule distance between point and line */ curr_dist = fabs(a*pos_x + b*pos_y + c)/ sqrt(pow(a, 2) + pow(b, 2)); if (curr_dist < sensi){ /* look the closest point on line */ /* equation from https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line */ double any_x, any_y; if (b != 0){ any_x = (b * (b*pos_x - a*pos_y) - a*c)/ (pow(a, 2) + pow(b, 2)); } else{ any_x = pt1_x; } if (a != 0){ any_y = (a * (-b*pos_x + a*pos_y) - b*c)/ (pow(a, 2) + pow(b, 2)); } else { any_y = pt1_y; } /* verify if point is in segment */ if ((((any_x <= pt1_x) && (any_x >= pt2_x))|| ((any_x <= pt2_x) && (any_x >= pt1_x))) && (((any_y <= pt1_y) && (any_y >= pt2_y))|| ((any_y <= pt2_y) && (any_y >= pt1_y)))){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = any_x; *ret_y = any_y; ret = ATRC_ANY; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = any_x; *ret_y = any_y; ret = ATRC_ANY; } } } } } return ret; } int dxf_text_attract(double pt1_x, double pt1_y, double pt2_x, double pt2_y, double w, double h, double rot, int alin_v, int alin_h, double above, double below, enum attract_type type, double pos_x, double pos_y, double sensi, double *ret_x, double *ret_y, int *init_dist, double *min_dist){ int ret = ATRC_NONE; double curr_dist; if(type & ATRC_INS){ /* if type of attractor is flaged as insert */ /* check if points of the line pass on distance criteria */ curr_dist = sqrt(pow(pt1_x - pos_x, 2) + pow(pt1_y - pos_y, 2)); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = pt1_x; *ret_y = pt1_y; ret = ATRC_INS; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = pt1_x; *ret_y = pt1_y; ret = ATRC_INS; } } } if(type & ATRC_NODE){ /* if type of attractor is flaged as node*/ curr_dist = sqrt(pow(pt2_x - pos_x, 2) + pow(pt2_y - pos_y, 2)); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = pt2_x; *ret_y = pt2_y; ret = ATRC_NODE; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = pt2_x; *ret_y = pt2_y; ret = ATRC_NODE; } } } if(type & ATRC_ANY){ /* if type of attractor is flaged as any point */ double t_base_x, t_base_y, t_center_x = 0, t_center_y = 0; double t_pos_x, t_pos_y, t_scale_x = 1, any_x, any_y; int i, j; t_base_x = pt2_x; t_base_y = pt2_y; if ((alin_v == 0) && (alin_h == 0)){ t_base_x = pt1_x; t_base_y = pt1_y; } /* find the insert point of text, in function of its aling */ else if(alin_h < 3){ t_center_x = (double)alin_h * w/2; } else{ if(alin_h == 4){ t_center_y = h/2; } else{ t_scale_x = sqrt(pow((pt2_x - pt1_x), 2) + pow((pt2_y - pt1_y), 2))/w; t_base_x = pt1_x + (pt2_x - pt1_x)/2; t_base_y = pt1_y + (pt2_y - pt1_y)/2; } t_center_x = t_scale_x*w/2; } if(alin_v >0){ if(alin_v != 1){ t_center_y = (double)(alin_v - 1) * h/2; } else{ t_center_y = -below; } } /* rotation constants */ double cosine = cos(rot*M_PI/180); double sine = sin(rot*M_PI/180); for(i = 0; i < 3; i++){ for(j = 0; j < 3; j++){ t_pos_x = (t_base_x - t_center_x) + (double)i * w/2; t_pos_y = (t_base_y - t_center_y) + (double)j * h/2; any_x = cosine*(t_pos_x - t_base_x) - sine*(t_pos_y - t_base_y) + t_base_x; any_y = sine*(t_pos_x - t_base_x) + cosine*(t_pos_y - t_base_y) + t_base_y; curr_dist = sqrt(pow(any_x - pos_x, 2) + pow(any_y - pos_y, 2)); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = any_x; *ret_y = any_y; ret = ATRC_ANY; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = any_x; *ret_y = any_y; ret = ATRC_ANY; } } } } } return ret; } int dxf_arc_attract(double radius, double ang_start, double ang_end, double center_x, double center_y, double ratio, double rot, enum attract_type type, double pos_x, double pos_y, double ref_x, double ref_y, double sensi, double *ret_x, double *ret_y, int *init_dist, double *min_dist){ /* elliptical arc */ int i, j, count; int ret = ATRC_NONE; double curr_dist; double test, start, end; /* rotation constants */ double cosine = cos(rot); double sine = sin(rot); /*ellipse's parameters */ double a = radius, b = radius * ratio; /* find the angle of point, referenced to arc center */ double ang_pt = atan2(pos_y - center_y, pos_x - center_x); angle_range(&rot); /* set angle range to 0-2*pi */ /* update by rotation */ ang_pt = ang_pt - rot; angle_range(&ang_pt); /* set angle range to 0-2*pi */ /* find the ellipse polar parameter (t) for point*/ double t = ellipse_par(ang_pt, a, b); /* verify if arc is a full circle */ if ((fabs(ang_end - ang_start) < 1e-6) || (fabs(ang_end - ang_start) >= (2*M_PI - 1e-6))){ ang_start = 0.0; ang_end = 2*M_PI; type &= ~ATRC_END; /* disable the endpoint attractor */ start = ang_start; end = ang_end; test = 0.0; } else{ angle_range(&ang_start); /* set angle range to 0-2*pi */ angle_range(&ang_end); /* set angle range to 0-2*pi */ /* verify if point angle is between start and end of arc */ test = t - ang_start; if (test < 0 ) test += 2*M_PI; end = ang_end - ang_start; if (end < 0 ) end += 2*M_PI; } if (test <= end){ /* point in ellipse near current position */ double near_x = center_x + a*cos(t)*cosine - b*sin(t)*sine; double near_y = center_y + a*cos(t)*sine + b*sin(t)*cosine; if(type & ATRC_END){ /* if type of attractor is flaged as endpoint */ /* start and end points of arc, in cartesian coodinates */ double pt1_x = center_x + a*cos(ang_start)*cosine - b*sin(ang_start)*sine; double pt1_y = center_y + a*cos(ang_start)*sine + b*sin(ang_start)*cosine; double pt2_x = center_x + a*cos(ang_end)*cosine - b*sin(ang_end)*sine; double pt2_y = center_y + a*cos(ang_end)*sine + b*sin(ang_end)*cosine; /* check if points of the arc pass on distance criteria */ curr_dist = sqrt(pow(pt1_x - pos_x, 2) + pow(pt1_y - pos_y, 2)); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = pt1_x; *ret_y = pt1_y; ret = ATRC_END; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = pt1_x; *ret_y = pt1_y; ret = ATRC_END; } } curr_dist = sqrt(pow(pt2_x - pos_x, 2) + pow(pt2_y - pos_y, 2)); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = pt2_x; *ret_y = pt2_y; ret = ATRC_END; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = pt2_x; *ret_y = pt2_y; ret = ATRC_END; } } } if(type & ATRC_QUAD){ /* if type of attractor is flaged as quadrant */ double quad_x[4], quad_y[4], t_q; quad_x[0] = center_x + a*cosine; quad_y[0] = center_y + a*sine; //quad_x[1] = center_x - b*sine; //quad_y[1] = center_y + b*cosine; t_q = ellipse_par(M_PI/2, a, b); quad_x[1] = center_x + a*cos(t_q)*cosine - b*sin(t_q)*sine; quad_y[1] = center_y + a*cos(t_q)*sine + b*sin(t_q)*cosine; quad_x[2] = center_x - a*cosine; quad_y[2] = center_y - a*sine; //quad_x[3] = center_x + b*sine; //quad_y[3] = center_y - b*cosine; t_q = ellipse_par(3*M_PI/2, a, b); quad_x[3] = center_x + a*cos(t_q)*cosine - b*sin(t_q)*sine; quad_y[3] = center_y + a*cos(t_q)*sine + b*sin(t_q)*cosine; /* check if point pass on distance criteria */ int i; for (i = 0; i < 4; i++){ curr_dist = sqrt(pow(quad_x[i] - pos_x, 2) + pow(quad_y[i] - pos_y, 2)); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = quad_x[i]; *ret_y = quad_y[i]; ret = ATRC_QUAD; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = quad_x[i]; *ret_y = quad_y[i]; ret = ATRC_QUAD; } } } } if ((type & ATRC_ANY) && (!ret)){ /* if type of attractor is flaged as any */ /* check if point pass on distance criteria */ curr_dist = sqrt(pow(near_x - pos_x, 2) + pow(near_y - pos_y, 2)); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = near_x; *ret_y = near_y; ret = ATRC_ANY; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = near_x; *ret_y = near_y; ret = ATRC_ANY; } } } if ((type & ATRC_CENTER) && (!ret)){ /* if type of attractor is flaged as center */ /* check if point pass on distance criteria */ curr_dist = fabs(sqrt(pow(near_x - pos_x, 2) + pow(near_y - pos_y, 2))); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = center_x; *ret_y = center_y; ret = ATRC_CENTER; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = center_x; *ret_y = center_y; ret = ATRC_CENTER; } } } if (type & ATRC_TAN){ /* if type of attractor is flaged as tangent */ double t_x[2], t_y[2]; int num_inter = 0; double ln_a, ln_b, ln_c, x, y; /* rotation constants */ cosine = cos(-rot); sine = sin(-rot); /* rotation of ref point to align to ellipse axis */ x = cosine*(ref_x - center_x) - sine*(ref_y - center_y) + center_x; y = sine*(ref_x - center_x) + cosine*(ref_y - center_y) + center_y; /* translate point to ellipse center */ x -= center_x; y -= center_y; /* chord of contact points - line in form ax+ bx =c */ ln_a = x/pow(a, 2); ln_b = y/pow(b, 2); ln_c = 1.0; num_inter = el_ln_inter(0, 0, radius, ratio, 0, ln_a, ln_b, ln_c, t_x, t_y); /* rotate and translate back the result points */ cosine = cos(rot); sine = sin(rot); for (i = 0; i < num_inter; i++){ x = t_x[i]; y = t_y[i]; x += center_x; y += center_y; /* rotation of ref point to align to ellipse axis */ t_x[i] = cosine*(x - center_x) - sine*(y - center_y) + center_x; t_y[i] = sine*(x - center_x) + cosine*(y - center_y) + center_y; /* check if point pass on distance criteria */ curr_dist = sqrt(pow(t_x[i] - pos_x, 2) + pow(t_y[i] - pos_y, 2)); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = t_x[i]; *ret_y = t_y[i]; ret = ATRC_TAN; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = t_x[i]; *ret_y = t_y[i]; ret = ATRC_TAN; } } } } if (type & ATRC_PERP){ /* if type of attractor is flaged as perpenticular */ /*find normal to an external point of ellipse*/ double f[2], dx[2], dy[2], x, y, xnew, ynew, den; int num_inter = 0; /* rotation constants */ cosine = cos(-rot); sine = sin(-rot); /* rotation of ref point to align to ellipse axis */ x = cosine*(ref_x - center_x) - sine*(ref_y - center_y) + center_x; y = sine*(ref_x - center_x) + cosine*(ref_y - center_y) + center_y; /* translate point to ellipse center */ x -= center_x; y -= center_y; /* equations parameters */ double a2 = pow(a, 2); double b2 = pow(b, 2); double c1 = -b2*y; double c2 = b2-a2; double c3 = a2*x; double c4 = 1/a2; double c5 = 1/b2; /* Newton-Raphson method, in ten iterations*/ for (i = 0; i < 10; i++){ /* normal to ellipse*/ f[0] = c1*x + c2*x*y + c3*y; /* partial derivates in point */ dx[0] = c1 + c2*y; dy[0] = c2*x + c3; /*ellipse equation */ f[1] = c4*x*x + c5*y*y -1; /* partial derivates in point */ dx[1] = 2*c4*x; dy[1] = 2*c5*y; /* denominator of inverse jacobian matrix*/ den = dx[0]*dy[1] - dy[0]*dx[1]; if (fabs(den) > TOL){ /* Newton-Raphson core => Pnew = P - F(P)*invJacob(P) */ xnew = x - (f[0]*dy[1] - f[1]*dy[0])/den; ynew = y - (-f[0]*dx[1] + f[1]*dx[0])/den; } else break; if ((fabs(xnew - x) < TOL) && (fabs(ynew - y) < TOL)){ /* has convergence*/ num_inter = 1; x = xnew; y = ynew; break; } /* for next iteration */ x = xnew; y = ynew; } if (num_inter){ /*rotate and translate back */ /* rotation constants */ cosine = cos(rot); sine = sin(rot); /* rotation of ref point to align to ellipse axis */ xnew = cosine*x - sine*y + center_x; ynew = sine*x + cosine*y + center_y; //printf("perp = %0.2f, %0.2f\n", xnew, ynew); /* check if point pass on distance criteria */ curr_dist = sqrt(pow(xnew - pos_x, 2) + pow(ynew - pos_y, 2)); if (curr_dist < sensi){ if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = xnew; *ret_y = ynew; ret = ATRC_PERP; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = xnew; *ret_y = ynew; ret = ATRC_PERP; } } } } } return ret; } int seg_inter(struct inter_obj obj1, struct inter_obj obj2, double *ret_x, double *ret_y){ if ((obj1.type == DXF_LINE) && (obj2.type == DXF_LINE)){ /* calcule the intersection point*/ /*from https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection*/ double den = (obj1.line.p1x - obj1.line.p2x) * (obj2.line.p1y - obj2.line.p2y) - (obj1.line.p1y - obj1.line.p2y) * (obj2.line.p1x - obj2.line.p2x); if (fabs(den) > TOL){ *ret_x = ((obj1.line.p1x*obj1.line.p2y - obj1.line.p1y*obj1.line.p2x)*(obj2.line.p1x - obj2.line.p2x) - (obj1.line.p1x - obj1.line.p2x)*(obj2.line.p1x*obj2.line.p2y - obj2.line.p1y*obj2.line.p2x)) / den; *ret_y = ((obj1.line.p1x*obj1.line.p2y - obj1.line.p1y*obj1.line.p2x)*(obj2.line.p1y - obj2.line.p2y) - (obj1.line.p1y - obj1.line.p2y)*(obj2.line.p1x*obj2.line.p2y - obj2.line.p1y*obj2.line.p2x)) / den; /* verify if point is in segments */ if (point_lies_seg(obj1.line.p1x, obj1.line.p1y, obj1.line.p2x, obj1.line.p2y, *ret_x, *ret_y) && point_lies_seg(obj2.line.p1x, obj2.line.p1y, obj2.line.p2x, obj2.line.p2y, *ret_x, *ret_y)){ return 1; } } } return 0; } int seg_inter2(double l1p1x, double l1p1y, double l1p2x, double l1p2y, double l2p1x, double l2p1y, double l2p2x, double l2p2y, double *ret_x, double *ret_y){ /* calcule the intersection point*/ /*from https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection*/ double den = (l1p1x - l1p2x) * (l2p1y - l2p2y) - (l1p1y - l1p2y) * (l2p1x - l2p2x); if (fabs(den) > TOL){ *ret_x = ((l1p1x*l1p2y - l1p1y*l1p2x)*(l2p1x - l2p2x) - (l1p1x - l1p2x)*(l2p1x*l2p2y - l2p1y*l2p2x)) / den; *ret_y = ((l1p1x*l1p2y - l1p1y*l1p2x)*(l2p1y - l2p2y) - (l1p1y - l1p2y)*(l2p1x*l2p2y - l2p1y*l2p2x)) / den; /* verify if point is in segments */ if (point_lies_seg(l1p1x, l1p1y, l1p2x, l1p2y, *ret_x, *ret_y) && point_lies_seg(l2p1x, l2p1y, l2p2x, l2p2y, *ret_x, *ret_y)){ return 1; } } return 0; } int line_inter(double a1, double b1, double c1, double a2, double b2, double c2, double *ret_x, double *ret_y){ double den =b1*a2-b2*a1; if (fabs(den) > TOL){ *ret_x = (b1*c2-b2*c1)/den; *ret_y = (a1*c2-a2*c1)/-den; return 1; } return 0; } int el_ln_inter( double center_x, double center_y, double axis, double ratio, double rot, double ln_a, double ln_b, double ln_c, /*line in general form ax+bx = c*/ double inter_x[2], double inter_y[2]){ int num_inter = 0; /* ellipse's rotation constants */ double cosine = cos(-rot); double sine = sin(-rot); /*ellipse's parameters */ double a = axis, b = axis * ratio; /*calc params*/ double k, l, m, n, p, q, r, delta = -1.0, s, d; if ((fabs(ln_b) < TOL) && (fabs(ln_a) > TOL)) { /* vertical line*/ d = ln_c/ln_a; k = -sine; m = cosine; l = center_y*sine - center_x*cosine + d*cosine; n = -center_y*cosine - center_x*sine + d*sine; p = pow(b,2)*pow(k,2) + pow(a,2)*pow(m,2); q = 2*(pow(b,2)*k*l + pow(a,2)*m*n); r = pow(b,2)*pow(l,2) + pow(a,2)*pow(n,2) - pow(a,2)*pow(b,2); delta = pow(q,2) - 4*p*r; if (p != 0.0){ /* exist intersection */ if (delta > 0.0){ /* 2 intersections */ num_inter = 2; inter_y[0] = (-q + sqrt(delta))/(2*p); inter_y[1] = (-q - sqrt(delta))/(2*p); inter_x[0] = d; inter_x[1] = d; } else if (fabs(delta) < TOL){ /* 1 intersection */ num_inter = 1; inter_y[1] = (-q)/(2*p); inter_x[0] = d; } } } else if(fabs(ln_b) > TOL){ s = -ln_a / ln_b; d = ln_c / ln_b; k = cosine - s*sine; m = sine + s*cosine; l = center_y*sine - center_x*cosine - d*sine; n = -center_y*cosine - center_x*sine + d*cosine; p = pow(b,2)*pow(k,2) + pow(a,2)*pow(m,2); q = 2*(pow(b,2)*k*l + pow(a,2)*m*n); r = pow(b,2)*pow(l,2) + pow(a,2)*pow(n,2) - pow(a,2)*pow(b,2); delta = pow(q,2) - 4*p*r; if (p != 0.0){ /* exist intersection */ if (delta > 0.0){ /* 2 intersections */ num_inter = 2; inter_x[0] = (-q + sqrt(delta))/(2*p); inter_x[1] = (-q - sqrt(delta))/(2*p); inter_y[0] = s*inter_x[0] + d; inter_y[1] = s*inter_x[1] + d; } else if (fabs(delta) < TOL){ /* 1 intersection */ num_inter = 1; inter_x[0] = (-q)/(2*p); inter_y[0] = s*inter_x[0] + d; } } } return num_inter; } int dxf_inter_attract(struct inter_obj obj1, struct inter_obj obj2, double pos_x, double pos_y, double sensi, double *ret_x, double *ret_y, int *init_dist, double *min_dist){ int ret = ATRC_NONE; double curr_dist = sensi; double inter_x[2]; double inter_y[2]; int num_inter = 0, i; if ((obj1.type == DXF_LINE) && (obj2.type == DXF_LINE)){ if (seg_inter(obj1, obj2, &inter_x[0], &inter_y[0])) num_inter = 1; //p1y - p2y, p2x - p1x, (p2x - p1x)*p1y + (p1y - p2y)*p1x, //if (line_inter(obj1.line.p1y - obj1.line.p2y, obj1.line.p2x - obj1.line.p1x, (obj1.line.p2x - obj1.line.p1x)*obj1.line.p1y + (obj1.line.p1y - obj1.line.p2y)*obj1.line.p1x, //obj2.line.p1y - obj2.line.p2y, obj2.line.p2x - obj2.line.p1x, (obj2.line.p2x - obj2.line.p1x)*obj2.line.p1y + (obj2.line.p1y - obj2.line.p2y)*obj2.line.p1x, //&inter_x[1], &inter_y[1])) printf("inter = %0.2f, %0.2f\n", inter_x[1], inter_y[1]); } else if (((obj1.type == DXF_LINE) && (obj2.type == DXF_ARC)) || ((obj1.type == DXF_ARC) && (obj2.type == DXF_LINE))){ if (obj1.type == DXF_ARC){ /*swap objects (obj1 is always a line and obj2 is always an arc*/ struct inter_obj tmp =obj1; obj1 = obj2; obj2 = tmp; } num_inter = el_ln_inter( obj2.arc.cx, obj2.arc.cy, obj2.arc.axis, obj2.arc.ratio, obj2.arc.rot, obj1.line.p1y - obj1.line.p2y, obj1.line.p2x - obj1.line.p1x, (obj1.line.p2x - obj1.line.p1x)*obj1.line.p1y + (obj1.line.p1y - obj1.line.p2y)*obj1.line.p1x, inter_x, inter_y); } else if ((obj1.type == DXF_ARC) && (obj2.type == DXF_ARC)){ double ang_cmp = obj2.arc.rot + M_PI; angle_range(&ang_cmp); /* verify if objects are not coincident */ if (!(fabs(obj1.arc.axis - obj2.arc.axis) < TOL && fabs(obj1.arc.ratio - obj2.arc.ratio) < TOL && (fabs(obj1.arc.rot - obj2.arc.rot) < TOL || fabs(obj1.arc.rot - ang_cmp) < TOL)&& fabs(obj1.arc.cx - obj2.arc.cx) < TOL && fabs(obj1.arc.cy - obj2.arc.cy) < TOL)){ num_inter = 0; double x = pos_x, y = pos_y, xnew, ynew; double c1[2], c2[2], c3[2], c4[2], c5[2], c6[2]; double a2, b2, cos1, cos2, sin1, sin2, xr, yr; double f[2], dx[2], dy[2], den; /* first arc parameters calculation */ a2 = pow(obj1.arc.axis, 2); b2 = pow(obj1.arc.axis*obj1.arc.ratio, 2); cos1 = cos(-obj1.arc.rot); cos2 = pow(cos1, 2); sin1 = sin(-obj1.arc.rot); sin2 = pow(sin1, 2); xr = obj1.arc.cx*cos1 - obj1.arc.cy*sin1; yr = obj1.arc.cx*sin1 + obj1.arc.cy*cos1; /* parameters for ellipse equation in general form */ c1[0] = cos2/a2 + sin2/b2; c2[0] = 2*sin1*cos1*(1/b2 - 1/a2); c3[0] = -2*(cos1*xr/a2 + sin1*yr/b2); c4[0] = cos2/b2 + sin2/a2; c5[0] = 2*(sin1*xr/a2 - cos1*yr/b2); c6[0] = pow(xr, 2)/a2 + pow(yr, 2)/b2 - 1; /* second arc parameters calculation */ a2 = pow(obj2.arc.axis, 2); b2 = pow(obj2.arc.axis*obj2.arc.ratio, 2); cos1 = cos(-obj2.arc.rot); cos2 = pow(cos1, 2); sin1 = sin(-obj2.arc.rot); sin2 = pow(sin1, 2); xr = obj2.arc.cx*cos1 - obj2.arc.cy*sin1; yr = obj2.arc.cx*sin1 + obj2.arc.cy*cos1; /* parameters for ellipse equation in general form */ c1[1] = cos2/a2 + sin2/b2; c2[1] = 2*sin1*cos1*(1/b2 - 1/a2); c3[1] = -2*(cos1*xr/a2 + sin1*yr/b2); c4[1] = cos2/b2 + sin2/a2; c5[1] = 2*(sin1*xr/a2 - cos1*yr/b2); c6[1] = pow(xr, 2)/a2 + pow(yr, 2)/b2 - 1; /* Newton-Raphson method, in ten iterations*/ for (i = 0; i < 10; i++){ /* first arc - ellipse equation */ f[0] = c1[0]*x*x + c2[0]*x*y + c3[0]*x+ c4[0]*y*y + c5[0]*y + c6[0]; /* partial derivates in point */ dx[0] = 2*c1[0]*x + c2[0]*y + c3[0]; dy[0] = c2[0]*x + 2*c4[0]*y + c5[0]; /* second arc - ellipse equation */ f[1] = c1[1]*x*x + c2[1]*x*y + c3[1]*x+ c4[1]*y*y + c5[1]*y + c6[1]; /* partial derivates in point */ dx[1] = 2*c1[1]*x + c2[1]*y + c3[1]; dy[1] = c2[1]*x + 2*c4[1]*y + c5[1]; /* denominator of inverse jacobian matrix*/ den = dx[0]*dy[1] - dy[0]*dx[1]; if (fabs(den) > TOL){ /* Newton-Raphson core => Pnew = P - F(P)*invJacob(P) */ xnew = x - (f[0]*dy[1] - f[1]*dy[0])/den; ynew = y - (-f[0]*dx[1] + f[1]*dx[0])/den; } else break; if ((fabs(xnew - x) < TOL) && (fabs(ynew - y) < TOL)){ /* has convergence*/ num_inter = 1; inter_x[0] = xnew; inter_y[0] = ynew; break; } /* for next iteration */ x = xnew; y = ynew; } } } for (i = 0; i < num_inter; i++){ curr_dist = sqrt(pow(inter_x[i] - pos_x, 2) + pow(inter_y[i] - pos_y, 2)); if (curr_dist < sensi){ //printf("INTER %0.2f, %0.2f\n", inter_x[i], inter_y[i]); if (*init_dist == 0){ *init_dist = 1; *min_dist = curr_dist; *ret_x = inter_x[i]; *ret_y = inter_y[i]; ret = ATRC_INTER; } else if (curr_dist < *min_dist){ *min_dist = curr_dist; *ret_x = inter_x[i]; *ret_y = inter_y[i]; ret = ATRC_INTER; } } } return ret; } int dxf_ent_attract (dxf_drawing *drawing, dxf_node * obj_hilite, enum attract_type type, double pos_x, double pos_y, double ref_x, double ref_y, double sensi, double *ret_x, double *ret_y){ dxf_node *current = NULL, *obj = NULL; dxf_node *prev = NULL; int ret = ATRC_NONE, found = 0; int init_dist = 0; double min_dist; enum dxf_graph ent_type = DXF_NONE; char name1[DXF_MAX_CHARS], name2[DXF_MAX_CHARS]; name1[0] = 0; name2[0] = 0; double pt1_x = 0, pt1_y = 0, pt1_z = 0; int pt1 = 0; /* flag */ double t_rot = 0, rot = 0, elev = 0; double scale_x = 1.0, scale_y = 1.0, scale_z = 1.0; double extru_x = 0.0, extru_y = 0.0, extru_z = 1.0; /* for insert objects */ dxf_node *insert_ent = NULL, *blk = NULL; struct ins_space ins_stack[10]; int ins_stack_pos = 0; struct ins_space ins_zero = { .ins_ent = obj, .prev = NULL, .ofs_x = 0.0, .ofs_y =0.0, .ofs_z =0.0, .rot = 0.0, .scale_x = 1.0 , .scale_y = 1.0, .scale_z = 1.0, .normal = {0.0, 0.0, 1.0} }; ins_stack[0] = ins_zero; int ins_flag = 0; /* ---- */ double rect_pt1[2]; double rect_pt2[2]; int num_el = 0; rect_pt1[0] = pos_x - sensi; rect_pt1[1] = pos_y - sensi; rect_pt2[0] = pos_x + sensi; rect_pt2[1] = pos_y + sensi; list_node * list = list_new(NULL, 1); list_node *list_el = NULL; num_el = dxf_ents_isect2(list, drawing, rect_pt1, rect_pt2); if ((list != NULL) && (num_el > 0)){ list_el = list->next; } struct inter_obj inter_cand[MAX_CAND]; int num_inter = 0; while (list_el){/* ###### LIST LOOP ########### */ obj = (dxf_node *)list_el->data; /* current obj */ /* reset variables for complex entities (DXF_INSERT) */ insert_ent = NULL; blk = NULL; ins_stack_pos = 0; ins_zero.ins_ent = obj; ins_stack[0] = ins_zero; ins_flag = 0; ent_type = DXF_NONE; name1[0] = 0; name2[0] = 0; pt1_x = 0; pt1_y = 0; pt1_z = 0; pt1 = 0; t_rot = 0; rot = 0; elev = 0; scale_x = 1.0; scale_y = 1.0; scale_z = 1.0; extru_x = 0.0; extru_y = 0.0; extru_z = 1.0; current = obj; while (current){ /* ########### OBJ LOOP ########*/ prev = current; if (current->type == DXF_ENT){ ent_type = dxf_ident_ent_type (current); if (ent_type == DXF_LINE){ double pt1_x = 0, pt1_y = 0, pt1_z = 0; double pt2_x = 0, pt2_y = 0, pt2_z = 0; if (dxf_line_get (drawing, current, &pt1_x, &pt1_y, &pt1_z, &pt2_x, &pt2_y, &pt2_z)){ /* transform coordinates, according insert space */ transform(&pt1_x, &pt1_y, ins_stack[ins_stack_pos]); transform(&pt2_x, &pt2_y, ins_stack[ins_stack_pos]); if (found = dxf_line_attract (pt1_x, pt1_y, pt2_x, pt2_y, type, pos_x, pos_y, ref_x, ref_y, sensi, ret_x, ret_y, &init_dist, &min_dist)){ ret = found; } if ((type & ATRC_INTER) && (num_inter < MAX_CAND) && (IN_BOUNDS(pos_x, pos_y, pt1_x, pt1_y, pt2_x, pt2_y) || NEAR_LN(pos_x, pos_y, pt1_x, pt1_y, pt2_x, pt2_y, sensi))){ inter_cand[num_inter].type = ent_type; inter_cand[num_inter].line.p1x = pt1_x; inter_cand[num_inter].line.p1y = pt1_y; inter_cand[num_inter].line.p2x = pt2_x; inter_cand[num_inter].line.p2y = pt2_y; inter_cand[num_inter].line.bulge = 0; num_inter++; } } //printf("line %d\n", found); } else if (ent_type == DXF_CIRCLE){ double center_x, center_y, center_z, radius; double axis = 0, rot = 0, ratio = 1; if (dxf_circle_get(drawing, current, &center_x, &center_y, &center_z, &axis, &ratio, &rot)){ /* transform coordinates, according insert space */ transform(&center_x, &center_y, ins_stack[ins_stack_pos]); axis *= fabs(ins_stack[ins_stack_pos].scale_x); rot += ins_stack[ins_stack_pos].rot * M_PI/180; ratio *= fabs(ins_stack[ins_stack_pos].scale_y / ins_stack[ins_stack_pos].scale_x); ellipse_transf(&center_x, &center_y, &center_z, &axis, &ratio, &rot, ins_stack[ins_stack_pos].normal); if (found = dxf_arc_attract(axis, 0.0, 0.0, center_x, center_y, ratio, rot, type, pos_x, pos_y, ref_x, ref_y, sensi, ret_x, ret_y, &init_dist, &min_dist)){ ret = found; } if ((type & ATRC_INTER) && (num_inter < MAX_CAND) && in_ellip_bound(pos_x, pos_y, sensi, center_x, center_y, axis, ratio, rot)){ inter_cand[num_inter].type = DXF_ARC; inter_cand[num_inter].arc.cx = center_x; inter_cand[num_inter].arc.cy = center_y; inter_cand[num_inter].arc.axis = axis; inter_cand[num_inter].arc.ratio = ratio; inter_cand[num_inter].arc.rot = rot; inter_cand[num_inter].arc.ang_start = 0.0; inter_cand[num_inter].arc.ang_end = 2*M_PI; num_inter++; } } } else if (ent_type == DXF_ARC){ double center_x, center_y, center_z, radius, start_ang, end_ang; double axis = 0, rot = 0, ratio = 1; //if (dxf_arc_get(drawing, current, &center_x, &center_y, &center_z, &radius, &start_ang, &end_ang)){ if (dxf_arc_get(drawing, current, &center_x, &center_y, &center_z, &axis, &ratio, &rot, &start_ang, &end_ang)){ /* transform coordinates, according insert space */ transform(&center_x, &center_y, ins_stack[ins_stack_pos]); axis *= fabs(ins_stack[ins_stack_pos].scale_x); rot += ins_stack[ins_stack_pos].rot * M_PI/180; ratio *= fabs(ins_stack[ins_stack_pos].scale_y / ins_stack[ins_stack_pos].scale_x); ellipse_transf(&center_x, &center_y, &center_z, &axis, &ratio, &rot, ins_stack[ins_stack_pos].normal); if (found = dxf_arc_attract(axis, start_ang, end_ang, center_x, center_y, ratio, rot, type, pos_x, pos_y, ref_x, ref_y, sensi, ret_x, ret_y, &init_dist, &min_dist)){ ret = found; } if ((type & ATRC_INTER) && (num_inter < MAX_CAND) && in_ellip_bound(pos_x, pos_y, sensi, center_x, center_y, axis, ratio, rot)){ inter_cand[num_inter].type = DXF_ARC; inter_cand[num_inter].arc.cx = center_x; inter_cand[num_inter].arc.cy = center_y; inter_cand[num_inter].arc.axis = axis; inter_cand[num_inter].arc.ratio = ratio; inter_cand[num_inter].arc.rot = rot; inter_cand[num_inter].arc.ang_start = start_ang; inter_cand[num_inter].arc.ang_end = end_ang; num_inter++; } } } else if (ent_type == DXF_ELLIPSE){ double center_x, center_y, center_z, radius, start_ang, end_ang; double axis = 0, rot = 0, ratio = 1; //if (dxf_arc_get(drawing, current, &center_x, &center_y, &center_z, &radius, &start_ang, &end_ang)){ if (dxf_ellipse_get(drawing, current, &center_x, &center_y, &center_z, &axis, &ratio, &rot, &start_ang, &end_ang)){ /* transform coordinates, according insert space */ transform(&center_x, &center_y, ins_stack[ins_stack_pos]); axis *= fabs(ins_stack[ins_stack_pos].scale_x); rot += ins_stack[ins_stack_pos].rot * M_PI/180; ratio *= fabs(ins_stack[ins_stack_pos].scale_y / ins_stack[ins_stack_pos].scale_x); ellipse_transf(&center_x, &center_y, &center_z, &axis, &ratio, &rot, ins_stack[ins_stack_pos].normal); if (found = dxf_arc_attract(axis, start_ang, end_ang, center_x, center_y, ratio, rot, type, pos_x, pos_y, ref_x, ref_y, sensi, ret_x, ret_y, &init_dist, &min_dist)){ ret = found; } if ((type & ATRC_INTER) && (num_inter < MAX_CAND) && in_ellip_bound(pos_x, pos_y, sensi, center_x, center_y, axis, ratio, rot)){ inter_cand[num_inter].type = DXF_ARC; inter_cand[num_inter].arc.cx = center_x; inter_cand[num_inter].arc.cy = center_y; inter_cand[num_inter].arc.axis = axis; inter_cand[num_inter].arc.ratio = ratio; inter_cand[num_inter].arc.rot = rot; inter_cand[num_inter].arc.ang_start = start_ang; inter_cand[num_inter].arc.ang_end = end_ang; num_inter++; } } } else if (ent_type == DXF_INSERT){ insert_ent = current; ins_flag = 1; //printf("insert %d\n", current->obj.content); if (current->obj.content){ /* starts the content sweep */ current = current->obj.content->next; //prev = current; continue; } printf("Error: empty entity\n"); } else if (ent_type == DXF_LWPOLYLINE){ double pt1_x = 0, pt1_y = 0, pt1_z = 0, bulge = 0; double pt2_x = 0, pt2_y = 0, pt2_z = 0, prev_bulge = 0; dxf_node * next_vert = NULL; if(dxf_lwpline_get_pt(current, &next_vert, &pt2_x, &pt2_y, &pt2_z, &bulge)){ //printf("%0.f,%0.2f - %d\n",pt2_x, pt2_y, next_vert); /* transform coordinates, according insert space */ while (next_vert){ transform(&pt2_x, &pt2_y, ins_stack[ins_stack_pos]); pt1_x = pt2_x; pt1_y = pt2_y; prev_bulge = bulge; if(!dxf_lwpline_get_pt(current, &next_vert, &pt2_x, &pt2_y, &pt2_z, &bulge)){ break; } if (fabs(prev_bulge) < TOL){ /* segment is a straight line*/ if (found = dxf_line_attract (pt1_x, pt1_y, pt2_x, pt2_y, type, pos_x, pos_y, ref_x, ref_y, sensi, ret_x, ret_y, &init_dist, &min_dist)){ ret = found; } if ((type & ATRC_INTER) && (num_inter < MAX_CAND) && (IN_BOUNDS(pos_x, pos_y, pt1_x, pt1_y, pt2_x, pt2_y) || NEAR_LN(pos_x, pos_y, pt1_x, pt1_y, pt2_x, pt2_y, sensi))){ inter_cand[num_inter].type = DXF_LINE; inter_cand[num_inter].line.p1x = pt1_x; inter_cand[num_inter].line.p1y = pt1_y; inter_cand[num_inter].line.p2x = pt2_x; inter_cand[num_inter].line.p2y = pt2_y; inter_cand[num_inter].line.bulge = 0; num_inter++; } } else{ /* segment is an arc*/ double radius, ang_start, ang_end, center_x, center_y, center_z = 0.0; double axis = 0, rot = 0, ratio = 1; arc_bulge(pt1_x, pt1_y, pt2_x, pt2_y, prev_bulge, &radius, &ang_start, &ang_end, &center_x, &center_y); /* transform coordinates, according insert space */ transform(&center_x, &center_y, ins_stack[ins_stack_pos]); axis = radius * fabs(ins_stack[ins_stack_pos].scale_x); rot = ins_stack[ins_stack_pos].rot * M_PI/180; ratio = fabs(ins_stack[ins_stack_pos].scale_y / ins_stack[ins_stack_pos].scale_x); ellipse_transf(&center_x, &center_y, &center_z, &axis, &ratio, &rot, ins_stack[ins_stack_pos].normal); if (found = dxf_arc_attract(axis, ang_start, ang_end, center_x, center_y, ratio, rot, type, pos_x, pos_y, ref_x, ref_y, sensi, ret_x, ret_y, &init_dist, &min_dist)){ ret = found; } if ((type & ATRC_INTER) && (num_inter < MAX_CAND) && in_ellip_bound(pos_x, pos_y, sensi, center_x, center_y, axis, ratio, rot)){ inter_cand[num_inter].type = DXF_ARC; inter_cand[num_inter].arc.cx = center_x; inter_cand[num_inter].arc.cy = center_y; inter_cand[num_inter].arc.axis = axis; inter_cand[num_inter].arc.ratio = ratio; inter_cand[num_inter].arc.rot = rot; inter_cand[num_inter].arc.ang_start = ang_start; inter_cand[num_inter].arc.ang_end = ang_end; num_inter++; } } } } } else if (ent_type == DXF_TEXT){ char text[DXF_MAX_CHARS]; double ins_x, ins_y, ins_z; double alin_x, alin_y, alin_z; double w, h, rot, above, below; int alin_v, alin_h, fnt_idx; if (dxf_text_get (drawing, current, text, &fnt_idx, &above, &below, &ins_x, &ins_y, &ins_z, &alin_x, &alin_y, &alin_z, &w, &h, &rot, &alin_v, &alin_h)){ /* transform coordinates, according insert space */ transform(&ins_x, &ins_y, ins_stack[ins_stack_pos]); transform(&alin_x, &alin_y, ins_stack[ins_stack_pos]); //printf ("text w=%0.2f, h=%0.2f\n", w, h); if (found = dxf_text_attract (ins_x, ins_y, alin_x, alin_y, w, h, rot, alin_v, alin_h, above, below, type, pos_x, pos_y, sensi, ret_x, ret_y, &init_dist, &min_dist)){ ret = found; } /* if ((type & ATRC_INTER) && (num_inter < MAX_CAND) && (IN_BOUNDS(pos_x, pos_y, pt1_x, pt1_y, pt2_x, pt2_y) || NEAR_LN(pos_x, pos_y, pt1_x, pt1_y, pt2_x, pt2_y, sensi))){ inter_cand[num_inter].type = ent_type; inter_cand[num_inter].line.p1x = pt1_x; inter_cand[num_inter].line.p1y = pt1_y; inter_cand[num_inter].line.p2x = pt2_x; inter_cand[num_inter].line.p2y = pt2_y; inter_cand[num_inter].line.bulge = 0; num_inter++; }*/ } //printf("line %d\n", found); } } /* ============================================================= */ else if ((current->type == DXF_ATTR) && (ins_flag != 0)){ /* read DXF attibutes of insert block */ //printf("%d\n", current->value.group); switch (current->value.group){ case 2: strcpy(name1, current->value.s_data); break; case 3: strcpy(name2, current->value.s_data); break; case 10: pt1_x = current->value.d_data; pt1 = 1; /* set flag */ break; case 20: pt1_y = current->value.d_data; pt1 = 1; /* set flag */ break; case 30: pt1_z = current->value.d_data; pt1 = 1; /* set flag */ break; case 38: elev = current->value.d_data; break; case 41: scale_x = current->value.d_data; break; case 42: scale_y = current->value.d_data; break; case 43: scale_z = current->value.d_data; break; case 50: t_rot = current->value.d_data; break; case 210: extru_x = current->value.d_data; break; case 220: extru_y = current->value.d_data; break; case 230: extru_z = current->value.d_data; break; } } current = current->next; /* go to the next in the list*/ /* ============================================================= */ /* complex entities */ if (((ins_flag != 0) && (current == NULL))|| ((ins_flag != 0) && (current != NULL) && (current != insert_ent) && (current->type == DXF_ENT))){ ins_flag = 0; /* look for block */ blk = dxf_find_obj_descr2(drawing->blks, "BLOCK", name1); if (blk) { //printf ("bloco %s\n", name1); /* save current entity for future process */ ins_stack_pos++; ins_stack[ins_stack_pos].ins_ent = blk; ins_stack[ins_stack_pos].prev = prev; if (ins_stack_pos > 1){ ins_stack[ins_stack_pos].ofs_x = pt1_x + ins_stack[ins_stack_pos - 1].ofs_x; ins_stack[ins_stack_pos].ofs_y = pt1_y + ins_stack[ins_stack_pos - 1].ofs_y; ins_stack[ins_stack_pos].ofs_z = pt1_z + ins_stack[ins_stack_pos - 1].ofs_z; ins_stack[ins_stack_pos].scale_x = scale_x * ins_stack[ins_stack_pos - 1].scale_x; ins_stack[ins_stack_pos].scale_y = scale_y * ins_stack[ins_stack_pos - 1].scale_y; ins_stack[ins_stack_pos].scale_z = scale_z * ins_stack[ins_stack_pos - 1].scale_z; ins_stack[ins_stack_pos].rot = t_rot + ins_stack[ins_stack_pos - 1].rot; ins_stack[ins_stack_pos].normal[0] = extru_x; ins_stack[ins_stack_pos].normal[1] = extru_y; ins_stack[ins_stack_pos].normal[2] = extru_z; } else{ ins_stack[ins_stack_pos].ofs_x = pt1_x; ins_stack[ins_stack_pos].ofs_y = pt1_y; ins_stack[ins_stack_pos].ofs_z = pt1_z; ins_stack[ins_stack_pos].scale_x = scale_x; ins_stack[ins_stack_pos].scale_y = scale_y; ins_stack[ins_stack_pos].scale_z = scale_z; ins_stack[ins_stack_pos].rot = t_rot; ins_stack[ins_stack_pos].normal[0] = extru_x; ins_stack[ins_stack_pos].normal[1] = extru_y; ins_stack[ins_stack_pos].normal[2] = extru_z; } /* if (v_return->size > 0){ ins_stack[ins_stack_pos].start_idx = v_return->size; } else{ ins_stack[ins_stack_pos].start_idx = 0; }*/ //p_space = paper; /*reinit_vars: */ ent_type = DXF_NONE; pt1_x = 0; pt1_y = 0; pt1_z = 0; rot = 0; elev = 0; t_rot = 0; scale_x = 1.0; scale_y = 1.0; scale_z = 1.0; extru_x = 0.0; extru_y = 0.0; extru_z = 1.0; /* clear the strings */ name1[0] = 0; name2[0] = 0; /*clear flags*/ pt1 = 0; if (blk->obj.content){ /* now, current is the block */ /* starts the content sweep */ current = blk->obj.content->next; continue; } printf("Error: empty block\n"); continue; } } if ((prev == NULL) || (prev == obj)){ /* stop the search if back on initial entity */ current = NULL; break; } /* ============================================================= */ while (current == NULL){ /* end of list sweeping */ if ((prev == NULL) || (prev == obj)){ /* stop the search if back on initial entity */ //printf("para\n"); current = NULL; break; } /* try to back in structure hierarchy */ prev = prev->master; if (prev){ /* up in structure */ /* try to continue on previous point in structure */ current = prev->next; if (prev == ins_stack[ins_stack_pos].ins_ent){/* back on initial entity */ if (ins_stack_pos < 1){ /* stop the search if back on initial entity */ current = NULL; break; } else{ prev = ins_stack[ins_stack_pos].prev; ins_stack_pos--; //prev = ins_stack[ins_stack_pos].ins_ent; //printf("retorna %d\n", ins_stack_pos); current = prev; } } } else{ /* stop the search if structure ends */ current = NULL; break; } } } /* ######### END OBJ LOOP ########### */ list_el = list_el->next; }/* ######### END LIST LOOP ############ */ list_mem_pool(ZERO_LIST, 1); /* verify if exist intersections between candidates*/ if(num_inter > 1){ int i, j; /* walk in all combinations */ for (i = 0; i < num_inter - 1; i++){ for (j = i+1; j < num_inter; j++){ if (found = dxf_inter_attract (inter_cand[i], inter_cand[j], pos_x, pos_y, sensi, ret_x, ret_y, &init_dist, &min_dist)){ ret = found; } } } } //printf("%d\n", ret); return ret; }
30.507533
254
0.562193
[ "shape", "transform" ]
0d1664b5af5ba3843c07f3c9628681401ad05233
4,883
h
C
iree/compiler/Dialect/VMLA/Conversion/ConversionTarget.h
silvrwolfboy/iree
6d8b59ba8db9c54450ea29e6d9d37b18fd40d12a
[ "Apache-2.0" ]
null
null
null
iree/compiler/Dialect/VMLA/Conversion/ConversionTarget.h
silvrwolfboy/iree
6d8b59ba8db9c54450ea29e6d9d37b18fd40d12a
[ "Apache-2.0" ]
null
null
null
iree/compiler/Dialect/VMLA/Conversion/ConversionTarget.h
silvrwolfboy/iree
6d8b59ba8db9c54450ea29e6d9d37b18fd40d12a
[ "Apache-2.0" ]
1
2020-03-06T06:22:26.000Z
2020-03-06T06:22:26.000Z
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef IREE_COMPILER_DIALECT_VMLA_CONVERSION_CONVERSIONTARGET_H_ #define IREE_COMPILER_DIALECT_VMLA_CONVERSION_CONVERSIONTARGET_H_ #include "iree/compiler/Dialect/VMLA/IR/VMLADialect.h" #include "iree/compiler/Dialect/VMLA/IR/VMLATypes.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/Module.h" #include "mlir/IR/StandardTypes.h" #include "mlir/Transforms/DialectConversion.h" namespace mlir { namespace iree_compiler { enum class VMLAOpSemantics { kDefault = 0, // Forces integers to be treated as unsigned integers. kForceUnsigned, }; // A conversion target for the VMLA dialect that ensures that tensor types are // fully removed. Conversions targeting the VMLA dialect should always use this. class VMLAConversionTarget : public ConversionTarget { public: VMLAConversionTarget(MLIRContext *context, TypeConverter &typeConverter); // Attempts to rewrite an op that may use tensor values into an op using VMLA // buffers. See VMLAOpConversion for more information. static LogicalResult applyDefaultBufferRewrite( Operation *srcOp, ArrayRef<Value> operands, VMLAOpSemantics semantics, StringRef dstOpName, TypeConverter &typeConverter, ConversionPatternRewriter &rewriter); // Returns the shape of the |originalValue| tensor as an SSA ranked shape. static Value getTensorShape(Location loc, Value originalValue, TypeConverter &typeConverter, ConversionPatternRewriter &rewriter); // Returns the offset, in bytes, of an index within a linearized dense buffer. static Value getBufferOffset(Location loc, Value tensorValue, Value indicesValue, TypeConverter &typeConverter, ConversionPatternRewriter &rewriter); static Value getBufferOffset(Location loc, Value tensorValue, ValueRange indices, TypeConverter &typeConverter, ConversionPatternRewriter &rewriter); // Returns the length, in bytes, of a linearized dense buffer. static Value getBufferLength(Location loc, Value tensorValue, TypeConverter &typeConverter, ConversionPatternRewriter &rewriter); // Allocates a VMLA buffer for an output operand of an op. // Returns a buffer allocated with the appropriate size for storing the value. // Callers must replace uses of |originalValue| with the returned value. static Value allocateOutputBuffer(Location loc, Value originalValue, TypeConverter &typeConverter, ConversionPatternRewriter &rewriter); private: bool isDynamicallyLegal(Operation *op) const override; MLIRContext &context; TypeConverter &typeConverter; }; // VMLA tensor-to-buffer conversion utility. // This can be used by dialects to model custom op conversion from a dialect // that uses the MLIR tensor type to the IREE VMLA buffer type. At this point // during conversion the source values will be TensorType and the target values // will be IREE::VMLA::BufferTypes. Any static information available about the // tensor (such as static dimensions, element type, layout, etc) are extracted // here and lowered as expanded values. template <typename SRC, typename DST, VMLAOpSemantics semantics = VMLAOpSemantics::kDefault> class VMLAOpConversion : public OpConversionPattern<SRC> { public: VMLAOpConversion(MLIRContext *context, TypeConverter &typeConverter) : OpConversionPattern<SRC>(context), typeConverter(typeConverter) {} PatternMatchResult matchAndRewrite( SRC srcOp, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const override { if (succeeded(VMLAConversionTarget::applyDefaultBufferRewrite( srcOp, operands, semantics, DST::getOperationName(), typeConverter, rewriter))) { return OpConversionPattern<SRC>::matchSuccess(); } return OpConversionPattern<SRC>::matchFailure(); } protected: TypeConverter &typeConverter; }; } // namespace iree_compiler } // namespace mlir #endif // IREE_COMPILER_DIALECT_VMLA_CONVERSION_CONVERSIONTARGET_H_
42.833333
80
0.72865
[ "shape", "model" ]
0d16cddcac6fbe619cbecf86216d53604d1d0643
1,242
h
C
hazytl/include/hazy/vector/pair.h
zuevmaxim/hogwildpp
40a035e5342df58b338c16bdcd94b9f20e38174e
[ "Apache-2.0" ]
36
2016-10-10T23:56:25.000Z
2021-04-20T16:24:05.000Z
hazytl/include/hazy/vector/pair.h
zuevmaxim/hogwildpp
40a035e5342df58b338c16bdcd94b9f20e38174e
[ "Apache-2.0" ]
null
null
null
hazytl/include/hazy/vector/pair.h
zuevmaxim/hogwildpp
40a035e5342df58b338c16bdcd94b9f20e38174e
[ "Apache-2.0" ]
8
2017-01-12T21:15:51.000Z
2022-02-14T07:04:47.000Z
// Copyright 2012 Chris Re, Victor Bittorf // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // The Hazy Project, http://research.cs.wisc.edu/hazy/ // Author : Victor Bittorf (bittorf [at] cs.wisc.edu) #ifndef HAZY_VECTOR_PAIR_H #define HAZY_VECTOR_PAIR_H #include <cstdlib> #include <inttypes.h> #include "fvector.h" namespace hazy { namespace vector { template <typename T> struct Pair { T value; int index; Pair() { } Pair(T v, int i) : value(v), index(i) { } Pair(Pair const& p) { value = p.value; index = p.index; } inline Pair& operator=(Pair const& p) { value = p.value; index = p.index; } }; typedef FVector<Pair<double> > PVectorDouble; } // namespace vector } // namespace hazy #endif
23.433962
75
0.699678
[ "vector" ]
0d173621871de3fd90cc523360652433cbe1f8b9
1,942
h
C
include/MazeImage++/utils/MazeImgGenerator.h
joshuainovero/Maze-Image-Generator
b913c97fa92a80c29befae32cd1cbcc350acb12a
[ "MIT" ]
null
null
null
include/MazeImage++/utils/MazeImgGenerator.h
joshuainovero/Maze-Image-Generator
b913c97fa92a80c29befae32cd1cbcc350acb12a
[ "MIT" ]
null
null
null
include/MazeImage++/utils/MazeImgGenerator.h
joshuainovero/Maze-Image-Generator
b913c97fa92a80c29befae32cd1cbcc350acb12a
[ "MIT" ]
null
null
null
/***************************************************************************** * * MazeImage++ - A library that generates maze images * Copyright (C) - 2021 Joshua Inovero (joshinovero@gmail.com) * * File: MazeImgGenerator.h * This file is used for the interface/public API calls * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the LICENSE file. * * 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. * *****************************************************************************/ #ifndef MAZEIMG_GENERATOR_H_ #define MAZEIMG_GENERATOR_H_ #include <MazeImage++/utils/ImageProcessor.h> #include <iostream> #include <fstream> namespace mazeimg_library { class MazeImgGenerator { public: // Constructor with immediate maze size specification MazeImgGenerator(M_SIZE m_size); // Changes the initial size of the maze that was set by the constructor void setMazeSize(M_SIZE m_size); // Calls the maze algorithm and saves the result as an image void generate(const char* output, IMG_FORMAT img_f); // Generates an extra image that shows the solution of a maze void enableSolution(bool cnd); // Sets the search algorithm to be used void setSearchAlgorithm(SEARCHALGOS s_type); private: ImageProcessor img_processor; // Object that handles image processing and output // Copy constructor and assignment is disabled MazeImgGenerator(const MazeImgGenerator&); MazeImgGenerator& operator=(const MazeImgGenerator&); }; } #endif // MAZEIMG_GENERATOR_H_
33.482759
88
0.65654
[ "object" ]
0d1c28cfe790dba007a7da615435c91ea70fa191
525
h
C
cases/adaptive_surfers_in_channel_flow_z/param/env/objects/static/surfer__us_0o8__surftimeprefactor_0o75/group/homogeneous/_member/agent/_active/_passive/point/parameters.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
cases/adaptive_surfers_in_channel_flow_z/param/env/objects/static/surfer__us_0o8__surftimeprefactor_0o75/group/homogeneous/_member/agent/_active/_passive/point/parameters.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
cases/adaptive_surfers_in_channel_flow_z/param/env/objects/static/surfer__us_0o8__surftimeprefactor_0o75/group/homogeneous/_member/agent/_active/_passive/point/parameters.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
#ifndef C0P_PARAM_OBJECTS_SURFER__US_0O8__SURFTIMEPREFACTOR_0O75_GROUP_HOMOGENEOUS_MEMBER_AGENT_ACTIVE_PASSIVE_POINT_PARAMETERS_H #define C0P_PARAM_OBJECTS_SURFER__US_0O8__SURFTIMEPREFACTOR_0O75_GROUP_HOMOGENEOUS_MEMBER_AGENT_ACTIVE_PASSIVE_POINT_PARAMETERS_H #pragma once // core #include "core/env/objects/object/passive/point/prop.h" namespace c0p { // Parameters of a point that is advected by the flow struct SurferUs0O8Surftimeprefactor0O75GroupHomogeneousMemberAgentActivePassivePointStepParameters { }; } #endif
30.882353
129
0.889524
[ "object" ]
982147125d9c976201bf1586ba7e1db91712c21f
39,791
c
C
build/gcc-2.6.3/cp/except.c
VivekMaran27/How-to-install-SimpleScalar-on-Ubuntu
2c0d4f4d41087508b304664fe1a6da6f86fb830b
[ "MIT" ]
null
null
null
build/gcc-2.6.3/cp/except.c
VivekMaran27/How-to-install-SimpleScalar-on-Ubuntu
2c0d4f4d41087508b304664fe1a6da6f86fb830b
[ "MIT" ]
null
null
null
build/gcc-2.6.3/cp/except.c
VivekMaran27/How-to-install-SimpleScalar-on-Ubuntu
2c0d4f4d41087508b304664fe1a6da6f86fb830b
[ "MIT" ]
null
null
null
/* Handle exceptional things in C++. Copyright (C) 1989, 1992, 1993, 1994 Free Software Foundation, Inc. Contributed by Michael Tiemann <tiemann@cygnus.com> Rewritten by Mike Stump <mrs@cygnus.com>, based upon an initial re-implementation courtesy Tad Hunt. This file is part of GNU CC. GNU CC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU CC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU CC; see the file COPYING. If not, write to the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ /* High-level class interface. */ #include "config.h" #include "tree.h" #include "rtl.h" #include "cp-tree.h" #include "flags.h" #include "obstack.h" #include "expr.h" extern void (*interim_eh_hook) PROTO((tree)); /* holds the fndecl for __builtin_return_address () */ tree builtin_return_address_fndecl; /* Define at your own risk! */ #ifndef CROSS_COMPILE #ifdef sun #ifdef sparc #define TRY_NEW_EH #endif #endif #endif #ifndef TRY_NEW_EH static void sorry_no_eh () { static int warned = 0; if (! warned) { sorry ("exception handling not supported"); warned = 1; } } void expand_exception_blocks () { } void start_protect () { } void end_protect (finalization) tree finalization; { } void expand_start_try_stmts () { sorry_no_eh (); } void expand_end_try_stmts () { } void expand_start_all_catch () { } void expand_end_all_catch () { } void expand_start_catch_block (declspecs, declarator) tree declspecs, declarator; { } void expand_end_catch_block () { } void init_exception_processing () { } void expand_throw (exp) tree exp; { sorry_no_eh (); } #else static int doing_eh (do_warn) int do_warn; { if (! flag_handle_exceptions) { static int warned = 0; if (! warned && do_warn) { error ("exception handling disabled, use -fhandle-exceptions to enable."); warned = 1; } return 0; } return 1; } /* NO GNEWS IS GOOD GNEWS WITH GARRY GNUS: This version is much closer to supporting exception handling as per Stroustrup's 2nd edition. It is a complete rewrite of all the EH stuff that was here before Shortcomings: 1. The type of the throw and catch must still match exactly (no support yet for matching base classes) 2. Throw specifications of functions still doesnt't work. Cool Things: 1. Destructors are called properly :-) 2. No overhead for the non-exception thrown case. 3. Fixing shortcomings 1 and 2 is simple. -Tad Hunt (tad@mail.csh.rit.edu) */ /* A couple of backend routines from m88k.c */ /* used to cache a call to __builtin_return_address () */ static tree BuiltinReturnAddress; #include <stdio.h> /* XXX - Tad: for EH */ /* output an exception table entry */ static void output_exception_table_entry (file, start_label, end_label, eh_label) FILE *file; rtx start_label, end_label, eh_label; { char label[100]; assemble_integer (start_label, BITS_PER_WORD/BITS_PER_UNIT, 1); assemble_integer (end_label, BITS_PER_WORD/BITS_PER_UNIT, 1); assemble_integer (eh_label, BITS_PER_WORD/BITS_PER_UNIT, 1); putc ('\n', file); /* blank line */ } static void easy_expand_asm (str) char *str; { expand_asm (build_string (strlen (str)+1, str)); } /* unwind the stack. */ static void do_unwind (throw_label) rtx throw_label; { #ifdef sparc extern FILE *asm_out_file; tree fcall; tree params; rtx return_val_rtx; /* call to __builtin_return_address () */ params=tree_cons (NULL_TREE, integer_zero_node, NULL_TREE); fcall = build_function_call (BuiltinReturnAddress, params); return_val_rtx = expand_expr (fcall, NULL_RTX, SImode, 0); /* In the return, the new pc is pc+8, as the value comming in is really the address of the call insn, not the next insn. */ emit_move_insn (return_val_rtx, plus_constant(gen_rtx (LABEL_REF, Pmode, throw_label), -8)); /* We use three values, PC, type, and value */ easy_expand_asm ("st %l0,[%fp]"); easy_expand_asm ("st %l1,[%fp+4]"); easy_expand_asm ("st %l2,[%fp+8]"); easy_expand_asm ("ret"); easy_expand_asm ("restore"); emit_barrier (); #endif #if m88k rtx temp_frame = frame_pointer_rtx; temp_frame = memory_address (Pmode, temp_frame); temp_frame = copy_to_reg (gen_rtx (MEM, Pmode, temp_frame)); /* hopefully this will successfully pop the frame! */ emit_move_insn (frame_pointer_rtx, temp_frame); emit_move_insn (stack_pointer_rtx, frame_pointer_rtx); emit_move_insn (arg_pointer_rtx, frame_pointer_rtx); emit_insn (gen_add2_insn (stack_pointer_rtx, gen_rtx (CONST_INT, VOIDmode, (HOST_WIDE_INT)m88k_debugger_offset (stack_pointer_rtx, 0)))); #if 0 emit_insn (gen_add2_insn (arg_pointer_rtx, gen_rtx (CONST_INT, VOIDmode, -(HOST_WIDE_INT)m88k_debugger_offset (arg_pointer_rtx, 0)))); emit_move_insn (stack_pointer_rtx, arg_pointer_rtx); emit_insn (gen_add2_insn (stack_pointer_rtx, gen_rtx (CONST_INT, VOIDmode, (HOST_WIDE_INT)m88k_debugger_offset (arg_pointer_rtx, 0)))); #endif #endif } #if 0 /* This is the startup, and finish stuff per exception table. */ /* XXX - Tad: exception handling section */ #ifndef EXCEPT_SECTION_ASM_OP #define EXCEPT_SECTION_ASM_OP "section\t.gcc_except_table,\"a\",@progbits" #endif #ifdef EXCEPT_SECTION_ASM_OP typedef struct { void *start_protect; void *end_protect; void *exception_handler; } exception_table; #endif /* EXCEPT_SECTION_ASM_OP */ #ifdef EXCEPT_SECTION_ASM_OP /* on machines which support it, the exception table lives in another section, but it needs a label so we can reference it... This sets up that label! */ asm (EXCEPT_SECTION_ASM_OP); exception_table __EXCEPTION_TABLE__[1] = { (void*)0, (void*)0, (void*)0 }; asm (TEXT_SECTION_ASM_OP); #endif /* EXCEPT_SECTION_ASM_OP */ #ifdef EXCEPT_SECTION_ASM_OP /* we need to know where the end of the exception table is... so this is how we do it! */ asm (EXCEPT_SECTION_ASM_OP); exception_table __EXCEPTION_END__[1] = { (void*)-1, (void*)-1, (void*)-1 }; asm (TEXT_SECTION_ASM_OP); #endif /* EXCEPT_SECTION_ASM_OP */ #endif void exception_section () { #ifdef ASM_OUTPUT_SECTION_NAME named_section (".gcc_except_table"); #else text_section (); #endif } /* from: my-cp-except.c */ /* VI: ":set ts=4" */ #if 0 #include <stdio.h> */ #include "config.h" #include "tree.h" #include "rtl.h" #include "cp-tree.h" #endif #include "decl.h" #if 0 #include "flags.h" #endif #include "insn-flags.h" #include "obstack.h" #if 0 #include "expr.h" #endif /* ====================================================================== Briefly the algorithm works like this: When a constructor or start of a try block is encountered, push_eh_entry (&eh_stack) is called. Push_eh_entry () creates a new entry in the unwind protection stack and returns a label to output to start the protection for that block. When a destructor or end try block is encountered, pop_eh_entry (&eh_stack) is called. Pop_eh_entry () returns the ehEntry it created when push_eh_entry () was called. The ehEntry structure contains three things at this point. The start protect label, the end protect label, and the exception handler label. The end protect label should be output before the call to the destructor (if any). If it was a destructor, then its parse tree is stored in the finalization variable in the ehEntry structure. Otherwise the finalization variable is set to NULL to reflect the fact that is the the end of a try block. Next, this modified ehEntry node is enqueued in the finalizations queue by calling enqueue_eh_entry (&queue,entry). +---------------------------------------------------------------+ |XXX: Will need modification to deal with partially | | constructed arrays of objects | | | | Basically, this consists of keeping track of how many | | of the objects have been constructed already (this | | should be in a register though, so that shouldn't be a | | problem. | +---------------------------------------------------------------+ When a catch block is encountered, there is a lot of work to be done. Since we don't want to generate the catch block inline with the regular flow of the function, we need to have some way of doing so. Luckily, we have a couple of routines "get_last_insn ()" and "set_last_insn ()" provided. When the start of a catch block is encountered, we save a pointer to the last insn generated. After the catch block is generated, we save a pointer to the first catch block insn and the last catch block insn with the routines "NEXT_INSN ()" and "get_last_insn ()". We then set the last insn to be the last insn generated before the catch block, and set the NEXT_INSN (last_insn) to zero. Since catch blocks might be nested inside other catch blocks, and we munge the chain of generated insns after the catch block is generated, we need to store the pointers to the last insn generated in a stack, so that when the end of a catch block is encountered, the last insn before the current catch block can be popped and set to be the last insn, and the first and last insns of the catch block just generated can be enqueue'd for output at a later time. Next we must insure that when the catch block is executed, all finalizations for the matching try block have been completed. If any of those finalizations throw an exception, we must call terminate according to the ARM (section r.15.6.1). What this means is that we need to dequeue and emit finalizations for each entry in the ehQueue until we get to an entry with a NULL finalization field. For any of the finalization entries, if it is not a call to terminate (), we must protect it by giving it another start label, end label, and exception handler label, setting its finalization tree to be a call to terminate (), and enqueue'ing this new ehEntry to be output at an outer level. Finally, after all that is done, we can get around to outputting the catch block which basically wraps all the "catch (...) {...}" statements in a big if/then/else construct that matches the correct block to call. ===================================================================== */ extern rtx emit_insn PROTO((rtx)); extern rtx gen_nop PROTO(()); /* local globals for function calls ====================================================================== */ /* used to cache "terminate ()", "unexpected ()", "set_terminate ()", and "set_unexpected ()" after default_conversion. (lib-except.c) */ static tree Terminate, Unexpected, SetTerminate, SetUnexpected, CatchMatch; /* used to cache __find_first_exception_table_match () for throw (lib-except.c) */ static tree FirstExceptionMatch; /* used to cache a call to __unwind_function () (lib-except.c) */ static tree Unwind; /* holds a ready to emit call to "terminate ()". */ static tree TerminateFunctionCall; /* ====================================================================== */ /* data structures for my various quick and dirty stacks and queues Eventually, most of this should go away, because I think it can be integrated with stuff already built into the compiler. */ /* =================================================================== */ struct labelNode { rtx label; struct labelNode *chain; }; /* this is the most important structure here. Basically this is how I store an exception table entry internally. */ struct ehEntry { rtx start_label; rtx end_label; rtx exception_handler_label; tree finalization; }; struct ehNode { struct ehEntry *entry; struct ehNode *chain; }; struct ehStack { struct ehNode *top; }; struct ehQueue { struct ehNode *head; struct ehNode *tail; }; struct exceptNode { rtx catchstart; rtx catchend; struct exceptNode *chain; }; struct exceptStack { struct exceptNode *top; }; /* ========================================================================= */ /* local globals - these local globals are for storing data necessary for generating the exception table and code in the correct order. ========================================================================= */ /* Holds the pc for doing "throw" */ rtx saved_pc; /* Holds the type of the thing being thrown. */ rtx saved_throw_type; /* Holds the value being thrown. */ rtx saved_throw_value; rtx throw_label; static struct ehStack ehstack; static struct ehQueue ehqueue; static struct ehQueue eh_table_output_queue; static struct exceptStack exceptstack; static struct labelNode *false_label_stack = NULL; static struct labelNode *caught_return_label_stack = NULL; /* ========================================================================= */ /* function prototypes */ static struct ehEntry *pop_eh_entry PROTO((struct ehStack *stack)); static void enqueue_eh_entry PROTO((struct ehQueue *queue, struct ehEntry *entry)); static void push_except_stmts PROTO((struct exceptStack *exceptstack, rtx catchstart, rtx catchend)); static int pop_except_stmts PROTO((struct exceptStack *exceptstack, rtx *catchstart, rtx *catchend)); static rtx push_eh_entry PROTO((struct ehStack *stack)); static struct ehEntry *dequeue_eh_entry PROTO((struct ehQueue *queue)); static void new_eh_queue PROTO((struct ehQueue *queue)); static void new_eh_stack PROTO((struct ehStack *stack)); static void new_except_stack PROTO((struct exceptStack *queue)); static void push_last_insn PROTO(()); static rtx pop_last_insn PROTO(()); static void push_label_entry PROTO((struct labelNode **labelstack, rtx label)); static rtx pop_label_entry PROTO((struct labelNode **labelstack)); static rtx top_label_entry PROTO((struct labelNode **labelstack)); static struct ehEntry *copy_eh_entry PROTO((struct ehEntry *entry)); /* All my cheesy stack/queue/misc data structure handling routines ========================================================================= */ static void push_label_entry (labelstack, label) struct labelNode **labelstack; rtx label; { struct labelNode *newnode=(struct labelNode*)xmalloc (sizeof (struct labelNode)); newnode->label = label; newnode->chain = *labelstack; *labelstack = newnode; } static rtx pop_label_entry (labelstack) struct labelNode **labelstack; { rtx label; struct labelNode *tempnode; if (! *labelstack) return NULL_RTX; tempnode = *labelstack; label = tempnode->label; *labelstack = (*labelstack)->chain; free (tempnode); return label; } static rtx top_label_entry (labelstack) struct labelNode **labelstack; { if (! *labelstack) return NULL_RTX; return (*labelstack)->label; } static void push_except_stmts (exceptstack, catchstart, catchend) struct exceptStack *exceptstack; rtx catchstart, catchend; { struct exceptNode *newnode = (struct exceptNode*) xmalloc (sizeof (struct exceptNode)); newnode->catchstart = catchstart; newnode->catchend = catchend; newnode->chain = exceptstack->top; exceptstack->top = newnode; } static int pop_except_stmts (exceptstack, catchstart, catchend) struct exceptStack *exceptstack; rtx *catchstart, *catchend; { struct exceptNode *tempnode; if (!exceptstack->top) { *catchstart = *catchend = NULL_RTX; return 0; } tempnode = exceptstack->top; exceptstack->top = exceptstack->top->chain; *catchstart = tempnode->catchstart; *catchend = tempnode->catchend; free (tempnode); return 1; } /* Push to permanent obstack for rtl generation. One level only! */ static struct obstack *saved_rtl_obstack; void push_rtl_perm () { extern struct obstack permanent_obstack; extern struct obstack *rtl_obstack; saved_rtl_obstack = rtl_obstack; rtl_obstack = &permanent_obstack; } /* Pop back to normal rtl handling. */ static void pop_rtl_from_perm () { extern struct obstack permanent_obstack; extern struct obstack *rtl_obstack; rtl_obstack = saved_rtl_obstack; } static rtx push_eh_entry (stack) struct ehStack *stack; { struct ehNode *node = (struct ehNode*)xmalloc (sizeof (struct ehNode)); struct ehEntry *entry = (struct ehEntry*)xmalloc (sizeof (struct ehEntry)); if (stack == NULL) { free (node); free (entry); return NULL_RTX; } /* These are saved for the exception table. */ push_rtl_perm (); entry->start_label = gen_label_rtx (); entry->end_label = gen_label_rtx (); entry->exception_handler_label = gen_label_rtx (); pop_rtl_from_perm (); entry->finalization = NULL_TREE; node->entry = entry; node->chain = stack->top; stack->top = node; enqueue_eh_entry (&eh_table_output_queue, copy_eh_entry (entry)); return entry->start_label; } static struct ehEntry * pop_eh_entry (stack) struct ehStack *stack; { struct ehNode *tempnode; struct ehEntry *tempentry; if (stack && (tempnode = stack->top)) { tempentry = tempnode->entry; stack->top = stack->top->chain; free (tempnode); return tempentry; } return NULL; } static struct ehEntry * copy_eh_entry (entry) struct ehEntry *entry; { struct ehEntry *newentry; newentry = (struct ehEntry*)xmalloc (sizeof (struct ehEntry)); memcpy ((void*)newentry, (void*)entry, sizeof (struct ehEntry)); return newentry; } static void enqueue_eh_entry (queue, entry) struct ehQueue *queue; struct ehEntry *entry; { struct ehNode *node = (struct ehNode*)xmalloc (sizeof (struct ehNode)); node->entry = entry; node->chain = NULL; if (queue->head == NULL) { queue->head = node; } else { queue->tail->chain = node; } queue->tail = node; } static struct ehEntry * dequeue_eh_entry (queue) struct ehQueue *queue; { struct ehNode *tempnode; struct ehEntry *tempentry; if (queue->head == NULL) return NULL; tempnode = queue->head; queue->head = queue->head->chain; tempentry = tempnode->entry; free (tempnode); return tempentry; } static void new_eh_queue (queue) struct ehQueue *queue; { queue->head = queue->tail = NULL; } static void new_eh_stack (stack) struct ehStack *stack; { stack->top = NULL; } static void new_except_stack (stack) struct exceptStack *stack; { stack->top = NULL; } /* ========================================================================= */ void lang_interim_eh (finalization) tree finalization; { if (finalization) end_protect (finalization); else start_protect (); } /* sets up all the global eh stuff that needs to be initialized at the start of compilation. This includes: - Setting up all the function call trees - Initializing the ehqueue - Initializing the eh_table_output_queue - Initializing the ehstack - Initializing the exceptstack */ void init_exception_processing () { extern tree define_function (); tree unexpected_fndecl, terminate_fndecl; tree set_unexpected_fndecl, set_terminate_fndecl; tree catch_match_fndecl; tree find_first_exception_match_fndecl; tree unwind_fndecl; tree temp, PFV; interim_eh_hook = lang_interim_eh; /* void (*)() */ PFV = build_pointer_type (build_function_type (void_type_node, void_list_node)); /* arg list for the build_function_type call for set_terminate () and set_unexpected () */ temp = tree_cons (NULL_TREE, PFV, void_list_node); push_lang_context (lang_name_c); set_terminate_fndecl = define_function ("set_terminate", build_function_type (PFV, temp), NOT_BUILT_IN, pushdecl, 0); set_unexpected_fndecl = define_function ("set_unexpected", build_function_type (PFV, temp), NOT_BUILT_IN, pushdecl, 0); unexpected_fndecl = define_function ("unexpected", build_function_type (void_type_node, void_list_node), NOT_BUILT_IN, pushdecl, 0); terminate_fndecl = define_function ("terminate", build_function_type (void_type_node, void_list_node), NOT_BUILT_IN, pushdecl, 0); catch_match_fndecl = define_function ("__throw_type_match", build_function_type (integer_type_node, tree_cons (NULL_TREE, string_type_node, tree_cons (NULL_TREE, ptr_type_node, void_list_node))), NOT_BUILT_IN, pushdecl, 0); find_first_exception_match_fndecl = define_function ("__find_first_exception_table_match", build_function_type (ptr_type_node, tree_cons (NULL_TREE, ptr_type_node, void_list_node)), NOT_BUILT_IN, pushdecl, 0); unwind_fndecl = define_function ("__unwind_function", build_function_type (void_type_node, tree_cons (NULL_TREE, ptr_type_node, void_list_node)), NOT_BUILT_IN, pushdecl, 0); Unexpected = default_conversion (unexpected_fndecl); Terminate = default_conversion (terminate_fndecl); SetTerminate = default_conversion (set_terminate_fndecl); SetUnexpected = default_conversion (set_unexpected_fndecl); CatchMatch = default_conversion (catch_match_fndecl); FirstExceptionMatch = default_conversion (find_first_exception_match_fndecl); Unwind = default_conversion (unwind_fndecl); BuiltinReturnAddress = default_conversion (builtin_return_address_fndecl); TerminateFunctionCall = build_function_call (Terminate, NULL_TREE); pop_lang_context (); throw_label = gen_label_rtx (); saved_pc = gen_rtx (REG, Pmode, 16); saved_throw_type = gen_rtx (REG, Pmode, 17); saved_throw_value = gen_rtx (REG, Pmode, 18); new_eh_queue (&ehqueue); new_eh_queue (&eh_table_output_queue); new_eh_stack (&ehstack); new_except_stack (&exceptstack); } /* call this to begin a block of unwind protection (ie: when an object is constructed) */ void start_protect () { if (doing_eh (0)) { emit_label (push_eh_entry (&ehstack)); } } /* call this to end a block of unwind protection. the finalization tree is the finalization which needs to be run in order to cleanly unwind through this level of protection. (ie: call this when a scope is exited)*/ void end_protect (finalization) tree finalization; { struct ehEntry *entry = pop_eh_entry (&ehstack); if (! doing_eh (0)) return; emit_label (entry->end_label); entry->finalization = finalization; enqueue_eh_entry (&ehqueue, entry); } /* call this on start of a try block. */ void expand_start_try_stmts () { if (doing_eh (1)) { start_protect (); } } void expand_end_try_stmts () { end_protect (integer_zero_node); } struct insn_save_node { rtx last; struct insn_save_node *chain; }; static struct insn_save_node *InsnSave = NULL; /* Used to keep track of where the catch blocks start. */ static void push_last_insn () { struct insn_save_node *newnode = (struct insn_save_node*) xmalloc (sizeof (struct insn_save_node)); newnode->last = get_last_insn (); newnode->chain = InsnSave; InsnSave = newnode; } /* Use to keep track of where the catch blocks start. */ static rtx pop_last_insn () { struct insn_save_node *tempnode; rtx temprtx; if (!InsnSave) return NULL_RTX; tempnode = InsnSave; temprtx = tempnode->last; InsnSave = InsnSave->chain; free (tempnode); return temprtx; } /* call this to start processing of all the catch blocks. */ void expand_start_all_catch () { struct ehEntry *entry; rtx label; if (! doing_eh (1)) return; emit_line_note (input_filename, lineno); label = gen_label_rtx (); /* The label for the exception handling block we will save. */ emit_label (label); push_label_entry (&caught_return_label_stack, label); /* Remember where we started. */ push_last_insn (); emit_insn (gen_nop ()); /* Will this help us not stomp on it? */ emit_insn (gen_rtx (USE, VOIDmode, saved_throw_type)); emit_insn (gen_rtx (USE, VOIDmode, saved_throw_value)); while (1) { entry = dequeue_eh_entry (&ehqueue); emit_label (entry->exception_handler_label); expand_expr (entry->finalization, const0_rtx, VOIDmode, 0); /* When we get down to the matching entry, stop. */ if (entry->finalization == integer_zero_node) break; free (entry); } /* This goes when the below moves out of our way. */ #if 1 label = gen_label_rtx (); emit_jump (label); #endif /* All this should be out of line, and saved back in the exception handler block area. */ #if 1 entry->start_label = entry->exception_handler_label; /* These are saved for the exception table. */ push_rtl_perm (); entry->end_label = gen_label_rtx (); entry->exception_handler_label = gen_label_rtx (); entry->finalization = TerminateFunctionCall; pop_rtl_from_perm (); emit_label (entry->end_label); enqueue_eh_entry (&eh_table_output_queue, copy_eh_entry (entry)); /* After running the finalization, continue on out to the next cleanup, if we have nothing better to do. */ emit_move_insn (saved_pc, gen_rtx (LABEL_REF, Pmode, entry->end_label)); /* Will this help us not stomp on it? */ emit_insn (gen_rtx (USE, VOIDmode, saved_throw_type)); emit_insn (gen_rtx (USE, VOIDmode, saved_throw_value)); emit_jump (throw_label); emit_label (entry->exception_handler_label); expand_expr (entry->finalization, const0_rtx, VOIDmode, 0); emit_barrier (); #endif emit_label (label); } /* call this to end processing of all the catch blocks. */ void expand_end_all_catch () { rtx catchstart, catchend, last; rtx label; if (! doing_eh (1)) return; /* Find the start of the catch block. */ last = pop_last_insn (); catchstart = NEXT_INSN (last); catchend = get_last_insn (); NEXT_INSN (last) = 0; set_last_insn (last); /* this level of catch blocks is done, so set up the successful catch jump label for the next layer of catch blocks. */ pop_label_entry (&caught_return_label_stack); push_except_stmts (&exceptstack, catchstart, catchend); /* Here we fall through into the continuation code. */ } /* this is called from expand_exception_blocks () to expand the toplevel finalizations for a function. */ void expand_leftover_cleanups () { struct ehEntry *entry; rtx first_label = NULL_RTX; if (! doing_eh (0)) return; /* Will this help us not stomp on it? */ emit_insn (gen_rtx (USE, VOIDmode, saved_throw_type)); emit_insn (gen_rtx (USE, VOIDmode, saved_throw_value)); while ((entry = dequeue_eh_entry (&ehqueue)) != 0) { if (! first_label) first_label = entry->exception_handler_label; emit_label (entry->exception_handler_label); expand_expr (entry->finalization, const0_rtx, VOIDmode, 0); /* leftover try block, opps. */ if (entry->finalization == integer_zero_node) abort (); free (entry); } if (first_label) { rtx label; struct ehEntry entry; /* These are saved for the exception table. */ push_rtl_perm (); label = gen_label_rtx (); entry.start_label = first_label; entry.end_label = label; entry.exception_handler_label = gen_label_rtx (); entry.finalization = TerminateFunctionCall; pop_rtl_from_perm (); emit_label (label); enqueue_eh_entry (&eh_table_output_queue, copy_eh_entry (&entry)); /* After running the finalization, continue on out to the next cleanup, if we have nothing better to do. */ emit_move_insn (saved_pc, gen_rtx (LABEL_REF, Pmode, entry.end_label)); /* Will this help us not stomp on it? */ emit_insn (gen_rtx (USE, VOIDmode, saved_throw_type)); emit_insn (gen_rtx (USE, VOIDmode, saved_throw_value)); emit_jump (throw_label); emit_label (entry.exception_handler_label); expand_expr (entry.finalization, const0_rtx, VOIDmode, 0); emit_barrier (); } } /* call this to start a catch block. Typename is the typename, and identifier is the variable to place the object in or NULL if the variable doesn't matter. If typename is NULL, that means its a "catch (...)" or catch everything. In that case we don't need to do any type checking. (ie: it ends up as the "else" clause rather than an "else if" clause) */ void expand_start_catch_block (declspecs, declarator) tree declspecs, declarator; { rtx false_label_rtx; rtx protect_label_rtx; tree type; tree decl; tree init; if (! doing_eh (1)) return; /* Create a binding level for the parm. */ expand_start_bindings (0); if (declspecs) { tree init_type; decl = grokdeclarator (declarator, declspecs, NORMAL, 1, NULL_TREE); /* Figure out the type that the initializer is. */ init_type = TREE_TYPE (decl); if (TREE_CODE (init_type) != REFERENCE_TYPE) init_type = build_reference_type (init_type); init = convert_from_reference (save_expr (make_tree (init_type, saved_throw_value))); /* Do we need the below two lines? */ /* Let `finish_decl' know that this initializer is ok. */ DECL_INITIAL (decl) = init; /* This needs to be preallocated under the try block, in a union of all catch variables. */ pushdecl (decl); type = TREE_TYPE (decl); /* peel back references, so they match. */ if (TREE_CODE (type) == REFERENCE_TYPE) type = TREE_TYPE (type); } else type = NULL_TREE; /* These are saved for the exception table. */ push_rtl_perm (); false_label_rtx = gen_label_rtx (); protect_label_rtx = gen_label_rtx (); pop_rtl_from_perm (); push_label_entry (&false_label_stack, false_label_rtx); push_label_entry (&false_label_stack, protect_label_rtx); if (type) { tree params; char *typestring; rtx call_rtx, return_value_rtx; tree catch_match_fcall; tree catchmatch_arg, argval; typestring = build_overload_name (type, 1, 1); params = tree_cons (NULL_TREE, combine_strings (build_string (strlen (typestring)+1, typestring)), tree_cons (NULL_TREE, make_tree (ptr_type_node, saved_throw_type), NULL_TREE)); catch_match_fcall = build_function_call (CatchMatch, params); call_rtx = expand_call (catch_match_fcall, NULL_RTX, 0); return_value_rtx = hard_function_value (integer_type_node, catch_match_fcall); /* did the throw type match function return TRUE? */ emit_cmp_insn (return_value_rtx, const0_rtx, NE, NULL_RTX, GET_MODE (return_value_rtx), 0, 0); /* if it returned FALSE, jump over the catch block, else fall into it */ emit_jump_insn (gen_bne (false_label_rtx)); finish_decl (decl, init, NULL_TREE, 0); } else { /* Fall into the catch all section. */ } /* This is the starting of something to protect. */ emit_label (protect_label_rtx); emit_line_note (input_filename, lineno); } /* Call this to end a catch block. Its responsible for emitting the code to handle jumping back to the correct place, and for emitting the label to jump to if this catch block didn't match. */ void expand_end_catch_block () { if (doing_eh (1)) { rtx start_protect_label_rtx; rtx end_protect_label_rtx; tree decls; struct ehEntry entry; /* label we jump to if we caught the exception */ emit_jump (top_label_entry (&caught_return_label_stack)); /* Code to throw out to outer context, if we get an throw from within our catch handler. */ /* These are saved for the exception table. */ push_rtl_perm (); entry.exception_handler_label = gen_label_rtx (); pop_rtl_from_perm (); emit_label (entry.exception_handler_label); emit_move_insn (saved_pc, gen_rtx (LABEL_REF, Pmode, top_label_entry (&caught_return_label_stack))); emit_jump (throw_label); /* No associated finalization. */ entry.finalization = NULL_TREE; /* Because we are reordered out of line, we have to protect this. */ /* label for the start of the protection region. */ start_protect_label_rtx = pop_label_entry (&false_label_stack); /* Cleanup the EH paramater. */ expand_end_bindings (decls = getdecls (), decls != NULL_TREE, 0); /* label we emit to jump to if this catch block didn't match. */ emit_label (end_protect_label_rtx = pop_label_entry (&false_label_stack)); /* Because we are reordered out of line, we have to protect this. */ entry.start_label = start_protect_label_rtx; entry.end_label = end_protect_label_rtx; /* These set up a call to throw the caught exception into the outer context. */ enqueue_eh_entry (&eh_table_output_queue, copy_eh_entry (&entry)); } } /* cheesyness to save some typing. returns the return value rtx */ rtx do_function_call (func, params, return_type) tree func, params, return_type; { tree func_call; func_call = build_function_call (func, params); expand_call (func_call, NULL_RTX, 0); if (return_type != NULL_TREE) return hard_function_value (return_type, func_call); return NULL_RTX; } /* is called from expand_excpetion_blocks () to generate the code in a function to "throw" if anything in the function needs to preform a throw. expands "throw" as the following psuedo code: throw: eh = find_first_exception_match (saved_pc); if (!eh) goto gotta_rethrow_it; goto eh; gotta_rethrow_it: saved_pc = __builtin_return_address (0); pop_to_previous_level (); goto throw; */ static void expand_builtin_throw () { tree fcall; tree params; rtx return_val_rtx; rtx gotta_rethrow_it = gen_label_rtx (); rtx gotta_call_terminate = gen_label_rtx (); rtx unwind_and_throw = gen_label_rtx (); rtx goto_unwind_and_throw = gen_label_rtx (); emit_label (throw_label); /* search for an exception handler for the saved_pc */ return_val_rtx = do_function_call (FirstExceptionMatch, tree_cons (NULL_TREE, make_tree (ptr_type_node, saved_pc), NULL_TREE), ptr_type_node); /* did we find one? */ emit_cmp_insn (return_val_rtx, const0_rtx, EQ, NULL_RTX, GET_MODE (return_val_rtx), 0, 0); /* if not, jump to gotta_rethrow_it */ emit_jump_insn (gen_beq (gotta_rethrow_it)); /* we found it, so jump to it */ emit_indirect_jump (return_val_rtx); /* code to deal with unwinding and looking for it again */ emit_label (gotta_rethrow_it); /* call to __builtin_return_address () */ params=tree_cons (NULL_TREE, integer_zero_node, NULL_TREE); fcall = build_function_call (BuiltinReturnAddress, params); return_val_rtx = expand_expr (fcall, NULL_RTX, SImode, 0); /* did __builtin_return_address () return a valid address? */ emit_cmp_insn (return_val_rtx, const0_rtx, EQ, NULL_RTX, GET_MODE (return_val_rtx), 0, 0); emit_jump_insn (gen_beq (gotta_call_terminate)); /* yes it did */ emit_move_insn (saved_pc, return_val_rtx); do_unwind (throw_label); emit_jump (throw_label); /* no it didn't --> therefore we need to call terminate */ emit_label (gotta_call_terminate); do_function_call (Terminate, NULL_TREE, NULL_TREE); } /* This is called to expand all the toplevel exception handling finalization for a function. It should only be called once per function. */ void expand_exception_blocks () { rtx catchstart, catchend; rtx last; static rtx funcend; funcend = gen_label_rtx (); emit_jump (funcend); /* expand_null_return (); */ while (pop_except_stmts (&exceptstack, &catchstart, &catchend)) { last = get_last_insn (); NEXT_INSN (last) = catchstart; PREV_INSN (catchstart) = last; NEXT_INSN (catchend) = 0; set_last_insn (catchend); } expand_leftover_cleanups (); { static int have_done = 0; if (! have_done && TREE_PUBLIC (current_function_decl) && ! DECL_INLINE (current_function_decl)) { have_done = 1; expand_builtin_throw (); } } emit_label (funcend); } /* call this to expand a throw statement. This follows the following algorithm: 1. Allocate space to save the current PC onto the stack. 2. Generate and emit a label and save its address into the newly allocate stack space since we can't save the pc directly. 3. If this is the first call to throw in this function: generate a label for the throw block 4. jump to the throw block label. */ void expand_throw (exp) tree exp; { rtx label; tree type; if (! doing_eh (1)) return; /* This is the label that represents where in the code we were, when we got an exception. This needs to be updated when we rethrow an exception, so that the matching routine knows to search out. */ label = gen_label_rtx (); emit_label (label); emit_move_insn (saved_pc, gen_rtx (LABEL_REF, Pmode, label)); if (exp) { /* throw expression */ /* First, decay it. */ exp = default_conversion (exp); type = TREE_TYPE (exp); { char *typestring = build_overload_name (type, 1, 1); tree throw_type = build1 (ADDR_EXPR, ptr_type_node, combine_strings (build_string (strlen (typestring)+1, typestring))); rtx throw_type_rtx = expand_expr (throw_type, NULL_RTX, VOIDmode, 0); rtx throw_value_rtx; emit_move_insn (saved_throw_type, throw_type_rtx); exp = convert_to_reference (build_reference_type (build_type_variant (TREE_TYPE (exp), 1, 0)), exp, CONV_STATIC, LOOKUP_COMPLAIN, NULL_TREE); if (exp == error_mark_node) error (" in thrown expression"); throw_value_rtx = expand_expr (build_unary_op (ADDR_EXPR, exp, 0), NULL_RTX, VOIDmode, 0); emit_move_insn (saved_throw_value, throw_value_rtx); } } else { /* rethrow current exception */ /* This part is easy, as we dont' have to do anything else. */ } emit_jump (throw_label); } /* end of: my-cp-except.c */ #endif /* Output the exception table. Return the number of handlers. */ int build_exception_table () { int count = 0; #ifdef TRY_NEW_EH extern FILE *asm_out_file; struct ehEntry *entry; tree eh_node_decl; if (! doing_eh (0)) return 0; while (entry = dequeue_eh_entry (&eh_table_output_queue)) { if (count == 0) { exception_section (); /* Beginning marker for table. */ ASM_OUTPUT_ALIGN (asm_out_file, 2); ASM_OUTPUT_LABEL (asm_out_file, "__EXCEPTION_TABLE__"); fprintf (asm_out_file, " .word 0, 0, 0\n"); } count++; output_exception_table_entry (asm_out_file, entry->start_label, entry->end_label, entry->exception_handler_label); } if (count) { /* Ending marker for table. */ ASM_OUTPUT_LABEL (asm_out_file, "__EXCEPTION_END__"); fprintf (asm_out_file, " .word -1, -1, -1\n"); } #endif /* TRY_NEW_EH */ return count; } void register_exception_table () { #ifdef TRY_NEW_EH emit_library_call (gen_rtx (SYMBOL_REF, Pmode, "__register_exceptions"), 0, VOIDmode, 1, gen_rtx (SYMBOL_REF, Pmode, "__EXCEPTION_TABLE__"), Pmode); #endif /* TRY_NEW_EH */ } /* Build a throw expression. */ tree build_throw (e) tree e; { e = build1 (THROW_EXPR, void_type_node, e); TREE_SIDE_EFFECTS (e) = 1; return e; }
26.903989
142
0.686587
[ "object" ]
982b4f64bd756db91d08da3ef191a99cb96e3b68
5,898
h
C
sim/utils/eigen_help.h
YilingQiao/diff_fem
83c6d2863057a9bdce3c740af42ae7e43dca6e08
[ "Apache-2.0" ]
18
2021-12-07T20:41:29.000Z
2022-02-27T21:57:20.000Z
sim/utils/eigen_help.h
YilingQiao/diff_fem
83c6d2863057a9bdce3c740af42ae7e43dca6e08
[ "Apache-2.0" ]
1
2022-03-17T07:17:52.000Z
2022-03-25T10:13:22.000Z
sim/utils/eigen_help.h
YilingQiao/diff_fem
83c6d2863057a9bdce3c740af42ae7e43dca6e08
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 by Inria, Mickaël Ly, Jean Jouve, Florence Bertails-Descoubes and Laurence Boissieux This file is part of ProjectiveFriction. ProjectiveFriction is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ProjectiveFriction is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ProjectiveFriction. If not, see <https://www.gnu.org/licenses/>. */ #ifndef EIGEN_KERNEL_H #define EIGEN_KERNEL_H /** @file * @brief Defines a CGAL cartesian kernel where the points are Eigen vectors. * Most CGAL libraries are parametrized by a Kernel which describe the space in * which the computation takes place. The file provide a Kernel EigenKernel in * which a point in space is described by an Eigen::Matrix<TinyScalar, 3, 1>. This Kernel allows * us to use the convenient CGAL algorithms on our Mesh. */ #include <CGAL/Bbox_3.h> #include <CGAL/Cartesian.h> #include <CGAL/Kernel/Return_base_tag.h> #include <CGAL/Kernel/Type_equality_wrapper.h> #include <CGAL/Origin.h> #include <Eigen/Core> template<typename TinyScalar, typename TinyConstants, class Construct_bbox_3> class EigenConstruct_bbox_3 : public Construct_bbox_3 { public: using Construct_bbox_3::operator(); CGAL::Bbox_3 operator()(const Eigen::Matrix<TinyScalar, 3, 1>& point) const { return CGAL::Bbox_3( point.x(), point.y(), point.z(), point.x(), point.y(), point.z()); } }; template<typename TinyScalar, typename TinyConstants> class EigenConstruct_coord_iterator { public: const typename Eigen::Matrix<TinyScalar, 3, 1>::Scalar* operator()(const Eigen::Matrix<TinyScalar, 3, 1>& point) { return point.data(); } const typename Eigen::Matrix<TinyScalar, 3, 1>::Scalar* operator()(const Eigen::Matrix<TinyScalar, 3, 1>& point, int) { return point.data() + point.size(); } }; template<typename TinyScalar, typename TinyConstants, typename Kernel, typename OldKernel> class EigenConstruct_point_3 { using Point_3 = typename Kernel::Point_3; using Rep = typename Point_3::Rep; using RT = typename Kernel::RT; using Line_3 = typename Kernel::Line_3; public: using result_type = Point_3; Rep operator()(CGAL::Return_base_tag, CGAL::Origin o) const { return Rep(o); } Rep operator()(CGAL::Return_base_tag, const RT& x, const RT& y, const RT& z) const { return Rep(x, y, z); } Rep operator()(CGAL::Return_base_tag, const RT& x, const RT& y, const RT& z, const RT& w) const { return Rep(x, y, z, w); } Point_3 operator()(const CGAL::Origin&) const { return Eigen::Matrix<TinyScalar, 3, 1>(0, 0, 0); } Point_3 operator()(const RT& x, const RT& y, const RT& z) const { return Eigen::Matrix<TinyScalar, 3, 1>(x, y, z); } const Point_3& operator()(const Point_3& p) const { return p; } template<typename OtherDerived> Point_3 operator()(const Eigen::EigenBase<OtherDerived>& other) const { return Eigen::Matrix<TinyScalar, 3, 1>(other); } Point_3 operator()(const Line_3& l) const { typename OldKernel::Construct_point_3 base_operator; return base_operator(l); } Point_3 operator()(const Line_3& l, int i) const { typename OldKernel::Construct_point_3 base_operator; return base_operator(l, i); } }; template<typename TinyScalar, typename TinyConstants, typename Kernel, typename Kernel_Base> class EigenCartesian_base : public Kernel_Base::template Base<Kernel>::Type { using OldKernel = typename Kernel_Base::template Base<Kernel>::Type; public: using Point_3 = Eigen::Matrix<TinyScalar, 3, 1>; using Construct_point_3 = EigenConstruct_point_3<TinyScalar, TinyConstants, Kernel, OldKernel>; using Cartesian_const_iterator_3 = const typename Eigen::Matrix<TinyScalar, 3, 1>::Scalar*; using Construct_cartesian_const_iterator_3 = EigenConstruct_coord_iterator<TinyScalar, TinyConstants>; using Construct_bbox_3 = EigenConstruct_bbox_3<TinyScalar, TinyConstants, typename OldKernel::Construct_bbox_3>; Construct_point_3 construct_point_3_object() const { return Construct_point_3(); } Construct_bbox_3 construct_bbox_3_object() const { return Construct_bbox_3(); } Construct_cartesian_const_iterator_3 construct_cartesian_const_iterator_3_object() const { return Construct_cartesian_const_iterator_3(); } template<typename Kernel2> struct Base { using Type = EigenCartesian_base<TinyScalar, TinyConstants, Kernel2, Kernel_Base>; }; }; /** * CGAL Cartesian Kernel where the points are Eigen Vectors. */ // struct EigenKernel // : public CGAL::Type_equality_wrapper< // EigenCartesian_base< // EigenKernel, // CGAL::Cartesian<typename Eigen::Matrix<TinyScalar, 3, 1>::Scalar> // >, // EigenKernel // > // { // }; template <typename TinyScalar, typename TinyConstants> struct EigenKernel : public CGAL::Type_equality_wrapper< EigenCartesian_base< TinyScalar, TinyConstants, EigenKernel<TinyScalar, TinyConstants>, CGAL::Cartesian<typename Eigen::Matrix<TinyScalar, 3, 1>::Scalar> >, EigenKernel<TinyScalar, TinyConstants> > { }; #endif
30.559585
121
0.683113
[ "mesh" ]
98305410061b2f1bb1e116866879daa8917a15e8
9,298
c
C
openair2/UTIL/OSA/osa_stream_eia.c
t0930198/OAI_nb_IoT
45212d3b2fd22fdeec8e0062844eaff8de3039a0
[ "Apache-2.0" ]
2
2018-01-08T06:59:34.000Z
2019-04-07T13:56:25.000Z
openair2/UTIL/OSA/osa_stream_eia.c
shahab1992/OAI
45212d3b2fd22fdeec8e0062844eaff8de3039a0
[ "Apache-2.0" ]
1
2021-05-28T09:06:21.000Z
2021-05-28T14:49:39.000Z
openair2/UTIL/OSA/osa_stream_eia.c
shahab1992/OAI
45212d3b2fd22fdeec8e0062844eaff8de3039a0
[ "Apache-2.0" ]
5
2019-02-14T16:06:26.000Z
2022-01-05T03:52:29.000Z
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the OAI Public License, Version 1.0 (the "License"); you may not use this file * except in compliance with the License. * You may obtain a copy of the License at * * http://www.openairinterface.org/?page_id=698 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <math.h> #include "assertions.h" #include <openssl/aes.h> #include <openssl/cmac.h> #include <openssl/evp.h> #include "UTIL/LOG/log.h" #include "osa_defs.h" #include "osa_snow3g.h" #include "osa_internal.h" // see spec 3GPP Confidentiality and Integrity Algorithms UEA2&UIA2. Document 1: UEA2 and UIA2 Specification. Version 1.1 /* OSA_MUL64x. * Input V: a 64-bit input. * Input c: a 64-bit input. * Output : a 64-bit output. * A 64-bit memory is allocated which is to be freed by the calling * function. * See section 4.3.2 for details. */ uint64_t OSA_MUL64x(uint64_t V, uint64_t c) { if ( V & 0x8000000000000000 ) return (V << 1) ^ c; else return V << 1; } /* OSA_MUL64xPOW. * Input V: a 64-bit input. * Input i: a positive integer. * Input c: a 64-bit input. * Output : a 64-bit output. * A 64-bit memory is allocated which is to be freed by the calling function. * See section 4.3.3 for details. */ uint64_t OSA_MUL64xPOW(uint64_t V, uint32_t i, uint64_t c) { if ( i == 0) return V; else return OSA_MUL64x( OSA_MUL64xPOW(V,i-1,c) , c); } /* OSA_MUL64. * Input V: a 64-bit input. * Input P: a 64-bit input. * Input c: a 64-bit input. * Output : a 64-bit output. * A 64-bit memory is allocated which is to be freed by the calling * function. * See section 4.3.4 for details. */ uint64_t OSA_MUL64(uint64_t V, uint64_t P, uint64_t c) { uint64_t result = 0; int i = 0; for ( i=0; i<64; i++) { if( ( P>>i ) & 0x1 ) result ^= OSA_MUL64xPOW(V,i,c); } return result; } /* osa_mask32bit. * Input n: an integer in 1-32. * Output : a 32 bit mask. * Prepares a 32 bit mask with required number of 1 bits on the MSB side. */ uint32_t osa_mask32bit(int n) { uint32_t mask=0x0; if ( n%32 == 0 ) return 0xffffffff; while (n--) mask = (mask>>1) ^ 0x80000000; return mask; } /*! * @brief Create integrity cmac t for a given message. * @param[in] stream_cipher Structure containing various variables to setup encoding * @param[out] out For EIA2 the output string is 32 bits long */ int stream_compute_integrity_eia1(stream_cipher_t *stream_cipher, uint8_t out[4]) { osa_snow_3g_context_t snow_3g_context; uint32_t K[4],IV[4], z[5]; int i=0,D; uint32_t MAC_I = 0; uint64_t EVAL; uint64_t V; uint64_t P; uint64_t Q; uint64_t c; uint64_t M_D_2; int rem_bits; uint32_t mask = 0; uint32_t *message; message = (uint32_t*)stream_cipher->message; /* To operate 32 bit message internally. */ /* Load the Integrity Key for SNOW3G initialization as in section 4.4. */ memcpy(K+3,stream_cipher->key+0,4); /*K[3] = key[0]; we assume K[3]=key[0]||key[1]||...||key[31] , with key[0] the * most important bit of key*/ memcpy(K+2,stream_cipher->key+4,4); /*K[2] = key[1];*/ memcpy(K+1,stream_cipher->key+8,4); /*K[1] = key[2];*/ memcpy(K+0,stream_cipher->key+12,4); /*K[0] = key[3]; we assume K[0]=key[96]||key[97]||...||key[127] , with key[127] the * least important bit of key*/ K[3] = hton_int32(K[3]); K[2] = hton_int32(K[2]); K[1] = hton_int32(K[1]); K[0] = hton_int32(K[0]); /* Prepare the Initialization Vector (IV) for SNOW3G initialization as in section 4.4. */ IV[3] = (uint32_t)stream_cipher->count; IV[2] = ((((uint32_t)stream_cipher->bearer) & 0x0000001F) << 27); IV[1] = (uint32_t)(stream_cipher->count) ^ ( (uint32_t)(stream_cipher->direction) << 31 ) ; IV[0] = ((((uint32_t)stream_cipher->bearer) & 0x0000001F) << 27) ^ ((uint32_t)(stream_cipher->direction & 0x00000001) << 15); //printf ("K:\n"); //hexprint(K, 16); //printf ("K[0]:%08X\n",K[0]); //printf ("K[1]:%08X\n",K[1]); //printf ("K[2]:%08X\n",K[2]); //printf ("K[3]:%08X\n",K[3]); //printf ("IV:\n"); //hexprint(IV, 16); //printf ("IV[0]:%08X\n",IV[0]); //printf ("IV[1]:%08X\n",IV[1]); //printf ("IV[2]:%08X\n",IV[2]); //printf ("IV[3]:%08X\n",IV[3]); z[0] = z[1] = z[2] = z[3] = z[4] = 0; /* Run SNOW 3G to produce 5 keystream words z_1, z_2, z_3, z_4 and z_5. */ osa_snow3g_initialize(K, IV, &snow_3g_context); osa_snow3g_generate_key_stream(5, z, &snow_3g_context); //printf ("z[0]:%08X\n",z[0]); //printf ("z[1]:%08X\n",z[1]); //printf ("z[2]:%08X\n",z[2]); //printf ("z[3]:%08X\n",z[3]); //printf ("z[4]:%08X\n",z[4]); P = ((uint64_t)z[0] << 32) | (uint64_t)z[1]; Q = ((uint64_t)z[2] << 32) | (uint64_t)z[3]; //printf ("P:%16lX\n",P); //printf ("Q:%16lX\n",Q); /* Calculation */ D = ceil( stream_cipher->blength / 64.0 ) + 1; //printf ("D:%d\n",D); EVAL = 0; c = 0x1b; /* for 0 <= i <= D-3 */ for (i=0; i<D-2; i++) { V = EVAL ^ ( (uint64_t)hton_int32(message[2*i]) << 32 | (uint64_t)hton_int32(message[2*i+1]) ); EVAL = OSA_MUL64(V,P,c); //printf ("Mi: %16X %16X\tEVAL: %16lX\n",hton_int32(message[2*i]),hton_int32(message[2*i+1]), EVAL); } /* for D-2 */ rem_bits = stream_cipher->blength % 64; if (rem_bits == 0) rem_bits = 64; mask = osa_mask32bit(rem_bits%32); if (rem_bits > 32) { M_D_2 = ( (uint64_t) hton_int32(message[2*(D-2)]) << 32 ) | (uint64_t) (hton_int32(message[2*(D-2)+1]) & mask); } else { M_D_2 = ( (uint64_t) hton_int32(message[2*(D-2)]) & mask) << 32 ; } V = EVAL ^ M_D_2; EVAL = OSA_MUL64(V,P,c); /* for D-1 */ EVAL ^= stream_cipher->blength; /* Multiply by Q */ EVAL = OSA_MUL64(EVAL,Q,c); MAC_I = (uint32_t)(EVAL >> 32) ^ z[4]; //printf ("MAC_I:%16X\n",MAC_I); MAC_I = hton_int32(MAC_I); memcpy(out, &MAC_I, 4); return 0; } int stream_compute_integrity_eia2(stream_cipher_t *stream_cipher, uint8_t out[4]) { uint8_t *m; uint32_t local_count; size_t size = 4; uint8_t data[16]; CMAC_CTX *cmac_ctx; uint32_t zero_bit = 0; uint32_t m_length; DevAssert(stream_cipher != NULL); DevAssert(stream_cipher->key != NULL); memset(data, 0, 16); zero_bit = stream_cipher->blength & 0x7; m_length = stream_cipher->blength >> 3; if (zero_bit > 0) m_length += 1; local_count = hton_int32(stream_cipher->count); m = calloc(m_length + 8, sizeof(uint8_t)); memcpy(&m[0], &local_count, 4); m[4] = ((stream_cipher->bearer & 0x1F) << 3) | ((stream_cipher->direction & 0x01) << 2); memcpy(&m[8], stream_cipher->message, m_length); #if defined(SECU_DEBUG) { int i; char payload[6 * sizeof(m) + 1]; int index = 0; LOG_T(OSA, "Blength: %u, Zero bits: %u\n", stream_cipher->blength, zero_bit); for (i = 0; i < sizeof(m); i++) index += sprintf(&payload[index], "0x%02x ", m[i]); LOG_D(OSA, "Payload: %s\n", payload); } #endif cmac_ctx = CMAC_CTX_new(); CMAC_Init(cmac_ctx, stream_cipher->key, stream_cipher->key_length, EVP_aes_128_cbc(), NULL); CMAC_Update(cmac_ctx, m, m_length + 8); CMAC_Final(cmac_ctx, data, &size); CMAC_CTX_free(cmac_ctx); memcpy(out, data, 4); free(m); return 0; } int stream_compute_integrity(uint8_t algorithm, stream_cipher_t *stream_cipher, uint8_t out[4]) { if (algorithm == EIA1_128_ALG_ID) { LOG_D(OSA, "EIA1 algorithm applied for integrity\n"); return stream_compute_integrity_eia1(stream_cipher, out); } else if (algorithm == EIA2_128_ALG_ID) { LOG_D(OSA, "EIA2 algorithm applied for integrity\n"); return stream_compute_integrity_eia2(stream_cipher, out); } LOG_E(OSA, "Provided integrity algorithm is currently not supported = %u\n", algorithm); return -1; } int stream_check_integrity(uint8_t algorithm, stream_cipher_t *stream_cipher, uint8_t *expected) { uint8_t result[4]; if (algorithm != EIA0_ALG_ID) { if (stream_compute_integrity(algorithm, stream_cipher, result) != 0) { return -1; } if (memcmp(result, expected, 4) != 0) { LOG_E(OSA, "Mismatch found in integrity for algorithm %u,\n" "\tgot %02x.%02x.%02x.%02x, expecting %02x.%02x.%02x.%02x\n", algorithm, result[0], result[1], result[2], result[3], expected[0], expected[1], expected[2], expected[3]); return -1; } } /* Integrity verification succeeded */ return 0; }
28.965732
127
0.627662
[ "vector" ]
9834f1558b643c2cab3651b5a2ed4fe43b7bf1d8
30,220
h
C
Surface_mesh_topology/include/CGAL/Face_graph_wrapper.h
baumhaus-project/cgal
f6f405009cbb8e682b088138d894429879d31d91
[ "CC0-1.0" ]
2
2020-12-12T09:30:07.000Z
2021-01-04T05:00:23.000Z
Surface_mesh_topology/include/CGAL/Face_graph_wrapper.h
baumhaus-project/cgal
f6f405009cbb8e682b088138d894429879d31d91
[ "CC0-1.0" ]
17
2018-01-10T13:32:24.000Z
2021-07-30T12:23:20.000Z
Surface_mesh_topology/include/CGAL/Face_graph_wrapper.h
baumhaus-project/cgal
f6f405009cbb8e682b088138d894429879d31d91
[ "CC0-1.0" ]
1
2019-02-21T15:26:25.000Z
2019-02-21T15:26:25.000Z
// Copyright (c) 2019 CNRS and LIRIS' Establishments (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org) // // $URL$ // $Id$ // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial // // Author(s) : Guillaume Damiand <guillaume.damiand@liris.cnrs.fr> // #ifndef CGAL_FACE_GRAPH_WRAPPER_H #define CGAL_FACE_GRAPH_WRAPPER_H 1 #include <CGAL/license/Surface_mesh_topology.h> #include <CGAL/Surface_mesh_topology/internal/Functors_for_face_graph_wrapper.h> #include <CGAL/Surface_mesh_topology/internal/Iterators_for_face_graph_wrapper.h> #include <CGAL/internal/Combinatorial_map_internal_functors.h> #include <CGAL/Polyhedron_3_fwd.h> #include <CGAL/Surface_mesh/Surface_mesh_fwd.h> #include <CGAL/Combinatorial_map_fwd.h> #include <CGAL/Generalized_map_fwd.h> #include <CGAL/Linear_cell_complex_fwd.h> #include <CGAL/Polygonal_schema_fwd.h> #include <bitset> namespace CGAL { //////////////////////////////////////////////////////////////////////////////// /** Class Face_graph_wrapper: to wrap any model of FaceGraph into a * Combinatorial map. For now, only for const models, i.e. does not support * modification operators. */ template<typename HEG_> class Face_graph_wrapper { public: typedef HEG_ HEG; typedef Face_graph_wrapper<HEG> Self; typedef boost::uint32_t /*std::size_t*/ size_type; typedef Self Refs; struct Dart_container { typedef typename boost::graph_traits<HEG>::halfedge_iterator iterator; typedef typename boost::graph_traits<HEG>::halfedge_iterator const_iterator; // TODO ? // typedef My_halfedge_iterator<HEG> iterator; // typedef My_halfedge_iterator<HEG> const_iterator; // TODO ? }; typedef typename boost::graph_traits<HEG>::halfedge_descriptor Dart_handle; typedef typename boost::graph_traits<HEG>::halfedge_descriptor Dart_const_handle; typedef Dart_handle Null_handle_type; // typedef CGAL::Void* Null_handle_type; static const Null_handle_type null_handle; //=Dart_handle(); static const Null_handle_type null_dart_handle; //=Dart_handle(); /// Number of marks static const size_type NB_MARKS = 32; static const size_type INVALID_MARK = NB_MARKS; /// The dimension of the combinatorial map. static const unsigned int dimension=2; static const unsigned int ambient_dimension=3; typedef typename boost::graph_traits<HEG>::vertex_descriptor vertex_descriptor; typedef typename boost::graph_traits<HEG>::edge_descriptor edge_descriptor; typedef typename boost::graph_traits<HEG>::face_descriptor face_descriptor; typedef boost::undirected_tag directed_category; typedef boost::disallow_parallel_edge_tag edge_parallel_category; struct SM_graph_traversal_category : public virtual boost::bidirectional_graph_tag, public virtual boost::vertex_list_graph_tag, public virtual boost::edge_list_graph_tag {}; typedef SM_graph_traversal_category traversal_category; Face_graph_wrapper(const HEG& f) : m_fg(f), mdarts(*this), m_nb_darts(0), m_marks_initialized(false), mnb_used_marks(0) { // Store locally the number of darts: the HEG must not be modified m_nb_darts=darts().size(); } void initialize_marks() const { if (m_marks_initialized) return; mmask_marks.reset(); for (size_type i=0; i<NB_MARKS; ++i) { mfree_marks_stack[i] =i; mindex_marks[i] =i; mnb_marked_darts[i] =0; mnb_times_reserved_marks[i]=0; } m_all_marks=get(CGAL::dynamic_halfedge_property_t<std::bitset<NB_MARKS> >(), m_fg); for (typename Dart_range::const_iterator it(darts().begin()), itend(darts().end()); it!=itend; ++it) { put(m_all_marks, it, std::bitset<NB_MARKS>()); } m_marks_initialized=true; } const HEG& get_fg() const { return m_fg; } template<unsigned int i> bool is_free(Dart_const_handle /* dh */) const { return false; } // Not possible to have a free dart with an HEG. bool is_free(Dart_const_handle /*dh*/, unsigned int /*i*/) const { return false; } // Not possible to have a free dart with an HEG. bool is_perforated(Dart_const_handle dh) const { return is_border(dh, m_fg); } Dart_const_handle get_beta(Dart_const_handle ADart, int B1) const { CGAL_assertion(B1>=0 && B1<=static_cast<int>(dimension)); if (B1==1) return internal::Get_beta<HEG, 1>::value(m_fg, ADart); if (B1==2) return internal::Get_beta<HEG, 2>::value(m_fg, ADart); return internal::Get_beta<HEG, 0>::value(m_fg, ADart); } template<int B1> Dart_const_handle get_beta(Dart_const_handle ADart) const { CGAL_assertion(B1>=0 && B1<=static_cast<int>(dimension)); return internal::Get_beta<HEG, B1>::value(m_fg, ADart); } bool is_empty() const { return number_of_darts()==0; } /* ?? bool is_dart_used(Dart_const_handle dh) const { return true; ?? } */ int highest_nonfree_dimension(Dart_const_handle /* dh */) const { return 2; } Dart_const_handle previous(Dart_const_handle ADart) const { return get_beta<0>(ADart); } Dart_const_handle next(Dart_const_handle ADart) const { return get_beta<1>(ADart); } Dart_const_handle opposite(Dart_const_handle dh) const { return get_beta<2>(dh); } Dart_const_handle opposite2(Dart_const_handle dh) const { return get_beta<2>(dh); } Dart_const_handle other_extremity(Dart_const_handle dh) const { return get_beta<1>(dh); } template<unsigned int dim> Dart_const_handle opposite(Dart_const_handle ADart) const { return this->template get_beta<dim>(ADart); } Dart_const_handle other_orientation(Dart_const_handle ADart) const { return ADart; } bool is_previous_exist(Dart_const_handle) const { return true; } bool is_next_exist(Dart_const_handle) const { return true; } template<unsigned int dim> bool is_opposite_exist(Dart_const_handle /* ADart */) const { return true; } template<typename ...Betas> Dart_handle beta(Dart_handle ADart, Betas... betas) { return CGAL::internal::Beta_functor<Self, Dart_handle, Betas...>:: run(*this, ADart, betas...); } template<typename ...Betas> Dart_const_handle beta(Dart_const_handle ADart, Betas... betas) const { return CGAL::internal::Beta_functor<const Self, Dart_const_handle, Betas...>:: run(*this, ADart, betas...); } template<int... Betas> Dart_handle beta(Dart_handle ADart) { return CGAL::internal::Beta_functor_static<Self, Dart_handle, Betas...>:: run(*this, ADart); } template<int... Betas> Dart_const_handle beta(Dart_const_handle ADart) const { return CGAL::internal::Beta_functor_static<const Self, Dart_const_handle, Betas...>:: run(*this, ADart); } size_type number_of_darts() const { return m_nb_darts; } size_type number_of_halfedges() const { return number_of_darts(); } size_type number_of_used_marks() const { return mnb_used_marks; } bool is_reserved(size_type amark) const { CGAL_assertion(amark<NB_MARKS); return (m_marks_initialized && mnb_times_reserved_marks[amark]!=0); } size_type number_of_marked_darts(size_type amark) const { CGAL_assertion( is_reserved(amark) ); return mnb_marked_darts[amark]; } size_type number_of_unmarked_darts(size_type amark) const { return number_of_darts() - number_of_marked_darts(amark); } bool is_whole_map_unmarked(size_type amark) const { return number_of_marked_darts(amark)==0; } bool is_whole_map_marked(size_type amark) const { return number_of_marked_darts(amark)==number_of_darts(); } class Exception_no_more_available_mark {}; size_type get_new_mark() const { initialize_marks(); if (mnb_used_marks==NB_MARKS) { std::cerr << "Not enough Boolean marks: " "increase NB_MARKS in item class." << std::endl; std::cerr << " (exception launched)" << std::endl; throw Exception_no_more_available_mark(); } size_type m=mfree_marks_stack[mnb_used_marks]; mused_marks_stack[mnb_used_marks]=m; mindex_marks[m]=mnb_used_marks; mnb_times_reserved_marks[m]=1; ++mnb_used_marks; CGAL_assertion(is_whole_map_unmarked(m)); return m; } void share_a_mark(size_type amark) const { CGAL_assertion( is_reserved(amark) ); ++mnb_times_reserved_marks[amark]; } size_type get_number_of_times_mark_reserved(size_type amark) const { CGAL_assertion( is_reserved(amark) ); return mnb_times_reserved_marks[amark]; } void negate_mark(size_type amark) const { CGAL_assertion(is_reserved(amark)); mnb_marked_darts[amark]=number_of_darts()-mnb_marked_darts[amark]; mmask_marks.flip(amark); } void mark_null_dart( size_type /*amark*/) const {} bool get_dart_mark(Dart_const_handle ADart, size_type amark) const { CGAL_assertion(is_reserved(amark)); return get(m_all_marks, ADart)[amark]; } void set_dart_mark(Dart_const_handle ADart, size_type amark, bool avalue) const { CGAL_assertion(is_reserved(amark)); const_cast<std::bitset<NB_MARKS>& >(get(m_all_marks, ADart)).set(amark, avalue); } void flip_dart_mark(Dart_const_handle ADart, size_type amark) const { set_dart_mark(ADart, amark, !get_dart_mark(ADart, amark)); } bool is_marked(Dart_const_handle adart, size_type amark) const { CGAL_assertion(is_reserved(amark)); return get_dart_mark(adart, amark)!=mmask_marks[amark]; } void set_mark_to(Dart_const_handle adart, size_type amark, bool astate) const { CGAL_assertion(is_reserved(amark)); if (is_marked(adart, amark)!=astate) { if (astate) ++mnb_marked_darts[amark]; else --mnb_marked_darts[amark]; flip_dart_mark(adart, amark); } } void mark(Dart_const_handle adart, size_type amark) const { CGAL_assertion(is_reserved(amark)); if (is_marked(adart, amark)) return; ++mnb_marked_darts[amark]; flip_dart_mark(adart, amark); } void unmark(Dart_const_handle adart, size_type amark) const { CGAL_assertion( adart!=this->null_dart_handle ); CGAL_assertion( is_reserved(amark) ); if (!is_marked(adart, amark)) return; --mnb_marked_darts[amark]; flip_dart_mark(adart, amark); } void unmark_all(size_type amark) const { CGAL_assertion( is_reserved(amark) ); if ( is_whole_map_marked(amark) ) { negate_mark(amark); } else if ( !is_whole_map_unmarked(amark) ) { for (typename Dart_range::const_iterator it(darts().begin()), itend(darts().end()); it!=itend; ++it) unmark(*it, amark); } CGAL_assertion(is_whole_map_unmarked(amark)); } void free_mark(size_type amark) const { CGAL_assertion( is_reserved(amark) ); if ( mnb_times_reserved_marks[amark]>1 ) { --mnb_times_reserved_marks[amark]; return; } unmark_all(amark); // 1) We remove amark from the array mused_marks_stack by // replacing it with the last mark in this array. mused_marks_stack[mindex_marks[amark]] = mused_marks_stack[--mnb_used_marks]; mindex_marks[mused_marks_stack[mnb_used_marks]] = mindex_marks[amark]; // 2) We add amark in the array mfree_marks_stack and update its index. mfree_marks_stack[ mnb_used_marks ]=amark; mindex_marks[amark] = mnb_used_marks; mnb_times_reserved_marks[amark]=0; } bool is_without_boundary(unsigned int i) const { CGAL_assertion(1<=i && i<=dimension); if (i==1) return true; for ( typename Dart_range::const_iterator it(darts().begin()), itend(darts().end()); it!=itend; ++it) { if (is_perforated(it)) return false; } return true; } bool is_without_boundary() const { return is_without_boundary(2); } //************************************************************************** // Dart_of_cell_range template<unsigned int i> struct Dart_of_cell_range { typedef CGAL::internal::FGW_cell_iterator<Self, i> iterator; typedef CGAL::internal::FGW_cell_iterator<Self, i> const_iterator; Dart_of_cell_range(const Self &amap, Dart_handle adart) : mmap(amap), m_initdart(adart), msize(0) {} const_iterator begin() const { return const_iterator(mmap, m_initdart); } const_iterator end() const { return const_iterator(mmap, m_initdart, mmap.null_handle); } size_type size() const { if (msize==0) { for (const_iterator it=begin(), itend=end(); it!=itend; ++it) { ++msize; } } return msize; } bool empty() const { return mmap.is_empty(); } private: const Self & mmap; Dart_handle m_initdart; mutable typename Self::size_type msize; }; //************************************************************************** // Dart_of_cell_const_range /* template<unsigned int i,int dim=Self::dimension> struct Dart_of_cell_const_range // TODO REMOVE ?? {}; */ //-------------------------------------------------------------------------- template<unsigned int i> Dart_of_cell_range<i> darts_of_cell(Dart_handle adart) { return Dart_of_cell_range<i>(*this,adart); } //-------------------------------------------------------------------------- template<unsigned int i> Dart_of_cell_range<i> darts_of_cell(Dart_const_handle adart) const { return Dart_of_cell_range<i>(*this,adart); } // Before it was Dart_of_cell_const_range<i> //************************************************************************** // Dart_range struct Dart_range { typedef CGAL::internal::FGW_dart_iterator_basic_of_all<Self> iterator; typedef CGAL::internal::FGW_dart_iterator_basic_of_all<Self> const_iterator; Dart_range(const Self &amap) : mmap(amap), msize(0) {} iterator begin() { return iterator(mmap); } iterator end() { return iterator(mmap,mmap.null_handle); } const_iterator begin() const { return const_iterator(mmap); } const_iterator end() const { return const_iterator(mmap,mmap.null_handle); } size_type size() const { if (msize==0) { msize=static_cast<size_type>(halfedges(mmap.get_fg()).size()); } return msize; } bool empty() const { return mmap.is_empty(); } size_type capacity() const { return static_cast<size_type>(num_halfedges(mmap.get_fg())); } bool is_used(size_type i) const { return internal::Is_index_used<HEG>::run(mmap.get_fg(), i); } size_type index(const_iterator it) const { return internal::Index_from_halfedge_descriptor<HEG>:: run(mmap.get_fg(), *it); } size_type index(Dart_const_handle it) const { return internal::Index_from_halfedge_descriptor<HEG>:: run(mmap.get_fg(), it); } private: const Self & mmap; mutable typename Self::size_type msize; }; //************************************************************************** // Dart_const_range // TODO REMOVE ? /* struct Dart_const_range { typedef CGAL::FGW_dart_iterator_basic_of_all<Self, true> const_iterator; Dart_const_range(const Self &amap) : mmap(amap), msize(0) {} const_iterator begin() const { return const_iterator(mmap); } const_iterator end() const { return const_iterator(mmap,mmap.null_handle); } size_type size() const { if (msize==0) { for (const_iterator it=begin(), itend=end(); it!=itend; ++it) { ++msize; } } return msize; } bool empty() const { return mmap.is_empty(); } private: const Self & mmap; mutable typename Self::size_type msize; };*/ //************************************************************************** Dart_range& darts() { return mdarts; } //-------------------------------------------------------------------------- const Dart_range& darts() const { return mdarts; } // Before it was Dart_const_range(*this) //************************************************************************** Dart_handle dart_handle(size_type i) { CGAL_assertion(darts().is_used(i)); return internal::Halfedge_descriptor_from_index<HEG>::run(get_fg(), i); } Dart_const_handle dart_handle(size_type i) const { CGAL_assertion(darts().is_used(i)); return internal::Halfedge_descriptor_from_index<HEG>::run(get_fg(), i); } template <unsigned int i> bool belong_to_same_cell(Dart_const_handle adart1, Dart_const_handle adart2) const { for (typename Dart_of_cell_range<i>::iterator it=darts_of_cell<i>(adart1).begin(), itend=darts_of_cell<i>(adart1).end(); it!=itend; ++it) { if (*it==adart2) { return true; } } return false; } template <unsigned int i> bool is_whole_cell_unmarked(Dart_const_handle adart, size_type amark) const { for (typename Dart_of_cell_range<i>::iterator it=darts_of_cell<i>(adart).begin(), itend=darts_of_cell<i>(adart).end(); it!=itend; ++it) { if (is_marked(*it, amark)) { return false; } } return true; } template <unsigned int i> bool is_whole_cell_marked(Dart_const_handle adart, size_type amark) const { for (typename Dart_of_cell_range<i>::iterator it=darts_of_cell<i>(adart).begin(), itend=darts_of_cell<i>(adart).end(); it!=itend; ++it) { if (!is_marked(*it, amark)) { return false; } } return true; } template <unsigned int i> size_type mark_cell(Dart_const_handle adart, size_type amark) const { size_type res=0; for (typename Dart_of_cell_range<i>::iterator it=darts_of_cell<i>(adart).begin(), itend=darts_of_cell<i>(adart).end(); it!=itend; ++it) { mark(*it, amark); ++res; } return res; } size_type mark_cell(Dart_const_handle adart, unsigned int i, size_type amark) const { if (i==0) { return mark_cell<0>(adart, amark); } else if (i==1) { return mark_cell<1>(adart, amark); } else if (i==2) { return mark_cell<2>(adart, amark); } return mark_cell<3>(adart, amark); } template <unsigned int i> size_type unmark_cell(Dart_const_handle adart, size_type amark) const { size_type res=0; for (typename Dart_of_cell_range<i>::iterator it=darts_of_cell<i>(adart).begin(), itend=darts_of_cell<i>(adart).end(); it!=itend; ++it) { unmark(*it, amark); ++res; } return res; } template <unsigned int i> size_type mark_oriented_cell(Dart_const_handle adart, size_type amark, size_type amark2=INVALID_MARK) const { size_type res=0; for (typename Dart_of_cell_range<i>::iterator it=darts_of_cell<i>(adart).begin(), itend=darts_of_cell<i>(adart).end(); it!=itend; ++it) { mark(*it, amark); ++res; if (amark2!=INVALID_MARK) { mark(*it, amark2); } } return res; } template <unsigned int i> size_type unmark_oriented_cell(Dart_const_handle adart, size_type amark, size_type amark2=INVALID_MARK) const { size_type res=0; for (typename Dart_of_cell_range<i>::iterator it=darts_of_cell<i>(adart).begin(), itend=darts_of_cell<i>(adart).end(); it!=itend; ++it) { unmark(*it, amark); ++res; if (amark2!=INVALID_MARK) { unmark(*it, amark2); } } return res; } std::size_t orient(size_type amark) const { negate_mark(amark); return number_of_darts(); } std::vector<unsigned int> count_marked_cells(size_type amark, const std::vector<unsigned int>& acells) const { std::vector<unsigned int> res(dimension+2); std::vector<size_type> marks(dimension+2); // Initialization of the result for (unsigned int i=0; i<dimension+2; ++i) { res[i]=0; marks[i]=INVALID_MARK; } // Mark reservation for (unsigned int i=0; i<acells.size(); ++i) { CGAL_assertion(acells[i]<=dimension+1); if (marks[acells[i]]==INVALID_MARK ) { marks[acells[i]]=get_new_mark(); assert(is_whole_map_unmarked(marks[acells[i]])); } } // Counting and marking cells for (typename Dart_range::const_iterator it(darts().begin()), itend(darts().end()); it!=itend; ++it) { if (is_marked(*it, amark)) { for (unsigned int i=0; i<acells.size(); ++i) { if (!is_marked(*it, marks[acells[i]])) { mark_cell(*it, acells[i], marks[acells[i]]); ++res[acells[i]]; } } } } // Unmarking darts std::vector<size_type> tounmark; for (unsigned int i=0; i<acells.size(); ++i) { if (is_whole_map_marked(marks[acells[i]]) || is_whole_map_unmarked(marks[acells[i]])) { free_mark(marks[acells[i]]); } else { tounmark.push_back(marks[acells[i]]); } } if (tounmark.size()>0) { for (typename Dart_range::const_iterator it(darts().begin()), itend(darts().end()); it!=itend; ++it) { for (unsigned int i=0; i<tounmark.size(); ++i) { unmark(*it, tounmark[i]); } } for (unsigned int i=0; i<tounmark.size(); ++i) { CGAL_assertion(is_whole_map_unmarked(tounmark[i])); free_mark(tounmark[i]); } } return res; } std::vector<unsigned int> count_cells(const std::vector<unsigned int>& acells) const { std::vector<unsigned int> res; size_type m=get_new_mark(); negate_mark(m); // We mark all the cells. res=count_marked_cells(m, acells); negate_mark(m); // We unmark the cells free_mark(m); return res; } std::vector<unsigned int> count_all_cells() const { std::vector<unsigned int> dim(dimension+2); for ( unsigned int i=0; i<=dimension+1; ++i) { dim[i]=i; } return count_cells(dim); } std::ostream& display_characteristics(std::ostream & os) const { std::vector<unsigned int> cells(dimension+2); for ( unsigned int i=0; i<=dimension+1; ++i) { cells[i]=i; } std::vector<unsigned int> res=count_cells(cells); os<<"#Darts="<<number_of_darts(); for (unsigned int i=0; i<=dimension; ++i) os<<", #"<<i<<"-cells="<<res[i]; os<<", #ccs="<<res[dimension+1]; return os; } protected: const HEG& m_fg; Dart_range mdarts; size_type m_nb_darts; mutable bool m_marks_initialized; /// True iff marks are initialized (we use lazy initialization) /// Number of times each mark is reserved. 0 if the mark is free. mutable size_type mnb_times_reserved_marks[NB_MARKS]; /// Mask marks to know the value of unmark dart, for each index i. mutable std::bitset<NB_MARKS> mmask_marks; /// Number of used marks. mutable size_type mnb_used_marks; /// Index of each mark, in mfree_marks_stack or in mfree_marks_stack. mutable size_type mindex_marks[NB_MARKS]; /// "Stack" of free marks. mutable size_type mfree_marks_stack[NB_MARKS]; /// "Stack" of used marks. mutable size_type mused_marks_stack[NB_MARKS]; /// Number of marked darts for each used marks. mutable size_type mnb_marked_darts[NB_MARKS]; /// Array of property maps; one for each reserved mark. typedef typename boost::property_map <HEG, CGAL::dynamic_halfedge_property_t<std::bitset<NB_MARKS> > >::const_type MarkPMap; mutable MarkPMap m_all_marks; }; /// null_handle // template <typename HEG> // const typename Face_graph_wrapper<HEG>::Null_handle_type // Face_graph_wrapper<HEG>::null_handle=nullptr; template <typename HEG> const typename Face_graph_wrapper<HEG>::Null_handle_type Face_graph_wrapper<HEG>::null_handle=typename Face_graph_wrapper<HEG>::Dart_handle(); /// null_dart_handle // template <typename HEG> // const typename Face_graph_wrapper<HEG>::Null_handle_type // Face_graph_wrapper<HEG>::null_dart_handle=nullptr; template <typename HEG> const typename Face_graph_wrapper<HEG>::Null_handle_type Face_graph_wrapper<HEG>::null_dart_handle=typename Face_graph_wrapper<HEG>::Dart_handle(); template<class Base, class HEG> struct Get_map { typedef Face_graph_wrapper<HEG> type; typedef const Face_graph_wrapper<HEG> storage_type; Get_map(const HEG& heg): m_map(heg) {} static const HEG& get_mesh(const storage_type& amap) { return amap.get_fg(); } storage_type m_map; }; template <unsigned int d, typename Refs, typename Items, typename Alloc, typename Storage, class Map> struct Get_map<CGAL::Combinatorial_map_base<d, Refs, Items, Alloc, Storage>, Map> { typedef Map type; typedef const Map& storage_type; Get_map(const Map& heg): m_map(heg) {} static const Map& get_mesh(storage_type& amap) { return amap; } storage_type m_map; }; template <unsigned int d, typename Refs, typename Items, typename Alloc, typename Storage, class Map> struct Get_map<CGAL::Generalized_map_base<d, Refs, Items, Alloc, Storage>, Map> { typedef Map type; typedef const Map& storage_type; Get_map(const Map& heg): m_map(heg) {} static const Map& get_mesh(storage_type& amap) { return amap; } storage_type m_map; }; template <unsigned int d, unsigned int d2, typename Traits, typename Items, typename Alloc, template<unsigned int,class,class,class,class> class Map, typename Refs, typename Storage, class LCC> struct Get_map<CGAL::Linear_cell_complex_base<d, d2, Traits, Items, Alloc, Map, Refs, Storage>, LCC> { typedef LCC type; typedef const LCC& storage_type; Get_map(const LCC& heg): m_map(heg) {} static const LCC& get_mesh(storage_type& amap) { return amap; } storage_type m_map; }; template <unsigned int d, typename Items, typename Alloc, typename Storage, class Map> struct Get_map<CGAL::Combinatorial_map<d, Items, Alloc, Storage>, Map> { typedef Map type; typedef const Map& storage_type; Get_map(const Map& heg): m_map(heg) {} static const Map& get_mesh(storage_type& amap) { return amap; } storage_type m_map; }; template <typename Items, typename Alloc, typename Storage, class Map> struct Get_map<CGAL::Surface_mesh_topology:: Polygonal_schema_with_combinatorial_map<Items, Alloc, Storage>, Map> { typedef Map type; typedef const Map& storage_type; Get_map(const Map& heg): m_map(heg) {} static const Map& get_mesh(storage_type& amap) { return amap; } storage_type m_map; }; template <unsigned int d, typename Items, typename Alloc, typename Storage, class Map> struct Get_map<CGAL::Generalized_map<d, Items, Alloc, Storage>, Map> { typedef Map type; typedef const Map& storage_type; Get_map(const Map& heg): m_map(heg) {} static const Map& get_mesh(storage_type& amap) { return amap; } storage_type m_map; }; template <typename Items, typename Alloc, typename Storage, class Map> struct Get_map<CGAL::Surface_mesh_topology:: Polygonal_schema_with_generalized_map<Items, Alloc, Storage>, Map> { typedef Map type; typedef const Map& storage_type; Get_map(const Map& heg): m_map(heg) {} static const Map& get_mesh(storage_type& amap) { return amap; } storage_type m_map; }; template <unsigned int d, unsigned int d2, typename Traits, typename Items, typename Alloc, template<unsigned int,class,class,class,class> class Map, typename Storage, class LCC> struct Get_map<CGAL::Linear_cell_complex_for_combinatorial_map <d, d2, Traits, Items, Alloc, Map, Storage>, LCC> { typedef LCC type; typedef const LCC& storage_type; Get_map(const LCC& heg): m_map(heg) {} static const LCC& get_mesh(storage_type& amap) { return amap; } storage_type m_map; }; template <unsigned int d, unsigned int d2, typename Traits, typename Items, typename Alloc, template<unsigned int,class,class,class,class> class Map, typename Storage, class LCC> struct Get_map<CGAL::Linear_cell_complex_for_generalized_map <d, d2, Traits, Items, Alloc, Map, Storage>, LCC> { typedef LCC type; typedef const LCC& storage_type; Get_map(const LCC& heg): m_map(heg) {} static const LCC& get_mesh(storage_type& amap) { return amap; } storage_type m_map; }; template<class Mesh_> struct Get_traits { typedef Mesh_ Mesh; typedef typename Mesh::Traits Kernel; typedef typename Mesh::Point Point; typedef typename Mesh::Vector Vector; template<class Dart_handle> static const Point& get_point(const Mesh& m, Dart_handle dh) { return m.point(dh); } }; template<class P> struct Get_traits<CGAL::Surface_mesh<P> > { typedef CGAL::Surface_mesh<P> Mesh; typedef typename CGAL::Kernel_traits<P>::Kernel Kernel; typedef typename Kernel::Point_3 Point; typedef typename Kernel::Vector_3 Vector; template<class Dart_handle> static const Point& get_point(const Mesh& m, Dart_handle dh) { return m.point(m.source(dh)); } }; template<class PolyhedronTraits_3, class PolyhedronItems_3, template<class T, class I, class A> class T_HDS, class Alloc> struct Get_traits<CGAL::Polyhedron_3<PolyhedronTraits_3, PolyhedronItems_3, T_HDS, Alloc> > { typedef CGAL::Polyhedron_3<PolyhedronTraits_3, PolyhedronItems_3, T_HDS, Alloc> Mesh; typedef PolyhedronTraits_3 Kernel; typedef typename Kernel::Point_3 Point; typedef typename Kernel::Vector_3 Vector; template<class Dart_handle> static const Point& get_point(const Mesh& /*m*/, Dart_handle dh) { return dh->opposite()->vertex()->point(); } }; } // Namespace CGAL #endif // CGAL_FACE_GRAPH_WRAPPER_H // // EOF //
32.35546
99
0.653375
[ "mesh", "vector", "model" ]
983507f0f8b5dfaed8dee0f67dc74d10132d8106
491
h
C
ZeroEngine/Tile.h
bamtoll09/GROWN
0f2098bce97a739f9b786d487136aa44f1b6a227
[ "MIT" ]
null
null
null
ZeroEngine/Tile.h
bamtoll09/GROWN
0f2098bce97a739f9b786d487136aa44f1b6a227
[ "MIT" ]
null
null
null
ZeroEngine/Tile.h
bamtoll09/GROWN
0f2098bce97a739f9b786d487136aa44f1b6a227
[ "MIT" ]
null
null
null
#pragma once #include <Zero.h> #include "Player.h" class Tile : public ZeroIScene { private: int tileNum; bool leftPushed, rightPushed; bool rectangleCollision(Player *_r1, ZeroIScene *_r2); public: ZeroSprite *tile, * border; Player *player; RECT R1, R2, temp; public: Tile(Player *_player, int no); ~Tile(); virtual void Update(float eTime); virtual void Render(); void isLeftPushed(bool tr); void isRightPushed(bool tr); bool isLeftPushed(); bool isRightPushed(); };
15.83871
55
0.714868
[ "render" ]
9836656e93fbd6b81adb07a1d2ada444e1133c0b
3,285
h
C
SDLWnd.h
ber4444/Galaxy-Renderer-on-iOS
f453a725f6925ef4815ae191bd18aad3f099b7f3
[ "Unlicense" ]
1
2017-02-01T23:17:16.000Z
2017-02-01T23:17:16.000Z
SDLWnd.h
ber4444/Galaxy-Renderer-on-iOS
f453a725f6925ef4815ae191bd18aad3f099b7f3
[ "Unlicense" ]
null
null
null
SDLWnd.h
ber4444/Galaxy-Renderer-on-iOS
f453a725f6925ef4815ae191bd18aad3f099b7f3
[ "Unlicense" ]
null
null
null
#ifndef _SDL_WINDOW_H #define _SDL_WINDOW_H #include <string> #ifdef __APPLE__ #include "TargetConditionals.h" #if TARGET_OS_IPHONE==1 extern "C" { #include "jwzglesI.h" } #include "jwzgles.h" #elif TARGET_OS_MAC==1 #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <OpenGL/glext.h> #define GL_POINT_SPRITE_OES GL_POINT_SPRITE #define GL_COORD_REPLACE_OES GL_COORD_REPLACE_ARB #else #error "Unsupported Apple platform (only OS X and iPhone are supported out of the box)" #endif #else /* ifdef __APPLE__ */ #error "Replace this line with #define linux, and prepare to do minor adjustments" #ifdef SDL_VIDEO_OPENGL_ES2 /* for Android, TODO: add proper ifdef Android version of SDL loads libGLESv1_CM.so and imports GL10 (ES 1.0 lib) but the manifest enables OpenGL ES 2.0 for some reason */ #error "You should use version 1 of GLES" #endif #endif /* ifdef __APPLE__ */ #ifdef linux #include <GL/gl.h> #include <GL/glu.h> #include <GL/glext.h> #include <GL/glx.h> # ifndef GL_GLEXT_PROTOTYPES # define GL_GLEXT_PROTOTYPES /* for glBindBuffer */ # endif #endif #include "SDL.h" #if TARGET_OS_IPHONE==1 #include "SDL_opengles.h" #else #include "SDL_opengl.h" #endif #include "Vector.h" /** \brief Basic infrastructure for grafical output using SDL/OpenGL */ class SDLWindow { public: SDLWindow(int width, int height, double axisLen, const std::string &caption); virtual ~SDLWindow(); void MainLoop(); void ExitMainLoop(); int GetWidth() const; int GetHeight() const; virtual void Render() = 0; protected: virtual void PollEvents(); virtual void OnProcessEvents(SDL_Event &e); //----------------------------------------- // Camera setup //----------------------------------------- const Vec3D& GetCamPos() const; const Vec3D& GetCamOrient() const; const Vec3D& GetCamLookAt() const; void SetCameraOrientation(const Vec3D &orientation); void SetCamera(const Vec3D &pos, const Vec3D &lookAt, const Vec3D &orient); void AdjustCamera(); //----------------------------------------- // Basic graphics functionality //----------------------------------------- #if TARGET_OS_IPHONE==0 void DrawAxis(const Vec2D &origin); #endif int GetFPS() const; void SaveToTGA(const std::string &sName); void SaveToTGA(int idx = -1); //----------------------------------------- // misc //----------------------------------------- void ScaleAxis(double scale); double GetFOV() const; SDL_Surface *Surface(); static void TextOut(int x, int y, const char *fmt, ...); protected: double m_fov; ///< Length of an axis int m_width; ///< Width of the window in pixel int m_height; ///< Height of the window in pixel float max_size; ///< for dust clouds int m_fps; int m_idxSnapshot; Vec3D m_camPos; ///< Position of the camera Vec3D m_camLookAt; ///< Point atwhich the camera is aimed Vec3D m_camOrient; ///< orientation of the camera (rotation as it aims at its target) SDL_Surface *surface; SDL_Window* window; GLuint m_texStar; volatile bool m_bRunning; private: void InitGL(); void TextureLoading(); }; #endif
25.076336
89
0.625875
[ "render", "vector" ]
983c4d8b000b3f7e9d7315f38df2c64adce09e2a
4,443
h
C
ResearchKit/ActiveTasks/ORKWorkoutResult.h
cshinoc/ResearchKit
8e1bfbbdaf0027ac05e385115358a01501b1c1d8
[ "BSD-3-Clause" ]
2
2017-12-01T23:38:14.000Z
2018-03-11T03:20:02.000Z
ResearchKit/ActiveTasks/ORKWorkoutResult.h
cshinoc/ResearchKit
8e1bfbbdaf0027ac05e385115358a01501b1c1d8
[ "BSD-3-Clause" ]
55
2015-12-10T20:52:44.000Z
2017-08-07T16:21:26.000Z
ResearchKit/ActiveTasks/ORKWorkoutResult.h
cshinoc/ResearchKit
8e1bfbbdaf0027ac05e385115358a01501b1c1d8
[ "BSD-3-Clause" ]
17
2016-07-28T06:21:05.000Z
2020-11-29T21:24:59.000Z
/* Copyright (c) 2017, Sage Bionetworks. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import <ResearchKit/ORKResult.h> NS_ASSUME_NONNULL_BEGIN @class ORKDevice; /** An `ORKWorkoutResult` contains information about the results of running the workout step. */ ORK_CLASS_AVAILABLE @interface ORKWorkoutResult : ORKResult /** The error (if any) when trying to connect to the watch. */ @property (nonatomic, copy, nullable) NSError *error; /** The device information for the Apple Watch (if any) used during this workout. */ @property (nonatomic, copy, nullable) ORKDevice *device; @end /** The `ORKDevice` represents a serializable representation of an `HKDevice`. */ ORK_CLASS_AVAILABLE @interface ORKDevice : NSObject <NSCopying, NSSecureCoding> /*! @property name @abstract The name of the receiver. @discussion The user-facing name, such as the one displayed in the Bluetooth Settings for a BLE device. */ @property (nonatomic, readonly, nullable) NSString *name; /*! @property manufacturer @abstract The manufacturer of the receiver. */ @property (nonatomic, readonly, nullable) NSString *manufacturer; /*! @property model @abstract The model of the receiver. */ @property (nonatomic, readonly, nullable) NSString *model; /*! @property hardwareVersion @abstract The hardware revision of the receiver. */ @property (nonatomic, readonly, nullable) NSString *hardwareVersion; /*! @property softwareVersion @abstract The software revision of the receiver. */ @property (nonatomic, readonly, nullable) NSString *softwareVersion; + (instancetype)new NS_UNAVAILABLE; - (instancetype)init NS_UNAVAILABLE; /** Returns a new device initialized from an `HKDevice` @param healthKitDevice `HKDevice` to copy values from @return A new device. */ - (instancetype)initWithDevice:(HKDevice *)healthKitDevice; /** Returns a new device initialized with the properties of this object @param name The name of the device @param manufacturer The manufacturer of the device @param model The model of the device @param hardwareVersion The hardware version of the device @param softwareVersion The software version of the device @return A new device. */ - (instancetype)initWithName:(nullable NSString *)name manufacturer:(nullable NSString *)manufacturer model:(nullable NSString *)model hardwareVersion:(nullable NSString *)hardwareVersion softwareVersion:(nullable NSString *)softwareVersion NS_DESIGNATED_INITIALIZER; /** Returns a new device initialized from data in the given unarchiver. @param aDecoder Coder from which to initialize the device. @return A new device. */ - (instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER; @end NS_ASSUME_NONNULL_END
33.156716
107
0.752194
[ "object", "model" ]
984358d4e6f7fd30cd84ba277d75d1465a6e39f6
4,831
h
C
source/operator/flexDiagonalOperator.h
HendrikMuenster/flexBox_CPP
b24fe192772ff84bf79a93985de4e5c0a94a5297
[ "BSD-4-Clause-UC" ]
2
2017-01-09T15:16:08.000Z
2017-01-10T08:26:00.000Z
source/operator/flexDiagonalOperator.h
HendrikMuenster/flexBox_CPP
b24fe192772ff84bf79a93985de4e5c0a94a5297
[ "BSD-4-Clause-UC" ]
1
2018-01-18T14:13:26.000Z
2018-02-02T09:35:45.000Z
source/operator/flexDiagonalOperator.h
HendrikMuenster/flexBox_CPP
b24fe192772ff84bf79a93985de4e5c0a94a5297
[ "BSD-4-Clause-UC" ]
2
2018-07-19T21:02:07.000Z
2021-05-20T06:32:52.000Z
#ifndef flexDiagonalOperator_H #define flexDiagonalOperator_H #include <vector> #include "flexLinearOperator.h" //! represents a diagonal operator template <typename T> class flexDiagonalOperator : public flexLinearOperator<T> { #ifdef __CUDACC__ typedef thrust::device_vector<T> Tdata; #else typedef std::vector<T> Tdata; #endif private: Tdata diagonalElements; public: //! initializes the concatenation operator for non-CUDA versions /*! \param aDiagonalElements vector of diagonal Elements \param aMinus determines if operator is negated \sa isMinus */ flexDiagonalOperator(std::vector<T> aDiagonalElements, bool aMinus) : flexLinearOperator<T>(static_cast<int>(aDiagonalElements.size()), static_cast<int>(aDiagonalElements.size()), diagonalOp, aMinus) { this->diagonalElements.resize(aDiagonalElements.size()); #ifdef __CUDACC__ thrust::copy(aDiagonalElements.begin(), aDiagonalElements.end(), this->diagonalElements.begin()); #else this->diagonalElements = aDiagonalElements; #endif } #ifdef __CUDACC__ //! initializes the concatenation operator for CUDA versions /*! \param aDiagonalElements vector of diagonal Elements where Tdata is of type thrust::device_vector<T> \param aMinus determines if operator is negated \sa isMinus */ flexDiagonalOperator(Tdata aDiagonalElements, bool aMinus) : diagonalElements(aDiagonalElements), flexLinearOperator<T>(static_cast<int>(aDiagonalElements.size()), static_cast<int>(aDiagonalElements.size()), diagonalOp, aMinus) { }; #endif flexDiagonalOperator<T>* copy() { flexDiagonalOperator<T>* A = new flexDiagonalOperator<T>(this->diagonalElements, this->isMinus); return A; } #ifdef __CUDACC__ struct flexDiagonalOperatorFunctor { __host__ __device__ flexDiagonalOperatorFunctor(const mySign _s) : s(_s){} template <typename Tuple> __host__ __device__ void operator()(Tuple t) { switch (this->s) { case PLUS: { thrust::get<0>(t) += thrust::get<1>(t) * thrust::get<2>(t); break; } case MINUS: { thrust::get<0>(t) -= thrust::get<1>(t) * thrust::get<2>(t); break; } case EQUALS: { thrust::get<0>(t) = thrust::get<1>(t) * thrust::get<2>(t); break; } } } mySign s; }; #endif //apply linear operator to vector void times(bool transposed, const Tdata &input, Tdata &output) { this->doTimes(input,output,EQUALS); } void timesPlus(bool transposed, const Tdata &input, Tdata &output) { if (this->isMinus) { this->doTimes(input,output, MINUS); } else { this->doTimes(input,output, PLUS); } } void timesMinus(bool transposed, const Tdata &input, Tdata &output) { if (this->isMinus) { this->doTimes(input,output, PLUS); } else { this->doTimes(input,output, MINUS); } } std::vector<T> getAbsRowSum(bool transposed) { std::vector<T> result(this->getNumRows()); #pragma omp parallel for for (int k = 0; k < this->getNumRows(); ++k) { result[k] = std::abs(this->diagonalElements[k]); } return result; } T getMaxRowSumAbs(bool transposed) { Tdata diagonalElementsCopy = this->diagonalElements; vectorAbs(diagonalElementsCopy); return vectorMax(diagonalElementsCopy); } #ifdef __CUDACC__ thrust::device_vector<T> getAbsRowSumCUDA(bool transposed) { Tdata diagonalElementsCopy = this->diagonalElements; vectorAbs(diagonalElementsCopy); return diagonalElementsCopy; } #endif private: void doTimesCPU(const Tdata &input, Tdata &output,const mySign s) { int numElements = (int)output.size(); #pragma omp parallel for for (int i = 0; i < numElements; ++i) { switch (s) { case PLUS: { output[i] += input[i] * this->diagonalElements[i]; break; } case MINUS: { output[i] -= input[i] * this->diagonalElements[i]; break; } case EQUALS: { output[i] = input[i] * this->diagonalElements[i]; break; } } } } void doTimes(const Tdata &input, Tdata &output,const mySign s) { #ifdef __CUDACC__ thrust::for_each( thrust::make_zip_iterator(thrust::make_tuple(output.begin(), input.begin(), this->diagonalElements.begin())), thrust::make_zip_iterator(thrust::make_tuple(output.end(), input.end(), this->diagonalElements.end())), flexDiagonalOperatorFunctor(s)); #else this->doTimesCPU(input,output,s); #endif } }; #endif
23.681373
229
0.627613
[ "vector" ]
984a4e50f327fd6ed45f5e4212ce7229432e78f7
12,534
c
C
src/fswAlgorithms/attDetermination/CSSEst/cssWlsEst.c
ian-cooke/basilisk_mag
a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14
[ "0BSD" ]
null
null
null
src/fswAlgorithms/attDetermination/CSSEst/cssWlsEst.c
ian-cooke/basilisk_mag
a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14
[ "0BSD" ]
1
2019-03-13T20:52:22.000Z
2019-03-13T20:52:22.000Z
src/fswAlgorithms/attDetermination/CSSEst/cssWlsEst.c
ian-cooke/basilisk_mag
a8b1e37c31c1287549d6fd4d71fcaa35b6fc3f14
[ "0BSD" ]
null
null
null
/* ISC License Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "attDetermination/CSSEst/cssWlsEst.h" #include "simulation/utilities/linearAlgebra.h" #include "simFswInterfaceMessages/macroDefinitions.h" #include "fswMessages/sunlineFilterFswMsg.h" #include <string.h> #include <math.h> /*! This method initializes the ConfigData for theCSS WLS estimator. It checks to ensure that the inputs are sane and then creates the output message @return void @param ConfigData The configuration data associated with the CSS WLS estimator */ void SelfInit_cssWlsEst(CSSWLSConfig *ConfigData, uint64_t moduleID) { /*! Begin method steps */ /*! - Create output message for module */ ConfigData->navStateOutMsgId = CreateNewMessage(ConfigData->navStateOutMsgName, sizeof(NavAttIntMsg), "NavAttIntMsg", moduleID); if(strlen(ConfigData->cssWLSFiltResOutMsgName) > 0) { ConfigData->cssWlsFiltResOutMsgId = CreateNewMessage(ConfigData->cssWLSFiltResOutMsgName, sizeof(SunlineFilterFswMsg), "SunlineFilterFswMsg", moduleID); } } /*! This method performs the second stage of initialization for the CSS sensor interface. It's primary function is to link the input messages that were created elsewhere. @return void @param ConfigData The configuration data associated with the CSS interface */ void CrossInit_cssWlsEst(CSSWLSConfig *ConfigData, uint64_t moduleID) { /*! - Loop over the number of sensors and find IDs for each one */ ConfigData->cssDataInMsgID = subscribeToMessage(ConfigData->cssDataInMsgName, sizeof(CSSArraySensorIntMsg), moduleID); ConfigData->cssConfigInMsgID = subscribeToMessage(ConfigData->cssConfigInMsgName, sizeof(CSSConfigFswMsg), moduleID); } /*! This method performs a complete reset of the module. Local module variables that retain time varying states between function calls are reset to their default values. @return void @param ConfigData The configuration data associated with the guidance module */ void Reset_cssWlsEst(CSSWLSConfig *ConfigData, uint64_t callTime, uint64_t moduleID) { uint64_t ClockTime; uint32_t ReadSize; memset(&(ConfigData->cssConfigInBuffer), 0x0, sizeof(CSSConfigFswMsg)); ReadMessage(ConfigData->cssConfigInMsgID, &ClockTime, &ReadSize, sizeof(CSSConfigFswMsg), &(ConfigData->cssConfigInBuffer), moduleID); ConfigData->priorSignalAvailable = 0; v3SetZero(ConfigData->dOld); ConfigData->sunlineOutBuffer.timeTag = 0.0; v3SetZero(ConfigData->sunlineOutBuffer.sigma_BN); v3SetZero(ConfigData->sunlineOutBuffer.omega_BN_B); /* Reset the prior time flag state. If zero, control time step not evaluated on the first function call */ ConfigData->priorTime = 0; return; } /*! This method computes the post-fit residuals for the WLS estimate. Note that everything has to have been allocated appropriately as this function operates directly on the arrays. @return void @param cssMeas The measured values for the CSS sensors @param cssConfig The CSS configuration information @param wlsEst The WLS estimate computed for the CSS measurements @param cssResiduals The measurement residuals output by this function */ void computeWlsResiduals(double *cssMeas, CSSConfigFswMsg *cssConfig, double *wlsEst, double *cssResiduals) { int i; double cssDotProd; memset(cssResiduals, 0x0, cssConfig->nCSS*sizeof(double)); for(i=0; i<cssConfig->nCSS; i++) { cssDotProd = v3Dot(wlsEst, cssConfig->cssVals[i].nHat_B); cssDotProd = cssDotProd > 0.0 ? cssDotProd : 0.0; /*CSS values can't be negative!*/ cssResiduals[i] = cssMeas[i] - cssDotProd; } } /*! This method computes a least squares fit with the given parameters. It treats the inputs as though they were double dimensioned arrays but they are all singly dimensioned for ease of use @return success indicator (1 for good, 0 for fail) @param numActiveCss The count on input measurements @param H The predicted pointing vector for each measurement @param W the weighting matrix for the set of measurements @param y the observation vector for the valid sensors @param x The output least squares fit for the observations */ int computeWlsmn(int numActiveCss, double *H, double *W, double *y, double x[3]) { double m22[2*2]; double m32[3*2]; int status = 0; double m33[3*3]; double m33_2[3*3]; double m3N[3*MAX_NUM_CSS_SENSORS]; double m3N_2[3*MAX_NUM_CSS_SENSORS]; uint32_t i; /*! Begin method steps */ /*! - If we only have one sensor, output best guess (cone of possiblities)*/ if(numActiveCss == 1) { /* Here's a guess. Do with it what you will. */ for(i = 0; i < 3; i=i+1) { x[i] = H[0*MAX_NUM_CSS_SENSORS+i] * y[0]; } } else if(numActiveCss == 2) { /*! - If we have two, then do a 2x2 fit */ /*! -# Find minimum norm solution */ mMultMt(H, 2, 3, H, 2, 3, m22); status = m22Inverse(RECAST2x2 m22, RECAST2x2 m22); mtMultM(H, 2, 3, m22, 2, 2, m32); /*! -# Multiply the Ht(HHt)^-1 by the observation vector to get fit*/ mMultV(m32, 3, 2, y, x); } else if(numActiveCss > 2) {/*! - If we have more than 2, do true LSQ fit*/ /*! -# Use the weights to compute (HtWH)^-1HW*/ mtMultM(H, numActiveCss, 3, W, numActiveCss, numActiveCss, m3N); mMultM(m3N, 3, numActiveCss, H, numActiveCss, 3, m33); status = m33Inverse(RECAST3X3 m33, RECAST3X3 m33_2); mMultMt(m33_2, 3, 3, H, numActiveCss, 3, m3N); mMultM(m3N, 3, numActiveCss, W, numActiveCss, numActiveCss, m3N_2); /*! -# Multiply the LSQ matrix by the obs vector for best fit*/ mMultV(m3N_2, 3, numActiveCss, y, x); } return(status); } /*! This method takes the parsed CSS sensor data and outputs an estimate of the sun vector in the ADCS body frame @return void @param ConfigData The configuration data associated with the CSS estimator @param callTime The clock time at which the function was called (nanoseconds) */ void Update_cssWlsEst(CSSWLSConfig *ConfigData, uint64_t callTime, uint64_t moduleID) { uint64_t ClockTime; uint32_t ReadSize; CSSArraySensorIntMsg InputBuffer; SunlineFilterFswMsg filtStatus; double H[MAX_NUM_CSS_SENSORS*3]; double y[MAX_NUM_CSS_SENSORS]; double W[MAX_NUM_CSS_SENSORS*MAX_NUM_CSS_SENSORS]; uint32_t i; uint32_t status; double temp; double dHatNew[3]; /*!< new normalized sun heading estimate */ double dHatOld[3]; /*!< prior normalized sun heading estimate */ double dt; /*!< [s] control update period */ /* Begin method steps*/ /* - Read the input parsed CSS sensor data message*/ memset(&InputBuffer, 0x0, sizeof(CSSArraySensorIntMsg)); ReadMessage(ConfigData->cssDataInMsgID, &ClockTime, &ReadSize, sizeof(CSSArraySensorIntMsg), (void*) (&InputBuffer), moduleID); /* compute control update time */ if (ConfigData->priorTime == 0) { dt = 0.0; } else { dt = (callTime - ConfigData->priorTime) * NANO2SEC; } ConfigData->priorTime = callTime; /* - Zero the observed active CSS count*/ ConfigData->numActiveCss = 0; /* - Loop over the maximum number of sensors to check for good measurements -# Isolate if measurement is good - Set body vector for this measurement - Get measurement value into observation vector - Set inverse noise matrix - increase the number of valid observations -# Otherwise just continue */ for(i=0; i<MAX_NUM_CSS_SENSORS; i = i+1) { if(InputBuffer.CosValue[i] > ConfigData->sensorUseThresh) { v3Scale(ConfigData->cssConfigInBuffer.cssVals[i].CBias, ConfigData->cssConfigInBuffer.cssVals[i].nHat_B, &H[ConfigData->numActiveCss*3]); y[ConfigData->numActiveCss] = InputBuffer.CosValue[i]; ConfigData->numActiveCss = ConfigData->numActiveCss + 1; } } memset(&filtStatus, 0x0, sizeof(SunlineFilterFswMsg)); if(ConfigData->numActiveCss == 0) /*! - If there is no sun, just quit*/ { /* no CSS got a strong enough signal. sun estimation is not possible. Return the zero vector instead */ v3SetZero(ConfigData->sunlineOutBuffer.vehSunPntBdy); /* zero the sun heading to indicate now CSS info is available */ v3SetZero(ConfigData->sunlineOutBuffer.omega_BN_B); /* zero the rate measure */ ConfigData->priorSignalAvailable = 0; /* reset the prior heading estimate flag */ computeWlsResiduals(InputBuffer.CosValue, &ConfigData->cssConfigInBuffer, ConfigData->sunlineOutBuffer.vehSunPntBdy, filtStatus.postFitRes); } else { /* at least one CSS got a strong enough signal. Proceed with the sun heading estimation */ /* - Configuration option to weight the measurements, otherwise set weighting matrix to identity*/ if(ConfigData->useWeights > 0) { mDiag(y, ConfigData->numActiveCss, W); } else { mSetIdentity(W, ConfigData->numActiveCss, ConfigData->numActiveCss); } /*! - Get least squares fit for sun pointing vector*/ status = computeWlsmn(ConfigData->numActiveCss, H, W, y, ConfigData->sunlineOutBuffer.vehSunPntBdy); computeWlsResiduals(InputBuffer.CosValue, &ConfigData->cssConfigInBuffer, ConfigData->sunlineOutBuffer.vehSunPntBdy, filtStatus.postFitRes); v3Normalize(ConfigData->sunlineOutBuffer.vehSunPntBdy, ConfigData->sunlineOutBuffer.vehSunPntBdy); /* estimate the inertial angular velocity from the rate of the sun heading measurements */ if (ConfigData->priorSignalAvailable && dt > 0.0) { v3Normalize(ConfigData->sunlineOutBuffer.vehSunPntBdy, dHatNew); v3Normalize(ConfigData->dOld, dHatOld); v3Cross(dHatNew, dHatOld, ConfigData->sunlineOutBuffer.omega_BN_B); v3Normalize(ConfigData->sunlineOutBuffer.omega_BN_B, ConfigData->sunlineOutBuffer.omega_BN_B); /* compute principal rotation angle between sun heading measurements */ temp = v3Dot(dHatNew,dHatOld); if (temp > 1.0) temp = 1.0; if (temp < -1.0) temp = -1.0; v3Scale(acos(temp)/dt, ConfigData->sunlineOutBuffer.omega_BN_B, ConfigData->sunlineOutBuffer.omega_BN_B); } else { ConfigData->priorSignalAvailable = 1; } /* store the sun heading estimate */ v3Copy(ConfigData->sunlineOutBuffer.vehSunPntBdy, ConfigData->dOld); } /* if the residual fit output message is set, then compute the residuals and stor them in the output message */ if(strlen(ConfigData->cssWLSFiltResOutMsgName) > 0) { filtStatus.numObs = ConfigData->numActiveCss; filtStatus.timeTag = (double) (callTime*NANO2SEC); v3Copy(ConfigData->sunlineOutBuffer.vehSunPntBdy, filtStatus.state); WriteMessage(ConfigData->cssWlsFiltResOutMsgId, callTime, sizeof(SunlineFilterFswMsg), &filtStatus, moduleID); } WriteMessage(ConfigData->navStateOutMsgId, callTime, sizeof(NavAttIntMsg), &(ConfigData->sunlineOutBuffer), moduleID); return; }
43.22069
132
0.675203
[ "vector" ]
984b5061a09f432f53a788a39a16ac1a0c22d148
35,218
c
C
lib/VLFeat/imopv.c
backwardn/colmap
07b46598471e8bd2185c843dd6450e3108aaa640
[ "BSD-3-Clause" ]
255
2018-12-14T05:59:29.000Z
2020-11-04T12:15:32.000Z
lib/VLFeat/imopv.c
Pascal-So/colmap
7c82a22a2ac97e54272d54a1c7276cb293bcdd2f
[ "BSD-3-Clause" ]
35
2018-12-25T03:02:48.000Z
2020-11-19T03:33:25.000Z
lib/VLFeat/imopv.c
Pascal-So/colmap
7c82a22a2ac97e54272d54a1c7276cb293bcdd2f
[ "BSD-3-Clause" ]
54
2018-12-14T06:09:21.000Z
2020-11-21T08:29:31.000Z
/** @file imopv.c ** @brief Vectorized image operations - Definition ** @author Andrea Vedaldi **/ /* Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. All rights reserved. This file is part of the VLFeat library and is made available under the terms of the BSD license (see the COPYING file). */ /** @file imopv.h ** ** This module provides the following image operations: ** ** - <b>Separable convolution.</b> The function ::vl_imconvcol_vf() ** can be used to compute separable convolutions. ** ** - <b>Convolution by a triangular kernel.</b> The function ** vl_imconvcoltri_vf() is an optimized convolution routine for ** triangular kernels. ** ** - <b>Distance transform.</b> ::vl_image_distance_transform_f() is ** a linear algorithm to compute the distance transform of an ** image. ** ** @remark Some operations are optimized to exploit possible SIMD ** instructions. This requires image data to be properly aligned (typically ** to 16 bytes). Similalry, the image stride (the number of bytes to skip to move ** to the next image row), must be aligned. **/ #ifndef VL_IMOPV_INSTANTIATING #include "imopv.h" #include "imopv_sse2.h" #include "mathop.h" #define FLT VL_TYPE_FLOAT #define VL_IMOPV_INSTANTIATING #include "imopv.c" #define FLT VL_TYPE_DOUBLE #define VL_IMOPV_INSTANTIATING #include "imopv.c" #define FLT VL_TYPE_UINT32 #define VL_IMOPV_INSTANTIATING #include "imopv.c" #define FLT VL_TYPE_INT32 #define VL_IMOPV_INSTANTIATING #include "imopv.c" /* VL_IMOPV_INSTANTIATING */ #endif #if defined(VL_IMOPV_INSTANTIATING) || defined(__DOXYGEN__) #include "float.h" /* ---------------------------------------------------------------- */ /* Image Convolution */ /* ---------------------------------------------------------------- */ #if (FLT == VL_TYPE_FLOAT || FLT == VL_TYPE_DOUBLE) /** @fn vl_imconvcol_vd(double*,vl_size,double const*,vl_size,vl_size,vl_size,double const*,vl_index,vl_index,int,unsigned int) ** @brief Convolve image along columns ** ** @param dst destination image. ** @param dst_stride width of the destination image including padding. ** @param src source image. ** @param src_width width of the source image. ** @param src_height height of the source image. ** @param src_stride width of the source image including padding. ** @param filt filter kernel. ** @param filt_begin coordinate of the first filter element. ** @param filt_end coordinate of the last filter element. ** @param step sub-sampling step. ** @param flags operation modes. ** ** The function convolves the column of the image @a src by the ** filter @a filt and saves the result to the image @a dst. The size ** of @a dst must be equal to the size of @a src. Formally, this ** results in the calculation ** ** @f[ ** \mathrm{dst} [x,y] = \sum_{p=y-\mathrm{filt\_end}}^{y-\mathrm{filt\_begin}} ** \mathrm{src}[x,y] \mathrm{filt}[y - p - \mathrm{filt\_begin}] ** @f] ** ** The function subsamples the image along the columns according to ** the parameter @a step. Setting @a step to 1 (one) computes the ** elements @f$\mathrm{dst}[x,y]@f$ for all pairs (x,0), (x,1), (x,2) ** and so on. Setting @a step two 2 (two) computes only (x,0), (x,2) ** and so on (in this case the height of the destination image is ** <code>floor(src_height/step)+1)</code>. ** ** Calling twice the function can be used to compute 2-D separable ** convolutions. Use the flag ::VL_TRANSPOSE to transpose the result ** (in this case @a dst has transposed dimension as well). ** ** The function allows the support of the filter to be any range. ** Usually the support is <code>@a filt_end = -@a filt_begin</code>. ** ** The convolution operation may pick up values outside the image ** boundary. To cope with this edge cases, the function either pads ** the image by zero (::VL_PAD_BY_ZERO) or with the values at the ** boundary (::VL_PAD_BY_CONTINUITY). **/ /** @fn vl_imconvcol_vf(float*,vl_size,float const*,vl_size,vl_size,vl_size,float const*,vl_index,vl_index,int,unsigned int) ** @see ::vl_imconvcol_vd **/ VL_EXPORT void VL_XCAT(vl_imconvcol_v, SFX) (T* dst, vl_size dst_stride, T const* src, vl_size src_width, vl_size src_height, vl_size src_stride, T const* filt, vl_index filt_begin, vl_index filt_end, int step, unsigned int flags) { vl_index x = 0 ; vl_index y ; vl_index dheight = (src_height - 1) / step + 1 ; vl_bool transp = flags & VL_TRANSPOSE ; vl_bool zeropad = (flags & VL_PAD_MASK) == VL_PAD_BY_ZERO ; /* dispatch to accelerated version */ #ifndef VL_DISABLE_SSE2 if (vl_cpu_has_sse2() && vl_get_simd_enabled()) { VL_XCAT3(_vl_imconvcol_v,SFX,_sse2) (dst,dst_stride, src,src_width,src_height,src_stride, filt,filt_begin,filt_end, step,flags) ; return ; } #endif /* let filt point to the last sample of the filter */ filt += filt_end - filt_begin ; while (x < (signed)src_width) { /* Calculate dest[x,y] = sum_p image[x,p] filt[y - p] * where supp(filt) = [filt_begin, filt_end] = [fb,fe]. * * CHUNK_A: y - fe <= p < 0 * completes VL_MAX(fe - y, 0) samples * CHUNK_B: VL_MAX(y - fe, 0) <= p < VL_MIN(y - fb, height - 1) * completes fe - VL_MAX(fb, height - y) + 1 samples * CHUNK_C: completes all samples */ T const *filti ; vl_index stop ; for (y = 0 ; y < (signed)src_height ; y += step) { T acc = 0 ; T v = 0, c ; T const* srci ; filti = filt ; stop = filt_end - y ; srci = src + x - stop * src_stride ; if (stop > 0) { if (zeropad) { v = 0 ; } else { v = *(src + x) ; } while (filti > filt - stop) { c = *filti-- ; acc += v * c ; srci += src_stride ; } } stop = filt_end - VL_MAX(filt_begin, y - (signed)src_height + 1) + 1 ; while (filti > filt - stop) { v = *srci ; c = *filti-- ; acc += v * c ; srci += src_stride ; } if (zeropad) v = 0 ; stop = filt_end - filt_begin + 1 ; while (filti > filt - stop) { c = *filti-- ; acc += v * c ; } if (transp) { *dst = acc ; dst += 1 ; } else { *dst = acc ; dst += dst_stride ; } } /* next y */ if (transp) { dst += 1 * dst_stride - dheight * 1 ; } else { dst += 1 * 1 - dheight * dst_stride ; } x += 1 ; } /* next x */ } /* VL_TYPE_FLOAT, VL_TYPE_DOUBLE */ #endif /* ---------------------------------------------------------------- */ /* Image distance transform */ /* ---------------------------------------------------------------- */ #if (FLT == VL_TYPE_FLOAT || FLT == VL_TYPE_DOUBLE) /** @fn ::vl_image_distance_transform_d(double const*,vl_size,vl_size,vl_size,vl_size,double*,vl_uindex*,double,double) ** @brief Compute the distance transform of an image ** @param image image. ** @param numColumns number of columns of the image. ** @param numRows number of rows of the image. ** @param columnStride offset from one column to the next. ** @param rowStride offset from one row to the next. ** @param distanceTransform distance transform (out). ** @param indexes nearest neighbor indexes (in/out). ** @param coeff quadratic cost coefficient (non-negative). ** @param offset quadratic cost offset. ** ** The function computes the distance transform along the first ** dimension of the image @a image. Let @f$ I(u,v) @f$ be @a image. ** Its distance transfrom @f$ D(u,v) @f$ is given by: ** ** @f[ ** u^*(u,v) = \min_{u'} I(u',v) + \mathtt{coeff} (u' - u - \mathtt{offset})^2, ** \quad D(u,v) = I(u^*(u,v),v). ** @f] ** ** Notice that @a coeff must be non negative. ** ** The function fills in the buffer @a distanceTransform with @f$ D ** @f$. This buffer must have the same size as @a image. ** ** If @a indexes is not @c NULL, it must be a matrix of the same size ** o the image. The function interprets the value of this matrix as ** indexes of the pixels, i.e @f$ \mathtt{indexes}(u,v) @f$ is the ** index of pixel @f$ (u,v) @f$. On output, the matrix @a indexes ** contains @f$ \mathtt{indexes}(u^*(u,v),v) @f$. This information ** can be used to determine for each pixel @f$ (u,v) @f$ its ** &ldquo;nearest neighbor&rdquo. ** ** Notice that by swapping @a numRows and @a numColumns and @a ** columnStride and @a rowStride, the function can be made to operate ** along the other image dimension. Specifically, to compute the ** distance transform along columns and rows, call the functinon ** twice: *** ** @code ** for (i = 0 ; i < numColumns * numRows ; ++i) indexes[i] = i ; ** vl_image_distance_transform_d(image,numColumns,numRows,1,numColumns, ** distanceTransform,indexes,u_coeff,u_offset) ; ** vl_image_distance_transform_d(distanceTransform,numRows,numColumns,numColumns,1, ** distanceTransform,indexes,u_coeff,u_offset) ; ** @endcode ** ** @par Algorithm ** ** The function implements the algorithm described in: ** P. F. Felzenszwalb and D. P. Huttenlocher, <em>Distance Transforms ** of Sampled Functions,</em> Technical Report, Cornell University, ** 2004. ** ** Since the algorithm operates along one dimension per time, ** consider the 1D version of the problem for simplicity: ** ** @f[ ** d(y) = \min_{x} g(y;x), \quad g(y;x) = f(x) + \alpha (y - x - \beta)^2, ** \quad x,y \in \{0,1,\dots,N-1\}. ** @f] ** ** Hence the distance transform @f$ d(y) @f$ is the lower envelope of ** the family of parabolas @f$ g(y;x) @f$ indexed by @f$ x ** @f$. Notice that all parabolas have the same curvature and that ** their centers are located at @f$ x + \beta, @f$ @f$ x=0,\dots,N-1 ** @f$. The algorithm considers one parabola per time, from left to ** right, and finds the interval for which the parabola belongs to ** the lower envelope (if any). ** ** Initially, only the leftmost parabola @f$ g(y;0) @f$ has been ** considered, and its validity interval is @f$(-\infty, \infty) @f$. ** Then the second parabola @f$ g(y;1) @f$ is considered. As long as ** @f$ \alpha > 0 @f$, the two parabolas @f$ g(y;0),\ g(y;1) @f$ ** intersect at a unique point @f$ \bar y @f$. Then the first ** parabola belongs to the envelope in the interval @f$ (-\infty, ** \bar y] @f$ and the second one in the interval @f$ (\bar y, ** +\infty] @f$. When the third parabola @f$ g(y;2) @f$ is ** considered, the intersection point @f$ \hat y @f$ with the ** previously added parabola @f$ g(y;1) @f$ is found. Now two cases ** may arise: ** ** - @f$ \hat y > \bar y @f$, in which case all three parabolas ** belong to the envelope in the intervals @f$ (-\infty,\bar y], ** (\bar y, \hat y], (\hat y, +\infty] @f$. ** ** - @f$ \hat y \leq \bar y @f$, in which case the second parabola ** @f$ g(y;1) @f$ has no point beloning to the envelope, and it is ** removed. One then remains with the two parabolas @f$ g(y;0),\ ** g(y;2) @f$ and the algorithm is re-iterated. ** ** The algorithm proceeds in this fashion. Every time a new parabola ** is considered, its intersection point with the previously added ** parabola on the left is computed, and that parabola is potentially ** removed. The cost of an iteration is 1 plus the number of deleted ** parabolas. Since there are @f$ N @f$ iterations and at most @f$ N ** @f$ parabolas to delete overall, the complexity is linear, ** i.e. @f$ O(N) @f$. **/ /** @fn ::vl_image_distance_transform_f(float const*,vl_size,vl_size,vl_size,vl_size,float*,vl_uindex*,float,float) ** @see ::vl_image_distance_transform_d **/ VL_EXPORT void VL_XCAT(vl_image_distance_transform_,SFX) (T const * image, vl_size numColumns, vl_size numRows, vl_size columnStride, vl_size rowStride, T * distanceTransform, vl_uindex * indexes, T coeff, T offset) { /* Each image pixel corresponds to a parabola. The algorithm scans such parabolas from left to right, keeping track of which parabolas belong to the lower envelope and in which interval. There are NUM active parabolas, FROM stores the beginning of the interval for which a certain parabola is part of the envoelope, and WHICH store the index of the parabola (that is, the pixel x from which the parabola originated). */ vl_uindex x, y ; T * from = vl_malloc (sizeof(T) * (numColumns + 1)) ; T * base = vl_malloc (sizeof(T) * numColumns) ; vl_uindex * baseIndexes = vl_malloc (sizeof(vl_uindex) * numColumns) ; vl_uindex * which = vl_malloc (sizeof(vl_uindex) * numColumns) ; vl_uindex num = 0 ; for (y = 0 ; y < numRows ; ++y) { num = 0 ; for (x = 0 ; x < numColumns ; ++x) { T r = image[x * columnStride + y * rowStride] ; T x2 = x * x ; #if (FLT == VL_TYPE_FLOAT) T from_ = - VL_INFINITY_F ; #else T from_ = - VL_INFINITY_D ; #endif /* Add next parabola (there are NUM so far). The algorithm finds intersection INTERS with the previously added parabola. If the intersection is on the right of the "starting point" of this parabola, then the previous parabola is kept, and the new one is added to its right. Otherwise the new parabola "eats" the old one, which gets deleted and the check is repeated with the parabola added before the deleted one. */ while (num >= 1) { vl_uindex x_ = which[num - 1] ; T x2_ = x_ * x_ ; T r_ = image[x_ * columnStride + y * rowStride] ; T inters ; if (r == r_) { /* handles the case r = r_ = \pm inf */ inters = (x + x_) / 2.0 + offset ; } #if (FLT == VL_TYPE_FLOAT) else if (coeff > VL_EPSILON_F) #else else if (coeff > VL_EPSILON_D) #endif { inters = ((r - r_) + coeff * (x2 - x2_)) / (x - x_) / (2*coeff) + offset ; } else { /* If coeff is very small, the parabolas are flat (= lines). In this case the previous parabola should be deleted if the current pixel has lower score */ #if (FLT == VL_TYPE_FLOAT) inters = (r < r_) ? - VL_INFINITY_F : VL_INFINITY_F ; #else inters = (r < r_) ? - VL_INFINITY_D : VL_INFINITY_D ; #endif } if (inters <= from [num - 1]) { /* delete a previous parabola */ -- num ; } else { /* accept intersection */ from_ = inters ; break ; } } /* add a new parabola */ which[num] = x ; from[num] = from_ ; base[num] = r ; if (indexes) baseIndexes[num] = indexes[x * columnStride + y * rowStride] ; num ++ ; } /* next column */ #if (FLT == VL_TYPE_FLOAT) from[num] = VL_INFINITY_F ; #else from[num] = VL_INFINITY_D ; #endif /* fill in */ num = 0 ; for (x = 0 ; x < numColumns ; ++x) { double delta ; while (x >= from[num + 1]) ++ num ; delta = (double) x - (double) which[num] - offset ; distanceTransform[x * columnStride + y * rowStride] = base[num] + coeff * delta * delta ; if (indexes) { indexes[x * columnStride + y * rowStride] = baseIndexes[num] ; } } } /* next row */ vl_free (from) ; vl_free (which) ; vl_free (base) ; vl_free (baseIndexes) ; } /* VL_TYPE_FLOAT, VL_TYPE_DOUBLE */ #endif /* ---------------------------------------------------------------- */ /* Image convolution by a triangular kernel */ /* ---------------------------------------------------------------- */ #if (FLT == VL_TYPE_FLOAT || FLT == VL_TYPE_DOUBLE) /** @fn vl_imconvcoltri_d(double*,vl_size,double const*,vl_size,vl_size,vl_size,vl_size,vl_size,int unsigned) ** @brief Convolve an image along the columns with a triangular kernel ** @param dest destination image. ** @param destStride destination image stride. ** @param image image to convolve. ** @param imageWidth width of the image. ** @param imageHeight height of the image. ** @param imageStride width of the image including padding. ** @param filterSize size of the triangular filter. ** @param step sub-sampling step. ** @param flags operation modes. ** ** The function convolves the columns of the image @a image with the ** triangular kernel ** ** @f[ ** k(t) = \frac{1}{\Delta^2} \max\{ \Delta - |t|, 0 \}, ** \quad t \in \mathbb{Z} ** @f] ** ** The paramter @f$ \Delta @f$, equal to the function argument @a ** filterSize, controls the width of the kernel. Notice that the ** support of @f$ k(x) @f$ as a continuous function of @f$ x @f$ is ** the open interval @f$ (-\Delta,\Delta) @f$, which has length @f$ ** 2\Delta @f$. However, @f$ k(x) @f$ restricted to the ingeter ** domain @f$ x \in \mathcal{Z} @f$ has support @f$ \{ -\Delta + 1, ** \Delta +2, \dots, \Delta-1 \} @f$, which counts @f$ 2 \Delta - 1 ** @f$ elements only. In particular, the discrete kernel is symmetric ** about the origin for all values of @f$ \Delta @f$. ** ** The normalization factor @f$ 1 / \Delta^2 @f$ guaratnees that the ** filter is normalized to one, i.e.: ** ** @f[ ** \sum_{t=-\infty}^{+\infty} k(t) = 1 ** @f] ** ** @par Algorithm ** ** The function exploits the fact that convolution by a triangular ** kernel can be expressed as the repeated convolution by a ** rectangular kernel, and that the latter can be performed in time ** indepenedent on the fiter width by using an integral-image type ** trick. Overall, the algorithm complexity is independent on the ** parameter @a filterSize and linear in the nubmer of image pixels. ** ** @see ::vl_imconvcol_vd for details on the meaning of the other parameters. **/ /** @fn vl_imconvcoltri_f(float*,vl_size,float const*,vl_size,vl_size,vl_size,vl_size,vl_size,int unsigned) ** @brief Convolve an image along the columns with a triangular kernel ** @see ::vl_imconvcoltri_d() **/ VL_EXPORT void VL_XCAT(vl_imconvcoltri_, SFX) (T * dest, vl_size destStride, T const * image, vl_size imageWidth, vl_size imageHeight, vl_size imageStride, vl_size filterSize, vl_size step, unsigned int flags) { vl_index x, y, dheight ; vl_bool transp = flags & VL_TRANSPOSE ; vl_bool zeropad = (flags & VL_PAD_MASK) == VL_PAD_BY_ZERO ; T scale = (T) (1.0 / ((double)filterSize * (double)filterSize)) ; T * buffer = vl_malloc (sizeof(T) * (imageHeight + filterSize)) ; buffer += filterSize ; if (imageHeight == 0) { return ; } x = 0 ; dheight = (imageHeight - 1) / step + 1 ; while (x < (signed)imageWidth) { T const * imagei ; imagei = image + x + imageStride * (imageHeight - 1) ; /* We decompose the convolution by a triangluar signal as the convolution * by two rectangular signals. The rectangular convolutions are computed * quickly by computing the integral signals. Each rectangular convolution * introduces a delay, which is compensated by convolving each in opposite * directions. */ /* integrate backward the column */ buffer[imageHeight - 1] = *imagei ; for (y = (signed)imageHeight - 2 ; y >= 0 ; --y) { imagei -= imageStride ; buffer[y] = buffer[y + 1] + *imagei ; } if (zeropad) { for ( ; y >= - (signed)filterSize ; --y) { buffer[y] = buffer[y + 1] ; } } else { for ( ; y >= - (signed)filterSize ; --y) { buffer[y] = buffer[y + 1] + *imagei ; } } /* compute the filter forward */ for (y = - (signed)filterSize ; y < (signed)imageHeight - (signed)filterSize ; ++y) { buffer[y] = buffer[y] - buffer[y + filterSize] ; } if (! zeropad) { for (y = (signed)imageHeight - (signed)filterSize ; y < (signed)imageHeight ; ++y) { buffer[y] = buffer[y] - buffer[imageHeight - 1] * ((signed)imageHeight - (signed)filterSize - y) ; } } /* integrate forward the column */ for (y = - (signed)filterSize + 1 ; y < (signed)imageHeight ; ++y) { buffer[y] += buffer[y - 1] ; } /* compute the filter backward */ { vl_size stride = transp ? 1 : destStride ; dest += dheight * stride ; for (y = step * (dheight - 1) ; y >= 0 ; y -= step) { dest -= stride ; *dest = scale * (buffer[y] - buffer[y - (signed)filterSize]) ; } dest += transp ? destStride : 1 ; } x += 1 ; } /* next x */ vl_free (buffer - filterSize) ; } /* VL_TYPE_FLOAT, VL_TYPE_DOUBLE */ #endif /* ---------------------------------------------------------------- */ /* Gaussian Smoothing */ /* ---------------------------------------------------------------- */ #if (FLT == VL_TYPE_FLOAT || FLT == VL_TYPE_DOUBLE) /** @fn vl_imsmooth_d(double*,vl_size,double const*,vl_size,vl_size,vl_size,double,double) ** @brief Smooth an image with a Gaussian filter ** @param smoothed ** @param smoothedStride ** @param image ** @param width ** @param height ** @param stride ** @param sigmax ** @param sigmay **/ /** @fn vl_imsmooth_f(float*,vl_size,float const*,vl_size,vl_size,vl_size,double,double) ** @brief Smooth an image with a Gaussian filter ** @see ::vl_imsmooth_d **/ static T* VL_XCAT(_vl_new_gaussian_fitler_,SFX)(vl_size *size, double sigma) { T* filter ; T mass = (T)1.0 ; vl_index i ; vl_size width = vl_ceil_d(sigma * 3.0) ; *size = 2 * width + 1 ; assert(size) ; filter = vl_malloc((*size) * sizeof(T)) ; filter[width] = 1.0 ; for (i = 1 ; i <= (signed)width ; ++i) { double x = (double)i / sigma ; double g = exp(-0.5 * x * x) ; mass += g + g ; filter[width-i] = g ; filter[width+i] = g ; } for (i = 0 ; i < (signed)(*size) ; ++i) {filter[i] /= mass ;} return filter ; } VL_EXPORT void VL_XCAT(vl_imsmooth_, SFX) (T * smoothed, vl_size smoothedStride, T const *image, vl_size width, vl_size height, vl_size stride, double sigmax, double sigmay) { T *filterx, *filtery, *buffer ; vl_size sizex, sizey ; filterx = VL_XCAT(_vl_new_gaussian_fitler_,SFX)(&sizex,sigmax) ; if (sigmax == sigmay) { filtery = filterx ; sizey = sizex ; } else { filtery = VL_XCAT(_vl_new_gaussian_fitler_,SFX)(&sizey,sigmay) ; } buffer = vl_malloc(width*height*sizeof(T)) ; VL_XCAT(vl_imconvcol_v,SFX) (buffer, height, image, width, height, stride, filtery, -((signed)sizey-1)/2, ((signed)sizey-1)/2, 1, VL_PAD_BY_CONTINUITY | VL_TRANSPOSE) ; VL_XCAT(vl_imconvcol_v,SFX) (smoothed, smoothedStride, buffer, height, width, height, filterx, -((signed)sizex-1)/2, ((signed)sizex-1)/2, 1, VL_PAD_BY_CONTINUITY | VL_TRANSPOSE) ; vl_free(buffer) ; vl_free(filterx) ; if (sigmax != sigmay) { vl_free(filtery) ; } } /* VL_TYPE_FLOAT, VL_TYPE_DOUBLE */ #endif /* ---------------------------------------------------------------- */ /* Image Gradient */ /* ---------------------------------------------------------------- */ #if (FLT == VL_TYPE_FLOAT || FLT == VL_TYPE_DOUBLE) /** @fn vl_imgradient_d(double*,double*,vl_size,vl_size,double*,vl_size,vl_size,vl_size) ** @brief Compute image gradient ** @param xGradient Pointer to amplitude gradient plane ** @param yGradient Pointer to angle gradient plane ** @param gradWidthStride Width of the gradient plane including padding ** @param gradHeightStride Height of the gradient plane including padding ** @param image Pointer to the source image ** @param imageWidth Source image width ** @param imageHeight Source image height ** @param imageStride Width of the image including padding. ** ** This functions computes the amplitudes and angles of input image gradient. ** ** Gradient is computed simple by gradient kernel \f$ (-1 ~ 1) \f$, ** \f$ (-1 ~ 1)^T \f$ for border pixels and with sobel filter kernel ** \f$ (-0.5 ~ 0 ~ 0.5) \f$, \f$ (-0.5 ~ 0 ~ 0.5)^T \f$ otherwise on the input ** image @a image yielding x-gradient \f$ dx \f$, stored in @a xGradient and ** y-gradient \f$ dy \f$, stored in @a yGradient, respectively. ** ** This function also allows to process only part of the input image ** defining the @a imageStride as original image width and @a width as ** width of the sub-image. ** ** Also it allows to easily align the output data by definition ** of the @a gradWidthStride and @a gradHeightStride . **/ /** @fn vl_imgradient_f(float*,float*,vl_size,vl_size,float*,vl_size,vl_size,vl_size) ** @brief Compute image gradient ** @see ::vl_imgradient_d **/ VL_EXPORT void VL_XCAT(vl_imgradient_, SFX) (T * xGradient, T * yGradient, vl_size gradWidthStride, vl_size gradHeightStride, T const * image, vl_size imageWidth, vl_size imageHeight, vl_size imageStride) { /* Shortcuts */ vl_index const xo = 1 ; vl_index const yo = imageStride ; vl_size const w = imageWidth; vl_size const h = imageHeight; T const *src, *end ; T *pgrad_x, *pgrad_y; vl_size y; src = image ; pgrad_x = xGradient ; pgrad_y = yGradient ; /* first pixel of the first row */ *pgrad_x = src[+xo] - src[0] ; pgrad_x += gradWidthStride; *pgrad_y = src[+yo] - src[0] ; pgrad_y += gradWidthStride; src++; /* middle pixels of the first row */ end = (src - 1) + w - 1 ; while (src < end) { *pgrad_x = 0.5 * (src[+xo] - src[-xo]) ; pgrad_x += gradWidthStride; *pgrad_y = src[+yo] - src[0] ; pgrad_y += gradWidthStride; src++; } /* last pixel of the first row */ *pgrad_x = src[0] - src[-xo] ; pgrad_x += gradWidthStride; *pgrad_y = src[+yo] - src[0] ; pgrad_y += gradWidthStride; src++; xGradient += gradHeightStride; pgrad_x = xGradient; yGradient += gradHeightStride; pgrad_y = yGradient; image += yo; src = image; for (y = 1 ; y < h -1 ; ++y) { /* first pixel of the middle rows */ *pgrad_x = src[+xo] - src[0] ; pgrad_x += gradWidthStride; *pgrad_y = 0.5 * (src[+yo] - src[-yo]) ; pgrad_y += gradWidthStride; src++; /* middle pixels of the middle rows */ end = (src - 1) + w - 1 ; while (src < end) { *pgrad_x = 0.5 * (src[+xo] - src[-xo]) ; pgrad_x += gradWidthStride; *pgrad_y = 0.5 * (src[+yo] - src[-yo]) ; pgrad_y += gradWidthStride; src++; } /* last pixel of the middle row */ *pgrad_x = src[0] - src[-xo] ; pgrad_x += gradWidthStride; *pgrad_y = 0.5 * (src[+yo] - src[-yo]) ; pgrad_y += gradWidthStride; src++; xGradient += gradHeightStride; pgrad_x = xGradient; yGradient += gradHeightStride; pgrad_y = yGradient; image += yo; src = image; } /* first pixel of the last row */ *pgrad_x = src[+xo] - src[0] ; pgrad_x += gradWidthStride; *pgrad_y = src[ 0] - src[-yo] ; pgrad_y += gradWidthStride; src++; /* middle pixels of the last row */ end = (src - 1) + w - 1 ; while (src < end) { *pgrad_x = 0.5 * (src[+xo] - src[-xo]) ; pgrad_x += gradWidthStride; *pgrad_y = src[0] - src[-yo] ; pgrad_y += gradWidthStride; src++; } /* last pixel of the last row */ *pgrad_x = src[0] - src[-xo] ; *pgrad_y = src[0] - src[-yo] ; } /* VL_TYPE_FLOAT, VL_TYPE_DOUBLE */ #endif /** @fn vl_imgradient_polar_d(double*,double*,vl_size,vl_size,double const*,vl_size,vl_size,vl_size) ** @brief Compute gradient mangitudes and directions of an image. ** @param amplitudeGradient Pointer to amplitude gradient plane ** @param angleGradient Pointer to angle gradient plane ** @param gradWidthStride Width of the gradient plane including padding ** @param gradHeightStride Height of the gradient plane including padding ** @param image Pointer to the source image ** @param imageWidth Source image width ** @param imageHeight Source image height ** @param imageStride Width of the source image including padding. ** ** This functions computes the amplitudes and angles of input image gradient. ** ** Gradient is computed simple by gradient kernel \f$ (-1 ~ 1) \f$, ** \f$ (-1 ~ 1)^T \f$ for border pixels and with sobel filter kernel ** \f$ (-0.5 ~ 0 ~ 0.5) \f$, \f$ (-0.5 ~ 0 ~ 0.5)^T \f$ otherwise on ** the input image @a image yielding x-gradient \f$ dx \f$, stored in ** @a xGradient and y-gradient \f$ dy \f$, stored in @a yGradient, ** respectively. ** ** The amplitude of the gradient, stored in plane @a ** amplitudeGradient, is then calculated as \f$ \sqrt(dx^2+dy^2) \f$ ** and the angle of the gradient, stored in @a angleGradient is \f$ ** atan(\frac{dy}{dx}) \f$ normalised into interval 0 and @f$ 2\pi ** @f$. ** ** This function also allows to process only part of the input image ** defining the @a imageStride as original image width and @a width ** as width of the sub-image. ** ** Also it allows to easily align the output data by definition ** of the @a gradWidthStride and @a gradHeightStride . **/ /** @fn vl_imgradient_polar_f(float*,float*,vl_size,vl_size,float const*,vl_size,vl_size,vl_size) ** @see ::vl_imgradient_polar_d **/ #if (FLT == VL_TYPE_FLOAT || FLT == VL_TYPE_DOUBLE) VL_EXPORT void VL_XCAT(vl_imgradient_polar_, SFX) (T * gradientModulus, T * gradientAngle, vl_size gradientHorizontalStride, vl_size gradHeightStride, T const* image, vl_size imageWidth, vl_size imageHeight, vl_size imageStride) { /* Shortcuts */ vl_index const xo = 1 ; vl_index const yo = imageStride ; vl_size const w = imageWidth; vl_size const h = imageHeight; T const *src, *end; T *pgrad_angl, *pgrad_ampl; T gx, gy ; vl_size y; #define SAVE_BACK \ *pgrad_ampl = vl_fast_sqrt_f (gx*gx + gy*gy) ; \ pgrad_ampl += gradientHorizontalStride ; \ *pgrad_angl = vl_mod_2pi_f (vl_fast_atan2_f (gy, gx) + 2*VL_PI) ; \ pgrad_angl += gradientHorizontalStride ; \ ++src ; \ src = image ; pgrad_angl = gradientAngle ; pgrad_ampl = gradientModulus ; /* first pixel of the first row */ gx = src[+xo] - src[0] ; gy = src[+yo] - src[0] ; SAVE_BACK ; /* middle pixels of the first row */ end = (src - 1) + w - 1 ; while (src < end) { gx = 0.5 * (src[+xo] - src[-xo]) ; gy = src[+yo] - src[0] ; SAVE_BACK ; } /* last pixel of the first row */ gx = src[0] - src[-xo] ; gy = src[+yo] - src[0] ; SAVE_BACK ; gradientModulus += gradHeightStride; pgrad_ampl = gradientModulus; gradientAngle += gradHeightStride; pgrad_angl = gradientAngle; image += imageStride; src = image; for (y = 1 ; y < h -1 ; ++y) { /* first pixel of the middle rows */ gx = src[+xo] - src[0] ; gy = 0.5 * (src[+yo] - src[-yo]) ; SAVE_BACK ; /* middle pixels of the middle rows */ end = (src - 1) + w - 1 ; while (src < end) { gx = 0.5 * (src[+xo] - src[-xo]) ; gy = 0.5 * (src[+yo] - src[-yo]) ; SAVE_BACK ; } /* last pixel of the middle row */ gx = src[0] - src[-xo] ; gy = 0.5 * (src[+yo] - src[-yo]) ; SAVE_BACK ; gradientModulus += gradHeightStride; pgrad_ampl = gradientModulus; gradientAngle += gradHeightStride; pgrad_angl = gradientAngle; image += imageStride; src = image; } /* first pixel of the last row */ gx = src[+xo] - src[0] ; gy = src[ 0] - src[-yo] ; SAVE_BACK ; /* middle pixels of the last row */ end = (src - 1) + w - 1 ; while (src < end) { gx = 0.5 * (src[+xo] - src[-xo]) ; gy = src[0] - src[-yo] ; SAVE_BACK ; } /* last pixel of the last row */ gx = src[0] - src[-xo] ; gy = src[0] - src[-yo] ; SAVE_BACK ; } /* VL_TYPE_FLOAT, VL_TYPE_DOUBLE */ #endif /* ---------------------------------------------------------------- */ /* Integral Image */ /* ---------------------------------------------------------------- */ /** @fn vl_imintegral_d(double*,vl_size,double const*,vl_size,vl_size,vl_size) ** @brief Compute integral image ** ** @param integral integral image. ** @param integralStride integral image stride. ** @param image source image. ** @param imageWidth source image width. ** @param imageHeight source image height. ** @param imageStride source image stride. ** ** Let @f$ I(x,y), (x,y) \in [0, W-1] \times [0, H-1] @f$. The ** function computes the integral image @f$ J(x,y) @f$ of @f$ I(x,g) ** @f$: ** ** @f[ ** J(x,y) = \sum_{x'=0}^{x} \sum_{y'=0}^{y} I(x',y') ** @f] ** ** The integral image @f$ J(x,y) @f$ can be used to compute quickly ** the integral of of @f$ I(x,y) @f$ in a rectangular region @f$ R = ** [x',x'']\times[y',y''] @f$: ** ** @f[ ** \sum_{(x,y)\in[x',x'']\times[y',y'']} I(x,y) = ** (J(x'',y'') - J(x'-1, y'')) - (J(x'',y'-1) - J(x'-1,y'-1)). ** @f] ** ** Note that the order of operations is important when the integral image ** has an unsigned data type (e.g. ::vl_uint32). The formula ** is easily derived as follows: ** ** @f{eqnarray*} ** \sum_{(x,y)\in R} I(x,y) ** &=& \sum_{x=x'}^{x''} \sum_{y=y'}^{y''} I(x,y)\\ ** &=& \sum_{x=0}^{x''} \sum_{y=y'}^{y''} I(x,y) ** - \sum_{x=0}^{x'-1} \sum_{y=y'}^{y''} I(x,y)\\ ** &=& \sum_{x=0}^{x''} \sum_{y=0}^{y''} I(x,y) ** - \sum_{x=0}^{x''} \sum_{y=0}^{y'-1} I(x,y) ** - \sum_{x=0}^{x'-1} \sum_{y=0}^{y''} I(x,y) ** + \sum_{x=0}^{x'-1} \sum_{y=0}^{y'-1} I(x,y)\\ ** &=& J(x'',y'') - J(x'-1,y'') - J(x'',y'-1) + J(x'-1,y'-1). ** @f} **/ /** @fn vl_imintegral_f(float*,vl_size,float const*,vl_size,vl_size,vl_size) ** @brief Compute integral image ** @see ::vl_imintegral_d. **/ /** @fn vl_imintegral_ui32(vl_uint32*,vl_size,vl_uint32 const*,vl_size,vl_size,vl_size) ** @brief Compute integral image ** @see ::vl_imintegral_d. **/ /** @fn vl_imintegral_i32(vl_int32*,vl_size,vl_int32 const*,vl_size,vl_size,vl_size) ** @brief Compute integral image ** @see ::vl_imintegral_d. **/ VL_EXPORT void VL_XCAT(vl_imintegral_, SFX) (T * integral, vl_size integralStride, T const * image, vl_size imageWidth, vl_size imageHeight, vl_size imageStride) { vl_uindex x, y ; T temp = 0 ; if (imageHeight > 0) { for (x = 0 ; x < imageWidth ; ++ x) { temp += *image++ ; *integral++ = temp ; } } for (y = 1 ; y < imageHeight ; ++ y) { T * integralPrev ; integral += integralStride - imageWidth ; image += imageStride - imageWidth ; integralPrev = integral - integralStride ; temp = 0 ; for (x = 0 ; x < imageWidth ; ++ x) { temp += *image++ ; *integral++ = *integralPrev++ + temp ; } } } /* endif VL_IMOPV_INSTANTIATING */ #undef FLT #undef VL_IMOPV_INSTANTIATING #endif
32.76093
127
0.595917
[ "transform" ]
984de4c417a9964a0ea3a73180a5e5fb3d6bbb11
1,122
h
C
knn/knn.h
Dtananaev/ml_classifiers
a090ebb3c0dc2815a8e8b517f5a2075238eba886
[ "BSD-2-Clause" ]
1
2021-02-15T14:21:28.000Z
2021-02-15T14:21:28.000Z
knn/knn.h
Dtananaev/ml_classifiers
a090ebb3c0dc2815a8e8b517f5a2075238eba886
[ "BSD-2-Clause" ]
null
null
null
knn/knn.h
Dtananaev/ml_classifiers
a090ebb3c0dc2815a8e8b517f5a2075238eba886
[ "BSD-2-Clause" ]
1
2016-10-24T15:46:22.000Z
2016-10-24T15:46:22.000Z
/* * File: knn.h * * Author: Denis Tananaev * * Date: 25.10.2016 */ #ifndef KNN_H #define KNN_H #include <QMainWindow> #include <QMenu> #include <QMenuBar> #include <QApplication> #include <QKeyEvent> #include <QString> #include <QScrollBar> #include <QFileDialog> #include <QDir> #include <stdio.h> /* printf, fgets */ #include <stdlib.h> /* atof */ #include <fstream> #include <iostream> #include <vector> #include "ui_knn.h" class knn : public QMainWindow, private Ui_knn { Q_OBJECT public slots: void updateImage(); void updateK(); void updateL1(); void updateL2(); void calculatePerformance(); public: explicit knn(QWidget* parent = 0); ~knn(); void init(); bool trainSetread(const char* dirname); bool testSetread(const char* dirname); int knnDistance(int test_picture_index); private slots: void open(); private: int currentIndex_; int k_ = 1; std::vector<int> train_labels_; std::vector<std::vector<int> > train_images_; std::vector<int> test_labels_; std::vector<std::vector<int> > test_images_; std::vector<std::string> categories_; }; #endif // KNN_H
18.7
48
0.68984
[ "vector" ]
984f1edc0f8cbc19bda3e58a60450316bd8f3baf
1,366
h
C
co-op/Common/FileProps.h
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
67
2018-03-02T10:50:02.000Z
2022-03-23T18:20:29.000Z
co-op/Common/FileProps.h
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
null
null
null
co-op/Common/FileProps.h
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
9
2018-03-01T16:38:28.000Z
2021-03-02T16:17:09.000Z
#if !defined (FILEPROPS_H) #define FILEPROPS_H //---------------------------------- // (c) Reliable Software, 2007 //---------------------------------- #include "GlobalId.h" class FileData; namespace Project { class Db; } namespace CheckOut { class Db; } class FileProps { public: FileProps (FileData const & fileData, Project::Db const & projectDb); void AddCheckoutNotifications (Project::Db const & projectDb, CheckOut::Db const & checkoutNotificationDb); void SetCheckoutNotifications (bool flag) { _isCheckoutNotificationOn = flag; } std::string GetCaption () const; bool IsCheckoutNotificationOn () const { return _isCheckoutNotificationOn; } public: class CheckoutSequencer { public: CheckoutSequencer (FileProps const & props) : _cur (props._checkedOutBy.begin ()), _end (props._checkedOutBy.end ()) {} bool AtEnd () const { return _cur == _end; } void Advance () { ++_cur; } std::string const & GetMember () const { return *_cur; } private: std::vector<std::string>::const_iterator _cur; std::vector<std::string>::const_iterator _end; }; friend class CheckoutSequencer; private: void AddCheckedOutBy (Project::Db const & projectDb, UserId userId); private: GlobalId _gid; std::string _fileName; bool _isCheckoutNotificationOn; std::vector<std::string> _checkedOutBy; }; #endif
21.015385
80
0.674231
[ "vector" ]
984f72f70207c3d6ffd701f68dd5a5ecb44e7a16
15,718
h
C
libs/sfm/ba_sparse_matrix.h
18892021125/f-k
ee8062c3e9e900d7d662a800402aef9b10a814c6
[ "BSD-3-Clause" ]
1
2020-09-11T09:14:29.000Z
2020-09-11T09:14:29.000Z
libs/sfm/ba_sparse_matrix.h
MasterShockwave/mve
7a96751db098bb6f5c0b4075921b0e8e43a69bb6
[ "BSD-3-Clause" ]
null
null
null
libs/sfm/ba_sparse_matrix.h
MasterShockwave/mve
7a96751db098bb6f5c0b4075921b0e8e43a69bb6
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2015, Simon Fuhrmann, Fabian Langguth * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the LICENSE.txt file for details. */ #ifndef SFM_SPARSE_MATRIX_HEADER #define SFM_SPARSE_MATRIX_HEADER #include <thread> #include <stdexcept> #include <vector> #include <algorithm> #include "sfm/ba_dense_vector.h" #include "sfm/defines.h" SFM_NAMESPACE_BEGIN SFM_BA_NAMESPACE_BEGIN /** * Sparse matrix class in Yale format for column-major matrices. */ template <typename T> class SparseMatrix { public: /** Triplet with row/col index, and the actual value. */ struct Triplet { Triplet (void) = default; Triplet (std::size_t row, std::size_t col, T const& value); std::size_t row; std::size_t col; T value; }; /** List of triplets. */ typedef std::vector<Triplet> Triplets; public: SparseMatrix (void); SparseMatrix (std::size_t rows, std::size_t cols); void allocate (std::size_t rows, std::size_t cols); void reserve (std::size_t num_elements); void set_from_triplets (Triplets const& triplets); void mult_diagonal (T const& factor); void cwise_invert (void); void column_nonzeros (std::size_t col, DenseVector<T>* vector) const; SparseMatrix transpose (void) const; SparseMatrix subtract (SparseMatrix const& rhs) const; SparseMatrix multiply (SparseMatrix const& rhs) const; SparseMatrix sequential_multiply (SparseMatrix const& rhs) const; SparseMatrix parallel_multiply (SparseMatrix const& rhs) const; DenseVector<T> multiply (DenseVector<T> const& rhs) const; SparseMatrix diagonal_matrix (void) const; std::size_t num_non_zero (void) const; std::size_t num_rows (void) const; std::size_t num_cols (void) const; T* begin (void); T* end (void); void debug (void) const; private: std::size_t rows; std::size_t cols; std::vector<T> values; std::vector<std::size_t> outer; std::vector<std::size_t> inner; }; SFM_BA_NAMESPACE_END SFM_NAMESPACE_END /* ------------------------ Implementation ------------------------ */ #include <iostream> SFM_NAMESPACE_BEGIN SFM_BA_NAMESPACE_BEGIN template <typename T> SparseMatrix<T>::Triplet::Triplet (std::size_t row, std::size_t col, T const& value) : row(row), col(col), value(value) { } /* --------------------------------------------------------------- */ template <typename T> SparseMatrix<T>::SparseMatrix (void) : rows(0) , cols(0) { } template <typename T> SparseMatrix<T>::SparseMatrix (std::size_t rows, std::size_t cols) { this->allocate(rows, cols); } template <typename T> void SparseMatrix<T>::allocate (std::size_t rows, std::size_t cols) { this->rows = rows; this->cols = cols; this->values.clear(); this->outer.clear(); this->inner.clear(); this->outer.resize(cols + 1, 0); } template <typename T> void SparseMatrix<T>::reserve (std::size_t num_elements) { this->inner.reserve(num_elements); this->values.reserve(num_elements); } template <typename T> void SparseMatrix<T>::set_from_triplets (Triplets const& triplets) { /* Create a temporary transposed matrix */ SparseMatrix<T> transposed(this->cols, this->rows); transposed.values.resize(triplets.size()); transposed.inner.resize(triplets.size()); /* Initialize outer indices with amount of inner values. */ for (std::size_t i = 0; i < triplets.size(); ++i) transposed.outer[triplets[i].row]++; /* Convert amounts to indices with prefix sum. */ std::size_t sum = 0; std::vector<std::size_t> scratch(transposed.outer.size()); for (std::size_t i = 0; i < transposed.outer.size(); ++i) { std::size_t const temp = transposed.outer[i]; transposed.outer[i] = sum; scratch[i] = sum; sum += temp; } /* Add triplets, inner indices are unsorted. */ for (std::size_t i = 0; i < triplets.size(); ++i) { Triplet const& t = triplets[i]; std::size_t pos = scratch[t.row]++; transposed.values[pos] = t.value; transposed.inner[pos] = t.col; } /* Transpose matrix, implicit sorting of inner indices. */ *this = transposed.transpose(); } template <typename T> SparseMatrix<T> SparseMatrix<T>::transpose (void) const { SparseMatrix ret(this->cols, this->rows); ret.values.resize(this->num_non_zero()); ret.inner.resize(this->num_non_zero()); /* Compute inner sizes of transposed matrix. */ for(std::size_t i = 0; i < this->inner.size(); ++i) ret.outer[this->inner[i]] += 1; /* Compute outer sizes of transposed matrix with prefix sum. */ std::size_t sum = 0; std::vector<std::size_t> scratch(ret.outer.size()); for (std::size_t i = 0; i < ret.outer.size(); ++i) { std::size_t const temp = ret.outer[i]; ret.outer[i] = sum; scratch[i] = sum; sum += temp; } /* Write inner indices and values of transposed matrix. */ for (std::size_t i = 0; i < this->outer.size() - 1; ++i) for (std::size_t j = this->outer[i]; j < this->outer[i + 1]; ++j) { std::size_t pos = scratch[this->inner[j]]++; ret.inner[pos] = i; ret.values[pos] = this->values[j]; } return ret; } template <typename T> SparseMatrix<T> SparseMatrix<T>::subtract (SparseMatrix const& rhs) const { if (this->rows != rhs.rows || this->cols != rhs.cols) throw std::invalid_argument("Incompatible matrix dimensions"); SparseMatrix ret(this->rows, this->cols); ret.reserve(this->num_non_zero() + rhs.num_non_zero()); std::size_t num_outer = this->outer.size() - 1; for (std::size_t outer = 0; outer < num_outer; ++outer) { ret.outer[outer] = ret.values.size(); std::size_t i1 = this->outer[outer]; std::size_t i2 = rhs.outer[outer]; std::size_t const i1_end = this->outer[outer + 1]; std::size_t const i2_end = rhs.outer[outer + 1]; while (i1 < i1_end || i2 < i2_end) { if (i1 >= i1_end) { ret.values.push_back(-rhs.values[i2]); ret.inner.push_back(rhs.inner[i2]); i2 += 1; continue; } if (i2 >= i2_end) { ret.values.push_back(this->values[i1]); ret.inner.push_back(this->inner[i1]); i1 += 1; continue; } std::size_t id1 = this->inner[i1]; std::size_t id2 = rhs.inner[i2]; if (id1 < id2) ret.values.push_back(this->values[i1]); else if (id2 < id1) ret.values.push_back(-rhs.values[i2]); else ret.values.push_back(this->values[i1] - rhs.values[i2]); i1 += static_cast<std::size_t>(id1 <= id2); i2 += static_cast<std::size_t>(id2 <= id1); ret.inner.push_back(std::min(id1, id2)); } } ret.outer.back() = ret.values.size(); return ret; } template <typename T> SparseMatrix<T> SparseMatrix<T>::multiply (SparseMatrix const& rhs) const { #ifdef _OPENMP return this->parallel_multiply(rhs); #else return this->sequential_multiply(rhs); #endif } template <typename T> SparseMatrix<T> SparseMatrix<T>::sequential_multiply (SparseMatrix const& rhs) const { if (this->cols != rhs.rows) throw std::invalid_argument("Incompatible matrix dimensions"); SparseMatrix ret(this->rows, rhs.cols); ret.reserve(this->num_non_zero() + rhs.num_non_zero()); /* Matrix-matrix multiplication. */ std::vector<T> ret_col(ret.rows, T(0)); std::vector<bool> ret_nonzero(ret.rows, false); for (std::size_t col = 0; col < ret.cols; ++col) { ret.outer[col] = ret.values.size(); std::fill(ret_col.begin(), ret_col.end(), T(0)); std::fill(ret_nonzero.begin(), ret_nonzero.end(), false); std::size_t rhs_col_begin = rhs.outer[col]; std::size_t rhs_col_end = rhs.outer[col + 1]; for (std::size_t i = rhs_col_begin; i < rhs_col_end; ++i) { T const& rhs_col_value = rhs.values[i]; std::size_t const lhs_col = rhs.inner[i]; std::size_t const lhs_col_begin = this->outer[lhs_col]; std::size_t const lhs_col_end = this->outer[lhs_col + 1]; for (std::size_t j = lhs_col_begin; j < lhs_col_end; ++j) { std::size_t const id = this->inner[j]; ret_col[id] += this->values[j] * rhs_col_value; ret_nonzero[id] = true; } } for (std::size_t i = 0; i < ret.rows; ++i) if (ret_nonzero[i]) { ret.inner.push_back(i); ret.values.push_back(ret_col[i]); } } ret.outer[ret.cols] = ret.values.size(); return ret; } template <typename T> SparseMatrix<T> SparseMatrix<T>::parallel_multiply (SparseMatrix const& rhs) const { if (this->cols != rhs.rows) throw std::invalid_argument("Incompatible matrix dimensions"); std::size_t nnz = this->num_non_zero() + rhs.num_non_zero(); SparseMatrix ret(this->rows, rhs.cols); ret.reserve(nnz); std::fill(ret.outer.begin(), ret.outer.end(), 0); std::size_t const chunk_size = 64; std::size_t const num_chunks = ret.cols / chunk_size + (ret.cols % chunk_size != 0); std::size_t const max_threads = std::max(1u, std::thread::hardware_concurrency()); std::size_t const num_threads = std::min(num_chunks, max_threads); #pragma omp parallel num_threads(num_threads) { /* Matrix-matrix multiplication. */ std::vector<T> ret_col(ret.rows, T(0)); std::vector<bool> ret_nonzero(ret.rows, false); std::vector<T> thread_values; thread_values.reserve(nnz / num_chunks); std::vector<std::size_t> thread_inner; thread_inner.reserve(nnz / num_chunks); #pragma omp for ordered schedule(static, 1) #if !defined(_MSC_VER) for (std::size_t chunk = 0; chunk < num_chunks; ++chunk) #else for (int64_t chunk = 0; chunk < num_chunks; ++chunk) #endif { thread_inner.clear(); thread_values.clear(); std::size_t const begin = chunk * chunk_size; std::size_t const end = std::min(begin + chunk_size, ret.cols); for (std::size_t col = begin; col < end; ++col) { std::fill(ret_col.begin(), ret_col.end(), T(0)); std::fill(ret_nonzero.begin(), ret_nonzero.end(), false); std::size_t const rhs_col_begin = rhs.outer[col]; std::size_t const rhs_col_end = rhs.outer[col + 1]; for (std::size_t i = rhs_col_begin; i < rhs_col_end; ++i) { T const& rhs_col_value = rhs.values[i]; std::size_t const lhs_col = rhs.inner[i]; std::size_t const lhs_col_begin = this->outer[lhs_col]; std::size_t const lhs_col_end = this->outer[lhs_col + 1]; for (std::size_t j = lhs_col_begin; j < lhs_col_end; ++j) { std::size_t const id = this->inner[j]; ret_col[id] += this->values[j] * rhs_col_value; ret_nonzero[id] = true; } } for (std::size_t i = 0; i < ret.rows; ++i) if (ret_nonzero[i]) { ret.outer[col + 1] += 1; thread_inner.push_back(i); thread_values.push_back(ret_col[i]); } } #pragma omp ordered { ret.inner.insert(ret.inner.end(), thread_inner.begin(), thread_inner.end()); ret.values.insert(ret.values.end(), thread_values.begin(), thread_values.end()); } } } for (std::size_t col = 0; col < ret.cols; ++col) ret.outer[col + 1] += ret.outer[col]; return ret; } template<typename T> DenseVector<T> SparseMatrix<T>::multiply (DenseVector<T> const& rhs) const { if (rhs.size() != this->cols) throw std::invalid_argument("Incompatible dimensions"); DenseVector<T> ret(this->rows, T(0)); for (std::size_t i = 0; i < this->cols; ++i) for (std::size_t id = this->outer[i]; id < this->outer[i + 1]; ++id) ret[this->inner[id]] += this->values[id] * rhs[i]; return ret; } template<typename T> SparseMatrix<T> SparseMatrix<T>::diagonal_matrix (void) const { std::size_t const diag_size = std::min(this->rows, this->cols); SparseMatrix ret(diag_size, diag_size); ret.reserve(diag_size); for (std::size_t i = 0; i < diag_size; ++i) { ret.outer[i] = ret.values.size(); for (std::size_t j = this->outer[i]; j < this->outer[i + 1]; ++j) if (this->inner[j] == i) { ret.inner.push_back(i); ret.values.push_back(this->values[j]); } else if (this->inner[j] > i) break; } ret.outer[diag_size] = ret.values.size(); return ret; } template<typename T> void SparseMatrix<T>::mult_diagonal (T const& factor) { for (std::size_t i = 0; i < this->outer.size() - 1; ++i) for (std::size_t j = this->outer[i]; j < this->outer[i + 1]; ++j) { if (this->inner[j] == i) this->values[j] *= factor; if (this->inner[j] >= i) break; } } template<typename T> void SparseMatrix<T>::cwise_invert (void) { for (std::size_t i = 0; i < this->values.size(); ++i) this->values[i] = T(1) / this->values[i]; } template<typename T> void SparseMatrix<T>::column_nonzeros (std::size_t col, DenseVector<T>* vector) const { std::size_t const start = this->outer[col]; std::size_t const end = this->outer[col + 1]; vector->resize(end - start); for (std::size_t row = start, i = 0; row < end; ++row, ++i) vector->at(i) = this->values[row]; } template<typename T> inline std::size_t SparseMatrix<T>::num_non_zero (void) const { return this->values.size(); } template<typename T> inline std::size_t SparseMatrix<T>::num_rows (void) const { return this->rows; } template<typename T> inline std::size_t SparseMatrix<T>::num_cols (void) const { return this->cols; } template<typename T> inline T* SparseMatrix<T>::begin (void) { return this->values.data(); } template<typename T> inline T* SparseMatrix<T>::end (void) { return this->values.data() + this->values.size(); } template<typename T> void SparseMatrix<T>::debug (void) const { std::cout << "SparseMatrix (" << this->rows << " rows, " << this->cols << " cols, " << this->num_non_zero() << " values)" << std::endl; std::cout << " Values:"; for (std::size_t i = 0; i < this->values.size(); ++i) std::cout << " " << this->values[i]; std::cout << std::endl << " Inner:"; for (std::size_t i = 0; i < this->inner.size(); ++i) std::cout << " " << this->inner[i]; std::cout << std::endl << " Outer:"; for (std::size_t i = 0; i < this->outer.size(); ++i) std::cout << " " << this->outer[i]; std::cout << std::endl; } SFM_BA_NAMESPACE_END SFM_NAMESPACE_END #endif // SFM_SPARSE_MATRIX_HEADER
29.545113
80
0.578
[ "vector" ]
98538b7cac5a1bfdde9c8a1020f11b6030bc79fd
6,361
h
C
src/trunk/libs/seiscomp3/core/record.h
thefroid/seiscomp3
0b05d5550dcea000a93c7d9a39c5347d8786a91a
[ "Naumen", "Condor-1.1", "MS-PL" ]
2
2015-09-17T22:43:50.000Z
2017-11-29T20:27:11.000Z
src/trunk/libs/seiscomp3/core/record.h
thefroid/seiscomp3
0b05d5550dcea000a93c7d9a39c5347d8786a91a
[ "Naumen", "Condor-1.1", "MS-PL" ]
2
2016-04-26T00:03:09.000Z
2017-12-05T02:24:50.000Z
src/trunk/libs/seiscomp3/core/record.h
salichon/seiscomp3
4f7715f9ff9a35e7912c379ebf10446d0bceaeb2
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2022-01-13T02:49:31.000Z
2022-01-13T02:49:31.000Z
/*************************************************************************** * Copyright (C) by GFZ Potsdam * * * * You can redistribute and/or modify this program under the * * terms of the SeisComP Public License. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * SeisComP Public License for more details. * ***************************************************************************/ #ifndef __SEISCOMP_CORE_RECORD_H__ #define __SEISCOMP_CORE_RECORD_H__ #include <string> #include <time.h> #include <iostream> #include <seiscomp3/core/baseobject.h> #include <seiscomp3/core/interfacefactory.h> #include <seiscomp3/core/timewindow.h> #include <seiscomp3/core/array.h> #include <seiscomp3/core/exceptions.h> namespace Seiscomp { class BitSet; DEFINE_SMARTPOINTER(Record); class SC_SYSTEM_CORE_API Record : public Seiscomp::Core::BaseObject { DECLARE_SC_CLASS(Record); DECLARE_SERIALIZATION; // ---------------------------------------------------------------------- // Public enumeration // ---------------------------------------------------------------------- public: //! Specifies the memory storage flags. enum Hint { META_ONLY, DATA_ONLY, SAVE_RAW, H_QUANTITY }; // ---------------------------------------------------------------------- // X'truction // ---------------------------------------------------------------------- public: //! Default Constructor Record(Array::DataType datatype, Hint); //! Initializing Constructor Record(Array::DataType, Hint, std::string net, std::string sta, std::string loc, std::string cha, Seiscomp::Core::Time stime, int nsamp, double fsamp, int tqual); //! Copy Constructor Record(const Record &rec); //! Destructor virtual ~Record(); // ---------------------------------------------------------------------- // Operators // ---------------------------------------------------------------------- public: //! Assignment operator Record &operator=(const Record &rec); // ---------------------------------------------------------------------- // Public attribute access // ---------------------------------------------------------------------- public: //! Returns the network code const std::string &networkCode() const; //! Sets the network code virtual void setNetworkCode(std::string net); //! Returns the station code const std::string &stationCode() const; //! Sets the station code virtual void setStationCode(std::string sta); //! Returns the location code const std::string &locationCode() const; //! Sets the location code virtual void setLocationCode(std::string loc); //! Returns the channel code const std::string &channelCode() const; //! Sets the channel code virtual void setChannelCode(std::string cha); //! Returns the start time const Core::Time& startTime() const; //! Sets the start time virtual void setStartTime(const Core::Time& time); //! Returns the end time Core::Time endTime() const; //! Returns the time window between start and end time of a record Core::TimeWindow timeWindow() const; //! Returns the sample number int sampleCount() const; //! Returns the sample frequency double samplingFrequency() const; //! Returns the timing quality int timingQuality() const; //! Sets the timing quality void setTimingQuality(int tqual); //! Returns the so called stream ID: <net>.<sta>.<loc>.<cha> std::string streamID() const; //! Returns the data type specified for the data sample requests Array::DataType dataType() const; //! Sets the data type for the data requests which can differ from the real type of the data samples void setDataType(Array::DataType dt); //! Sets the hint used for data operations void setHint(Hint h); // ---------------------------------------------------------------------- // Public data access // ---------------------------------------------------------------------- public: //! Returns a nonmutable pointer to the data samples if the data is available; otherwise 0 //! (the data type is independent from the original one and was given by the DataType flag in the constructor) virtual const Array* data() const = 0; //! Returns the raw data of the record if existing virtual const Array* raw() const = 0; //! Returns a deep copy of the calling object. virtual Record* copy() const = 0; //! Return the clip mask for the data in the record. The clip mask //! holds a bit for each sample and sets that bit to 1 if the sample //! is clipped. The default implementation always returns NULL. //! Support has to be provided in derived implementations. virtual const BitSet *clipMask() const; // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- public: //! Frees the memory allocated for the data samples. virtual void saveSpace() const = 0; virtual void read(std::istream &in) = 0; virtual void write(std::ostream &out) = 0; // ---------------------------------------------------------------------- // Protected members // ---------------------------------------------------------------------- protected: std::string _net; std::string _sta; std::string _loc; std::string _cha; Core::Time _stime; Array::DataType _datatype; Hint _hint; int _nsamp; double _fsamp; int _timequal; }; DEFINE_INTERFACE_FACTORY(Record); #define REGISTER_RECORD(Class, Service) \ Seiscomp::Core::Generic::InterfaceFactory<Seiscomp::Record, Class> __##Class##InterfaceFactory__(Service) } SC_SYSTEM_CORE_API std::istream& operator>>(std::istream &is, Seiscomp::Record &rec); SC_SYSTEM_CORE_API std::ostream& operator<<(std::ostream &os, Seiscomp::Record &rec); #endif
30.290476
112
0.536551
[ "object" ]
986cd8972c08b7e115a6b3dc55b6217ec4e2f5dd
2,855
h
C
kubernetes/model/io_k8s_api_events_v1_event.h
zouxiaoliang/nerv-kubernetes-client-c
07528948c643270fd757d38edc68da8c9628ee7a
[ "Apache-2.0" ]
null
null
null
kubernetes/model/io_k8s_api_events_v1_event.h
zouxiaoliang/nerv-kubernetes-client-c
07528948c643270fd757d38edc68da8c9628ee7a
[ "Apache-2.0" ]
null
null
null
kubernetes/model/io_k8s_api_events_v1_event.h
zouxiaoliang/nerv-kubernetes-client-c
07528948c643270fd757d38edc68da8c9628ee7a
[ "Apache-2.0" ]
null
null
null
/* * io_k8s_api_events_v1_event.h * * Event is a report of an event somewhere in the cluster. It generally denotes some state change in the system. Events have a limited retention time and triggers and messages may evolve with time. Event consumers should not rely on the timing of an event with a given Reason reflecting a consistent underlying trigger, or the continued existence of events with that Reason. Events should be treated as informative, best-effort, supplemental data. */ #ifndef _io_k8s_api_events_v1_event_H_ #define _io_k8s_api_events_v1_event_H_ #include <string.h> #include "../external/cJSON.h" #include "../include/list.h" #include "../include/keyValuePair.h" #include "../include/binary.h" typedef struct io_k8s_api_events_v1_event_t io_k8s_api_events_v1_event_t; #include "io_k8s_api_core_v1_event_source.h" #include "io_k8s_api_core_v1_object_reference.h" #include "io_k8s_api_events_v1_event_series.h" #include "io_k8s_apimachinery_pkg_apis_meta_v1_object_meta.h" typedef struct io_k8s_api_events_v1_event_t { char *action; // string char *api_version; // string int deprecated_count; //numeric char *deprecated_first_timestamp; //date time char *deprecated_last_timestamp; //date time struct io_k8s_api_core_v1_event_source_t *deprecated_source; //model char *event_time; //date time char *kind; // string struct io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_t *metadata; //model char *note; // string char *reason; // string struct io_k8s_api_core_v1_object_reference_t *regarding; //model struct io_k8s_api_core_v1_object_reference_t *related; //model char *reporting_controller; // string char *reporting_instance; // string struct io_k8s_api_events_v1_event_series_t *series; //model char *type; // string } io_k8s_api_events_v1_event_t; io_k8s_api_events_v1_event_t *io_k8s_api_events_v1_event_create( char *action, char *api_version, int deprecated_count, char *deprecated_first_timestamp, char *deprecated_last_timestamp, io_k8s_api_core_v1_event_source_t *deprecated_source, char *event_time, char *kind, io_k8s_apimachinery_pkg_apis_meta_v1_object_meta_t *metadata, char *note, char *reason, io_k8s_api_core_v1_object_reference_t *regarding, io_k8s_api_core_v1_object_reference_t *related, char *reporting_controller, char *reporting_instance, io_k8s_api_events_v1_event_series_t *series, char *type ); void io_k8s_api_events_v1_event_free(io_k8s_api_events_v1_event_t *io_k8s_api_events_v1_event); io_k8s_api_events_v1_event_t *io_k8s_api_events_v1_event_parseFromJSON(cJSON *io_k8s_api_events_v1_eventJSON); cJSON *io_k8s_api_events_v1_event_convertToJSON(io_k8s_api_events_v1_event_t *io_k8s_api_events_v1_event); #endif /* _io_k8s_api_events_v1_event_H_ */
38.581081
449
0.796848
[ "model" ]
9871f4b3dffd3437fb632b498f5eb69dfa79e023
2,979
c
C
SLIP_LU/Source/slip_get_largest_pivot.c
gabrielfougeron/SuiteSparse
f196042715861c28846f3e01a394931c00860de2
[ "Apache-2.0" ]
27
2016-10-25T08:07:32.000Z
2022-02-06T20:20:59.000Z
SLIP_LU/Source/slip_get_largest_pivot.c
gabrielfougeron/SuiteSparse
f196042715861c28846f3e01a394931c00860de2
[ "Apache-2.0" ]
2
2020-01-28T18:47:50.000Z
2021-09-09T17:56:52.000Z
SLIP_LU/Source/slip_get_largest_pivot.c
gabrielfougeron/SuiteSparse
f196042715861c28846f3e01a394931c00860de2
[ "Apache-2.0" ]
10
2016-03-02T04:15:56.000Z
2021-03-31T03:20:46.000Z
//------------------------------------------------------------------------------ // SLIP_LU/slip_get_largest_pivot: find a pivot entry in a column //------------------------------------------------------------------------------ // SLIP_LU: (c) 2019-2020, Chris Lourenco, Jinhao Chen, Erick Moreno-Centeno, // Timothy A. Davis, Texas A&M University. All Rights Reserved. See // SLIP_LU/License for the license. //------------------------------------------------------------------------------ /* Purpose: This function selects the pivot element as the largest in the * column This is activated if the user sets option->pivot = SLIP_LARGEST. * * Note: This pivoting scheme is NOT recommended for SLIP LU. It is provided * for comparison with other pivoting options. * * On output, the index of the largest pivot is returned. */ #define SLIP_FREE_ALL \ SLIP_MPZ_CLEAR(big); #include "slip_internal.h" SLIP_info slip_get_largest_pivot ( int64_t *pivot, // the index of largest pivot SLIP_matrix* x, // kth column of L and U int64_t* pivs, // vector which indicates whether each row // has been pivotal int64_t n, // dimension of problem int64_t top, // nonzero pattern is located in xi[top..n-1] int64_t* xi // nonzero pattern of x ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- SLIP_REQUIRE(x, SLIP_DENSE, SLIP_MPZ); SLIP_info info ; if (!pivs || !xi || !pivot) {return SLIP_INCORRECT_INPUT;} //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- int64_t i, inew ; int r ; (*pivot) = -1 ; mpz_t big ; SLIP_MPZ_SET_NULL (big) ; SLIP_CHECK (SLIP_mpz_init (big)) ; //-------------------------------------------------------------------------- // Iterate accross the nonzeros in x //-------------------------------------------------------------------------- for (i = top; i < n; i++) { // Location of the ith nonzero inew = xi[i]; // inew can be pivotal SLIP_CHECK(SLIP_mpz_cmpabs(&r, big, x->x.mpz[inew])); if (pivs[inew] < 0 && r < 0) { // Current largest pivot location (*pivot) = inew; // Current largest pivot value SLIP_CHECK(SLIP_mpz_set(big, x->x.mpz[inew])); } } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- SLIP_FREE_ALL; if ((*pivot) == -1) { return SLIP_SINGULAR; } else { return SLIP_OK; } }
32.736264
80
0.417925
[ "vector" ]
9873926b8da3c096f0d69100345269fce66fc8c0
3,255
h
C
include/gmath/obox.h
gatgui/gmath
42b5efc3ce39888fc2b6e5168dea41f165d6f388
[ "MIT" ]
null
null
null
include/gmath/obox.h
gatgui/gmath
42b5efc3ce39888fc2b6e5168dea41f165d6f388
[ "MIT" ]
null
null
null
include/gmath/obox.h
gatgui/gmath
42b5efc3ce39888fc2b6e5168dea41f165d6f388
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2009 Gaetan Guidet This file is part of gmath. 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. */ #ifndef __gmath_obox_h_ #define __gmath_obox_h_ #include <gmath/box.h> #include <gmath/quat.h> namespace gmath { class GMATH_API AABox; class GMATH_API OBox : public Box { public: OBox(); OBox(const Vector3 &minPt, const Vector3 &maxPt); OBox(const Vector3 &c, const Quat &q, const Vector3 &e); OBox(const OBox &rhs); virtual ~OBox(); OBox& operator=(const OBox &rhs); virtual Box& transform(const Matrix4 &m); inline bool isNull() const { return mExtents == Vector3::ZERO; } inline void reset() { mExtents = Vector3::ZERO; dirty(); } inline const Vector3& getCenter() const { return mCenter; } inline const Vector3& getX() const { return mAxis[0]; } inline const Vector3& getY() const { return mAxis[1]; } inline const Vector3& getZ() const { return mAxis[2]; } inline const Vector3& getExtents() const { return mExtents; } inline const Vector3& getAxis(int i) const { return mAxis[i]; } inline float getExtent(int i) const { return mExtents[i]; } inline void setCenter(const Vector3 &c) { mCenter = c; dirty(); } inline void setExtents(const Vector3 &e) { mExtents = e; dirty(); } void setOrientation(const Quat &q); Quat getOrientation() const; void merge(const AABox &aab); void merge(const OBox &ob); void merge(const Vector3 &pt); bool intersect(const AABox &aab) const; bool intersect(const OBox &ob) const; protected: float getRadius(const Vector3 &dir) const; virtual void updateCorners() const; Vector3 mAxis[3]; Vector3 mCenter; Vector3 mExtents; }; } inline gmath::OBox operator*(const gmath::Matrix4 &m, const gmath::OBox &box) { gmath::OBox tmp(box); tmp.transform(m); return tmp; } #endif
25.038462
79
0.631336
[ "transform" ]
98772c51907e3a7fe005515ae5948e96e7878273
11,193
c
C
d/dagger/marsh/witchlair/obj/bonestaff.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/dagger/marsh/witchlair/obj/bonestaff.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/dagger/marsh/witchlair/obj/bonestaff.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
#include <std.h> #include "../witchlair.h" inherit "/d/common/obj/weapon/sstaff"; void create() { ::create(); set_name("shaman's staff"); set_id(({ "staff", "small staff", "shaman staff", "bone staff", "small bone staff" })); set_obvious_short("%^WHITE%^a %^BOLD%^s%^RESET%^ma%^BOLD%^" "ll %^RESET%^st%^BOLD%^a%^RESET%^f%^BOLD%^f %^RESET%^of b" "%^BOLD%^o%^RESET%^ne"); set_short("%^BOLD%^%^WHITE%^S%^BLACK%^t%^WHITE%^aff" " %^BLACK%^o%^WHITE%^f T%^BLACK%^h%^WHITE%^e " "%^BOLD%^%^WHITE%^Sha%^BLACK%^m%^WHITE%^an%^RESET%^"); set_long("%^BOLD%^%^WHITE%^Formed from the tibia of" " a large humanoid, this meter-long staff would easily fit " "into the hands of a gnome-size person. Lashed to the bone is " "an intact spinal cord, held together by fetid sinew. " "Surprisingly, it appears to be very sturdy. A small jawless " "skull, likely some sort of feline's, is affixed to one end of " "the bone, twin orbs of %^RESET%^%^ORANGE%^a%^YELLOW%^mb" "%^RESET%^%^ORANGE%^er %^BOLD%^%^WHITE%^wedged into the eye " "sockets. Most of the teeth are still attached, and when " "combined with the jagged shards of %^BOLD%^%^BLACK%^ob" "%^WHITE%^s%^BLACK%^id%^BLUE%^i%^WHITE%^a%^BLACK%^n " "%^WHITE%^attached to the jaw, would leave quite" " the nasty wound.%^RESET%^"); set_lore("%^BOLD%^%^WHITE%^It is common knowledge that " "goblinoids and kobolds are all repulsive species, easily capable" " of decimating an entire region's resources. What is known to " "few outside of these crude cultures is the nature of their " "magics, and the enchantment of their unholy artifacts. This is" " one such item, passed on to the shamanic leaders of a tribe by " "the %^BLACK%^B%^GREEN%^l%^BLACK%^a%^RED%^c%^BLACK%^k" " Ha%^GREEN%^n%^BLACK%^d %^WHITE%^himself. The two races" ", however, are in violent opposition as to its true origin. " "The former believe it is a gift from their patron god " "%^RESET%^%^RED%^Maglubiyet%^BOLD%^%^WHITE%^, as reward for" " laying waste to the human realms," " while the latter insist it to be granted to the strongest of " "kobold chiefs by mighty %^BOLD%^%^RED%^Kurtulmak" "%^BOLD%^%^WHITE%^, the first of their kind. Gods only know " "how terrible a threat their kind would be to the civilized " "world if not for millenia of mutual hatred.%^RESET%^"); set_value(250); set_size(1); set_property("lore difficulty", 25); set_property("id difficulty", 18); set_property("enchantment", 3); set_wield((: TO, "wield_func" :)); set_unwield((: TO, "unwield_func" :)); set_hit((: TO, "hit_func" :)); } int wield_func(string str) { if ((int)ETO->query_lowest_level() < 15) { tell_object(ETO, "%^BOLD%^%^WHITE%^A brief glow from the" " skull's eye sockets and a ghostly felid %^RESET%^%^GREEN%^h" "%^CYAN%^i%^BOLD%^%^GREEN%^s%^RESET%^%^GREEN%^s " "%^BOLD%^%^WHITE%^are all it takes to change your mind about " "doing that!"); tell_room(EETO, "%^BOLD%^%^BLACK%^" + ETO->QCN + " gives their" " staff a wary look before setting it aside."); return 0; } if ((string)ETO->query_race() != "goblin" && (string)ETO->query_race() != "hobgoblin" && (string)ETO->query_race() != "bugbear" && (string)ETO->query_race() != "kobold") { tell_room(EETO, "%^BOLD%^%^BLACK%^The staff refuses" " " + ETO->QCN + "'s hand!"); return 0; } if ((string)ETO->query_race() == "goblin" || (string)ETO->query_race() == "hobgoblin" || (string)ETO->query_race() == "bugbear") { tell_object(ETO, "%^BOLD%^%^GREEN%^You feel the " "%^RESET%^%^RED%^High Chieftain's %^BOLD%^%^GREEN%^approval" " as your hand wraps around the grisly staff.%^RESET%^"); tell_room(EETO, "%^RESET%^%^GREEN%^A wicked grin crosses " "" + ETO->QCN + "'s face as " + ETO->QS + " takes up the bone staff.", ETO); clear_item_bonus(); set_item_bonus("attack bonus", 1); set_item_bonus("fortitude", 1); return 1; }else { if ((string)ETO->query_race() == "kobold") { tell_object(ETO, "%^BOLD%^%^RED%^Pride and power " "flow through you. You feel as if %^RESET%^%^ORANGE%^Kurtulmak" " %^BOLD%^%^RED%^himself is smiling upon your prescience!"); tell_room(EETO, "%^RESET%^%^RED%^A low growl escapes " "" + ETO->QCN + "'s grinning jaws as " + ETO->QS + " takes a grip " "on the staff.", ETO); clear_item_bonus(); set_item_bonus("will", 1); set_item_bonus("spell penetration", 1); return 1; } } } void unwield_func(string str) { tell_object(ETO, "%^BOLD%^%^BLACK%^You feel as though your" " lord's favor is turned elsewhere as you loosen your hold" " of the staff...%^RESET%^"); tell_room(EETO, "%^BOLD%^%^WHITE%^" + ETO->QCN + " looks just" " a little deflated as " + ETO->QS + " lets go of the macabre" " staff.%^RESET%^", ETO); return 1; } void hit_func(object vict) { object obj2; vict = ETO->query_current_attacker(); if (!objectp(vict)) { return 0; } if (!random(1000) < 200) { switch (random(20)) { case 0..12: tell_room(EETO, "%^RESET%^%^RED%^" + ETO->QCN + " snarls" " and pulls the staff back, then swings it forward and " "%^BOLD%^%^RED%^rakes %^RESET%^%^RED%^it viciously across" " " + vict->QCN + "'s flesh! You can't help but wince, that " "looked painful!", ({ vict, ETO })); tell_object(ETO, "%^RESET%^%^RED%^A sudden " "%^BOLD%^%^RED%^RAGE %^RESET%^%^RED%^overcomes you as you" " bring the staff back with a snarl, then %^BOLD%^%^RED%^r" "ake %^RESET%^%^RED%^the sharp %^BOLD%^%^BLACK%^f" "%^RESET%^%^BLUE%^a%^BOLD%^%^WHITE%^n%^BLACK%^gs " "%^RESET%^%^RED%^of the skull across " + vict->QCN + "'s " "flesh!%^RESET%^"); tell_object(vict, "%^RESET%^%^RED%^" + ETO->QCN + " snarls" " and pulls the staff back, then swings it forward and " "%^BOLD%^%^RED%^rakes %^RESET%^%^RED%^it viciously across" " your flesh! Oh, the pain!"); set_property("magic", 1); vict->cause_typed_damage(vict, vict->return_target_limb(), random(5) + 12, "slashing"); remove_property("magic"); return 1; break; case 13..16: tell_room(EETO, "%^RESET%^%^CYAN%^" + ETO->QCN + "'s eyes " "and the eyes of " + ETO->QP + " staff flash bright " "%^ORANGE%^a%^YELLOW%^m%^BLACK%^b%^YELLOW%^e" "%^RESET%^%^ORANGE%^r %^CYAN%^in unison as " + ETO->QS + " " "swings the staff in a quick arc, sending a " "%^BOLD%^%^GREEN%^sp%^BLACK%^h%^WHITE%^e%^GREEN%^re " "%^RESET%^%^CYAN%^of %^BOLD%^%^BLACK%^un%^RED%^h" "%^BLACK%^oly p%^GREEN%^o%^BLUE%^w%^BLACK%^er " "%^RESET%^%^CYAN%^slamming into " + vict->QCN + "!", ({ ETO, vict })); tell_object(ETO, "%^RESET%^%^CYAN%^A sudden insight " "jumps to the fore of your mind! The %^ORANGE%^e" "%^YELLOW%^y%^RESET%^%^ORANGE%^es %^CYAN%^of the staff " "flash and your vision turns %^ORANGE%^go%^YELLOW%^l" "%^WHITE%^d%^RESET%^%^ORANGE%^en %^CYAN%^as you swing the" " staff in a quick arc, sending a %^BOLD%^%^GREEN%^sp" "%^BLACK%^h%^WHITE%^e%^GREEN%^re %^RESET%^%^CYAN%^of " "%^BOLD%^%^BLACK%^un%^RED%^h%^BLACK%^oly p%^GREEN%^o" "%^BLUE%^w%^BLACK%^er %^RESET%^%^CYAN%^slamming into " "" + vict->QCN + "!"); tell_object(vict, "%^RESET%^%^CYAN%^" + ETO->QCN + "'s" " eyes and the eyes of " + ETO->QP + " staff flash bright " "%^ORANGE%^a%^YELLOW%^m%^BLACK%^b%^YELLOW%^e" "%^RESET%^%^ORANGE%^r %^CYAN%^in unison as " + ETO->QO + " " "swings the staff in a quick arc, sending a " "%^BOLD%^%^GREEN%^sp%^BLACK%^h%^WHITE%^e%^GREEN%^re " "%^RESET%^%^CYAN%^of %^BOLD%^%^BLACK%^un%^RED%^h" "%^BLACK%^oly p%^GREEN%^o%^BLUE%^w%^BLACK%^er " "%^RESET%^%^CYAN%^slamming into you!"); set_property("magic", 1); vict->cause_typed_damage(vict, 0, roll_dice(2, 6) + 2, "negative energy"); remove_property("magic"); return 1; break; case 17..19: tell_room(EETO, "%^BOLD%^%^WHITE%^" + ETO->QCN + " " "raises " + ETO->QP + " staff parallel with " + vict->QCN + "" "'s face. A brief pause, and then - a spectral " "%^BLACK%^displacer beast %^WHITE%^fades into sight, " "leaping forth from the staff with a pantherlike roar!" , ({ ETO, vict })); tell_object(ETO, "%^BOLD%^%^WHITE%^As if of its own" " accord, the staff pulls itself and your arm upward " "until parallel with " + vict->QCN + "'s face. A brief " "pause, and then - a spectral %^BLACK%^displacer " "beast %^WHITE%^fades into sight, leaping forth from " "the staff with a pantherlike roar!"); tell_object(vict, "%^BOLD%^%^WHITE%^" + ETO->QCN + " " "raises " + ETO->QP + " staff parallel with your face. A " "brief pause, and then - a spectral %^BLACK%^displacer" " beast %^WHITE%^fades into sight, leaping forth from " "the staff with a pantherlike roar!"); obj2 = new(MON "disbeast"); obj2->move(EETO); obj2->force_me("protect " + ETO->query_name()); ETO->add_follower(obj2); break; default: break; } return 1; } }
52.060465
89
0.485839
[ "object" ]
987fd1b293bfff3ce8bb7e95c98f08f619fa08e9
9,522
h
C
Code/Base/accessors/current/dataaccess/DataIteratorAdapter.h
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
1
2020-06-18T08:37:43.000Z
2020-06-18T08:37:43.000Z
Code/Base/accessors/current/dataaccess/DataIteratorAdapter.h
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Base/accessors/current/dataaccess/DataIteratorAdapter.h
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
/// @file /// @brief an adapter to both IConstDataIterator and IDataIterator /// /// @details This class is similar to DataAccessorAdapter, but it adaps /// the iterator interface (rather than accessor interface). The current /// design of the synthesis code is largely iterator-based. This adapter /// and derived classes allow to reduce ugliness of the design in the case /// when break of the iteration is required. For example, one of the motivations /// is to provide more than one calibration solution per dataset (i.e. per iterator). /// In its current form, this iterator could be used if one needs to adapt a /// const iterator when non-const iterator is required by the interface /// (yes, the current code is quite messy), but all operations are read-only. /// /// @copyright (c) 2007 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// atnf-enquiries@csiro.au /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// @author Max Voronkov <maxim.voronkov@csiro.au> /// #ifndef ASKAP_ACCESSORS_DATA_ITERATOR_ADAPTER_H #define ASKAP_ACCESSORS_DATA_ITERATOR_ADAPTER_H // own includes #include <dataaccess/IConstDataIterator.h> #include <dataaccess/IDataIterator.h> #include <dataaccess/IDataAccessor.h> #include <dataaccess/DataAccessorAdapter.h> #include <utils/ChangeMonitor.h> // boost includes #include <boost/shared_ptr.hpp> namespace askap { namespace accessors { /// @details This class is similar to DataAccessorAdapter, but it adaps /// the iterator interface (rather than accessor interface). The current /// design of the synthesis code is largely iterator-based. This adapter /// and derived classes allow to reduce ugliness of the design in the case /// when break of the iteration is required. For example, one of the motivations /// is to provide more than one calibration solution per dataset (i.e. per iterator). /// In its current form, this iterator could be used if one needs to adapt a /// const iterator when non-const iterator is required by the interface /// (yes, the current code is quite messy), but all operations are read-only. /// @ingroup dataaccess_hlp class DataIteratorAdapter : virtual public IDataIterator { public: // constructors /// @brief default constructor to get an uninitialised adapter DataIteratorAdapter(); /// @brief setup with the given iterator /// @details /// @param[in] iter shared pointer to iterator to be wrapped /// @note the code tries to cast the shared pointer to a non-const iterator type. If /// successul, non-const methods of the adapter will also work explicit DataIteratorAdapter(const boost::shared_ptr<IConstDataIterator> &iter); // methods to associate, detach and check status of this accessor /// @brief associate this adapter /// @details This method associates the adapter with the given iterator /// @param[in] iter shared pointer to iterator to be wrapped /// @note the code tries to cast the shared pointer to a non-const iterator type. If /// successul, non-const methods of the adapter will also work void associate(const boost::shared_ptr<IConstDataIterator> &iter); /// @brief check whether the adapter is associated with some iterator /// @return true if adapter is associated with an iterator, false otherwise bool isAssociated() const; /// @brief detach adapter from the currently associated iterator, if any void detach(); /// @brief check whether write operation is permitted /// @return true, if write is possible bool canWrite() const; // const iterator methods /// Restart the iteration from the beginning virtual void init(); // Return the data accessor (current chunk) in various ways /// operator* delivers a reference to data accessor (current chunk) /// @return a reference to the current chunk virtual IDataAccessor& operator*() const; /// Checks whether there are more data available. /// @return True if there are more data available virtual casa::Bool hasMore() const throw(); /// advance the iterator one step further /// @return True if there are more data (so constructions like /// while(it.next()) {} are possible) virtual casa::Bool next(); // methods specific for non-const iterator /// Switch the output of operator* and operator-> to one of /// the buffers. This is meant to be done to provide the same /// interface for a buffer access as exists for the original /// visibilities (e.g. it->visibility() to get the cube). /// It can be used for an easy substitution of the original /// visibilities to ones stored in a buffer, when the iterator is /// passed as a parameter to mathematical algorithms. /// /// The operator* and operator-> will refer to the chosen buffer /// until a new buffer is selected or the chooseOriginal() method /// is executed to revert operators to their default meaning /// (to refer to the primary visibility data). /// /// @param[in] bufferID the name of the buffer to choose /// virtual void chooseBuffer(const std::string &bufferID); /// Switch the output of operator* and operator-> to the original /// state (present after the iterator is just constructed) /// where they point to the primary visibility data. This method /// is indended to cancel the results of chooseBuffer(casa::uInt) /// virtual void chooseOriginal(); /// return any associated buffer for read/write access. The /// buffer is identified by its bufferID. The method /// ignores a chooseBuffer/chooseOriginal setting. /// /// @param[in] bufferID the name of the buffer requested /// @return a reference to writable data accessor to the /// buffer requested /// /// Because IDataAccessor has both const and non-const visibility() /// methods defined separately, it is possible to detect when a /// write operation took place and implement a delayed writing virtual IDataAccessor& buffer(const std::string &bufferID) const; protected: /// @brief obtain change monitor /// @details It can be used in derived classes to compare whether we still /// deal with the same iterator as the one which might be used for some more evolved calculations. /// This change monitor tracks detach and associate calls and allows to avoid /// overriding of all these methods (and to avoid making them virtual), if a simple /// caching of derived products is found to be necessary in the derived classes. /// A comparison of two change monitors with a non-equal result means that the /// accessor was updated some time in between these two calls inline scimath::ChangeMonitor changeMonitor() const { return itsChangeMonitor; } /// @brief obtain a reference to associated iterator for read-only access /// @details This method checks the validity of the shared pointer and /// returns a reference of the const iterator type. The operation should always be /// successful, provided this adapter is associated with an iterator. Otherwise an /// exception is thrown /// @return a refernce to associated read-only iterator IConstDataIterator & roIterator() const; /// @brief obtain a reference to associated iterator for read-write access /// @details This method checks that the iterator is writeable (i.e. the appropriate /// shared pointer is valid) and returns the reference. An exception /// is thrown if the associated iterator is of the const type. /// @return a refernce to associated non-const iterator IDataIterator & rwIterator() const; private: /// @brief shared pointer to const iterator /// @details It is always initialised, if the adapter is attached to some iterator boost::shared_ptr<IConstDataIterator> itsConstIterator; /// @brief shared pointer to non-const iterator /// @details This data field is initialised only if the adapter is attached to some /// non-const iterator. It points to the same object as itsConstIterator and used /// in non-const methods. boost::shared_ptr<IDataIterator> itsIterator; /// @brief change monitor for iterators /// @details we may need to know when iterator is /// updated in the derived classes. Change monitor provides /// an efficient way of doing it. scimath::ChangeMonitor itsChangeMonitor; /// @brief shared pointer to an accessor /// @details We need this persistence because accessors are returned by reference. /// In addition, we might need to setup an accessor adapter to ensure a correct /// type is returned mutable DataAccessorAdapter itsAccessorAdapter; }; } // namespace accessors } // namespace askap #endif // #ifndef DATA_ITERATOR_ADAPTER_H
43.880184
100
0.735455
[ "object" ]
9881388d9e91d1bdb81059a6e17c0a7799efe043
5,108
h
C
Src/boundary.h
liuyangggg/mplb
4a079e13ad3576b5fbf034203d90860945ab51f0
[ "BSD-3-Clause" ]
1
2021-09-03T09:02:43.000Z
2021-09-03T09:02:43.000Z
Src/boundary.h
liuyangggg/mplb
4a079e13ad3576b5fbf034203d90860945ab51f0
[ "BSD-3-Clause" ]
null
null
null
Src/boundary.h
liuyangggg/mplb
4a079e13ad3576b5fbf034203d90860945ab51f0
[ "BSD-3-Clause" ]
3
2021-06-21T21:21:41.000Z
2021-09-12T04:21:13.000Z
/** * Copyright 2019 United Kingdom Research and Innovation * * Authors: See AUTHORS * * Contact: [jianping.meng@stfc.ac.uk and/or jpmeng@gmail.com] * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice * this list of conditions and the following disclaimer in the documentation * and or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * ANDANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /*! @brief Head files for boundary conditions * @author Jianping Meng * @details Declaring functions related to boundary conditions. */ #ifndef BOUNDARY_H #define BOUNDARY_H #include "type.h" #include <vector> #include "block.h" #include "flowfield_host_device.h" #include "boundary_host_device.h" #include "model.h" #include "model_host_device.h" const std::vector<BoundarySurface> AllBoundarySurface{BoundarySurface::Left, BoundarySurface::Right, BoundarySurface::Top, BoundarySurface::Bottom, #ifdef OPS_3D BoundarySurface::Front, BoundarySurface::Back, BoundarySurface::LeftBack, BoundarySurface::LeftFront, BoundarySurface::RightBack, BoundarySurface::RightFront, BoundarySurface::TopBack, BoundarySurface::TopFront, BoundarySurface::BottomBack, BoundarySurface::BottomFront, #endif BoundarySurface::LeftTop, BoundarySurface::LeftBottom, BoundarySurface::RightTop, BoundarySurface::RightBottom }; enum class BoundaryScheme { KineticDiffuseWall = 11, KineticSpelluarWall = 12, ExtrapolPressure1ST = 16, ExtrapolPressure2ND = 17, MDPeriodic = 18, FDPeriodic = 19, BounceBack = 20, FreeFlux = 21, ZouHeVelocity = 22, EQNNoSlip = 23, EQMDiffuseRefl = 24, None = -1 }; struct BlockBoundary { int blockIndex; int componentID; std::vector<Real> givenVars; BoundarySurface boundarySurface; BoundaryScheme boundaryScheme; std::vector<VariableTypes> macroVarTypesatBoundary; VertexType boundaryType; }; int BoundaryHaloNum(); void SetBoundaryHaloNum(const int boundaryhaloNum); void BoundaryNormal3D(const VertexGeometryType vg, int* unitNormal); void DefineBlockBoundary(int blockIndex, int componentID, BoundarySurface boundarySurface, BoundaryScheme boundaryScheme, const std::vector<VariableTypes>& macroVarTypes, const std::vector<Real>& macroVarValues, const VertexType boundaryType = VertexType::Wall); void DefineBlockBoundary( int blockIndex, int componentID, BoundarySurface boundarySurface, const VertexType boundaryType = VertexType::VirtualBoundary); const std::vector<BlockBoundary>& BlockBoundaries(); #ifdef OPS_3D void TreatBlockBoundary3D(const Block& block, const int componentID, const Real* givenVars, const BoundaryScheme boundaryScheme, const BoundarySurface boundarySurface); void ImplementBoundary3D(); #endif #ifdef OPS_2D void TreatBlockBoundary(const Block& block, const int componentID, const Real* givenVars, const BoundaryScheme boundaryScheme, const BoundarySurface boundarySurface); void ImplementBoundary(); #endif #endif // BOUNDARY_H
40.220472
80
0.646633
[ "vector", "model" ]
98875eb46257dd8011c3f99a00dca7dd3dc9e52d
7,676
h
C
metrics/metrics.h
EluvK/E-metrics
6c82a78b2ed97ab5b68809e2eda076829718232a
[ "MIT" ]
null
null
null
metrics/metrics.h
EluvK/E-metrics
6c82a78b2ed97ab5b68809e2eda076829718232a
[ "MIT" ]
null
null
null
metrics/metrics.h
EluvK/E-metrics
6c82a78b2ed97ab5b68809e2eda076829718232a
[ "MIT" ]
null
null
null
#pragma once #include "metrics_event.h" #include "metrics_handler/counter_handler.h" #include "metrics_handler/flow_handler.h" #include "metrics_handler/metrics_packet_info.h" #include "metrics_handler/timer_handler.h" #include "metrics_unit.h" #include "mylib/mpsc_queue.h" #include "mylib/runnable.h" #include <chrono> #include <map> #include <string> #include <thread> NS_BEG1(metrics) class e_metrics : public mylib::runnable_t<e_metrics> { public: DELETED_COPY_AND_MOVE_SEMANTICS(e_metrics); DEFAULTED_OVERRIDE_DESTRUCTOR(e_metrics); static e_metrics & get_instance() { static e_metrics instance; return instance; } void start() override; void stop() override; private: e_metrics() = default; void run_process(); void process_message_queue(); void update_dump(); public: void timer_start(std::string metrics_name, time_point value); void timer_end(std::string metrics_name, time_point value, metrics_appendant_info info = 0, microseconds timed_out = DEFAULT_TIMED_OUT); void counter_increase(std::string metrics_name, int64_t value); void counter_decrease(std::string metrics_name, int64_t value); void counter_set(std::string metrics_name, int64_t value); void flow_count(std::string metrics_name, int64_t value, time_point timestamp); private: std::thread m_process_thread; std::size_t m_dump_interval; std::chrono::microseconds m_queue_procss_behind_sleep_time; handler::counter_handler_t m_counter_handler; handler::timer_handler_t m_timer_handler; handler::flow_handler_t m_flow_handler; // constexpr static std::size_t message_queue_size{100000}; mylib::mpsc_queue<event_message> m_message_queue; // top::threading::xthreadsafe_queue<event_message, std::vector<event_message>> m_message_queue{message_queue_size}; std::map<std::string, metrics_variant_ptr> m_metrics_hub; // {metrics_name, metrics_vaiant_ptr} }; class metrics_time_auto { public: metrics_time_auto(std::string metrics_name, metrics_appendant_info key = std::string{"NOT SET appendant_info"}, microseconds timed_out = DEFAULT_TIMED_OUT) : m_metrics_name{metrics_name}, m_key{key}, m_timed_out{timed_out} { char c[15] = {0}; snprintf(c, 14, "%p", this); m_metrics_name = m_metrics_name + "&" + c; e_metrics::get_instance().timer_start(m_metrics_name, std::chrono::system_clock::now()); } ~metrics_time_auto() { e_metrics::get_instance().timer_end(m_metrics_name, std::chrono::system_clock::now(), m_key, m_timed_out); } std::string m_metrics_name; metrics_appendant_info m_key; microseconds m_timed_out; }; // #ifdef ENABLE_METRICS #define METRICS_INIT() \ { \ auto & ins = metrics::e_metrics::get_instance(); \ ins.start(); \ } #define SSTR(x) static_cast<std::ostringstream &>((std::ostringstream() << x)).str() #define ADD_THREAD_HASH(metrics_name) SSTR(metrics_name) + "&0x" + std::to_string(std::hash<std::thread::id>{}(std::this_thread::get_id())) #define STR_CONCAT_IMPL(a, b) a##b #define STR_CONCAT(str_a, str_b) STR_CONCAT_IMPL(str_a, str_b) #define MICROSECOND(timeout) \ std::chrono::microseconds { timeout } #define METRICS_TIME_RECORD(metrics_name) \ metrics::metrics_time_auto STR_CONCAT(metrics_time_auto, __LINE__) { metrics_name } #define METRICS_TIME_RECORD_KEY(metrics_name, key) \ metrics::metrics_time_auto STR_CONCAT(metrics_time_auto, __LINE__) { metrics_name, key } #define METRICS_TIME_RECORD_KEY_WITH_TIMEOUT(metrics_name, key, timeout) \ metrics::metrics_time_auto STR_CONCAT(metrics_time_auto, __LINE__) { metrics_name, key, MICROSECOND(timeout) } #define METRICS_TIMER_START(metrics_name) metrics::e_metrics::get_instance().timer_start(ADD_THREAD_HASH(metrics_name), std::chrono::system_clock::now()); #define METRICS_TIMER_STOP(metrics_name) metrics::e_metrics::get_instance().timer_end(ADD_THREAD_HASH(metrics_name), std::chrono::system_clock::now()); #define METRICS_TIMER_STOP_KEY(metrics_name, key) metrics::e_metrics::get_instance().timer_end(ADD_THREAD_HASH(metrics_name), std::chrono::system_clock::now(), key); #define METRICS_TIMER_STOP_KEY_WITH_TIMEOUT(metrics_name, key, timeout) \ metrics::e_metrics::get_instance().timer_end(ADD_THREAD_HASH(metrics_name), std::chrono::system_clock::now(), key, MICROSECOND(timeout)); #define METRICS_COUNTER_INCREMENT(metrics_name, value) metrics::e_metrics::get_instance().counter_increase(metrics_name, value) #define METRICS_COUNTER_DECREMENT(metrics_name, value) metrics::e_metrics::get_instance().counter_decrease(metrics_name, value) #define METRICS_COUNTER_SET(metrics_name, value) metrics::e_metrics::get_instance().counter_set(metrics_name, value) #define METRICS_FLOW_COUNT(metrics_name, value) metrics::e_metrics::get_instance().flow_count(metrics_name, value, std::chrono::system_clock::now()); #define METRICS_PACKET_INFO(metrics_name, ...) \ metrics::handler::metrics_pack_unit STR_CONCAT(packet_info_auto_, __LINE__){metrics_name}; \ metrics::handler::metrics_packet_impl(STR_CONCAT(packet_info_auto_, __LINE__), __VA_ARGS__); #define METRICS_XBASE_DATA_CATEGORY_NEW(key) METRICS_COUNTER_INCREMENT("dataobject_cur_xbase_type" + std::to_string(key), 1); #define METRICS_XBASE_DATA_CATEGORY_DELETE(key) METRICS_COUNTER_INCREMENT("dataobject_cur_xbase_type" + std::to_string(key), -1); // #else // #define METRICS_INIT() // #define METRICS_TIME_RECORD(metrics_name) // #define METRICS_TIME_RECORD_KEY(metrics_name, key) // #define METRICS_TIME_RECORD_KEY_WITH_TIMEOUT(metrics_name, key, timeout) // #define METRICS_TIMER_START(metrics_name) // #define METRICS_TIMER_STOP(metrics_name) // #define METRICS_TIMER_STOP_KEY(metrics_name, key) // #define METRICS_TIMER_STOP_KEY_WITH_TIMEOUT(metrics_name, key, timeout) // #define METRICS_COUNTER_INCREMENT(metrics_name, value) // #define METRICS_COUNTER_DECREMENT(metrics_name, value) // #define METRICS_COUNTER_SET(metrics_name, value) // #define METRICS_FLOW_COUNT(metrics_name, value) // #define METRICS_PACKET_INFO(metrics_name, ...) // #define METRICS_XBASE_DATA_CATEGORY_NEW(key) // #define METRICS_XBASE_DATA_CATEGORY_DELETE(key) // #endif NS_END1
56.441176
180
0.626238
[ "vector" ]
9887635cb24d63a6d59bcd6c2d8e08d6a44ae54c
4,117
h
C
liballofw/include/allofw/config.h
donghaoren/AllofwModule
4367327cda0605aad53469294ed8751f8befbdc3
[ "Unlicense" ]
3
2016-05-04T23:23:48.000Z
2021-08-03T21:48:07.000Z
liballofw/include/allofw/config.h
donghaoren/AllofwModule
4367327cda0605aad53469294ed8751f8befbdc3
[ "Unlicense" ]
null
null
null
liballofw/include/allofw/config.h
donghaoren/AllofwModule
4367327cda0605aad53469294ed8751f8befbdc3
[ "Unlicense" ]
2
2016-01-31T04:06:51.000Z
2016-09-30T16:38:36.000Z
#ifndef ALLOFW_CONFIG_H #define ALLOFW_CONFIG_H #include "common.h" #include <memory> #include <string> namespace allofw { //! YAML-based configuration reader. class Configuration { public: //! Config node. class Node { public: virtual bool isArray() const = 0; //! Is this an array? virtual bool isDictionary() const = 0; //! Is this a dictionary? virtual bool isValue() const = 0; //! Is this a value? //! Get string. virtual void getString(char* output, size_t output_capacity, const char* fallback = "") const = 0; //! Get the length of the string. virtual size_t getStringLength(const char* fallback = "") const = 0; //! Get int32 value. virtual int getInt32(int fallback = 0) const = 0; //! Get uint32 value. virtual unsigned int getUInt32(unsigned int fallback = 0) const = 0; //! Get float value. virtual float getFloat(float fallback = 0.0f) const = 0; //! Get double value. virtual double getDouble(double fallback = 0.0) const = 0; //! Get boolean value. virtual bool getBoolean(bool fallback = 0.0) const = 0; //! Get STL string value. std::string getString(const char* fallback = "") { size_t len = getStringLength(fallback); char* buffer = new char[len + 1]; getString(buffer, len + 1, fallback); std::string result(buffer); delete [] buffer; return result; } //! Get array item by index. virtual Node* get(int index) const = 0; //! Get dictionary item by key. virtual Node* get(const char* key) const = 0; //! Get size of the node (for array and dictionary). virtual size_t size() const = 0; protected: virtual ~Node() { } }; //! Get a node with a key (pair with destroyNode). virtual Node* getNode(const char* key) = 0; //! Destroy the node. virtual void destroyNode(Node* node) = 0; //! Get the string at a given path. virtual void getString(const char* path, char* output, size_t output_capacity, const char* fallback = "") = 0; //! Get the length of the string at a give path. virtual size_t getStringLength(const char* path, const char* fallback = "") = 0; //! Get int32 at a given path. virtual int getInt32(const char* path, int fallback = 0) = 0; //! Get uint32 at a given path. virtual unsigned int getUInt32(const char* path, unsigned int fallback = 0) = 0; //! Get float at a given path. virtual float getFloat(const char* path, float fallback = 0.0f) = 0; //! Get double at a given path. virtual double getDouble(const char* path, double fallback = 0.0) = 0; //! Get boolean at a given path. virtual bool getBoolean(const char* path, bool fallback = 0.0) = 0; //! Parse a YAML file. virtual void parseFile(const char* path) = 0; //! Parse a YAML file to a give key. virtual void parseFile(const char* path, const char* key) = 0; //! Get STL string at a given path. std::string getString(const char* path, const char* fallback = "") { size_t len = getStringLength(path, fallback); char* buffer = new char[len + 1]; getString(path, buffer, len + 1, fallback); std::string result(buffer); delete [] buffer; return result; } virtual ~Configuration() { } //! Create Configuration object. static Configuration* Create(); //! Create Configuration object by C++ main() arguments. static Configuration* ParseMainArgs(int argc, char* argv[]); //! Create Configuration object from file. static Configuration* CreateFromFile(const char* args = nullptr); }; } #endif
38.12037
118
0.567161
[ "object" ]
988c1686df7bed740b412b0a9b66f0249d14fbdd
456
h
C
GraphicsProject/Entity.h
Noaheasley/Bootstrap
fbcf53bffa42fe41233726ba42218568ce0dba60
[ "MIT" ]
null
null
null
GraphicsProject/Entity.h
Noaheasley/Bootstrap
fbcf53bffa42fe41233726ba42218568ce0dba60
[ "MIT" ]
null
null
null
GraphicsProject/Entity.h
Noaheasley/Bootstrap
fbcf53bffa42fe41233726ba42218568ce0dba60
[ "MIT" ]
null
null
null
#pragma once #include "Transform.h" #include "Shader.h" #include "glm\mat4x4.hpp" class Entity { public: Entity(); ~Entity(); void start(); void update(float deltaTime); void draw(); void end(); virtual void onStart() {}; virtual void onUpdate(float deltaTime) {}; virtual void onDraw() {}; virtual void onEnd() {}; Transform* getTransform() { return m_transform; } private: Transform* m_transform = nullptr; bool m_started = false; };
15.2
50
0.682018
[ "transform" ]
989f1fb34cd0d2b4985d46a5d3028b72f344face
3,295
h
C
usr/libexec/vot/VOTBrailleGesturePatternRecognitionEngine.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
usr/libexec/vot/VOTBrailleGesturePatternRecognitionEngine.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
usr/libexec/vot/VOTBrailleGesturePatternRecognitionEngine.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 Steve Nygard. // #import <objc/NSObject.h> @class NSMutableArray, VOTBrailleGestureDataRepository; @protocol VOTBrailleGesturePatternRecognitionEngineDelegate; @interface VOTBrailleGesturePatternRecognitionEngine : NSObject { VOTBrailleGestureDataRepository *_repository; // 8 = 0x8 NSMutableArray *_lastBrailleGestures; // 16 = 0x10 long long _typingMode; // 24 = 0x18 struct CGSize _keyboardSize; // 32 = 0x20 _Bool _shouldUseEightDotBraille; // 48 = 0x30 _Bool _shouldReverseDots; // 49 = 0x31 id <VOTBrailleGesturePatternRecognitionEngineDelegate> _delegate; // 56 = 0x38 } - (void).cxx_destruct; // IMP=0x00000001000f03a4 @property(nonatomic) __weak id <VOTBrailleGesturePatternRecognitionEngineDelegate> delegate; // @synthesize delegate=_delegate; - (double)_averageOfOldFloat:(double)arg1 newFloat:(double)arg2 dataCount:(unsigned long long)arg3; // IMP=0x00000001000f0354 - (struct CGPoint)_averageOfOldPoint:(struct CGPoint)arg1 newPoint:(struct CGPoint)arg2 dataCount:(unsigned long long)arg3; // IMP=0x00000001000f02dc - (id)_averagePointValueWithDataCount:(unsigned long long)arg1 currentPointValue:(id)arg2 newPointValue:(id)arg3; // IMP=0x00000001000f01f8 - (_Bool)_bothObjectsAreNilOrBothAreNonNil:(id)arg1 object:(id)arg2; // IMP=0x00000001000f01d0 - (_Bool)_halfPattern:(id)arg1 hasSameDotsAsHalfPattern:(id)arg2; // IMP=0x00000001000f002c - (id)_sortTouches:(id)arg1 fromTopToBottomForSide:(unsigned long long)arg2; // IMP=0x00000001000efee0 - (double)_distanceBetweenPoint:(struct CGPoint)arg1 andPoint:(struct CGPoint)arg2; // IMP=0x00000001000efec4 - (id)_orderedTouchesFromHalfPattern:(id)arg1; // IMP=0x00000001000efcfc - (double)_totalDistanceBetweenCorrespondingPointsInTouches:(id)arg1 andTouches:(id)arg2; // IMP=0x00000001000efba8 - (id)_halfPatternFromOrderedTouches:(id)arg1 correspondingHalfPattern:(id)arg2; // IMP=0x00000001000ef9b8 - (id)_closestHalfPatternForOrderedTouches:(id)arg1 possibleMatches:(id)arg2 side:(unsigned long long)arg3; // IMP=0x00000001000ef75c - (id)_halfPatternFromTouches:(id)arg1 side:(unsigned long long)arg2; // IMP=0x00000001000ef650 - (unsigned short)_printBrailleCharacterFromBraillePattern:(id)arg1; // IMP=0x00000001000ef16c - (void)_populateLeftTouchPoints:(id)arg1 rightTouchPoints:(id)arg2 fromTouchPoints:(id)arg3; // IMP=0x00000001000eefdc - (_Bool)areDotNumberPositionsCalibrated; // IMP=0x00000001000eefcc @property(readonly, nonatomic) _Bool shouldReverseDots; @property(readonly, nonatomic) _Bool shouldUseEightDotBraille; - (void)calibrateWithTouchPoints:(id)arg1; // IMP=0x00000001000eeb30 - (id)dotNumberPositions; // IMP=0x00000001000eeb20 - (void)setTypingMode:(long long)arg1 keyboardSize:(struct CGSize)arg2 shouldUseEightDotBraille:(_Bool)arg3 shouldReverseDots:(_Bool)arg4; // IMP=0x00000001000eea30 - (void)savePersistentGestureData; // IMP=0x00000001000eea20 - (void)resetLastGestures; // IMP=0x00000001000eea10 - (void)unlearnLastGesture; // IMP=0x00000001000ee984 - (id)printBrailleForTouchPoints:(id)arg1 shouldLearn:(_Bool)arg2 error:(id *)arg3; // IMP=0x00000001000ee734 - (id)init; // IMP=0x00000001000ee5e0 @end
62.169811
164
0.8
[ "object" ]
98a43e5d23af36c880799e10422c09f4bec3707b
1,327
h
C
llvm-project/llvm/tools/llvm-objcopy/llvm-objcopy.h
Little-W/tc-build
8217fdf3112f2e964b231a8f82b8a7aa7c0b2f87
[ "Apache-2.0" ]
null
null
null
llvm-project/llvm/tools/llvm-objcopy/llvm-objcopy.h
Little-W/tc-build
8217fdf3112f2e964b231a8f82b8a7aa7c0b2f87
[ "Apache-2.0" ]
null
null
null
llvm-project/llvm/tools/llvm-objcopy/llvm-objcopy.h
Little-W/tc-build
8217fdf3112f2e964b231a8f82b8a7aa7c0b2f87
[ "Apache-2.0" ]
null
null
null
//===- llvm-objcopy.h -------------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLVM_TOOLS_OBJCOPY_OBJCOPY_H #define LLVM_TOOLS_OBJCOPY_OBJCOPY_H #include "llvm/Support/Error.h" #include "llvm/Support/raw_ostream.h" namespace llvm { struct NewArchiveMember; namespace object { class Archive; } // end namespace object namespace objcopy { struct CopyConfig; Expected<std::vector<NewArchiveMember>> createNewArchiveMembers(CopyConfig &Config, const object::Archive &Ar); /// A writeToFile helper creates an output stream, based on the specified /// \p OutputFileName: std::outs for the "-", raw_null_ostream for /// the "/dev/null", temporary file in the same directory as the final output /// file for other names. The final output file is atomically replaced with /// the temporary file after \p Write handler is finished. Error writeToFile(StringRef OutputFileName, std::function<Error(raw_ostream &)> Write); } // end namespace objcopy } // end namespace llvm #endif // LLVM_TOOLS_OBJCOPY_OBJCOPY_H
31.595238
80
0.675961
[ "object", "vector" ]
98ac794c83cc11d66ee05ead05c33913d2d048fc
2,280
h
C
driver/fuzz_target_runner.h
Han0nly/jazzer
b34f6aad8151551005bd502e42fbc1472e69f10b
[ "Apache-2.0" ]
536
2021-02-10T08:05:19.000Z
2022-03-31T17:39:46.000Z
driver/fuzz_target_runner.h
Han0nly/jazzer
b34f6aad8151551005bd502e42fbc1472e69f10b
[ "Apache-2.0" ]
91
2021-02-11T19:36:59.000Z
2022-03-31T09:02:27.000Z
driver/fuzz_target_runner.h
Han0nly/jazzer
b34f6aad8151551005bd502e42fbc1472e69f10b
[ "Apache-2.0" ]
60
2021-02-10T10:46:55.000Z
2022-03-31T03:06:37.000Z
/* * Copyright 2021 Code Intelligence GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <jni.h> #include <string> #include <vector> #include "jvm_tooling.h" namespace jazzer { enum class RunResult { kOk, kException, kDumpAndContinue, }; // Invokes the following static methods in the java fuzz target class: // 1. On construction: // - `public static void fuzzerInitialize()` // OR // - `public static void fuzzerInitialize(String[] args)` // 2. On every call of Run(): // - `public static void fuzzerTestOneInput(FuzzedDataProvider data)` // OR // - `public static void fuzzerTestOneInput(byte[] input)` // 3. On destruction: // - `public static void fuzzerTearDown()` class FuzzTargetRunner : public ExceptionPrinter { private: const JVM &jvm_; jclass jclass_; jmethodID fuzzer_initialize_; jmethodID fuzzer_initialize_with_args_; jmethodID fuzzer_test_one_input_bytes_; jmethodID fuzzer_test_one_input_data_; jmethodID fuzzer_tear_down_; jclass jazzer_; jfieldID last_finding_; std::vector<jlong> ignore_tokens_; [[nodiscard]] std::string DetectFuzzTargetClass() const; [[nodiscard]] jthrowable GetFinding() const; public: // Initializes the java fuzz target by calling `void fuzzerInitialize(...)`. explicit FuzzTargetRunner( JVM &jvm, const std::vector<std::string> &additional_target_args = {}); // Calls the fuzz target tear down function. This can be useful to join any // Threads so that the JVM shuts down correctly. virtual ~FuzzTargetRunner(); // Propagate the fuzzer input to the java fuzz target. RunResult Run(const uint8_t *data, std::size_t size); void DumpReproducer(const uint8_t *data, std::size_t size); }; } // namespace jazzer
29.61039
78
0.730263
[ "vector" ]
98ace47c9787bd83b8848c9851fd4004ab857313
3,682
h
C
lib/spatial/cubic_neighborhood.h
itko/scanbox
9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3
[ "BSD-3-Clause" ]
1
2020-01-09T09:30:23.000Z
2020-01-09T09:30:23.000Z
lib/spatial/cubic_neighborhood.h
itko/scanbox
9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3
[ "BSD-3-Clause" ]
23
2018-03-19T20:54:52.000Z
2018-05-16T12:36:59.000Z
lib/spatial/cubic_neighborhood.h
itko/scanbox
9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3
[ "BSD-3-Clause" ]
1
2018-03-14T20:00:43.000Z
2018-03-14T20:00:43.000Z
/// \file /// Maintainer: Felice Serena /// #pragma once #include "cube_iterator.h" #include <Eigen/Core> #include <unordered_map> #include <unordered_set> #include <vector> namespace MouseTrack { namespace SpatialImpl { // typedefs template <int _Dim> using CellCoordinate = typename Eigen::Matrix<int, _Dim, 1>; // declarations template <int _Dim> class CubicNeighborhoodLayer; /// Ideally, a neighborhood would correspond to all cells with distance [r,R] to /// the reference cell (for a [r,R] as tight as possible) (they would build one /// cube thick shells of a sphere) As a first implementation we'll use the /// shells of a cube (from inside to outside) template <int _Dim> class CubicNeighborhood { std::vector<CubicNeighborhoodLayer<_Dim>> _layers; void _createLayersUpTo(const int maxLayer, const int dims) { assert(maxLayer >= 0); CubeIterator<_Dim, CellCoordinate<_Dim>> iter(2 * maxLayer + 1, dims); CubeIterator<_Dim, CellCoordinate<_Dim>> end; /// move cube from [0,2*maxLayer] to [-maxLayer, maxLayer] CellCoordinate<_Dim> toCenter; if (_Dim == -1) { toCenter.resize(dims); } toCenter.setConstant(dims, -maxLayer); std::vector<std::vector<CellCoordinate<_Dim>>> layerCells(maxLayer + 1); for (; iter != end; ++iter) { auto centered = *iter + toCenter; int highestDimension = centered.array().abs().maxCoeff(); assert(highestDimension <= maxLayer); assert(0 <= highestDimension); layerCells[highestDimension].push_back(centered); } _layers.resize(maxLayer + 1); for (int i = 0; i < maxLayer + 1; i += 1) { _layers[i] = CubicNeighborhoodLayer<_Dim>(std::move(layerCells[i]), dims); } } public: /// maxLayer: index of outtest layer you intend to access /// 0th layer: only the central cube is generated /// 1st layer: coordinates for which the largest component magnitude is equal /// 1 /// /// `dims`: number of dimensions, ignored if defined by template CubicNeighborhood(int maxLayer, int dims = -1) { int d = _Dim == -1 ? dims : _Dim; if (_Dim == -1 && dims <= 0) { throw "Dynamic sized CubicNeighborhood needs positive number of " "dimensions."; } _createLayersUpTo(maxLayer, d); } /// creates empty neighborhood CubicNeighborhood() { // empty } int size() const { return _layers.size(); } const CubicNeighborhoodLayer<_Dim> &operator[](int l) const { return _layers[l]; } }; template <int _Dim> class CubicNeighborhoodLayer { double minDist; double maxDist; /// holds a list of grid cells corresponding to the desired /// layer `l` std::vector<CellCoordinate<_Dim>> coordinates; public: CubicNeighborhoodLayer() { // empty } /// Construct cells of layer `l` CubicNeighborhoodLayer(std::vector<CellCoordinate<_Dim>> &&cells, int dims = -1) { int dim = _Dim == -1 ? dims : _Dim; if (_Dim == -1 && dims <= 0) { throw "Dynamic sized neighborhood layer needs positive number of " "dimension."; } coordinates = std::move(cells); int layer = coordinates[0].array().abs().maxCoeff(); minDist = std::max(0.0, .5 + layer - 1); maxDist = std::sqrt(dim * std::pow(.5 + layer, 2)); } const CellCoordinate<_Dim> operator[](int i) const { return coordinates[i]; } int size() const { return coordinates.size(); } /// minimal point distance from center cell measured in cell counts double min() const { return minDist; } /// maximal point distance from center cell measured in cell counts double max() const { return maxDist; } }; } // namespace SpatialImpl } // namespace MouseTrack
32.017391
80
0.662955
[ "vector" ]
98ae5ee7c899a6e39961f12178de58998dbd78e6
12,234
c
C
base/hals/halia64/ia64/pmbus.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/hals/halia64/ia64/pmbus.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/hals/halia64/ia64/pmbus.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1997 Microsoft Corporation Module Name: pmbus.c Abstract: Implements functions that were done in previous HALs by bus handlers. Basically, these will be somewhat simplified versions since much of the code in the bus handlers has effectively been moved into bus drivers in NT5. Author: Jake Oshins (jakeo) 1-Dec-1997 Environment: Kernel mode only. Revision History: --*/ #include "halp.h" #include "pci.h" #include "pcip.h" ULONG HalpGetCmosData ( IN ULONG BusNumber, IN ULONG SlotNumber, IN PVOID Buffer, IN ULONG Length ); ULONG HalpSetCmosData ( IN ULONG BusNumber, IN ULONG SlotNumber, IN PVOID Buffer, IN ULONG Length ); HalpGetEisaData ( IN PVOID BusHandler, IN PVOID RootHandler, IN ULONG SlotNumber, IN PVOID Buffer, IN ULONG Offset, IN ULONG Length ); ULONG HalpGetSystemInterruptVector ( IN PBUS_HANDLER BusHandler, IN PBUS_HANDLER RootHandler, IN ULONG InterruptLevel, IN ULONG InterruptVector, OUT PKIRQL Irql, OUT PKAFFINITY Affinity ); NTSTATUS HalpAssignSlotResources ( IN PUNICODE_STRING RegistryPath, IN PUNICODE_STRING DriverClassName OPTIONAL, IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT DeviceObject OPTIONAL, IN INTERFACE_TYPE BusType, IN ULONG BusNumber, IN ULONG SlotNumber, IN OUT PCM_RESOURCE_LIST *AllocatedResources ); BOOLEAN HalpTranslateBusAddress( IN INTERFACE_TYPE InterfaceType, IN ULONG BusNumber, IN PHYSICAL_ADDRESS BusAddress, IN OUT PULONG AddressSpace, OUT PPHYSICAL_ADDRESS TranslatedAddress ); BOOLEAN HalpFindBusAddressTranslation( IN PHYSICAL_ADDRESS BusAddress, IN OUT PULONG AddressSpace, OUT PPHYSICAL_ADDRESS TranslatedAddress, IN OUT PULONG_PTR Context, IN BOOLEAN NextBus ); extern BUS_HANDLER HalpFakePciBusHandler; extern ULONG HalpMinPciBus; extern ULONG HalpMaxPciBus; extern ULONG HalpPicVectorRedirect[]; #ifdef ALLOC_PRAGMA #pragma alloc_text(INIT,HalpInitNonBusHandler) #pragma alloc_text(PAGE,HalpAssignSlotResources) #if !defined(NO_LEGACY_DRIVERS) #pragma alloc_text(PAGE,HalAssignSlotResources) #endif #endif VOID HalpInitNonBusHandler ( VOID ) { HALPDISPATCH->HalPciTranslateBusAddress = HalpTranslateBusAddress; HALPDISPATCH->HalPciAssignSlotResources = HalpAssignSlotResources; HALPDISPATCH->HalFindBusAddressTranslation = HalpFindBusAddressTranslation; } #if !defined(NO_LEGACY_DRIVERS) NTSTATUS HalAdjustResourceList ( IN OUT PIO_RESOURCE_REQUIREMENTS_LIST *pResourceList ) { return STATUS_SUCCESS; } ULONG HalGetBusData( IN BUS_DATA_TYPE BusDataType, IN ULONG BusNumber, IN ULONG SlotNumber, IN PVOID Buffer, IN ULONG Length ) { return HalGetBusDataByOffset (BusDataType,BusNumber,SlotNumber,Buffer,0,Length); } #endif // NO_LEGACY_DRIVERS ULONG HalGetBusDataByOffset ( IN BUS_DATA_TYPE BusDataType, IN ULONG BusNumber, IN ULONG SlotNumber, IN PVOID Buffer, IN ULONG Offset, IN ULONG Length ) /*++ Routine Description: Dispatcher for GetBusData --*/ { PCI_SLOT_NUMBER slot; BUS_HANDLER bus; ULONG length; switch (BusDataType) { case PCIConfiguration: // // Hack. If the bus is outside of the known PCI busses, return // a length of zero. // if ((BusNumber < HalpMinPciBus) || (BusNumber > HalpMaxPciBus)) { return 0; } RtlCopyMemory(&bus, &HalpFakePciBusHandler, sizeof(BUS_HANDLER)); bus.BusNumber = BusNumber; slot.u.AsULONG = SlotNumber; length = HalpGetPCIData(&bus, &bus, slot, Buffer, Offset, Length ); return length; case Cmos: return HalpGetCmosData(0, SlotNumber, Buffer, Length); #ifdef EISA_SUPPORTED case EisaConfiguration: // // Fake a bus handler. // bus.BusNumber = 0; return HalpGetEisaData(&bus, &bus, SlotNumber, Buffer, Offset, Length ); #endif default: return 0; } } #if !defined(NO_LEGACY_DRIVERS) ULONG HalSetBusData( IN BUS_DATA_TYPE BusDataType, IN ULONG BusNumber, IN ULONG SlotNumber, IN PVOID Buffer, IN ULONG Length ) { return HalSetBusDataByOffset (BusDataType,BusNumber,SlotNumber,Buffer,0,Length); } #endif // NO_LEGACY_DRIVERS ULONG HalSetBusDataByOffset( IN BUS_DATA_TYPE BusDataType, IN ULONG BusNumber, IN ULONG SlotNumber, IN PVOID Buffer, IN ULONG Offset, IN ULONG Length ) /*++ Routine Description: Dispatcher for SetBusData --*/ { PCI_SLOT_NUMBER slot; BUS_HANDLER bus; switch (BusDataType) { case PCIConfiguration: RtlCopyMemory(&bus, &HalpFakePciBusHandler, sizeof(BUS_HANDLER)); bus.BusNumber = BusNumber; slot.u.AsULONG = SlotNumber; return HalpSetPCIData(&bus, &bus, slot, Buffer, Offset, Length ); case Cmos: return HalpSetCmosData(0, SlotNumber, Buffer, Length); default: return 0; } } #if !defined(NO_LEGACY_DRIVERS) NTSTATUS HalAssignSlotResources ( IN PUNICODE_STRING RegistryPath, IN PUNICODE_STRING DriverClassName OPTIONAL, IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT DeviceObject OPTIONAL, IN INTERFACE_TYPE BusType, IN ULONG BusNumber, IN ULONG SlotNumber, IN OUT PCM_RESOURCE_LIST *AllocatedResources ) { if (BusType == PCIBus) { // // Call through the HAL private dispatch table // for PCI-related translations. This is part // of transitioning the HAL out of the bus // management business. // return HALPDISPATCH->HalPciAssignSlotResources(RegistryPath, DriverClassName, DriverObject, DeviceObject, BusType, BusNumber, SlotNumber, AllocatedResources); } else { return HalpAssignSlotResources(RegistryPath, DriverClassName, DriverObject, DeviceObject, BusType, BusNumber, SlotNumber, AllocatedResources); } } #endif // NO_LEGACY_DRIVERS NTSTATUS HalpAssignSlotResources ( IN PUNICODE_STRING RegistryPath, IN PUNICODE_STRING DriverClassName OPTIONAL, IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT DeviceObject OPTIONAL, IN INTERFACE_TYPE BusType, IN ULONG BusNumber, IN ULONG SlotNumber, IN OUT PCM_RESOURCE_LIST *AllocatedResources ) /*++ Routine Description: Dispatcher for AssignSlotResources --*/ { BUS_HANDLER busHand; PAGED_CODE(); switch (BusType) { case PCIBus: // // Fake a bus handler. // RtlCopyMemory(&busHand, &HalpFakePciBusHandler, sizeof(BUS_HANDLER)); busHand.BusNumber = BusNumber; return HalpAssignPCISlotResources(&busHand, &busHand, RegistryPath, DriverClassName, DriverObject, DeviceObject, SlotNumber, AllocatedResources); default: return STATUS_NOT_IMPLEMENTED; } } #if !defined(NO_LEGACY_DRIVERS) ULONG HalGetInterruptVector( IN INTERFACE_TYPE InterfaceType, IN ULONG BusNumber, IN ULONG BusInterruptLevel, IN ULONG BusInterruptVector, OUT PKIRQL Irql, OUT PKAFFINITY Affinity ) /*++ Routine Description: Dispatcher for GetInterruptVector --*/ { BUS_HANDLER busHand; // // If this is an ISA vector, pass it through the ISA vector // redirection table. // if (InterfaceType == Isa) { ASSERT(BusInterruptVector < PIC_VECTORS); BusInterruptVector = HalpPicVectorRedirect[BusInterruptVector]; BusInterruptLevel = HalpPicVectorRedirect[BusInterruptLevel]; } // // Fake bus handlers. // RtlCopyMemory(&busHand, &HalpFakePciBusHandler, sizeof(BUS_HANDLER)); busHand.BusNumber = BusNumber; busHand.InterfaceType = InterfaceType; busHand.ParentHandler = &busHand; return HalpGetSystemInterruptVector(&busHand, &busHand, BusInterruptLevel, BusInterruptVector, Irql, Affinity); } #endif // NO_LEGACY_DRIVERS BOOLEAN HalTranslateBusAddress( IN INTERFACE_TYPE InterfaceType, IN ULONG BusNumber, IN PHYSICAL_ADDRESS BusAddress, IN OUT PULONG AddressSpace, OUT PPHYSICAL_ADDRESS TranslatedAddress ) { if (InterfaceType == PCIBus) { // // Call through the HAL private dispatch table // for PCI-related translations. This is part // of transitioning the HAL out of the bus // management business. // return HALPDISPATCH->HalPciTranslateBusAddress(InterfaceType, BusNumber, BusAddress, AddressSpace, TranslatedAddress); } else { return HalpTranslateBusAddress(InterfaceType, BusNumber, BusAddress, AddressSpace, TranslatedAddress); } }; BOOLEAN HalpTranslateBusAddress( IN INTERFACE_TYPE InterfaceType, IN ULONG BusNumber, IN PHYSICAL_ADDRESS BusAddress, IN OUT PULONG AddressSpace, OUT PPHYSICAL_ADDRESS TranslatedAddress ) /*++ Routine Description: Dispatcher for TranslateBusAddress --*/ { //*(&TranslatedAddress->QuadPart) = BusAddress.QuadPart; *(&TranslatedAddress->LowPart) = BusAddress.LowPart; *(&TranslatedAddress->HighPart) = BusAddress.HighPart; return TRUE; }
25.434511
85
0.530325
[ "vector" ]
98b13977ccb5fcd631220fb5ba7d8fd8125f2bec
2,565
h
C
OutPutHeaders/MMBrandHeadImageView.h
cocos543/WeChatTimeLineRobot
1e93480e502e36ca9a21a506f481aa1fcb70ac4b
[ "MIT" ]
106
2016-04-09T01:16:14.000Z
2021-06-04T00:20:24.000Z
OutPutHeaders/MMBrandHeadImageView.h
cocos543/WeChatTimeLineRobot
1e93480e502e36ca9a21a506f481aa1fcb70ac4b
[ "MIT" ]
2
2017-06-13T09:41:29.000Z
2018-03-26T03:32:07.000Z
OutPutHeaders/MMBrandHeadImageView.h
cocos543/WeChatTimeLineRobot
1e93480e502e36ca9a21a506f481aa1fcb70ac4b
[ "MIT" ]
58
2016-04-28T09:52:08.000Z
2021-12-25T06:42:14.000Z
/** * This header is generated by class-dump-z 0.2a. * class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3. * * Source: (null) */ #import "IContactMgrExt.h" #import "WeChat-Structs.h" #import <XXUnknownSuperclass.h> // Unknown library #import "IStrangerContactMgrExt.h" #import "MMWebImageViewDelegate.h" @class UIImageView, NSString, MMWebImageView; @interface MMBrandHeadImageView : XXUnknownSuperclass <IContactMgrExt, IStrangerContactMgrExt, MMWebImageViewDelegate> { UIImageView* m_frameView; MMWebImageView* m_headView; CGSize m_headSize; NSString* m_username; id m_oTarget; SEL m_selAction; id m_object; BOOL m_addCertIcon; UIImageView* m_certInfoView; } @property(readonly, copy) NSString* debugDescription; @property(readonly, copy) NSString* description; @property(readonly, assign) Class superclass; @property(readonly, assign) unsigned hash; @property(assign, nonatomic) BOOL m_addCertIcon; @property(assign, nonatomic) CGSize m_headSize; @property(retain, nonatomic) MMWebImageView* m_headView; @property(retain, nonatomic) UIImageView* m_frameView; @property(retain, nonatomic) id m_object; @property(assign, nonatomic) SEL m_selAction; @property(assign, nonatomic) __weak id m_oTarget; +(id)getWCCardTicketHeadImageViewFromUrl:(id)url username:(id)username; +(id)getWCCardCardHeadImageViewFromUrl:(id)url username:(id)username; +(id)getFTSFeatureBrandHeadImageViewFromUrl:(id)url username:(id)username; +(id)getFTSBrandHeadImageViewFromUrl:(id)url username:(id)username; +(id)getWCPayServiceBrandAppHeadImageViewFromUrl:(id)url username:(id)username; +(id)getBottleHeadImageViewFromUrl:(id)url username:(id)username; +(id)getProfileHeadImageViewFromUrl:(id)url username:(id)username; +(id)getBrandServiceListHeaderFromUrl:(id)url username:(id)username; +(id)getUserInfoCellHeaderFromUrl:(id)url username:(id)username; +(id)getProfileCellHeaderFromUrl:(id)url username:(id)username; -(void).cxx_destruct; -(void)onLoadImageOK:(id)ok; -(void)updateCertInfoView; -(void)OnPress:(id)press; -(void)setTarget:(id)target action:(SEL)action withObject:(id)object; -(void)setTarget:(id)target action:(SEL)action; -(void)layoutSubviews; -(void)onStrangerContactUpdated:(id)updated; -(void)onModifyContact:(id)contact; -(void)setHeadViewByUsername:(id)username; -(void)setUserName:(id)name; -(void)setUpdateUrl:(id)url; -(id)getUpdateUrl; -(void)dealloc; -(void)SetHeadImage:(id)image; -(void)TrySetDefaultHeadImage:(id)image; -(void)TrySetDefaultHeadImage; -(void)SetDefaultFrameImage; -(id)initWithFrame:(CGRect)frame; @end
37.173913
120
0.794152
[ "object" ]
98b27d23f08f7e13f8bc3e5617e87e36e15b40f1
7,883
h
C
mem-axc-64/apps/macsim.r.d.b.s/macsim-mem-axc-64/gems-lib-ooo/ruby_clean/interfaces/OpalInterface.h
vnaveen0/nachos
99933b0da5474bf43bd167d2540438375237b2d9
[ "MIT" ]
1
2018-02-28T10:00:00.000Z
2018-02-28T10:00:00.000Z
mem-axc-64/apps/macsim.r.d.b.s/macsim-mem-axc-64/gems-lib-ooo/ruby_clean/interfaces/OpalInterface.h
vnaveen0/nachos
99933b0da5474bf43bd167d2540438375237b2d9
[ "MIT" ]
1
2020-04-06T22:30:00.000Z
2020-04-06T22:30:00.000Z
mem-axc-64/apps/macsim.r.d.b.s/macsim-mem-axc-64/gems-lib-ooo/ruby_clean/interfaces/OpalInterface.h
vnaveen0/nachos
99933b0da5474bf43bd167d2540438375237b2d9
[ "MIT" ]
null
null
null
/* Copyright (C) 1999-2008 by Mark D. Hill and David A. Wood for the Wisconsin Multifacet Project. Contact: gems@cs.wisc.edu http://www.cs.wisc.edu/gems/ -------------------------------------------------------------------- This file is part of the Ruby Multiprocessor Memory System Simulator, a component of the Multifacet GEMS (General Execution-driven Multiprocessor Simulator) software toolset originally developed at the University of Wisconsin-Madison. Ruby was originally developed primarily by Milo Martin and Daniel Sorin with contributions from Ross Dickson, Carl Mauer, and Manoj Plakal. Substantial further development of Multifacet GEMS at the University of Wisconsin was performed by Alaa Alameldeen, Brad Beckmann, Jayaram Bobba, Ross Dickson, Dan Gibson, Pacia Harper, Derek Hower, Milo Martin, Michael Marty, Carl Mauer, Michelle Moravan, Kevin Moore, Andrew Phelps, Manoj Plakal, Daniel Sorin, Haris Volos, Min Xu, and Luke Yen. -------------------------------------------------------------------- If your use of this software contributes to a published paper, we request that you (1) cite our summary paper that appears on our website (http://www.cs.wisc.edu/gems/) and (2) e-mail a citation for your published paper to gems@cs.wisc.edu. If you redistribute derivatives of this software, we request that you notify us and either (1) ask people to register with us at our website (http://www.cs.wisc.edu/gems/) or (2) collect registration information and periodically send it to us. -------------------------------------------------------------------- Multifacet GEMS is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. Multifacet GEMS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the Multifacet GEMS; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA The GNU General Public License is contained in the file LICENSE. ### END HEADER ### */ /* * $Id$ * * Description: * */ #ifndef OpalInterface_H #define OpalInterface_H /*------------------------------------------------------------------------*/ /* Includes */ /*------------------------------------------------------------------------*/ #include "Global.h" #include "Driver.h" #include "mf_api.h" #include "CacheRequestType.h" /*------------------------------------------------------------------------*/ /* Class declaration(s) */ /*------------------------------------------------------------------------*/ class System; class TransactionInterfaceManager; class Sequencer; /** * the processor model (opal) calls these OpalInterface APIs to access * the memory hierarchy (ruby). * @see pseq_t * @author cmauer * @version $Id$ */ class OpalInterface : public Driver { public: // Constructors OpalInterface(System* sys_ptr); // Destructor // ~OpalInterface(); integer_t getInstructionCount(int procID) const; void hitCallback( NodeID proc, SubBlock& data, CacheRequestType type, int thread ); void printStats(ostream& out) const; void clearStats(); void printConfig(ostream& out) const; void print(ostream& out) const; integer_t readPhysicalMemory(int procID, physical_address_t address, int len ); void writePhysicalMemory( int procID, physical_address_t address, integer_t value, int len ); uint64 getOpalTime(int procID) const; // for WATTCH power void incrementL2Access(int procID) const; void incrementPrefetcherAccess(int procID, int num_prefetches, int isinstr) const; // notifies Opal of an L2 miss void notifyL2Miss(int procID, physical_address_t physicalAddr, OpalMemop_t type, int tagexists) const; void printDebug(); /// The static opalinterface instance static OpalInterface *inst; /// static methods static int getNumberOutstanding(int cpuNumber); static int getNumberOutstandingDemand(int cpuNumber); static int getNumberOutstandingPrefetch( int cpuNumber ); /* returns true if the sequencer is able to handle more requests. This implements "back-pressure" by which the processor knows not to issue more requests if the network or cache's limits are reached. */ static int isReady( int cpuNumber, la_t logicalAddr, pa_t physicalAddr, OpalMemop_t typeOfRequest, int thread ); /* makeRequest performs the coherence transactions necessary to get the physical address in the cache with the correct permissions. More than one request can be outstanding to ruby, but only one per block address. The size of the cache line is defined to Intf_CacheLineSize. When a request is finished (e.g. the cache contains physical address), ruby calls completedRequest(). No request can be bigger than Opal_CacheLineSize. It is illegal to request non-aligned memory locations. A request of size 2 must be at an even byte, a size 4 must be at a byte address half-word aligned, etc. Requests also can't cross a cache-line boundaries. */ static void makeRequest(int cpuNumber, la_t logicalAddr, pa_t physicalAddr, int requestSize, OpalMemop_t typeOfRequest, la_t virtualPC, int isPriv, int thread); /* prefetch a given block... */ static void makePrefetch(int cpuNumber, la_t logicalAddr, pa_t physicalAddr, int requestSize, OpalMemop_t typeOfRequest, la_t virtualPC, int isPriv, int thread); /* * request data from the cache, even if it's state is "Invalid". */ static int staleDataRequest( int cpuNumber, pa_t physicalAddr, int requestSize, int8 *buffer ); /* notify ruby of opal's status */ static void notify( int status ); /* * advance ruby one cycle */ static void advanceTime( void ); /* * return ruby's cycle count. */ static unsigned long long getTime( void ); /* prints Ruby's outstanding request table */ static void printProgress(int cpuNumber); /* * initialize / install the inter-module interface */ static void installInterface( mf_ruby_api_t *api ); /* * Test if opal is loaded or not */ static bool isOpalLoaded( void ); /* * query opal for its api */ void queryOpalInterface( void ); /* * remove the opal interface (opal is unloaded). */ void removeOpalInterface( void ); /* * set the opal interface (used if stand-alone testing) */ void setOpalInterface( mf_opal_api_t *opal_intf ) { m_opal_intf = opal_intf; } /** * Signal an abort */ //void abortCallback(NodeID proc); private: // Private Methods // Private copy constructor and assignment operator OpalInterface(const OpalInterface& obj); OpalInterface& operator=(const OpalInterface& obj); // Data Members (m_ prefix) mf_opal_api_t *m_opal_intf; Time m_simicsStartTime; static int s_advance_counter; }; // Output operator declaration ostream& operator<<(ostream& out, const OpalInterface& obj); // ******************* Definitions ******************* // Output operator definition extern inline ostream& operator<<(ostream& out, const OpalInterface& obj) { // obj.print(out); out << flush; return out; } #endif // OpalInterface_H
32.57438
115
0.645947
[ "model" ]
c2c8f7fcfb60a717fd3f0599af1410bdd1f54f2e
23,661
c
C
src/lbm3D.c
dawuweijun/LBM-classic
97c9bc31657757cc660e871857020e939a7c3a77
[ "BSD-2-Clause" ]
25
2015-01-09T19:13:04.000Z
2022-03-22T07:26:50.000Z
src/lbm3D.c
NablaCFD/LBM-classic
d60ad7e65c950524c05899a129bd56f39737f987
[ "BSD-2-Clause" ]
null
null
null
src/lbm3D.c
NablaCFD/LBM-classic
d60ad7e65c950524c05899a129bd56f39737f987
[ "BSD-2-Clause" ]
16
2015-01-09T19:13:09.000Z
2022-03-26T01:59:29.000Z
/// \file lbm3D.c /// \brief D3Q19 model implementation. // // Copyright (c) 2014, Christian B. Mendl // All rights reserved. // http://christian.mendl.net // // This program is free software; you can redistribute it and/or // modify it under the terms of the Simplified BSD License // http://www.opensource.org/licenses/bsd-license.php // // Reference: // Nils Thuerey, Physically based animation of free surface flows with the lattice Boltzmann method, // PhD thesis, University of Erlangen-Nuremberg (2007) //_______________________________________________________________________________________________________________________ // #include "lbm3D.h" #include "util.h" #include <stdlib.h> #include <memory.h> //_______________________________________________________________________________________________________________________ // /// \brief Velocity vectors for D3Q19 as integers static const int vel3Di[19][3] = { { 0, 0, 0 }, // zero direction { -1, 0, 0 }, // 6 directions with velocity 1 { 1, 0, 0 }, { 0, -1, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, { 0, 0, 1 }, { -1, -1, 0 }, // 12 directions with velocity sqrt(2) { -1, 1, 0 }, { 1, -1, 0 }, { 1, 1, 0 }, { 0, -1, -1 }, { 0, -1, 1 }, { 0, 1, -1 }, { 0, 1, 1 }, { -1, 0, -1 }, { -1, 0, 1 }, { 1, 0, -1 }, { 1, 0, 1 }, }; /// \brief Velocity vectors for D3Q19 as floating-point values static const vec3_t vel3Dv[19] = { { 0, 0, 0 }, // zero direction { -1, 0, 0 }, // 6 directions with velocity 1 { 1, 0, 0 }, { 0, -1, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, { 0, 0, 1 }, { -1, -1, 0 }, // 12 directions with velocity sqrt(2) { -1, 1, 0 }, { 1, -1, 0 }, { 1, 1, 0 }, { 0, -1, -1 }, { 0, -1, 1 }, { 0, 1, -1 }, { 0, 1, 1 }, { -1, 0, -1 }, { -1, 0, 1 }, { 1, 0, -1 }, { 1, 0, 1 }, }; /// \brief Index of inverse direction static const int invVel3D[19] = { 0, 2, 1, 4, 3, 6, 5, 10, 9, 8, 7, 14, 13, 12, 11, 18, 17, 16, 15 }; //_______________________________________________________________________________________________________________________ // /// \brief D3Q19 weights static const real weights3D[19] = { (real)1./3, (real)1./18, (real)1./18, (real)1./18, (real)1./18, (real)1./18, (real)1./18, (real)1./36, (real)1./36, (real)1./36, (real)1./36, (real)1./36, (real)1./36, (real)1./36, (real)1./36, (real)1./36, (real)1./36, (real)1./36, (real)1./36 }; //_______________________________________________________________________________________________________________________ /// /// \brief Calculate derived quantities density and velocity from distribution functions /// static inline void DFD3Q19_DeriveQuantities(dfD3Q19_t *df) { int i; // calculate average density df->rho = 0; for (i = 0; i < 19; i++) { df->rho += df->f[i]; } assert(df->rho >= 0); // calculate average velocity u df->u.x = 0; df->u.y = 0; df->u.z = 0; if (df->rho > 0) { for (i = 0; i < 19; i++) { df->u.x += df->f[i]*vel3Dv[i].x; df->u.y += df->f[i]*vel3Dv[i].y; df->u.z += df->f[i]*vel3Dv[i].z; } real s = 1 / df->rho; df->u.x *= s; df->u.y *= s; df->u.z *= s; } // rescale in case maximum velocity is exceeded real n = Vec3_Norm(df->u); if (n > v_max) { df->u = Vec3_ScalarMultiply(v_max/n, df->u); } } //_______________________________________________________________________________________________________________________ /// /// \brief Calculate the equilibrium distribution function /// static inline void DFD3Q19_CalcEquilibrium(const vec3_t u, const real rho, real f_eq[19]) { int i; for (i = 0; i < 19; i++) { real eiu = Vec3_Dot(vel3Dv[i], u); real usq = Vec3_Dot(u, u); // note that f_eq[i] can be negative also f_eq[i] = weights3D[i]*rho*(1 + 3*eiu - ((real)1.5)*usq + ((real)4.5)*squaref(eiu)); } } //_______________________________________________________________________________________________________________________ /// /// \brief Initialize D3Q19 structure /// void DFD3Q19_Init(const int type, const real f[19], dfD3Q19_t *df) { // initially set all values to zero memset(df, 0, sizeof(dfD3Q19_t)); // copy cell type df->type = type; if (type & CT_FLUID) { // distribution functions and derived quantities memcpy(df->f, f, 19*sizeof(real)); DFD3Q19_DeriveQuantities(df); // fluid cells have same mass as density df->mass = df->rho; } else if (type & CT_INTERFACE) { // distribution functions and derived quantities memcpy(df->f, f, 19*sizeof(real)); DFD3Q19_DeriveQuantities(df); // (arbitrarily) assign half-filled mass df->mass = 0.5f*df->rho; } } //_______________________________________________________________________________________________________________________ /// /// \brief Allocate memory for D3Q19 field /// void LBM3DField_Allocate(const real omega, lbm_field3D_t *field) { field->omega = omega; field->df = (dfD3Q19_t *)calloc(SIZE_3D_X*SIZE_3D_Y*SIZE_3D_Z, sizeof(dfD3Q19_t)); } //_______________________________________________________________________________________________________________________ /// /// \brief Delete D3Q19 field (free memory) /// void LBM3DField_Free(lbm_field3D_t *field) { free(field->df); } //_______________________________________________________________________________________________________________________ /// /// \brief Collision step for D3Q19 (3 dimensions, 19 velocities) /// static inline void CalculateLBMCollisionStep3D(const lbm_field3D_t *restrict_ f0, const vec3_t gravity, lbm_field3D_t *restrict_ f_coll) { int x, y, z; int i; // copy omega value f_coll->omega = f0->omega; for (z = 0; z < SIZE_3D_Z; z++) { for (y = 0; y < SIZE_3D_Y; y++) { for (x = 0; x < SIZE_3D_X; x++) { // current cells const dfD3Q19_t *df = LBM3DField_Get(f0, x, y, z); dfD3Q19_t *df_coll = LBM3DField_Get(f_coll, x, y, z); // copy cell type and mass df_coll->type = df->type; df_coll->mass = df->mass; // ignore obstacle and empty cells if (df->type & (CT_OBSTACLE | CT_EMPTY)) { continue; } // calculate equilibrium distribution function real df_eq[19]; DFD3Q19_CalcEquilibrium(df->u, df->rho, df_eq); // perform collision for (i = 0; i < 19; i++) { // Eq. (3.4) df_coll->f[i] = (1 - f0->omega)*df->f[i] + f0->omega*df_eq[i]; // gravity df_coll->f[i] += df->rho*weights3D[i] * Vec3_Dot(vel3Dv[i], gravity); } // average density and velocity remain constant df_coll->rho = df->rho; df_coll->u = df->u; } } } } //_______________________________________________________________________________________________________________________ /// /// \brief Calculate the epsilon parameter (mass to density ratio) /// static inline real DFD3Q19_CalcEpsilon(const dfD3Q19_t *df) { if (df->type & (CT_FLUID | CT_OBSTACLE)) { return 1; } else if (df->type & CT_INTERFACE) { assert(df->rho >= 0); if (df->rho > 0) { real epsilon = df->mass / df->rho; // df->mass can even be < 0 or > df->rho for interface cells to be converted to fluid or empty cells in the next step; // clamp to [0,1] range for numerical stability if (epsilon > 1) { epsilon = 1; } else if (epsilon < 0) { epsilon = 0; } return epsilon; } else { // return (somewhat arbitrarily) a ratio of 1/2 return (real)0.5; } } else // df->type & CT_EMPTY { assert(df->type & CT_EMPTY); return 0; } } //_______________________________________________________________________________________________________________________ /// /// \brief Approximate the free surface normal using central differences of fluid fractions (epsilon parameter) /// static inline vec3_t LBM3DField_CalcNormal(const lbm_field3D_t *field, const int x, const int y, const int z) { // Eq. (4.6) vec3_t normal; normal.x = 0.5f*(DFD3Q19_CalcEpsilon(LBM3DField_GetMod(field, x-1, y , z )) - DFD3Q19_CalcEpsilon(LBM3DField_GetMod(field, x+1, y , z ))); normal.y = 0.5f*(DFD3Q19_CalcEpsilon(LBM3DField_GetMod(field, x, y-1, z )) - DFD3Q19_CalcEpsilon(LBM3DField_GetMod(field, x, y+1, z ))); normal.z = 0.5f*(DFD3Q19_CalcEpsilon(LBM3DField_GetMod(field, x, y, z-1)) - DFD3Q19_CalcEpsilon(LBM3DField_GetMod(field, x, y, z+1))); return normal; } //_______________________________________________________________________________________________________________________ /// /// \brief Stream step for D3Q19 (3 dimensions, 19 velocities) /// static inline void CalculateLBMStreamStep3D(const lbm_field3D_t *restrict_ f0, lbm_field3D_t *restrict_ f_strm) { int x, y, z; int i; // copy omega value f_strm->omega = f0->omega; // stream step for (z = 0; z < SIZE_3D_Z; z++) { for (y = 0; y < SIZE_3D_Y; y++) { for (x = 0; x < SIZE_3D_X; x++) { const dfD3Q19_t *df = LBM3DField_Get(f0, x, y, z); dfD3Q19_t *df_strm = LBM3DField_Get(f_strm, x, y, z); // copy cell type and mass df_strm->type = df->type; df_strm->mass = df->mass; // ignore obstacle and empty cells if (df->type & (CT_OBSTACLE | CT_EMPTY)) { continue; } // copy distribution function corresponding to velocity zero df_strm->f[0] = df->f[0]; if (df->type & CT_FLUID) { // for fluid cells, mass should be equal to density assert(df->mass == df->rho); for (i = 1; i < 19; i++) // omit zero vector { // neighbor cell const dfD3Q19_t *df_neigh = LBM3DField_GetMod(f0, x - vel3Di[i][0], y - vel3Di[i][1], z - vel3Di[i][2]); // fluid cell must not be adjacent to an empty cell assert((df_neigh->type & CT_EMPTY) == 0); if (df_neigh->type & (CT_FLUID | CT_INTERFACE)) { // mass exchange with fluid or interface cell, Eq. (4.2) df_strm->mass += (df_neigh->f[i] - df->f[invVel3D[i]]); // standard streaming, Eq. (3.1) df_strm->f[i] = df_neigh->f[i]; } else // df_neigh->type & CT_OBSTACLE { assert(df_neigh->type & CT_OBSTACLE); // reflect density functions, Eq. (3.5) df_strm->f[i] = df->f[invVel3D[i]]; } } } else if (df->type & CT_INTERFACE) { const real epsilon = DFD3Q19_CalcEpsilon(df); // calculate atmospheric equilibrium distribution function real f_atm_eq[19]; DFD3Q19_CalcEquilibrium(df->u, rhoA, f_atm_eq); for (i = 1; i < 19; i++) // omit zero vector { // neighbor cell const dfD3Q19_t *df_neigh = LBM3DField_GetMod(f0, x - vel3Di[i][0], y - vel3Di[i][1], z - vel3Di[i][2]); if (df_neigh->type & CT_FLUID) { // mass exchange between fluid and interface cell, Eq. (4.2) df_strm->mass += (df_neigh->f[i] - df->f[invVel3D[i]]); // standard streaming, Eq. (3.1) df_strm->f[i] = df_neigh->f[i]; } else if (df_neigh->type & CT_INTERFACE) { const real eps_neigh = DFD3Q19_CalcEpsilon(df_neigh); // mass exchange between two interface cells, Eq. (4.3) df_strm->mass += CalculateMassExchange(df->type, df_neigh->type, df_neigh->f[i], df->f[invVel3D[i]]) * 0.5f*(eps_neigh + epsilon); // standard streaming, Eq. (3.1) df_strm->f[i] = df_neigh->f[i]; } else if (df_neigh->type & CT_EMPTY) { // no mass exchange from or to empty cell // reconstructed atmospheric distribution function, Eq. (4.5) df_strm->f[i] = f_atm_eq[i] + f_atm_eq[invVel3D[i]] - df->f[invVel3D[i]]; } else // df_neigh->type & CT_OBSTACLE { assert(df_neigh->type & CT_OBSTACLE); // reflect density functions, Eq. (3.5) df_strm->f[i] = df->f[invVel3D[i]]; } } // calculate surface normal const vec3_t normal = LBM3DField_CalcNormal(f0, x, y, z); // always use reconstructed atmospheric distribution function for directions along surface normal; // separate loop to handle mass exchange correctly for (i = 1; i < 19; i++) // omit zero vector { if (Vec3_Dot(normal, vel3Dv[invVel3D[i]]) > 0) // Eq. (4.6) { // reconstructed atmospheric distribution function, Eq. (4.5) df_strm->f[i] = f_atm_eq[i] + f_atm_eq[invVel3D[i]] - df->f[invVel3D[i]]; } } } // df->type & CT_INTERFACE // calculate average density and velocity DFD3Q19_DeriveQuantities(df_strm); // for fluid cells, set density exactly to mass to avoid numerical drift if (df_strm->type & CT_FLUID) { assert(fabs(df_strm->rho / df_strm->mass - 1) < 5e-6); df_strm->rho = df_strm->mass; } } } } } //_______________________________________________________________________________________________________________________ /// /// \brief Initialize 'df' with average density and velocity from cells surrounding (x,y,z) /// static inline void LBM3DField_AverageSurrounding(const lbm_field3D_t *field, const int x, const int y, const int z, dfD3Q19_t *df) { int i; int n = 0; // counter // set mass initially to zero df->mass = 0; // average density and velocity of surrounding cells df->rho = 0; df->u.x = 0; df->u.y = 0; df->u.z = 0; for (i = 1; i < 19; i++) // omit zero vector { dfD3Q19_t *df_neigh = LBM3DField_GetMod(field, x - vel3Di[i][0], y - vel3Di[i][1], z - vel3Di[i][2]); // fluid or interface cells only if (df_neigh->type & (CT_FLUID | CT_INTERFACE)) { df->rho += df_neigh->rho; df->u.x += df_neigh->u.x; df->u.y += df_neigh->u.y; df->u.z += df_neigh->u.z; n++; } } if (n > 0) { df->rho /= n; df->u.x /= n; df->u.y /= n; df->u.z /= n; } // calculate equilibrium distribution function DFD3Q19_CalcEquilibrium(df->u, df->rho, df->f); } //_______________________________________________________________________________________________________________________ /// /// \brief Update the cell types after streaming for D3Q19 (3 dimensions, 19 velocities) /// static inline void UpdateTypesLBMStep3D(const lbm_field3D_t *restrict_ f0, lbm_field3D_t *restrict_ f_distr, lbm_field3D_t *restrict_ f_next) { // define additional temporary cell types; only for this function #define CT_IF_TO_FLUID (1 << 7) #define CT_IF_TO_EMPTY (1 << 8) int x, y, z; int i; // copy omega value f_next->omega = f0->omega; #define FILL_OFFSET ((real)0.003) #define LONELY_THRESH ((real)0.1) for (z = 0; z < SIZE_3D_Z; z++) { for (y = 0; y < SIZE_3D_Y; y++) { for (x = 0; x < SIZE_3D_X; x++) { // current cell const dfD3Q19_t *df = LBM3DField_Get(f0, x, y, z); dfD3Q19_t *df_next = LBM3DField_Get(f_next, x, y, z); // copy values *df_next = *df; // check whether interface cells emptied or filled if (df_next->type & CT_INTERFACE) { // Eq. (4.7), and remove interface cell artifacts if ((df_next->mass > (1 + FILL_OFFSET) * df_next->rho) || (df_next->mass >= (1 - LONELY_THRESH)*df_next->rho && (df_next->type & CT_NO_EMPTY_NEIGH))) { // interface to fluid cell df_next->type = CT_IF_TO_FLUID; } else if ((df_next->mass < -FILL_OFFSET * df_next->rho) || (df_next->mass <= LONELY_THRESH*df_next->rho && (df_next->type & CT_NO_FLUID_NEIGH)) || ((df_next->type & CT_NO_IFACE_NEIGH) && (df_next->type & CT_NO_FLUID_NEIGH))) // isolated interface cell: only empty or obstacle neighbors { // interface to empty cell df_next->type = CT_IF_TO_EMPTY; } } // clear neighborhood flags (will be determined later) df_next->type &= ~(CT_NO_FLUID_NEIGH | CT_NO_EMPTY_NEIGH | CT_NO_IFACE_NEIGH); } } } // set flags for filled interface cells (interface to fluid) for (z = 0; z < SIZE_3D_Z; z++) { for (y = 0; y < SIZE_3D_Y; y++) { for (x = 0; x < SIZE_3D_X; x++) { // current cell dfD3Q19_t *df = LBM3DField_Get(f_next, x, y, z); if (df->type & CT_IF_TO_FLUID) { // keep flag 'CT_IF_TO_FLUID' for later excess mass distribution // convert neighboring empty cells to interface cells for (i = 1; i < 19; i++) // omit zero vector { // neighbor cell int x_neigh = x - vel3Di[i][0]; int y_neigh = y - vel3Di[i][1]; int z_neigh = z - vel3Di[i][2]; dfD3Q19_t *df_neigh = LBM3DField_GetMod(f_next, x_neigh, y_neigh, z_neigh); if (df_neigh->type & CT_EMPTY) { df_neigh->type = CT_INTERFACE; // initialize cell with average density and velocity of surrounding cells, using f0 LBM3DField_AverageSurrounding(f0, x_neigh, y_neigh, z_neigh, df_neigh); } } // prevent neighboring cells from becoming empty for (i = 1; i < 19; i++) // omit zero vector { // neighbor cell dfD3Q19_t *df_neigh = LBM3DField_GetMod(f_next, x - vel3Di[i][0], y - vel3Di[i][1], z - vel3Di[i][2]); if (df_neigh->type & CT_IF_TO_EMPTY) { df_neigh->type = CT_INTERFACE; } } } } } } // set flags for emptied interface cells (interface to empty) for (z = 0; z < SIZE_3D_Z; z++) { for (y = 0; y < SIZE_3D_Y; y++) { for (x = 0; x < SIZE_3D_X; x++) { // current cell dfD3Q19_t *df = LBM3DField_Get(f_next, x, y, z); if (df->type & CT_IF_TO_EMPTY) { // keep flag 'CT_IF_TO_EMPTY' for later excess mass distribution // convert neighboring fluid cells to interface cells for (i = 1; i < 19; i++) // omit zero vector { // neighbor cell dfD3Q19_t *df_neigh = LBM3DField_GetMod(f_next, x - vel3Di[i][0], y - vel3Di[i][1], z - vel3Di[i][2]); if (df_neigh->type & CT_FLUID) { df_neigh->type = CT_INTERFACE; } } } } } } // distribute excess mass for (z = 0; z < SIZE_3D_Z; z++) { for (y = 0; y < SIZE_3D_Y; y++) { for (x = 0; x < SIZE_3D_X; x++) { // current cell dfD3Q19_t *df = LBM3DField_Get(f_next, x, y, z); // calculate surface normal using 'f0', such that excess mass distribution is independent of the filled cell ordering vec3_t normal = LBM3DField_CalcNormal(f0, x, y, z); // excess mass real mex; if (df->type & CT_IF_TO_FLUID) { mex = df->mass - df->rho; // after excess mass has been distributed, remaining mass equals density df->mass = df->rho; } else if (df->type & CT_IF_TO_EMPTY) { mex = df->mass; // flip sign of normal normal.x = -normal.x; normal.y = -normal.y; normal.z = -normal.z; // after negative excess mass has been distributed, remaining mass is zero df->mass = 0; } else { continue; } // Eq. (4.9) real eta[19] = { 0 }; real eta_total = 0; unsigned int isIF[19] = { 0 }; unsigned int numIF = 0; // number of interface cell neighbors for (i = 1; i < 19; i++) // omit zero vector { // neighbor cell in the direction of velocity vector dfD3Q19_t *df_neigh = LBM3DField_GetMod(f_next, x + vel3Di[i][0], y + vel3Di[i][1], z + vel3Di[i][2]); if (df_neigh->type & CT_INTERFACE) { eta[i] = Vec3_Dot(vel3Dv[i], normal); if (eta[i] < 0) { eta[i] = 0; } eta_total += eta[i]; isIF[i] = 1; numIF++; } } // store excess mass to be distributed in 'f_distr'; // don't actually distribute yet to ensure independence of cell traversal order // cell for excess mass distribution, store in distribution functions dfD3Q19_t *df_distr = LBM3DField_Get(f_distr, x, y, z); if (eta_total > 0) { real eta_fac = 1/eta_total; for (i = 1; i < 19; i++) // omit zero vector { // eta[i] is zero for non-interface cells df_distr->f[i] = mex * eta[i]*eta_fac; } } else if (numIF > 0) { // distribute uniformly real mex_rel = mex / numIF; for (i = 1; i < 19; i++) // omit zero vector { df_distr->f[i] = (isIF[i] ? mex_rel : 0); } } // else, excess mass cannot be distributed, i.e., has leaked } } } // collect distributed mass and finalize cell flags for (z = 0; z < SIZE_3D_Z; z++) { for (y = 0; y < SIZE_3D_Y; y++) { for (x = 0; x < SIZE_3D_X; x++) { // current cell dfD3Q19_t *df = LBM3DField_Get(f_next, x, y, z); if (df->type & CT_INTERFACE) { for (i = 1; i < 19; i++) // omit zero vector { // neighbor cell from distribution field dfD3Q19_t *df_distr = LBM3DField_GetMod(f_distr, x - vel3Di[i][0], y - vel3Di[i][1], z - vel3Di[i][2]); df->mass += df_distr->f[i]; } } else if (df->type & CT_IF_TO_FLUID) { df->type = CT_FLUID; } else if (df->type & CT_IF_TO_EMPTY) { df->type = CT_EMPTY; } assert((df->type & (CT_OBSTACLE | CT_FLUID | CT_INTERFACE | CT_EMPTY)) != 0); assert((df->type & ~(CT_OBSTACLE | CT_FLUID | CT_INTERFACE | CT_EMPTY)) == 0); } } } // set cell neighborhood flags for (z = 0; z < SIZE_3D_Z; z++) { for (y = 0; y < SIZE_3D_Y; y++) { for (x = 0; x < SIZE_3D_X; x++) { // current cell dfD3Q19_t *df = LBM3DField_Get(f_next, x, y, z); // ignore obstacle cells if (df->type & CT_OBSTACLE) { continue; } // set "no ... neighbor" flags df->type |= (CT_NO_FLUID_NEIGH | CT_NO_EMPTY_NEIGH | CT_NO_IFACE_NEIGH); for (i = 1; i < 19; i++) // omit zero vector { // neighbor cell dfD3Q19_t *df_neigh = LBM3DField_GetMod(f_next, x - vel3Di[i][0], y - vel3Di[i][1], z - vel3Di[i][2]); if (df_neigh->type & CT_FLUID) { // remove "no fluid neighbor" flag df->type &= ~CT_NO_FLUID_NEIGH; } else if (df_neigh->type & CT_EMPTY) { // remove "no empty neighbor" flag df->type &= ~CT_NO_EMPTY_NEIGH; } else if (df_neigh->type & CT_INTERFACE) { // remove "no interface neighbor" flag df->type &= ~CT_NO_IFACE_NEIGH; } } // both flags should not be set simultaneously if (df->type & CT_NO_EMPTY_NEIGH) { df->type &= ~CT_NO_FLUID_NEIGH; } } } } } //_______________________________________________________________________________________________________________________ /// /// \brief Implement the LBM step for D3Q19 (3 dimensions, 19 velocities) /// static void CalculateLBMStep3D(const lbm_field3D_t *restrict_ f0, const vec3_t gravity, lbm_field3D_t *restrict_ f1) { // allocate intermediate fields for collision, stream and cell type step lbm_field3D_t f_coll, f_strm, f_distr; LBM3DField_Allocate(f0->omega, &f_coll); LBM3DField_Allocate(f0->omega, &f_strm); LBM3DField_Allocate(f0->omega, &f_distr); // collision step CalculateLBMCollisionStep3D(f0, gravity, &f_coll); // stream step CalculateLBMStreamStep3D(&f_coll, &f_strm); // update cell types UpdateTypesLBMStep3D(&f_strm, &f_distr, f1); // clean up LBM3DField_Free(&f_distr); LBM3DField_Free(&f_strm); LBM3DField_Free(&f_coll); } //_______________________________________________________________________________________________________________________ /// /// \brief Lattice Boltzmann time evolution using D3Q19 (3 dimensions, 19 velocities) /// void LatticeBoltzmann3DEvolution(const lbm_field3D_t *restrict_ startfield, const int numsteps, const vec3_t gravity, lbm_field3D_t *restrict_ fieldevolv) { int it; // copy initial field LBM3DField_Allocate(startfield->omega, fieldevolv); memcpy(fieldevolv->df, startfield->df, SIZE_3D_X*SIZE_3D_Y*SIZE_3D_Z*sizeof(dfD3Q19_t)); for (it = 1; it < numsteps; it++) { LBM3DField_Allocate(startfield->omega, &fieldevolv[it]); CalculateLBMStep3D(&fieldevolv[it-1], gravity, &fieldevolv[it]); } }
27.385417
158
0.6277
[ "vector", "model" ]
c2d14b2a971f0700a509c1b540437667d46306a4
11,345
c
C
src/vue/graphics.c
TERRUSS/yote
c4b91221e90af047de960893acd5bffa35aa2441
[ "Unlicense" ]
1
2019-11-23T16:07:47.000Z
2019-11-23T16:07:47.000Z
src/vue/graphics.c
TERRUSS/yote
c4b91221e90af047de960893acd5bffa35aa2441
[ "Unlicense" ]
null
null
null
src/vue/graphics.c
TERRUSS/yote
c4b91221e90af047de960893acd5bffa35aa2441
[ "Unlicense" ]
null
null
null
#include "graphics.h" #include <stdio.h> #include <unistd.h> /*---------------- UTILS ----------------*/ void initGraphics(){ printLog(LOGGING_TASK, "Starting Initialisation"); window = 0; if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0){ printLog(LOGGING_STEP, "Window Creation ERROR : "); quitGraphics(); } else { printLog(LOGGING_STEP, "Window Created"); } window = SDL_CreateWindow("Yoté", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_SHOWN); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if ( renderer ) { printLog(LOGGING_STEP, "Renderer Created"); } else { printLog(LOGGING_STEP, "Renderer Creation ERROR : "); printLog(STEP_ERROR, SDL_GetError()); quitGraphics(); } cell_sprite_blue = IMG_Load("./src/assets/board_blue.png"); cell_sprite_red = IMG_Load("./src/assets/board_red.png"); white_pawn_sprite = IMG_Load("./src/assets/pawn_white.png"); black_pawn_sprite = IMG_Load("./src/assets/pawn_black.png"); menubg = IMG_Load("./src/assets/menubg.png"); boardbg = IMG_Load("./src/assets/boardbg.jpg"); winbg1 = IMG_Load("./src/assets/winbg1.jpg"); winbg2 = IMG_Load("./src/assets/winbg2.jpg"); btn_jvj = IMG_Load("./src/assets/buttons/jvj.png"); btn_jvia = IMG_Load("./src/assets/buttons/jvia.png"); btn_score = IMG_Load("./src/assets/buttons/score.png"); btn_back = IMG_Load("./src/assets/buttons/back.png"); btn_quit = IMG_Load("./src/assets/buttons/quit.png"); btn_v1 = IMG_Load("./src/assets/buttons/v1.png"); btn_v2 = IMG_Load("./src/assets/buttons/v2.png"); if ( cell_sprite_blue && cell_sprite_red && white_pawn_sprite && black_pawn_sprite ) { printLog(LOGGING_STEP, "Assets Loaded"); SDL_Delay(50); } else { printLog(LOGGING_STEP, "Loading assets ERROR : "); printLog(STEP_ERROR, SDL_GetError()); quitGraphics(); } printLog(LOGGING_STEP, "Loading fonts"); TTF_Init(); char cwd[250],cwd_font[500]; getcwd(cwd, sizeof(cwd)); sprintf(cwd_font,"%s/src/assets/fonts/font.ttf",cwd); if (!(font = TTF_OpenFont(cwd_font, 24))){ printLog(STEP_ERROR, TTF_GetError()); quitGraphics(); } printLog(FINISHED_TASK, "Initialisation Completed"); } void quitGraphics(){ SDL_DestroyWindow(window); SDL_Quit(); exit(0); } void render(){ SDL_RenderPresent(renderer); // Affichage } void print (Point pt, char* string, int color) { switch (color) { case WHITE: textColor.r = 255; textColor.g = 255; textColor.b = 255; break; case BLACK: textColor.r = 0; textColor.g = 0; textColor.b = 0; break; } textColor.a = 255; int text_width, text_height; textSurface = TTF_RenderText_Solid(font, string, textColor); SDL_Texture * text = (SDL_Texture*)SDL_CreateTextureFromSurface(renderer, textSurface); text_width = textSurface->w; text_height = textSurface->h; SDL_FreeSurface(textSurface); SDL_Rect renderQuad = { pt.x, pt.y, text_width, text_height }; SDL_RenderCopy(renderer, text, NULL, &renderQuad); SDL_DestroyTexture(text); } /*--------- PRINTING FUNCTIONS ----------*/ void displayBoard(Game * game){ // printLog(LOGGING_TASK, "Displaying Board"); Point pt; for (int r = 0; r < CELL_R; r++) { for (int c = CELL_C-1; c >= 0; c--) { pt.x=c; pt.y=r; pt = cartToIso(pt); print_board_cell( ((r+c)%2) ? WHITE : BLACK, pt); if (game->board[r][c].state == ACCESSIBLE){ SDL_Rect rectangle = {pt.x+HIT_BOX_HEIGHT/2.3,pt.y+HIT_BOX_HEIGHT/3.8,HIT_BOX_HEIGHT/2,HIT_BOX_WIDTH/2}; SDL_SetRenderDrawColor(renderer,200,0,0,150); SDL_RenderDrawRect(renderer,&rectangle); } if (game->board[r][c].state == FILL || game->board[r][c].state == SELECTED ) { if (game->board[r][c].color == WHITE) { if (game->currentPlayer == WHITE) print_pawn(WHITE, pt,PAWN_SELECT_OPACITY); else print_pawn(WHITE, pt,PAWN_UNSELECT_OPACITY); } else if (game->board[r][c].color == BLACK) { if (game->currentPlayer == BLACK) print_pawn(BLACK, pt,PAWN_SELECT_OPACITY); else print_pawn(BLACK, pt,PAWN_UNSELECT_OPACITY); } } } } // printLog(FINISHED_TASK, "Ok"); } void print_hover_cell(Point coord){ coord = cartToIso(isoToCart(coord)); SDL_Rect rectangle = {coord.x+HIT_BOX_HEIGHT/2.3,coord.y+HIT_BOX_HEIGHT/3.8,HIT_BOX_HEIGHT/2,HIT_BOX_WIDTH/2}; SDL_SetRenderDrawColor(renderer,0,0,255,150); SDL_RenderDrawRect(renderer,&rectangle); } void print_board_cell(int color, Point pt){ SDL_Texture* pTexture; if (color == WHITE) { // Préparation du sprite de la case pTexture = SDL_CreateTextureFromSurface(renderer, cell_sprite_blue); } else { pTexture = SDL_CreateTextureFromSurface(renderer, cell_sprite_red); } if ( pTexture ) { SDL_Rect dest = { pt.x, pt.y, SPRITE_WIDTH, SPRITE_WIDTH}; SDL_RenderCopy(renderer, pTexture, NULL, &dest); // Copie du pawn_sprite grâce au SDL_Renderer SDL_DestroyTexture(pTexture); // Libération de la mémoire associée à la texture } else { printLog(STEP_ERROR, SDL_GetError()); } } void print_pawn(int color, Point pt,Uint8 alpha){ SDL_Texture* pTexture = 0; if (color == WHITE){ SDL_SetSurfaceAlphaMod(white_pawn_sprite,alpha);pTexture = SDL_CreateTextureFromSurface(renderer,white_pawn_sprite);} // Préparation du pawn_sprite else{SDL_SetSurfaceAlphaMod(black_pawn_sprite,alpha); pTexture = SDL_CreateTextureFromSurface(renderer, black_pawn_sprite);} // Préparation du pawn_sprite if ( pTexture ) { SDL_Rect dest = { pt.x+SPRITE_WIDTH/4, pt.y+SPRITE_WIDTH/10, SPRITE_WIDTH/2, SPRITE_WIDTH/2}; SDL_RenderCopy(renderer, pTexture, NULL, &dest); // Copie du pawn_sprite grâce au SDL_Renderer SDL_DestroyTexture(pTexture); // Libération de la mémoire associée à la texture } else { printLog(STEP_ERROR, SDL_GetError()); } } void print_score(Player * player) { Point pt; char text[50+MAX_NAME_LENGTH]; pt.x = 15; pt.y= 50; sprintf(text,"Score : %d",player->score); print(pt,text,WHITE); } void print_select_stock(int color,int number){ Point pt; if (color == BLACK){ pt.x = 0; }else{ pt.x = WINDOW_WIDTH-SPRITE_WIDTH; } pt.y=WINDOW_HEIGHT-30-50; SDL_Rect rectangle = {pt.x,pt.y-(10*number),(SPRITE_WIDTH),(10*number)+50}; SDL_SetRenderDrawColor(renderer,200,0,0,150); SDL_RenderDrawRect(renderer,&rectangle); } void print_stock(int color, int number,Uint8 alpha){ Point pt; char text[25]; if (color == BLACK){ pt.x = 0; }else{ pt.x = WINDOW_WIDTH-SPRITE_WIDTH; } pt.y=WINDOW_HEIGHT-30-50; if(number < 10) sprintf(text," %d",number); else sprintf(text," %d",number); pt.y+=50; print(pt,text,WHITE); pt.y-=50; for(int i = 0;i<number;i++){ print_pawn(color,pt,alpha); pt.y-=10; } } void updateBoard(Game * game) { // SDL_RenderClear(renderer); // backgroundColor(222, 49, 99); backgroundImage(GAME); displayBoard(game); if (game->currentPlayer == BLACK){ print_stock(BLACK, game->black.stock,PAWN_SELECT_OPACITY); print_stock(WHITE, game->white.stock,PAWN_UNSELECT_OPACITY); print_score(&(game->black)); }else{ print_stock(WHITE, game->white.stock,PAWN_SELECT_OPACITY); print_stock(BLACK, game->black.stock,PAWN_UNSELECT_OPACITY); print_score(&(game->white)); } displayPlayerName(game); } void backgroundColor(int r, int g, int b){ SDL_SetRenderDrawColor(renderer, r, b, b, 255); SDL_Rect rectangle; rectangle.x = 0; rectangle.y = 0; rectangle.w = WINDOW_WIDTH; rectangle.h = WINDOW_HEIGHT; SDL_RenderFillRect(renderer, &rectangle); } void backgroundImage(int image){ SDL_Texture* pTexture = 0; switch (image) { case MENU: pTexture = SDL_CreateTextureFromSurface(renderer, menubg); // Préparation du pawn_sprite break; case GAME: pTexture = SDL_CreateTextureFromSurface(renderer, boardbg); // Préparation du pawn_sprite break; case VICTOIRE1: pTexture = SDL_CreateTextureFromSurface(renderer, winbg1); // Préparation du pawn_sprite break; case VICTOIRE2: pTexture = SDL_CreateTextureFromSurface(renderer, winbg2); // Préparation du pawn_sprite break; } if ( pTexture ) { SDL_Rect dest = { 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT}; SDL_RenderCopy(renderer, pTexture, NULL, &dest); // Copie du pawn_sprite grâce au SDL_Renderer SDL_DestroyTexture(pTexture); // Libération de la mémoire associée à la texture } else { printLog(STEP_ERROR, SDL_GetError()); printLog(STEP_ERROR, "Go background color instead"); SDL_RenderClear(renderer); backgroundColor(222, 49, 99); } } void displayPlayerName(Game * game){ Point pt = {15,15}; char text[MAX_NAME_LENGTH+10]; if (game->currentPlayer == BLACK){ sprintf(text,"Joueur : %s",game->black.name); }else{ sprintf(text,"Joueur : %s",game->white.name); } print(pt,text,WHITE); } void print_button(Point pt, int type){ SDL_Texture* pTexture = 0; int width = BTN_WIDTH, height = BTN_HEIGHT; switch (type) { case JVJ: pTexture = SDL_CreateTextureFromSurface(renderer, btn_jvj); break; case JVIA: pTexture = SDL_CreateTextureFromSurface(renderer, btn_jvia); break; case SCORE: pTexture = SDL_CreateTextureFromSurface(renderer, btn_score); break; case BACK: pTexture = SDL_CreateTextureFromSurface(renderer, btn_back); break; case V1: pTexture = SDL_CreateTextureFromSurface(renderer, btn_v1); break; case V2: pTexture = SDL_CreateTextureFromSurface(renderer, btn_v2); break; case QUIT: pTexture = SDL_CreateTextureFromSurface(renderer, btn_quit); width /=1.5; height /=1.5; break; } if ( pTexture ) { SDL_Rect dest = { pt.x, pt.y, width, height}; if (type == BACK){ dest.w = BTN_WIDTH/2; dest.h = BTN_HEIGHT/2; } SDL_RenderCopy(renderer, pTexture, NULL, &dest); // Copie du pawn_sprite grâce au SDL_Renderer SDL_DestroyTexture(pTexture); // Libération de la mémoire associée à la texture } } /*******************************************/ void VictoryScreen (Player * winner) { Point pt = {WINDOW_WIDTH/3, WINDOW_HEIGHT/3}; char text[1000] = {0}; int i=0; int frame = 0; do { SDL_RenderClear(renderer); if (frame) { backgroundImage(VICTOIRE1); }else{ backgroundImage(VICTOIRE2); } pt.y = WINDOW_HEIGHT/3; sprintf(text,"VICTOIRE ROYALE"); print(pt,text,WHITE); pt.y = 50; sprintf(text,"%s vainqueur",winner->name); print(pt,text,WHITE); render(); i++; if(i>100) { i = 0; frame = !frame; } } while(!waitClick_pulling()); } void printLeaderboard(){ Point pt = {WINDOW_WIDTH/3, 50}; SDL_RenderClear(renderer); // backgroundColor(222, 49, 99); backgroundImage(MENU); char score[MAXCHAR] = {0}; char tmp_name[MAXCHAR]; char tmp_score[MAXCHAR]; int y = 0, offset = 0; print(pt, "Leaderboard", WHITE); int i = 0; pt.x = 50; pt.y = 100; while(readScore(i, score) && i<10){ pt.y += 50; y = 0;offset = 0; while (score[y] != ';') { tmp_name[y] = score[y]; y++; } tmp_name[y] = '\0'; y++; offset = y; while (score[y] != '\n' && score[y] != '\0') { tmp_score[y-offset] = score[y]; y++; } tmp_score[y-offset] = '\0'; print(pt, tmp_name, WHITE); pt.x+=MAXCHAR; print(pt, tmp_score, WHITE); pt.x-=MAXCHAR; i++; } pt.x = 10; pt.y = 10; print_button(pt, BACK); render(); Point click; click.x = -1; click.y = -1; do{ waitClick(&click); } while(!(click.x > 10 && click.x < BTN_WIDTH/2 && click.y < BTN_HEIGHT/2 && click.y > 10)); }
24.345494
170
0.683649
[ "render" ]
c2dfb082e87ffffb6a576e7901c3c7d935268dcc
120,093
c
C
lib/bcore/bcore_tbman.c
johsteffens/beth
d1812bde925f8622b3016ac6822f099b860af03d
[ "Apache-2.0" ]
3
2019-08-12T12:44:08.000Z
2020-08-05T16:41:50.000Z
lib/bcore/bcore_tbman.c
johsteffens/beth
d1812bde925f8622b3016ac6822f099b860af03d
[ "Apache-2.0" ]
null
null
null
lib/bcore/bcore_tbman.c
johsteffens/beth
d1812bde925f8622b3016ac6822f099b860af03d
[ "Apache-2.0" ]
null
null
null
/** Author and Copyright 2017 Johannes Bernhard Steffens * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** Token Block Memory Manager. * An adapted, simplified and stand-alone version of this memory manager has * been released on https://github.com/johsteffens/tbman under a public license. */ #include "bcore_tbman.h" #include "bcore_control.h" #include "bcore_btree.h" #include "bcore_st.h" #include "bcore_threads.h" #include "bcore_name_manager.h" #include "bcore_signal.h" #include <time.h> #include <math.h> /**********************************************************************************************************************/ // default parameters static const uz_t default_pool_size = 0x10000; static const uz_t default_min_block_size = 8; static const uz_t default_max_block_size = 1024 * 16; static const uz_t default_stepping_method = 1; static const bool default_full_align = true; /// Minimum alignment of memory blocks #define TBMAN_ALIGN 0x100 /**********************************************************************************************************************/ // forward declarations typedef struct block_manager_s block_manager_s; typedef struct down_manager_s down_manager_s; typedef void (*fp_lost_alignment)( vd_t ); /**********************************************************************************************************************/ // shutdown-management // --------------------------------------------------------------------------------------------------------------------- /// shuts down an object (obj), o is the down structure typedef void (*fp_down )( vc_t o, vd_t obj ); /// first element of down structures below typedef struct down_s { fp_down _; } down_s; static void down_s_discard( down_manager_s* o, down_s* obj ); typedef struct down_obj_s { down_s _; // pointer to _down_obj fp_down_obj fp; // external down function } down_obj_s; static void _down_obj( const down_obj_s* o, vd_t obj ) { o->fp( obj ); } static down_obj_s* down_obj_s_create( down_manager_s* o, fp_down_obj fp ); // --------------------------------------------------------------------------------------------------------------------- typedef struct down_arg_s { down_s _; // pointer to _down_arg fp_down_arg fp; // external down function vc_t arg; // argument for external function } down_arg_s; // --------------------------------------------------------------------------------------------------------------------- static void _down_arg( const down_arg_s* o, vd_t obj ) { o->fp( o->arg, obj ); } static down_arg_s* down_arg_s_create( down_manager_s* o, fp_down_arg fp, vc_t arg ); // --------------------------------------------------------------------------------------------------------------------- typedef struct down_obj_arr_s { down_s _; // internal down function fp_down_obj fp; // external down function uz_t size; // number of active array elements uz_t step; // stepping between array elements in bytes } down_obj_arr_s; // --------------------------------------------------------------------------------------------------------------------- static void _down_obj_arr( const down_obj_arr_s* o, vd_t obj ) { for( uz_t i = o->size; i > 0; i-- ) { o->fp( obj ); obj = ( u0_t* )obj + o->step; } } // --------------------------------------------------------------------------------------------------------------------- static down_obj_arr_s* down_obj_arr_s_create( down_manager_s* o, fp_down_obj fp, uz_t size, uz_t step ); // --------------------------------------------------------------------------------------------------------------------- typedef struct down_arg_arr_s { down_s _; // internal down function fp_down_arg fp; // external down function vc_t arg; // argument for external function uz_t size; // number of active array elements uz_t step; // stepping between array elements in bytes } down_arg_arr_s; // --------------------------------------------------------------------------------------------------------------------- static void _down_arg_arr( const down_arg_arr_s* o, vd_t obj ) { for( uz_t i = o->size; i > 0; i-- ) { o->fp( o->arg, obj ); obj = ( u0_t* )obj + o->step; } } // --------------------------------------------------------------------------------------------------------------------- static down_arg_arr_s* down_arg_arr_s_create( down_manager_s* o, fp_down_arg fp, vc_t arg, uz_t size, uz_t step ); // --------------------------------------------------------------------------------------------------------------------- /**********************************************************************************************************************/ // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_external_b_alloc( vd_t current_ptr, uz_t requested_bytes, uz_t* granted_bytes ) { if( requested_bytes == 0 ) { if( current_ptr ) free( current_ptr ); current_ptr = NULL; if( granted_bytes ) *granted_bytes = 0; } else { if( current_ptr ) { current_ptr = realloc( current_ptr, requested_bytes ); } else { current_ptr = malloc( requested_bytes ); } if( !current_ptr ) ERR( "Failed allocating %zu bytes", requested_bytes ); if( granted_bytes ) *granted_bytes = requested_bytes; } return current_ptr; } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_external_bn_alloc( vd_t current_ptr, uz_t current_bytes, uz_t requested_bytes, uz_t* granted_bytes ) { return bcore_tbman_external_b_alloc( current_ptr, requested_bytes, granted_bytes ); } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_external_alloc( vd_t ptr, uz_t size ) { return bcore_tbman_external_b_alloc( ptr, size, NULL ); } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_external_un_alloc( uz_t unit_bytes, vd_t current_ptr, uz_t current_units, uz_t requested_units, uz_t* reserved_units ) { vd_t reserved_ptr = bcore_tbman_external_bn_alloc( current_ptr, unit_bytes * current_units, unit_bytes * requested_units, reserved_units ); if( reserved_units ) *reserved_units /= ( unit_bytes > 0 ? unit_bytes : 1 ); return reserved_ptr; } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_external_u_alloc( uz_t unit_bytes, vd_t current_ptr, uz_t requested_units, uz_t* reserved_units ) { vd_t reserved_ptr = bcore_tbman_external_b_alloc( current_ptr, unit_bytes * requested_units, reserved_units ); if( reserved_units ) *reserved_units /= ( unit_bytes > 0 ? unit_bytes : 1 ); return reserved_ptr; } // --------------------------------------------------------------------------------------------------------------------- /**********************************************************************************************************************/ /**********************************************************************************************************************/ /** Token-Manager * * Fragmentation-free and fast (O(1)) pool based dynamic management using fixed sized blocks. * A free block is identified by a token representing its address. Tokens are managed in a stack. * An alloc-request consumes the top token from stack. A free-request pushes the token back onto the stack. * * The instance token_manager_s occupies the memory-pool; being its header. This supports efficient (O(log(n)) * determination of the correct token-manager by the memory-manager (s. algorithm below). * * Token managers can be run in full-alignment-mode in which they are aligned to pool_size, which is * a power of two. This allows O(1) lookup of the pool manager from any of its managed allocations. * */ typedef struct token_manager_s { uz_t pool_size; // size of pool in bytes uz_t block_size; // size of block in bytes u1_t stack_size; // size of token-stack ( == pool_size / block_size ) u1_t stack_index; // index into token-stack /** aligned * The memory-pool is considered aligned when the integer-evaluation of its address * is a multiple of pool_size, which means that the pool address can be obtained * from any pointer inside the pool by a mere integer division. */ bl_t aligned; bcore_mutex_s* mutex; // governing mutex block_manager_s* parent; uz_t parent_index; uz_t* rc_count_arr; // array of reference counters vd_t* rc_down_arr; // array of shut down methods down_manager_s* down_manager; // manager of down objects u1_t token_stack[]; // stack of block-tokens (part of pool) } token_manager_s; // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_init( token_manager_s* o ) { bcore_memzero( o, sizeof( *o ) ); } // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_down( token_manager_s* o ) { if( o->rc_count_arr ) free( o->rc_count_arr ); if( o->rc_down_arr ) free( o->rc_down_arr ); } // --------------------------------------------------------------------------------------------------------------------- static token_manager_s* token_manager_s_create ( uz_t pool_size, uz_t block_size, bl_t align, down_manager_s* down_manager, bcore_mutex_s* mutex ) { if( ( pool_size & ( pool_size - 1 ) ) != 0 ) ERR( "pool_size %zu is not a power of two", pool_size ); uz_t stack_size = pool_size / block_size; if( stack_size > 0x10000 ) ERR( "stack_size %zu exceeds 0x10000", stack_size ); uz_t reserved_size = sizeof( token_manager_s ) + sizeof( u1_t ) * stack_size; uz_t reserved_blocks = reserved_size / block_size + ( ( reserved_size % block_size ) > 0 ); if( stack_size < ( reserved_blocks + 1 ) ) ERR( "pool_size %zu is too small", pool_size ); token_manager_s* o; if( align ) { /* We align to the entire pool_size (not just block_size). * This is to enable quick O(1) location of the token manager from any memory instance * by computing the next lower alignment point form a given address. */ o = aligned_alloc( pool_size, pool_size ); if( !o ) ERR( "Failed aligned allocating %zu bytes", pool_size ); } else { o = aligned_alloc( TBMAN_ALIGN, pool_size ); if( !o ) ERR( "Failed allocating %zu bytes", pool_size ); } token_manager_s_init( o ); /* We explicitly check alignment allowing for unexpected behavior of aligned_alloc. * If alignment (according to tbman's definition) fails, o->aligned is set to 'false' and * tbman falls back to a slightly slower btree-search to locate the token manager. */ o->aligned = ( ( intptr_t )o & ( intptr_t )( pool_size - 1 ) ) == 0; o->pool_size = pool_size; o->block_size = block_size; o->stack_size = stack_size; o->stack_index = 0; for( uz_t i = 0; i < o->stack_size; i++ ) o->token_stack[ i ] = ( i + reserved_blocks ) < stack_size ? ( i + reserved_blocks ) : 0; o->down_manager = down_manager; o->mutex = mutex; return o; } // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_discard( token_manager_s* o ) { if( !o ) return; token_manager_s_down( o ); free( o ); } // --------------------------------------------------------------------------------------------------------------------- static bl_t token_manager_s_is_full( token_manager_s* o ) { return o->token_stack[ o->stack_index ] == 0; } // --------------------------------------------------------------------------------------------------------------------- static bl_t token_manager_s_is_empty( token_manager_s* o ) { return o->stack_index == 0; } // --------------------------------------------------------------------------------------------------------------------- static vd_t token_manager_s_alloc( token_manager_s* o ) { assert( !token_manager_s_is_full( o ) ); vd_t ret = ( u0_t* )o + o->token_stack[ o->stack_index ] * o->block_size; assert( ( u0_t* )ret >= ( u0_t* )o + sizeof( token_manager_s ) ); o->stack_index++; return ret; } // --------------------------------------------------------------------------------------------------------------------- // forward declarations (implementation below) static void block_manager_s_full_to_free( struct block_manager_s* o, token_manager_s* child ); static void block_manager_s_free_to_empty( struct block_manager_s* o, token_manager_s* child ); // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_free_token( token_manager_s* o, u1_t token ) { #ifdef RTCHECKS if( token * o->block_size < sizeof( token_manager_s ) ) ERR( "Attempt to free reserved memory." ); for( uz_t i = o->stack_index; i < o->stack_size; i++ ) if( o->token_stack[ i ] == token ) ERR( "Attempt to free memory that is declared free." ); #endif // RTCHECKS // reference control if( o->rc_count_arr ) { if( o->rc_count_arr[ token ] ) { o->rc_count_arr[ token ]--; return; } if( o->rc_down_arr ) { vd_t down = o->rc_down_arr[ token ]; if( down ) { bcore_mutex_s_unlock( o->mutex ); ( ( down_s* )down )->_( down, ( u0_t* )o + token * o->block_size ); bcore_mutex_s_lock( o->mutex ); assert( o->down_manager ); down_s_discard( o->down_manager, down ); o->rc_down_arr[ token ] = NULL; } } } if( o->token_stack[ o->stack_index ] == 0 ) block_manager_s_full_to_free( o->parent, o ); o->stack_index--; o->token_stack[ o->stack_index ] = token; if( o->stack_index == 0 ) block_manager_s_free_to_empty( o->parent, o ); } // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_free( token_manager_s* o, vd_t ptr ) { #ifdef RTCHECKS if( o->stack_index == 0 ) ERR( "Block manager is empty." ); if( ( uz_t )( ( ptrdiff_t )( ( u0_t* )ptr - ( u0_t* )o ) ) > o->pool_size ) ERR( "Attempt to free memory outside pool." ); #endif token_manager_s_free_token( o, ( ( ptrdiff_t )( ( u0_t* )ptr - ( u0_t* )o ) ) / o->block_size ); } // --------------------------------------------------------------------------------------------------------------------- /// Finds the root address of given memory instance; returns NULL in case ptr is outside token_manager's memory space static vd_t token_manager_s_root( token_manager_s* o, vc_t ptr ) { u3_t token = ( ( ptrdiff_t )( ( u0_t* )ptr - ( u0_t* )o ) ) / o->block_size; return ( token < o->stack_size ) ? ( u0_t* )o + token * o->block_size : NULL; } // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_create_rc_count_arr( token_manager_s* o ) { uz_t alloc_size = sizeof( uz_t ) * o->stack_size; o->rc_count_arr = malloc( alloc_size ); memset( o->rc_count_arr, 0, alloc_size ); } // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_create_rc_down_arr( token_manager_s* o ) { uz_t alloc_size = sizeof( vd_t ) * o->stack_size; o->rc_down_arr = malloc( alloc_size ); memset( o->rc_down_arr, 0, alloc_size ); } // --------------------------------------------------------------------------------------------------------------------- static uz_t token_manager_s_references( token_manager_s* o, vc_t ptr ) { u1_t token = ( ( ptrdiff_t )( ( u0_t* )ptr - ( u0_t* )o ) ) / o->block_size; if( !o->rc_count_arr ) return 1; return 1 + o->rc_count_arr[ token ]; } // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_fork( token_manager_s* o, vd_t ptr ) { u1_t token = ( ( ptrdiff_t )( ( u0_t* )ptr - ( u0_t* )o ) ) / o->block_size; #ifdef RTCHECKS if( token * o->block_size < sizeof( token_manager_s ) ) ERR( "Attempt to fork reserved memory." ); for( uz_t i = o->stack_index; i < o->stack_size; i++ ) { if( o->token_stack[ i ] == token ) { ERR( "Attempt to fork memory that is declared free." ); } } #endif // RTCHECKS if( !o->rc_count_arr ) token_manager_s_create_rc_count_arr( o ); o->rc_count_arr[ token ]++; assert( o->rc_count_arr[ token ] ); // overflow check } // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_release( token_manager_s* o, vd_t ptr ) { token_manager_s_free( o, ptr ); } // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_release_obj( token_manager_s* o, fp_down_obj down, vd_t ptr ) { u1_t token = ( ( ptrdiff_t )( ( u0_t* )ptr - ( u0_t* )o ) ) / o->block_size; bl_t ptr_is_root = ( ( u0_t* )o + ( ( uz_t )token * o->block_size ) == ptr ); if( !o->rc_count_arr ) { bcore_mutex_s_unlock( o->mutex ); if( !ptr_is_root ) ERR( "Object is not root." ); down( ptr ); bcore_mutex_s_lock( o->mutex ); token_manager_s_free_token( o, token ); return; } if( o->rc_count_arr[ token ] ) { o->rc_count_arr[ token ]--; /* We only safe down instruction when the object is root. * Otherwise 'token' refers to a parent to which function down does not apply. * In that case shut down information is controlled by the parent object. */ if( ptr_is_root ) { if( !o->rc_down_arr ) token_manager_s_create_rc_down_arr( o ); if( !o->rc_down_arr[ token ] ) o->rc_down_arr[ token ] = down_obj_s_create( o->down_manager, down ); } return; } if( !o->rc_down_arr || !o->rc_down_arr[ token ] ) { bcore_mutex_s_unlock( o->mutex ); down( ptr ); bcore_mutex_s_lock( o->mutex ); } token_manager_s_free_token( o, token ); } // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_release_arg( token_manager_s* o, fp_down_arg down, vc_t arg, vd_t ptr ) { u1_t token = ( ( ptrdiff_t )( ( u0_t* )ptr - ( u0_t* )o ) ) / o->block_size; bl_t ptr_is_root = ( ( u0_t* )o + ( ( uz_t )token * o->block_size ) == ptr ); if( !o->rc_count_arr ) { bcore_mutex_s_unlock( o->mutex ); if( !ptr_is_root ) ERR( "Object is not root." ); down( arg, ptr ); bcore_mutex_s_lock( o->mutex ); token_manager_s_free_token( o, token ); return; } if( o->rc_count_arr[ token ] ) { o->rc_count_arr[ token ]--; /* We only safe down instruction when the object is root. * Otherwise 'token' refers to a parent to which function down does not apply. * In that case shut down information is controlled by the parent object. */ if( ptr_is_root ) { if( !o->rc_down_arr ) token_manager_s_create_rc_down_arr( o ); if( !o->rc_down_arr[ token ] ) o->rc_down_arr[ token ] = down_arg_s_create( o->down_manager, down, arg ); } return; } if( !o->rc_down_arr || !o->rc_down_arr[ token ] ) { bcore_mutex_s_unlock( o->mutex ); down( arg, ptr ); bcore_mutex_s_lock( o->mutex ); } token_manager_s_free_token( o, token ); } // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_release_obj_arr( token_manager_s* o, fp_down_obj down, vd_t ptr, uz_t size, uz_t step ) { u1_t token = ( ( ptrdiff_t )( ( u0_t* )ptr - ( u0_t* )o ) ) / o->block_size; bl_t free_token = true; bl_t direct_down = true; if( o->rc_count_arr ) { if( o->rc_count_arr[ token ] ) { o->rc_count_arr[ token ]--; if( !o->rc_down_arr ) token_manager_s_create_rc_down_arr( o ); free_token = false; direct_down = false; } else if( o->rc_down_arr && o->rc_down_arr[ token ] ) { direct_down = false; } } if( direct_down ) { bcore_mutex_s_unlock( o->mutex ); for( uz_t i = 0; i < size; i++ ) down( ( u0_t* )ptr + i * step ); bcore_mutex_s_lock( o->mutex ); } else { down_s** p_down = ( down_s** )&o->rc_down_arr[ token ]; if ( !( *p_down ) || ( ( ( *p_down )->_ != ( fp_down )_down_obj_arr ) && ( ( *p_down )->_ != ( fp_down )_down_arg_arr ) ) ) { if( *p_down ) { down_s_discard( o->down_manager, *p_down ); // *p_down came from a forked reference } *p_down = ( down_s* )down_obj_arr_s_create( o->down_manager, down, size, step ); } } if( free_token ) { token_manager_s_free_token( o, token ); } } // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_release_arg_arr( token_manager_s* o, fp_down_arg down, vc_t arg, vd_t ptr, uz_t size, uz_t step ) { u1_t token = ( ( ptrdiff_t )( ( u0_t* )ptr - ( u0_t* )o ) ) / o->block_size; bl_t free_token = true; bl_t direct_down = true; if( o->rc_count_arr ) { if( o->rc_count_arr[ token ] ) { o->rc_count_arr[ token ]--; if( !o->rc_down_arr ) token_manager_s_create_rc_down_arr( o ); free_token = false; direct_down = false; } else if( o->rc_down_arr && o->rc_down_arr[ token ] ) { direct_down = false; } } if( direct_down ) { bcore_mutex_s_unlock( o->mutex ); for( uz_t i = 0; i < size; i++ ) down( arg, ( u0_t* )ptr + i * step ); bcore_mutex_s_lock( o->mutex ); } else { down_s** p_down = ( down_s** )&o->rc_down_arr[ token ]; if ( !( *p_down ) || ( ( ( *p_down )->_ != ( fp_down )_down_obj_arr ) && ( ( *p_down )->_ != ( fp_down )_down_arg_arr ) ) ) { if( *p_down ) { down_s_discard( o->down_manager, *p_down ); // *p_down came from a forked reference } *p_down = ( down_s* )down_arg_arr_s_create( o->down_manager, down, arg, size, step ); } } if( free_token ) { token_manager_s_free_token( o, token ); } } // --------------------------------------------------------------------------------------------------------------------- static uz_t token_manager_s_total_alloc( const token_manager_s* o ) { return o->block_size * o->stack_index; } // --------------------------------------------------------------------------------------------------------------------- static uz_t token_manager_s_total_instances( const token_manager_s* o ) { return o->stack_index; } // --------------------------------------------------------------------------------------------------------------------- static uz_t token_manager_s_total_references( const token_manager_s* o ) { uz_t count = 0; for( uz_t i = 0; i < o->stack_index; i++ ) { uz_t token = o->token_stack[ i ]; count++; if( o->rc_count_arr ) count += o->rc_count_arr[ token ]; } return count; } // --------------------------------------------------------------------------------------------------------------------- static uz_t token_manager_s_total_space( const token_manager_s* o ) { return o->pool_size + o->stack_size * sizeof( u1_t ); } // --------------------------------------------------------------------------------------------------------------------- static void token_manager_s_for_each_instance( token_manager_s* o, void (*cb)( vd_t arg, vd_t ptr, uz_t space ), vd_t arg ) { if( !cb ) return; for( uz_t i = 0; i < o->stack_index; i++ ) { uz_t token = o->token_stack[ i ]; cb( arg, ( u0_t* )o + token * o->block_size, o->block_size ); } } // --------------------------------------------------------------------------------------------------------------------- static st_s* token_manager_s_status( const token_manager_s* o, int detail_level ) { st_s* str = st_s_create(); if( detail_level <= 0 ) return str; st_s_pushf( str, " pool_size: %zu\n", o->pool_size ); st_s_pushf( str, " block_size: %zu\n", o->block_size ); st_s_pushf( str, " stack_size: %zu\n", o->stack_size ); st_s_pushf( str, " aligned: %s\n", o->aligned ? "true" : "false" ); st_s_pushf( str, " stack_index: %zu\n", ( uz_t )o->stack_index ); st_s_pushf( str, " total alloc: %zu\n", token_manager_s_total_alloc( o ) ); st_s_pushf( str, " total space: %zu\n", token_manager_s_total_space( o ) ); return str; } // --------------------------------------------------------------------------------------------------------------------- /**********************************************************************************************************************/ /**********************************************************************************************************************/ /** Block-Manager * * Contains an array of token-managers, each of the same block-size. * A token-manager has one of three stats: 'full', 'free' and 'empty'. * A 'full' token-manager has no space left for allocation * A 'free' token-manager has (some) space available for allocation. * An 'empty' token-manager has all space available for allocation. * Token managers are linearly arranged by state in the order: full, free, empty. * An index (free_index) points to the full-free border. * * Alloc request: O(1) * - redirected to the free_indexe(d) token-manager. * - if that token-manager becomes 'full', free_index is incremented * - if all token-managers are full, a new token-manager is appended at the next alloc request * * Free request: * - block_manager_s does not directly receive free requests. Instead the parent-manager directly invokes the * the corresponding token manager. * - If a token-manager turns from full to free, it reports to the block manager, which swaps its position * with the last full token_manager and decrements free_index. * - If a token-manager turns from free to empty, it reports to the block manager, which swaps its position * with the last free token_manager. When enough empty token-managers accumulated (sweep_hysteresis), they * are discarded (memory returned to the system). * */ typedef struct block_manager_s { uz_t pool_size; // pool size of all token-managers uz_t block_size; // block size of all token-managers bl_t align; // attempt to align token_managers to pool_size token_manager_s** data; uz_t size, space; uz_t free_index; // entries equal or above free_index have space for allocation f3_t sweep_hysteresis; // if ( empty token-managers ) / ( used token-managers ) < sweep_hysteresis, empty token-managers are discarded bl_t aligned; // all token managers are aligned to pool_size vd_t parent; // parent fp_lost_alignment lost_alignment_fp; // callback for lost alignment bcore_btree_vd_s* internal_btree; down_manager_s* down_manager; bcore_mutex_s* mutex; // governing mutex } block_manager_s; // --------------------------------------------------------------------------------------------------------------------- static void block_manager_s_init ( block_manager_s* o, vd_t parent, uz_t pool_size, uz_t block_size, bl_t align, fp_lost_alignment lost_alignment_fp, bcore_btree_vd_s* internal_btree, down_manager_s* down_manager, bcore_mutex_s* mutex ) { bcore_memzero( o, sizeof( *o ) ); o->parent = parent; o->aligned = true; o->sweep_hysteresis = 0.125; o->pool_size = pool_size; o->block_size = block_size; o->align = align; o->lost_alignment_fp = lost_alignment_fp; o->internal_btree = internal_btree; o->down_manager = down_manager; o->mutex = mutex; } // --------------------------------------------------------------------------------------------------------------------- static void block_manager_s_down( block_manager_s* o ) { if( o->data ) { for( uz_t i = 0; i < o->size; i++ ) token_manager_s_discard( o->data[ i ] ); free( o->data ); o->data = NULL; o->size = o->space = 0; } } // --------------------------------------------------------------------------------------------------------------------- static block_manager_s* block_manager_s_create ( vd_t parent, uz_t pool_size, uz_t block_size, bl_t align, fp_lost_alignment lost_alignment_fp, bcore_btree_vd_s* internal_btree, down_manager_s* down_manager, bcore_mutex_s* mutex ) { block_manager_s* o = malloc( sizeof( block_manager_s ) ); if( !o ) ERR( "Failed allocating %zu bytes", sizeof( block_manager_s ) ); block_manager_s_init( o, parent, pool_size, block_size, align, lost_alignment_fp, internal_btree, down_manager, mutex ); return o; } // --------------------------------------------------------------------------------------------------------------------- static void block_manager_s_discard( block_manager_s* o ) { if( !o ) return; block_manager_s_down( o ); free( o ); } // --------------------------------------------------------------------------------------------------------------------- static void block_manager_s_acquire_token_manager( block_manager_s* o ) { if( o->size == o->space ) { o->space = ( o->space > 0 ) ? o->space * 2 : 1; if( o->data ) { o->data = realloc( o->data, sizeof( token_manager_s* ) * o->space ); } else { o->data = malloc( sizeof( token_manager_s* ) * o->space ); } if( !o->data ) ERR( "Failed allocating %zu bytes", sizeof( token_manager_s* ) * o->space ); } o->data[ o->size ] = token_manager_s_create( o->pool_size, o->block_size, o->align, o->down_manager, o->mutex ); o->data[ o->size ]->parent_index = o->size; o->data[ o->size ]->parent = o; if( o->aligned && !o->data[ o->size ]->aligned ) { o->aligned = false; if( o->lost_alignment_fp ) o->lost_alignment_fp( o->parent ); } if( bcore_btree_vd_s_set( o->internal_btree, o->data[ o->size ] ) != 1 ) ERR( "Failed registering block address." ); o->size++; } // --------------------------------------------------------------------------------------------------------------------- static vd_t block_manager_s_alloc( block_manager_s* o ) { if( o->free_index == o->size ) block_manager_s_acquire_token_manager( o ); token_manager_s* child = o->data[ o->free_index ]; vd_t ret = token_manager_s_alloc( child ); if( token_manager_s_is_full( child ) ) o->free_index++; return ret; } // --------------------------------------------------------------------------------------------------------------------- // A child reports turning full --> free static void block_manager_s_full_to_free( block_manager_s* o, token_manager_s* child ) { assert( o->free_index > 0 ); o->free_index--; // swap child with current free position uz_t child_index = child->parent_index; uz_t swapc_index = o->free_index; token_manager_s* swapc = o->data[ swapc_index ]; o->data[ swapc_index ] = child; o->data[ child_index ] = swapc; child->parent_index = swapc_index; swapc->parent_index = child_index; } // --------------------------------------------------------------------------------------------------------------------- static uz_t block_manager_s_empty_tail( const block_manager_s* o ) { if( o->size == 0 ) return 0; uz_t empty_index = o->size; while( empty_index > 0 && token_manager_s_is_empty( o->data[ empty_index - 1 ] ) ) empty_index--; return o->size - empty_index; } // --------------------------------------------------------------------------------------------------------------------- // A child reports turning free --> empty static void block_manager_s_free_to_empty( block_manager_s* o, token_manager_s* child ) { // move empty manager to tail (if not already there) uz_t child_index = child->parent_index; uz_t empty_tail = block_manager_s_empty_tail( o ); if( empty_tail < o->size ) { uz_t swapc_index = o->size - empty_tail - 1; if( child_index < swapc_index ) { token_manager_s* swapc = o->data[ swapc_index ]; o->data[ child_index ] = swapc; o->data[ swapc_index ] = child; child->parent_index = swapc_index; swapc->parent_index = child_index; empty_tail++; } } if( empty_tail > ( o->size - empty_tail ) * o->sweep_hysteresis ) // discard empty managers when enough accumulated { while( o->size > 0 && token_manager_s_is_empty( o->data[ o->size - 1 ] ) ) { o->size--; if( bcore_btree_vd_s_remove( o->internal_btree, o->data[ o->size ] ) != 1 ) ERR( "Failed removing block address." ); #ifdef RTCHECKS if( bcore_btree_vd_s_exists( o->internal_btree, o->data[ o->size ] ) ) ERR( "Removed block address still exists" ); #endif token_manager_s_discard( o->data[ o->size ] ); o->data[ o->size ] = NULL; } } } // --------------------------------------------------------------------------------------------------------------------- static uz_t block_manager_s_total_alloc( const block_manager_s* o ) { uz_t sum = 0; for( uz_t i = 0; i < o->size; i++ ) { sum += token_manager_s_total_alloc( o->data[ i ] ); } return sum; } // --------------------------------------------------------------------------------------------------------------------- static uz_t block_manager_s_total_instances( const block_manager_s* o ) { uz_t sum = 0; for( uz_t i = 0; i < o->size; i++ ) { sum += token_manager_s_total_instances( o->data[ i ] ); } return sum; } // --------------------------------------------------------------------------------------------------------------------- static uz_t block_manager_s_total_references( const block_manager_s* o ) { uz_t sum = 0; for( uz_t i = 0; i < o->size; i++ ) { sum += token_manager_s_total_references( o->data[ i ] ); } return sum; } // --------------------------------------------------------------------------------------------------------------------- static uz_t block_manager_s_total_space( const block_manager_s* o ) { uz_t sum = 0; for( uz_t i = 0; i < o->size; i++ ) { sum += token_manager_s_total_space( o->data[ i ] ); } return sum; } // --------------------------------------------------------------------------------------------------------------------- static void block_manager_s_for_each_instance( block_manager_s* o, void (*cb)( vd_t arg, vd_t ptr, uz_t space ), vd_t arg ) { for( uz_t i = 0; i < o->size; i++ ) token_manager_s_for_each_instance( o->data[ i ], cb, arg ); } // --------------------------------------------------------------------------------------------------------------------- static st_s* block_manager_s_status( const block_manager_s* o, int detail_level ) { st_s* str = st_s_create(); if( detail_level <= 0 ) return str; st_s_pushf( str, " pool_size: %zu\n", o->pool_size ); st_s_pushf( str, " block_size: %zu\n", o->block_size ); st_s_pushf( str, " sweep_hysteresis: %g\n", o->sweep_hysteresis ); st_s_pushf( str, " aligned: %s\n", o->aligned ? "true" : "false" ); st_s_pushf( str, " token_managers: %zu\n", o->size ); st_s_pushf( str, " full: %zu\n", o->free_index ); st_s_pushf( str, " empty: %zu\n", block_manager_s_empty_tail( o ) ); st_s_pushf( str, " total alloc: %zu\n", block_manager_s_total_alloc( o ) ); st_s_pushf( str, " total space: %zu\n", block_manager_s_total_space( o ) ); if( detail_level > 1 ) { for( uz_t i = 0; i < o->size; i++ ) { st_s_pushf( str, "\nblock manager %zu:\n", i ); st_s_push_st_d( str, token_manager_s_status( o->data[ i ], detail_level - 1 ) ); } } return str; } // --------------------------------------------------------------------------------------------------------------------- /**********************************************************************************************************************/ /**********************************************************************************************************************/ /** External-Control * Control framework for external storage */ // --------------------------------------------------------------------------------------------------------------------- typedef struct ext_s // external item { uz_t size; // allocated size uz_t rc_count; // reference counters vd_t rc_down; // shut down method } ext_s; // --------------------------------------------------------------------------------------------------------------------- static void ext_s_init( ext_s* o ) { bcore_memzero( o, sizeof( ext_s ) ); } static void ext_s_down( ext_s* o ) {} // --------------------------------------------------------------------------------------------------------------------- typedef struct external_manager_s { block_manager_s bm_ext; bcore_btree_vd_s* tm_btree; // btree of token managers bcore_btree_pp_s* ex_btree; // btree of external references uz_t pool_size; bl_t aligned; down_manager_s* down_manager; // manager of down objects bcore_mutex_s* mutex; // governing mutex } external_manager_s; // --------------------------------------------------------------------------------------------------------------------- static void external_manager_s_lost_alignment( external_manager_s* o ) { o->aligned = false; } // --------------------------------------------------------------------------------------------------------------------- static void external_manager_s_init ( external_manager_s* o, uz_t pool_size, bl_t full_align, down_manager_s* down_manager, bcore_mutex_s* mutex ) { bcore_memzero( o, sizeof( *o ) ); o->pool_size = pool_size; o->tm_btree = bcore_btree_vd_s_create( bcore_tbman_external_alloc ); o->ex_btree = bcore_btree_pp_s_create( bcore_tbman_external_alloc ); block_manager_s_init ( &o->bm_ext, o, pool_size, sizeof( ext_s ), full_align, ( fp_lost_alignment )external_manager_s_lost_alignment, o->tm_btree, NULL, mutex ); o->aligned = true; o->down_manager = down_manager; o->mutex = mutex; } // --------------------------------------------------------------------------------------------------------------------- static void external_manager_s_down( external_manager_s* o ) { block_manager_s_down( &o->bm_ext ); bcore_btree_vd_s_discard( o->tm_btree ); bcore_btree_pp_s_discard( o->ex_btree ); } // --------------------------------------------------------------------------------------------------------------------- static ext_s* ext_s_create( external_manager_s* o ) { ext_s* ext = block_manager_s_alloc( &o->bm_ext ); ext_s_init( ext ); return ext; } // --------------------------------------------------------------------------------------------------------------------- static void ext_s_discard( external_manager_s* o, ext_s* ext ) { ext_s_down( ext ); if( o->aligned ) { token_manager_s* token_manager = ( token_manager_s* )( ( intptr_t )ext & ~( intptr_t )( o->pool_size - 1 ) ); token_manager_s_free( token_manager, ext ); } else { token_manager_s_free( bcore_btree_vd_s_largest_below_equal( o->tm_btree, ext ), ext ); } } // --------------------------------------------------------------------------------------------------------------------- static vd_t external_manager_s_malloc( external_manager_s* o, uz_t requested_bytes, uz_t* granted_bytes ) { vd_t ptr = aligned_alloc( TBMAN_ALIGN, requested_bytes ); if( !ptr ) ERR( "Failed allocating %zu bytes.", requested_bytes ); if( granted_bytes ) *granted_bytes = requested_bytes; ext_s* ext = ext_s_create( o ); ext->size = requested_bytes; if( bcore_btree_pp_s_set( o->ex_btree, ptr, ext ) != 1 ) ERR( "Registering new address failed" ); return ptr; } // --------------------------------------------------------------------------------------------------------------------- static void external_manager_s_free_ext( external_manager_s* o, vd_t ptr, ext_s* ext ) { // reference control if( ext->rc_count ) { ext->rc_count--; return; } if( ext->rc_down ) { down_s* down = ext->rc_down; bcore_mutex_s_unlock( o->mutex ); down->_( down, ptr ); bcore_mutex_s_lock( o->mutex ); assert( o->down_manager ); down_s_discard( o->down_manager, down ); ext->rc_down = NULL; } bcore_btree_pp_s_remove( o->ex_btree, ptr ); ext_s_discard( o, ext ); free( ptr ); } // --------------------------------------------------------------------------------------------------------------------- static void external_manager_s_free( external_manager_s* o, vd_t ptr ) { vd_t* ext_p = bcore_btree_pp_s_val( o->ex_btree, ptr ); if( !ext_p ) { ERR( "Attempt to free invalid memory" ); } external_manager_s_free_ext( o, ptr, *ext_p ); } // --------------------------------------------------------------------------------------------------------------------- static void external_manager_s_get_instance( external_manager_s* o, vc_t ptr, vd_t* root, uz_t* granted_space ) { bcore_btree_pp_kv_s* kv = bcore_btree_pp_s_largest_below_equal( o->ex_btree, ( vd_t )ptr ); if( !kv ) ERR( "Object has no root address in dynamic memory address in dynamic memory." ); ext_s* ext = kv->val; if( ( ( ptrdiff_t )( ( u0_t* )ptr - ( u0_t* )kv->key ) ) >= ext->size ) ERR( "Object has no root address in dynamic memory." ); if( root ) *root = kv->key; if( granted_space ) *granted_space = ext->size; } // --------------------------------------------------------------------------------------------------------------------- static uz_t external_manager_s_granted_bytes( external_manager_s* o, vd_t ptr ) { vd_t* ext_p = bcore_btree_pp_s_val( o->ex_btree, ptr ); if( !ext_p ) ERR( "Could not retrieve current external memory" ); return ( ( ext_s* )*ext_p )->size; } // --------------------------------------------------------------------------------------------------------------------- static void ext_sum( vd_t val, bcore_btree_pp_kv_s kv ) { *(uz_t*)val += ( ( ext_s* )kv.val )->size; } // --------------------------------------------------------------------------------------------------------------------- static uz_t external_manager_s_total_alloc( const external_manager_s* o ) { uz_t size = 0; bcore_btree_pp_s_run( o->ex_btree, ext_sum, &size ); return size; } // --------------------------------------------------------------------------------------------------------------------- static void ext_count( vd_t val, bcore_btree_pp_kv_s kv ) { *(uz_t*)val += 1; } // --------------------------------------------------------------------------------------------------------------------- static uz_t external_manager_s_total_instances( const external_manager_s* o ) { uz_t size = 0; bcore_btree_pp_s_run( o->ex_btree, ext_count, &size ); return size; } // --------------------------------------------------------------------------------------------------------------------- static void ext_rc_ref_count( vd_t val, bcore_btree_pp_kv_s kv ) { *(uz_t*)val += 1 + ( ( ext_s* )kv.val )->rc_count; } // --------------------------------------------------------------------------------------------------------------------- static uz_t external_manager_s_total_references( const external_manager_s* o ) { uz_t size = 0; bcore_btree_pp_s_run( o->ex_btree, ext_rc_ref_count, &size ); return size; } // --------------------------------------------------------------------------------------------------------------------- typedef struct ext_for_instance_arg { void (*cb)( vd_t arg, vd_t ptr, uz_t space ); vd_t arg; } ext_for_instance_arg; // --------------------------------------------------------------------------------------------------------------------- static void ext_for_instance( vd_t val, bcore_btree_pp_kv_s kv ) { ext_for_instance_arg* iarg = val; iarg->cb( iarg->arg, kv.key, ( ( ext_s* )kv.val )->size ); } // --------------------------------------------------------------------------------------------------------------------- static void external_manager_s_for_each_instance( external_manager_s* o, void (*cb)( vd_t arg, vd_t ptr, uz_t space ), vd_t arg ) { ext_for_instance_arg iarg = { .cb = cb, .arg = arg }; bcore_btree_pp_s_run( o->ex_btree, ext_for_instance, &iarg ); } // --------------------------------------------------------------------------------------------------------------------- static uz_t external_manager_s_references( external_manager_s* o, vc_t ptr ) { bcore_btree_pp_kv_s* kv = bcore_btree_pp_s_largest_below_equal( o->ex_btree, ( vd_t )ptr ); if( !kv ) return 0; ext_s* ext = kv->val; if( ( ( ptrdiff_t )( ( u0_t* )ptr - ( u0_t* )kv->key ) ) >= ext->size ) return 0; return 1 + ext->rc_count; } // --------------------------------------------------------------------------------------------------------------------- static void external_manager_s_fork( external_manager_s* o, vd_t ptr ) { bcore_btree_pp_kv_s* kv = bcore_btree_pp_s_largest_below_equal( o->ex_btree, ptr ); if( !kv ) ERR( "Object has no root address in dynamic memory." ); ext_s* ext = kv->val; if( ( ( ptrdiff_t )( ( u0_t* )ptr - ( u0_t* )kv->key ) ) >= ext->size ) ERR( "Object has no root address in dynamic memory." ); ext->rc_count++; assert( ext->rc_count ); // overflow check } // --------------------------------------------------------------------------------------------------------------------- static void external_manager_s_release( external_manager_s* o, vd_t ptr ) { bcore_btree_pp_kv_s* kv = bcore_btree_pp_s_largest_below_equal( o->ex_btree, ptr ); if( !kv ) ERR( "Object has no root address in dynamic memory." ); ext_s* ext = kv->val; if( ( ( ptrdiff_t )( ( u0_t* )ptr - ( u0_t* )kv->key ) ) >= ext->size ) ERR( "Object has no root address in dynamic memory." ); external_manager_s_free_ext( o, kv->key, ext ); } // --------------------------------------------------------------------------------------------------------------------- static void external_manager_s_release_obj( external_manager_s* o, fp_down_obj down, vd_t ptr ) { bcore_btree_pp_kv_s* kv = bcore_btree_pp_s_largest_below_equal( o->ex_btree, ptr ); if( !kv ) ERR( "Object has no root address in dynamic memory." ); bl_t ptr_is_root = ( kv->key == ptr ); ext_s* ext = kv->val; if( ext->rc_count ) { ext->rc_count--; /* We only safe 'down' instruction when the object is root. * Otherwise 'token' refers to a parent to which function down does not apply. * In that case shut down information is controlled by the parent object. */ if( ptr_is_root && !ext->rc_down ) { assert( o->down_manager ); ext->rc_down = down_obj_s_create( o->down_manager, down ); } } else { if( !ext->rc_down ) { bcore_mutex_s_unlock( o->mutex ); if( !ptr_is_root ) ERR( "Object is not root." ); down( ptr ); bcore_mutex_s_lock( o->mutex ); } external_manager_s_free_ext( o, ptr, ext ); } } // --------------------------------------------------------------------------------------------------------------------- static void external_manager_s_release_arg( external_manager_s* o, fp_down_arg down, vc_t arg, vd_t ptr ) { bcore_btree_pp_kv_s* kv = bcore_btree_pp_s_largest_below_equal( o->ex_btree, ptr ); if( !kv ) ERR( "Object has no root address in dynamic memory." ); bl_t ptr_is_root = ( kv->key == ptr ); ext_s* ext = kv->val; if( ext->rc_count ) { ext->rc_count--; /* We only safe 'down' instruction when the object is root. * Otherwise shut down information is controlled by the parent object. */ if( ptr_is_root ) { if( !ext->rc_down ) { assert( o->down_manager ); ext->rc_down = down_arg_s_create( o->down_manager, down, arg ); } } } else { if( !ext->rc_down ) { bcore_mutex_s_unlock( o->mutex ); if( !ptr_is_root ) ERR( "Object is not root." ); down( arg, ptr ); bcore_mutex_s_lock( o->mutex ); } external_manager_s_free_ext( o, ptr, ext ); } } // --------------------------------------------------------------------------------------------------------------------- static void external_manager_s_release_obj_arr( external_manager_s* o, fp_down_obj down, vd_t ptr, uz_t size, uz_t step ) { vd_t* ext_p = bcore_btree_pp_s_val( o->ex_btree, ptr ); if( !ext_p ) ERR( "Object is not root." ); ext_s* ext = *ext_p; bl_t free_token = true; bl_t direct_down = true; if( ext->rc_count ) { ext->rc_count--; assert( o->down_manager ); free_token = false; direct_down = false; } else if( ext->rc_down ) { direct_down = false; } if( direct_down ) { bcore_mutex_s_unlock( o->mutex ); for( uz_t i = 0; i < size; i++ ) down( ( u0_t* )ptr + i * step ); bcore_mutex_s_lock( o->mutex ); } else { down_s** p_down = ( down_s** )&ext->rc_down; if ( !( *p_down ) || ( ( ( *p_down )->_ != ( fp_down )_down_obj_arr ) && ( ( *p_down )->_ != ( fp_down )_down_arg_arr ) ) ) { if( *p_down ) { down_s_discard( o->down_manager, *p_down ); // *p_down came from a forked reference } *p_down = ( down_s* )down_obj_arr_s_create( o->down_manager, down, size, step ); } } if( free_token ) { external_manager_s_free_ext( o, ptr, ext ); } } // --------------------------------------------------------------------------------------------------------------------- static void external_manager_s_release_arg_arr( external_manager_s* o, fp_down_arg down, vc_t arg, vd_t ptr, uz_t size, uz_t step ) { vd_t* ext_p = bcore_btree_pp_s_val( o->ex_btree, ptr ); if( !ext_p ) ERR( "Object is not root." ); ext_s* ext = *ext_p; bl_t free_token = true; bl_t direct_down = true; if( ext->rc_count ) { ext->rc_count--; assert( o->down_manager ); free_token = false; direct_down = false; } else if( ext->rc_down ) { direct_down = false; } if( direct_down ) { bcore_mutex_s_unlock( o->mutex ); for( uz_t i = 0; i < size; i++ ) down( arg, ( u0_t* )ptr + i * step ); bcore_mutex_s_lock( o->mutex ); } else { down_s** p_down = ( down_s** )&ext->rc_down; if ( !( *p_down ) || ( ( ( *p_down )->_ != ( fp_down )_down_obj_arr ) && ( ( *p_down )->_ != ( fp_down )_down_arg_arr ) ) ) { if( *p_down ) { down_s_discard( o->down_manager, *p_down ); // *p_down came from a forked reference } *p_down = ( down_s* )down_arg_arr_s_create( o->down_manager, down, arg, size, step ); } } if( free_token ) { external_manager_s_free_ext( o, ptr, ext ); } } // --------------------------------------------------------------------------------------------------------------------- /**********************************************************************************************************************/ /**********************************************************************************************************************/ /// Manager of down-objects // --------------------------------------------------------------------------------------------------------------------- typedef struct down_manager_s { block_manager_s bm_down_obj; block_manager_s bm_down_arg; block_manager_s bm_down_obj_arr; block_manager_s bm_down_arg_arr; bcore_btree_vd_s* tm_btree; // btree of token managers uz_t pool_size; bl_t aligned; bcore_mutex_s* mutex; // governing mutex } down_manager_s; // --------------------------------------------------------------------------------------------------------------------- static void down_manager_s_lost_alignment( external_manager_s* o ) { o->aligned = false; } // --------------------------------------------------------------------------------------------------------------------- static void down_manager_s_init( down_manager_s* o, uz_t pool_size, bl_t full_align, bcore_mutex_s* mutex ) { bcore_memzero( o, sizeof( *o ) ); o->pool_size = pool_size; o->tm_btree = bcore_btree_vd_s_create( bcore_tbman_external_alloc ); block_manager_s_init ( &o->bm_down_obj, o, pool_size, sizeof( down_obj_s ), full_align, ( fp_lost_alignment )down_manager_s_lost_alignment, o->tm_btree, NULL, mutex ); block_manager_s_init ( &o->bm_down_arg, o, pool_size, sizeof( down_arg_s ), full_align, ( fp_lost_alignment )down_manager_s_lost_alignment, o->tm_btree, NULL, mutex ); block_manager_s_init ( &o->bm_down_obj_arr, o, pool_size, sizeof( down_obj_arr_s ), full_align, ( fp_lost_alignment )down_manager_s_lost_alignment, o->tm_btree, NULL, mutex ); block_manager_s_init ( &o->bm_down_arg_arr, o, pool_size, sizeof( down_arg_arr_s ), full_align, ( fp_lost_alignment )down_manager_s_lost_alignment, o->tm_btree, NULL, mutex ); o->aligned = true; } // --------------------------------------------------------------------------------------------------------------------- static void down_manager_s_down( down_manager_s* o ) { block_manager_s_down( &o->bm_down_obj ); block_manager_s_down( &o->bm_down_arg ); block_manager_s_down( &o->bm_down_obj_arr ); block_manager_s_down( &o->bm_down_arg_arr ); bcore_btree_vd_s_discard( o->tm_btree ); } // --------------------------------------------------------------------------------------------------------------------- static void down_s_discard( down_manager_s* o, down_s* down ) { if( o->aligned ) { token_manager_s* token_manager = ( token_manager_s* )( ( intptr_t )down & ~( intptr_t )( o->pool_size - 1 ) ); token_manager_s_free( token_manager, down ); } else { token_manager_s_free( bcore_btree_vd_s_largest_below_equal( o->tm_btree, down ), down ); } } // --------------------------------------------------------------------------------------------------------------------- static down_obj_s* down_obj_s_create( down_manager_s* o, fp_down_obj fp ) { down_obj_s* down = block_manager_s_alloc( &o->bm_down_obj ); down->_._ = ( fp_down )_down_obj; down->fp = fp; return down; } // --------------------------------------------------------------------------------------------------------------------- static down_arg_s* down_arg_s_create( down_manager_s* o, fp_down_arg fp, vc_t arg ) { down_arg_s* down = block_manager_s_alloc( &o->bm_down_arg ); down->_._ = ( fp_down )_down_arg; down->fp = fp; down->arg = arg; return down; } // --------------------------------------------------------------------------------------------------------------------- static down_obj_arr_s* down_obj_arr_s_create( down_manager_s* o, fp_down_obj fp, uz_t size, uz_t step ) { down_obj_arr_s* down = block_manager_s_alloc( &o->bm_down_obj_arr ); down->_._ = ( fp_down )_down_obj_arr; down->fp = fp; down->size = size; down->step = step; return down; } // --------------------------------------------------------------------------------------------------------------------- static down_arg_arr_s* down_arg_arr_s_create( down_manager_s* o, fp_down_arg fp, vc_t arg, uz_t size, uz_t step ) { down_arg_arr_s* down = block_manager_s_alloc( &o->bm_down_arg_arr ); down->_._ = ( fp_down )_down_arg_arr; down->fp = fp; down->arg = arg; down->size = size; down->step = step; return down; } // --------------------------------------------------------------------------------------------------------------------- /**********************************************************************************************************************/ /**********************************************************************************************************************/ /** Memory-Manager * * Contains a fixed-size array of block-managers with exponentially increasing block_size. * (E.g. via size-doubling, but other arrangements are also possible) * * Alloc request: * - directed to the block-manager with the smallest fitting bock-size * - if the largest block size is yet too small, the request is passed on to the OS (-->aligned_alloc) * --> O(1) for size requests equal or below largest block size assuming alloc and free requests are statistically * balanced such the overall memory in use is not dramatically varying. * * Free request: * - If the previously allocated size is available and all token managers are aligned * the address of the token manager is directly calculated from the allocated address. (O(1)) * - Otherwise: The corresponding token-manager is determined via internal_btree from the memory-address * (O(log(n)) - where 'n' is the current amount of token managers.) * */ typedef struct bcore_tbman_s { block_manager_s** data; // block managers are sorted by increasing block size uz_t size; uz_t pool_size; // pool size for all token managers uz_t min_block_size; uz_t max_block_size; bl_t aligned; // all token managers are aligned uz_t* block_size_array; // copy of block size values (for fast access) bcore_btree_vd_s* internal_btree; external_manager_s external_manager; down_manager_s down_manager; bcore_mutex_s mutex; } bcore_tbman_s; // --------------------------------------------------------------------------------------------------------------------- static inline void tbman_s_lock( bcore_tbman_s* o ) { bcore_mutex_s_lock( &o->mutex ); } // --------------------------------------------------------------------------------------------------------------------- static inline void tbman_s_unlock( bcore_tbman_s* o ) { bcore_mutex_s_unlock( &o->mutex ); } // --------------------------------------------------------------------------------------------------------------------- static void tbman_s_lost_alignment( struct bcore_tbman_s* o ) { o->aligned = false; } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_s_init( bcore_tbman_s* o, uz_t pool_size, uz_t min_block_size, uz_t max_block_size, uz_t stepping_method, bl_t full_align ) { bcore_memzero( o, sizeof( *o ) ); bcore_mutex_s_init( &o->mutex ); o->internal_btree = bcore_btree_vd_s_create( bcore_tbman_external_alloc ); /// The following three values are configurable parameters of memory manager o->pool_size = pool_size; o->min_block_size = min_block_size; o->max_block_size = max_block_size; uz_t mask_bxp = stepping_method; uz_t size_mask = ( 1 << mask_bxp ) - 1; uz_t size_inc = o->min_block_size; while( ( size_mask < o->min_block_size ) || ( ( size_mask << 1 ) & o->min_block_size ) != 0 ) size_mask <<= 1; uz_t space = 0; for( uz_t block_size = o->min_block_size; block_size <= o->max_block_size; block_size += size_inc ) { if( o->size == space ) { space = space > 0 ? space * 2 : 16; if( o->data ) { o->data = realloc( o->data, sizeof( block_manager_s* ) * space ); } else { o->data = malloc( sizeof( block_manager_s* ) * space ); } if( !o->data ) ERR( "Failed allocating %zu bytes", sizeof( block_manager_s* ) * space ); } o->data[ o->size ] = block_manager_s_create ( o, o->pool_size, block_size, full_align, ( fp_lost_alignment )tbman_s_lost_alignment, o->internal_btree, &o->down_manager, &o->mutex ); o->size++; if( block_size > size_mask ) { size_mask <<= 1; size_inc <<= 1; } } o->block_size_array = malloc( o->size * sizeof( uz_t ) ); if( !o->block_size_array ) ERR( "Failed allocating %zu bytes", o->size * sizeof( uz_t ) ); o->aligned = true; for( uz_t i = 0; i < o->size; i++ ) { o->aligned = o->aligned && o->data[ i ]->aligned; o->block_size_array[ i ] = o->data[ i ]->block_size; } external_manager_s_init( &o->external_manager, pool_size, full_align, &o->down_manager, &o->mutex ); down_manager_s_init( &o->down_manager, pool_size, full_align, &o->mutex ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_s_down( bcore_tbman_s* o ) { tbman_s_lock( o ); external_manager_s_down( &o->external_manager ); down_manager_s_down( &o->down_manager ); if( o->data ) { for( uz_t i = 0; i < o->size; i++ ) block_manager_s_discard( o->data[ i ] ); free( o->data ); } bcore_btree_vd_s_discard( o->internal_btree ); if( o->block_size_array ) free( o->block_size_array ); tbman_s_unlock( o ); bcore_mutex_s_down( &o->mutex ); } // --------------------------------------------------------------------------------------------------------------------- bcore_tbman_s* bcore_tbman_s_create( uz_t pool_size, uz_t min_block_size, uz_t max_block_size, uz_t stepping_method, bl_t full_align ) { bcore_tbman_s* o = malloc( sizeof( bcore_tbman_s ) ); if( !o ) ERR( "Failed allocating %zu bytes", sizeof( bcore_tbman_s ) ); bcore_tbman_s_init( o, pool_size, min_block_size, max_block_size, stepping_method, full_align ); return o; } // --------------------------------------------------------------------------------------------------------------------- bcore_tbman_s* bcore_tbman_s_create_default() { return bcore_tbman_s_create ( default_pool_size, default_min_block_size, default_max_block_size, default_stepping_method, default_full_align ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_s_discard( bcore_tbman_s* o ) { if( !o ) return; bcore_tbman_s_down( o ); free( o ); } // --------------------------------------------------------------------------------------------------------------------- static vd_t tbman_s_mem_alloc( bcore_tbman_s* o, uz_t requested_bytes, uz_t* granted_bytes ) { block_manager_s* block_manager = NULL; for( uz_t i = 0; i < o->size; i++ ) { if( requested_bytes <= o->block_size_array[ i ] ) { block_manager = o->data[ i ]; break; } } vd_t reserved_ptr = NULL; if( block_manager ) { reserved_ptr = block_manager_s_alloc( block_manager ); if( granted_bytes ) *granted_bytes = block_manager->block_size; } else { reserved_ptr = external_manager_s_malloc( &o->external_manager, requested_bytes, granted_bytes ); } return reserved_ptr; } // --------------------------------------------------------------------------------------------------------------------- static void tbman_s_mem_free( bcore_tbman_s* o, vd_t current_ptr, const uz_t* current_bytes ) { if( current_bytes && *current_bytes <= o->max_block_size && o->aligned ) { token_manager_s* token_manager = ( token_manager_s* )( ( intptr_t )current_ptr & ~( intptr_t )( o->pool_size - 1 ) ); token_manager_s_free( token_manager, current_ptr ); } else { vd_t block_ptr = bcore_btree_vd_s_largest_below_equal( o->internal_btree, current_ptr ); if( block_ptr && ( ( ptrdiff_t )( (u0_t*)current_ptr - (u0_t*)block_ptr ) < o->pool_size ) ) { token_manager_s_free( block_ptr, current_ptr ); } else { external_manager_s_free( &o->external_manager, current_ptr ); } } } // --------------------------------------------------------------------------------------------------------------------- static void tbman_s_fork( bcore_tbman_s* o, vd_t ptr ) { vd_t block_ptr = bcore_btree_vd_s_largest_below_equal( o->internal_btree, ptr ); if( block_ptr && ( ( ptrdiff_t )( (u0_t*)ptr - (u0_t*)block_ptr ) < o->pool_size ) ) { token_manager_s_fork( block_ptr, ptr ); } else { external_manager_s_fork( &o->external_manager, ptr ); } } // --------------------------------------------------------------------------------------------------------------------- static void tbman_s_release( bcore_tbman_s* o, vd_t ptr ) { vd_t block_ptr = bcore_btree_vd_s_largest_below_equal( o->internal_btree, ptr ); if( block_ptr && ( ( ptrdiff_t )( (u0_t*)ptr - (u0_t*)block_ptr ) < o->pool_size ) ) { token_manager_s_release( block_ptr, ptr ); } else { external_manager_s_release( &o->external_manager, ptr ); } } // --------------------------------------------------------------------------------------------------------------------- static void tbman_s_release_obj( bcore_tbman_s* o, fp_down_obj down, vd_t ptr ) { if( down ) { vd_t block_ptr = bcore_btree_vd_s_largest_below_equal( o->internal_btree, ptr ); if( block_ptr && ( ( ptrdiff_t )( (u0_t*)ptr - (u0_t*)block_ptr ) < o->pool_size ) ) { token_manager_s_release_obj( block_ptr, down, ptr ); } else { external_manager_s_release_obj( &o->external_manager, down, ptr ); } } else { tbman_s_release( o, ptr ); } } // --------------------------------------------------------------------------------------------------------------------- static void tbman_s_release_arg( bcore_tbman_s* o, fp_down_arg down, vc_t arg, vd_t ptr ) { if( down ) { vd_t block_ptr = bcore_btree_vd_s_largest_below_equal( o->internal_btree, ptr ); if( block_ptr && ( ( ptrdiff_t )( (u0_t*)ptr - (u0_t*)block_ptr ) < o->pool_size ) ) { token_manager_s_release_arg( block_ptr, down, arg, ptr ); } else { external_manager_s_release_arg( &o->external_manager, down, arg, ptr ); } } else { tbman_s_release( o, ptr ); } } // --------------------------------------------------------------------------------------------------------------------- static void tbman_s_release_obj_arr( bcore_tbman_s* o, fp_down_obj down, vd_t ptr, uz_t size, uz_t step ) { if( down ) { vd_t block_ptr = bcore_btree_vd_s_largest_below_equal( o->internal_btree, ptr ); if( block_ptr && ( ( ptrdiff_t )( (u0_t*)ptr - (u0_t*)block_ptr ) < o->pool_size ) ) { token_manager_s_release_obj_arr( block_ptr, down, ptr, size, step ); } else { external_manager_s_release_obj_arr( &o->external_manager, down, ptr, size, step ); } } else { tbman_s_release( o, ptr ); } } // --------------------------------------------------------------------------------------------------------------------- static void tbman_s_release_arg_arr( bcore_tbman_s* o, fp_down_arg down, vc_t arg, vd_t ptr, uz_t size, uz_t step ) { if( down ) { vd_t block_ptr = bcore_btree_vd_s_largest_below_equal( o->internal_btree, ptr ); if( block_ptr && ( ( ptrdiff_t )( (u0_t*)ptr - (u0_t*)block_ptr ) < o->pool_size ) ) { token_manager_s_release_arg_arr( block_ptr, down, arg, ptr, size, step ); } else { external_manager_s_release_arg_arr( &o->external_manager, down, arg, ptr, size, step ); } } else { tbman_s_release( o, ptr ); } } // --------------------------------------------------------------------------------------------------------------------- static uz_t tbman_s_references( bcore_tbman_s* o, vc_t ptr ) { vd_t block_ptr = bcore_btree_vd_s_largest_below_equal( o->internal_btree, ( vd_t )ptr ); if( block_ptr && ( ( ptrdiff_t )( (u0_t*)ptr - (u0_t*)block_ptr ) < o->pool_size ) ) { return token_manager_s_references( block_ptr, ptr ); } else { return external_manager_s_references( &o->external_manager, ptr ); } } // --------------------------------------------------------------------------------------------------------------------- static vd_t tbman_s_mem_realloc( bcore_tbman_s* o, vd_t current_ptr, const uz_t* current_bytes, uz_t requested_bytes, uz_t* granted_bytes ) { token_manager_s* token_manager = NULL; if( current_bytes && *current_bytes <= o->max_block_size && o->aligned ) { token_manager = ( token_manager_s* )( ( intptr_t )current_ptr & ~( intptr_t )( o->pool_size - 1 ) ); } else { vd_t block_ptr = bcore_btree_vd_s_largest_below_equal( o->internal_btree, current_ptr ); if( block_ptr && ( ( (u0_t*)current_ptr - (u0_t*)block_ptr ) < o->pool_size ) ) token_manager = block_ptr; } if( token_manager ) { if( requested_bytes > token_manager->block_size ) { vd_t reserved_ptr = tbman_s_mem_alloc( o, requested_bytes, granted_bytes ); bcore_memcpy( reserved_ptr, current_ptr, token_manager->block_size ); token_manager_s_free( token_manager, current_ptr ); return reserved_ptr; } else // size reduction { block_manager_s* block_manager = NULL; for( uz_t i = 0; i < o->size; i++ ) { if( requested_bytes <= o->block_size_array[ i ] ) { block_manager = o->data[ i ]; break; } } if( block_manager->block_size != token_manager->block_size ) { vd_t reserved_ptr = block_manager_s_alloc( block_manager ); bcore_memcpy( reserved_ptr, current_ptr, requested_bytes ); token_manager_s_free( token_manager, current_ptr ); if( granted_bytes ) *granted_bytes = block_manager->block_size; return reserved_ptr; } else { // same block-size: keep current location if( granted_bytes ) *granted_bytes = token_manager->block_size; return current_ptr; } } } else { if( requested_bytes <= o->max_block_size ) // new size fits into manager, old size was outside manager { vd_t reserved_ptr = tbman_s_mem_alloc( o, requested_bytes, granted_bytes ); bcore_memcpy( reserved_ptr, current_ptr, requested_bytes ); external_manager_s_free( &o->external_manager, current_ptr ); return reserved_ptr; } else // neither old nor new size handled by this manager { uz_t current_ext_bytes = external_manager_s_granted_bytes( &o->external_manager, current_ptr ); // if requested bytes is less but not significantly less than current bytes, keep current memory if( ( requested_bytes < current_ext_bytes ) && ( requested_bytes >= ( current_ext_bytes >> 1 ) ) ) { if( granted_bytes ) *granted_bytes = current_ext_bytes; return current_ptr; } vd_t reserved_ptr = external_manager_s_malloc( &o->external_manager, requested_bytes, granted_bytes ); uz_t copy_bytes = ( requested_bytes < current_ext_bytes ) ? requested_bytes : current_ext_bytes; bcore_memcpy( reserved_ptr, current_ptr, copy_bytes ); external_manager_s_free( &o->external_manager, current_ptr ); return reserved_ptr; } } } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_s_fork( bcore_tbman_s* o, vd_t ptr ) { if( !ptr ) return NULL; tbman_s_lock( o ); tbman_s_fork( o, ptr ); tbman_s_unlock( o ); return ptr; } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_s_release( bcore_tbman_s* o, vd_t ptr ) { if( !ptr ) return; tbman_s_lock( o ); tbman_s_release( o, ptr ); tbman_s_unlock( o ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_s_release_obj( bcore_tbman_s* o, fp_down_obj down, vd_t ptr ) { if( !ptr ) return; tbman_s_lock( o ); tbman_s_release_obj( o, down, ptr ); tbman_s_unlock( o ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_s_release_arg( bcore_tbman_s* o, fp_down_arg down, vc_t arg, vd_t ptr ) { if( !ptr ) return; tbman_s_lock( o ); tbman_s_release_arg( o, down, arg, ptr ); tbman_s_unlock( o ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_s_release_obj_arr( bcore_tbman_s* o, fp_down_obj down, vd_t ptr, uz_t size, uz_t step ) { if( !ptr ) return; tbman_s_lock( o ); tbman_s_release_obj_arr( o, down, ptr, size, step ); tbman_s_unlock( o ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_s_release_arg_arr( bcore_tbman_s* o, fp_down_arg down, vc_t arg, vd_t ptr, uz_t size, uz_t step ) { if( !ptr ) return; tbman_s_lock( o ); tbman_s_release_arg_arr( o, down, arg, ptr, size, step ); tbman_s_unlock( o ); } // --------------------------------------------------------------------------------------------------------------------- uz_t bcore_tbman_s_references( bcore_tbman_s* o, vc_t ptr ) { if( !ptr ) return 0; tbman_s_lock( o ); uz_t n = tbman_s_references( o, ptr ); tbman_s_unlock( o ); return n; } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_s_b_alloc( bcore_tbman_s* o, vd_t current_ptr, uz_t requested_bytes, uz_t* granted_bytes ) { tbman_s_lock( o ); vd_t ret = NULL; if( requested_bytes == 0 ) { if( current_ptr ) { tbman_s_mem_free( o, current_ptr, NULL ); } if( granted_bytes ) *granted_bytes = 0; } else { if( current_ptr ) { ret = tbman_s_mem_realloc( o, current_ptr, NULL, requested_bytes, granted_bytes ); } else { ret = tbman_s_mem_alloc( o, requested_bytes, granted_bytes ); } } tbman_s_unlock( o ); return ret; } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_s_bn_alloc( bcore_tbman_s* o, vd_t current_ptr, uz_t current_bytes, uz_t requested_bytes, uz_t* granted_bytes ) { tbman_s_lock( o ); vd_t ret = NULL; if( requested_bytes == 0 ) { if( current_bytes ) // 0 means current_ptr may not be used for free or realloc { tbman_s_mem_free( o, current_ptr, &current_bytes ); } if( granted_bytes ) *granted_bytes = 0; } else { if( current_bytes ) // 0 means current_ptr may not be used for free or realloc { ret = tbman_s_mem_realloc( o, current_ptr, &current_bytes, requested_bytes, granted_bytes ); } else { ret = tbman_s_mem_alloc( o, requested_bytes, granted_bytes ); } } tbman_s_unlock( o ); return ret; } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_s_u_alloc( bcore_tbman_s* o, uz_t unit_bytes, vd_t current_ptr, uz_t requested_units, uz_t* reserved_units ) { vd_t reserved_ptr = bcore_tbman_s_b_alloc( o, current_ptr, unit_bytes * requested_units, reserved_units ); if( reserved_units ) *reserved_units /= ( unit_bytes > 0 ? unit_bytes : 1 ); return reserved_ptr; } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_s_un_alloc( bcore_tbman_s* o, uz_t unit_bytes, vd_t current_ptr, uz_t current_units, uz_t requested_units, uz_t* reserved_units ) { vd_t reserved_ptr = bcore_tbman_s_bn_alloc( o, current_ptr, unit_bytes * current_units, unit_bytes * requested_units, reserved_units ); if( reserved_units ) *reserved_units /= ( unit_bytes > 0 ? unit_bytes : 1 ); return reserved_ptr; } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_s_get_instance( bcore_tbman_s* o, vc_t ptr, vd_t* root, uz_t* granted_space ) { tbman_s_lock( o ); vd_t block_ptr = bcore_btree_vd_s_largest_below_equal( o->internal_btree, ( vd_t )ptr ); if( block_ptr && ( ( ptrdiff_t )( (u0_t*)ptr - (u0_t*)block_ptr ) < o->pool_size ) ) { token_manager_s* token_manager = block_ptr; if( root ) *root = token_manager_s_root( token_manager, ptr ); if( granted_space ) *granted_space = token_manager->block_size; } else { external_manager_s_get_instance( &o->external_manager, ptr, root, granted_space ); } tbman_s_unlock( o ); } // --------------------------------------------------------------------------------------------------------------------- static uz_t tbman_s_internal_total_alloc( const bcore_tbman_s* o ) { uz_t sum = 0; for( uz_t i = 0; i < o->size; i++ ) { sum += block_manager_s_total_alloc( o->data[ i ] ); } return sum; } // --------------------------------------------------------------------------------------------------------------------- static uz_t tbman_s_internal_total_instances( const bcore_tbman_s* o ) { uz_t sum = 0; for( uz_t i = 0; i < o->size; i++ ) { sum += block_manager_s_total_instances( o->data[ i ] ); } return sum; } // --------------------------------------------------------------------------------------------------------------------- static uz_t tbman_s_internal_total_references( const bcore_tbman_s* o ) { uz_t sum = 0; for( uz_t i = 0; i < o->size; i++ ) { sum += block_manager_s_total_references( o->data[ i ] ); } return sum; } // --------------------------------------------------------------------------------------------------------------------- static uz_t tbman_s_total_alloc( const bcore_tbman_s* o ) { return external_manager_s_total_alloc( &o->external_manager ) + tbman_s_internal_total_alloc( o ); } // --------------------------------------------------------------------------------------------------------------------- static uz_t tbman_s_total_instances( const bcore_tbman_s* o ) { return external_manager_s_total_instances( &o->external_manager ) + tbman_s_internal_total_instances( o ); } // --------------------------------------------------------------------------------------------------------------------- static uz_t tbman_s_total_references( const bcore_tbman_s* o ) { return external_manager_s_total_references( &o->external_manager ) + tbman_s_internal_total_references( o ); } // --------------------------------------------------------------------------------------------------------------------- static uz_t tbman_s_total_space( const bcore_tbman_s* o ) { uz_t sum = 0; for( uz_t i = 0; i < o->size; i++ ) { sum += block_manager_s_total_space( o->data[ i ] ); } sum += block_manager_s_total_space( &o->external_manager.bm_ext ); return sum; } // --------------------------------------------------------------------------------------------------------------------- static void tbman_s_for_each_instance( bcore_tbman_s* o, void (*cb)( vd_t arg, vd_t ptr, uz_t space ), vd_t arg ) { for( uz_t i = 0; i < o->size; i++ ) { block_manager_s_for_each_instance( o->data[ i ], cb, arg ); } external_manager_s_for_each_instance( &o->external_manager, cb, arg ); } /**********************************************************************************************************************/ /**********************************************************************************************************************/ /**********************************************************************************************************************/ // Interface // --------------------------------------------------------------------------------------------------------------------- static bcore_tbman_s* tbman_s_g = NULL; static void create_tbman() { tbman_s_g = bcore_tbman_s_create_default(); } // --------------------------------------------------------------------------------------------------------------------- static void discard_tbman() { bcore_tbman_s_discard( tbman_s_g ); tbman_s_g = NULL; } // --------------------------------------------------------------------------------------------------------------------- static void tbman_open() { static bcore_once_s flag = bcore_once_init; bcore_once_s_run( &flag, create_tbman ); } // --------------------------------------------------------------------------------------------------------------------- static void tbman_close() { discard_tbman(); } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_fork( vd_t ptr ) { assert( tbman_s_g != NULL ); return bcore_tbman_s_fork( tbman_s_g, ptr ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_release( vd_t ptr ) { assert( tbman_s_g != NULL ); bcore_tbman_s_release( tbman_s_g, ptr ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_release_obj( fp_down_obj down, vd_t ptr ) { assert( tbman_s_g != NULL ); bcore_tbman_s_release_obj( tbman_s_g, down, ptr ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_release_arg( fp_down_arg down, vc_t arg, vd_t ptr ) { assert( tbman_s_g != NULL ); bcore_tbman_s_release_arg( tbman_s_g, down, arg, ptr ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_release_obj_arr( fp_down_obj down, vd_t ptr, uz_t size, uz_t step ) { assert( tbman_s_g != NULL ); bcore_tbman_s_release_obj_arr( tbman_s_g, down, ptr, size, step ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_release_arg_arr( fp_down_arg down, vc_t arg, vd_t ptr, uz_t size, uz_t step ) { assert( tbman_s_g != NULL ); bcore_tbman_s_release_arg_arr( tbman_s_g, down, arg, ptr, size, step ); } // --------------------------------------------------------------------------------------------------------------------- uz_t bcore_tbman_references( vc_t ptr ) { assert( tbman_s_g != NULL ); return bcore_tbman_s_references( tbman_s_g, ptr ); } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_b_alloc( vd_t current_ptr, uz_t requested_bytes, uz_t* granted_bytes ) { assert( tbman_s_g != NULL ); return bcore_tbman_s_b_alloc( tbman_s_g, current_ptr, requested_bytes, granted_bytes ); } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_bn_alloc( vd_t current_ptr, uz_t current_bytes, uz_t requested_bytes, uz_t* granted_bytes ) { assert( tbman_s_g != NULL ); return bcore_tbman_s_bn_alloc( tbman_s_g, current_ptr, current_bytes, requested_bytes, granted_bytes ); } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_u_alloc( uz_t unit_bytes, vd_t current_ptr, uz_t requested_units, uz_t* reserved_units ) { vd_t reserved_ptr = bcore_tbman_b_alloc( current_ptr, unit_bytes * requested_units, reserved_units ); if( reserved_units ) *reserved_units /= ( unit_bytes > 0 ? unit_bytes : 1 ); return reserved_ptr; } // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_un_alloc( uz_t unit_bytes, vd_t current_ptr, uz_t current_units, uz_t requested_units, uz_t* reserved_units ) { vd_t reserved_ptr = bcore_tbman_bn_alloc( current_ptr, unit_bytes * current_units, unit_bytes * requested_units, reserved_units ); if( reserved_units ) *reserved_units /= ( unit_bytes > 0 ? unit_bytes : 1 ); return reserved_ptr; } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_get_instance( vc_t ptr, vd_t* root, uz_t* granted_space ) { bcore_tbman_s_get_instance( tbman_s_g, ptr, root, granted_space ); } // --------------------------------------------------------------------------------------------------------------------- uz_t bcore_tbman_s_granted_space( bcore_tbman_s* o, vc_t ptr ) { uz_t space = 0; bcore_tbman_s_get_instance( o, ptr, NULL, &space ); return space; } // --------------------------------------------------------------------------------------------------------------------- uz_t bcore_tbman_s_total_granted_space( bcore_tbman_s* o ) { tbman_s_lock( o ); uz_t space = tbman_s_total_alloc( o ); tbman_s_unlock( o ); return space; } // --------------------------------------------------------------------------------------------------------------------- uz_t bcore_tbman_s_total_instances( bcore_tbman_s* o ) { tbman_s_lock( o ); uz_t size = tbman_s_total_instances( o ); tbman_s_unlock( o ); return size; } // --------------------------------------------------------------------------------------------------------------------- uz_t bcore_tbman_s_total_references( bcore_tbman_s* o ) { tbman_s_lock( o ); uz_t size = tbman_s_total_references( o ); tbman_s_unlock( o ); return size; } // --------------------------------------------------------------------------------------------------------------------- typedef struct bcore_tbman_mnode { vd_t p; uz_t s; } bcore_tbman_mnode; typedef struct bcore_tbman_mnode_arr { bcore_tbman_mnode* data; uz_t size; uz_t space; } bcore_tbman_mnode_arr; static void for_each_instance_collect_callback( vd_t arg, vd_t ptr, uz_t space ) { assert( arg ); bcore_tbman_mnode_arr* arr = arg; assert( arr->size < arr->space ); arr->data[ arr->size ] = ( bcore_tbman_mnode ){ .p = ptr, .s = space }; arr->size++; } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_s_for_each_instance( bcore_tbman_s* o, void (*cb)( vd_t arg, vd_t ptr, uz_t space ), vd_t arg ) { if( !cb ) return; sz_t size = bcore_tbman_s_total_instances( o ); if( !size ) return; bcore_tbman_mnode_arr arr; arr.data = malloc( sizeof( bcore_tbman_mnode ) * size ); arr.space = size; arr.size = 0; tbman_s_lock( o ); tbman_s_for_each_instance( o, for_each_instance_collect_callback, &arr ); tbman_s_unlock( o ); assert( arr.size == arr.space ); for( sz_t i = 0; i < size; i++ ) cb( arg, arr.data[ i ].p, arr.data[ i ].s ); free( arr.data ); } // --------------------------------------------------------------------------------------------------------------------- static void tbman_s_free_all_callback( vd_t o, vd_t ptr, uz_t space ) { bcore_tbman_s_b_alloc( o, ptr, 0, NULL ); } void bcore_tbman_s_free_all( bcore_tbman_s* o ) { bcore_tbman_s_for_each_instance( o, tbman_s_free_all_callback, o ); } // --------------------------------------------------------------------------------------------------------------------- uz_t bcore_tbman_granted_space( vc_t ptr ) { assert( tbman_s_g != NULL ); return bcore_tbman_s_granted_space( tbman_s_g, ptr ); } // --------------------------------------------------------------------------------------------------------------------- uz_t bcore_tbman_total_granted_space() { assert( tbman_s_g != NULL ); return bcore_tbman_s_total_granted_space( tbman_s_g ); } // --------------------------------------------------------------------------------------------------------------------- uz_t bcore_tbman_total_instances() { assert( tbman_s_g != NULL ); return bcore_tbman_s_total_instances( tbman_s_g ); } // --------------------------------------------------------------------------------------------------------------------- uz_t bcore_tbman_total_references() { assert( tbman_s_g != NULL ); return bcore_tbman_s_total_references( tbman_s_g ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_for_each_instance( void (*cb)( vd_t arg, vd_t ptr, uz_t space ), vd_t arg ) { assert( tbman_s_g != NULL ); bcore_tbman_s_for_each_instance( tbman_s_g, cb, arg ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_free_all( void ) { assert( tbman_s_g != NULL ); bcore_tbman_s_free_all( tbman_s_g ); } // --------------------------------------------------------------------------------------------------------------------- // not thread-safe st_s* bcore_tbman_s_status( bcore_tbman_s* o, int detail_level ) { if( detail_level <= 0 ) return NULL; st_s* str = st_s_create(); st_s_pushf( str, "main manager\n" ); st_s_pushf( str, " pool_size ........... %zu\n", o->pool_size ); st_s_pushf( str, " block managers ...... %zu\n", o->size ); st_s_pushf( str, " token managers ...... %zu\n", bcore_btree_vd_s_count( o->internal_btree, NULL, NULL ) ); st_s_pushf( str, " external allocs ..... %zu\n", bcore_btree_pp_s_count( o->external_manager.ex_btree, NULL, NULL ) ); st_s_pushf( str, " internal_btree depth %zu\n", bcore_btree_vd_s_depth( o->internal_btree ) ); st_s_pushf( str, " external_btree depth %zu\n", bcore_btree_pp_s_depth( o->external_manager.ex_btree ) ); st_s_pushf( str, " min_block_size ...... %zu\n", o->size > 0 ? o->data[ 0 ]->block_size : 0 ); st_s_pushf( str, " max_block_size ...... %zu\n", o->size > 0 ? o->data[ o->size - 1 ]->block_size : 0 ); st_s_pushf( str, " aligned ............. %s\n", o->aligned ? "true" : "false" ); st_s_pushf( str, "external manager\n" ); st_s_pushf( str, " pool_size ........... %zu\n", o->external_manager.pool_size ); st_s_pushf( str, " token managers ...... %zu\n", bcore_btree_vd_s_count( o->external_manager.tm_btree, NULL, NULL ) ); st_s_pushf( str, " aligned ............. %s\n", o->external_manager.aligned ? "true" : "false" ); st_s_pushf( str, " item size ........... %zu\n", sizeof( ext_s ) ); st_s_pushf( str, " items ............... %zu\n", block_manager_s_total_alloc( &o->external_manager.bm_ext ) / sizeof( ext_s ) ); st_s_pushf( str, " alloc ............... %zu\n", block_manager_s_total_alloc( &o->external_manager.bm_ext ) ); st_s_pushf( str, " space ............... %zu\n", block_manager_s_total_space( &o->external_manager.bm_ext ) ); st_s_pushf( str, "down manager\n" ); st_s_pushf( str, " pool_size ........... %zu\n", o->down_manager.pool_size ); st_s_pushf( str, " token managers ...... %zu\n", bcore_btree_vd_s_count( o->down_manager.tm_btree, NULL, NULL ) ); st_s_pushf( str, " aligned ............. %s\n", o->down_manager.aligned ? "true" : "false" ); st_s_pushf( str, " down_obj_s size ..... %zu\n", sizeof( down_obj_s ) ); st_s_pushf( str, " down_obj_s items .... %zu\n", block_manager_s_total_alloc( &o->down_manager.bm_down_obj ) / sizeof( down_obj_s ) ); st_s_pushf( str, " down_obj_s alloc .... %zu\n", block_manager_s_total_alloc( &o->down_manager.bm_down_obj ) ); st_s_pushf( str, " down_obj_s space .... %zu\n", block_manager_s_total_space( &o->down_manager.bm_down_obj ) ); st_s_pushf( str, " down_arg_s size ..... %zu\n", sizeof( down_arg_s ) ); st_s_pushf( str, " down_arg_s items .... %zu\n", block_manager_s_total_alloc( &o->down_manager.bm_down_arg ) / sizeof( down_arg_s ) ); st_s_pushf( str, " down_arg_s alloc .... %zu\n", block_manager_s_total_alloc( &o->down_manager.bm_down_arg ) ); st_s_pushf( str, " down_arg_s space .... %zu\n", block_manager_s_total_space( &o->down_manager.bm_down_arg ) ); st_s_pushf( str, " down_obj_arr_s size %zu\n", sizeof( down_obj_arr_s ) ); st_s_pushf( str, " down_obj_arr_s items %zu\n", block_manager_s_total_alloc( &o->down_manager.bm_down_obj_arr ) / sizeof( down_obj_arr_s ) ); st_s_pushf( str, " down_obj_arr_s alloc %zu\n", block_manager_s_total_alloc( &o->down_manager.bm_down_obj_arr ) ); st_s_pushf( str, " down_obj_arr_s space %zu\n", block_manager_s_total_space( &o->down_manager.bm_down_obj_arr ) ); st_s_pushf( str, " down_arg_arr_s size %zu\n", sizeof( down_arg_arr_s ) ); st_s_pushf( str, " down_arg_arr_s items %zu\n", block_manager_s_total_alloc( &o->down_manager.bm_down_arg_arr ) / sizeof( down_arg_arr_s ) ); st_s_pushf( str, " down_arg_arr_s alloc %zu\n", block_manager_s_total_alloc( &o->down_manager.bm_down_arg_arr ) ); st_s_pushf( str, " down_arg_arr_s space %zu\n", block_manager_s_total_space( &o->down_manager.bm_down_arg_arr ) ); st_s_pushf( str, "overall allocations\n" ); st_s_pushf( str, " total bytes granted . %zu\n", tbman_s_total_alloc( o ) ); st_s_pushf( str, " external .......... %zu\n", external_manager_s_total_alloc( &o->external_manager ) ); st_s_pushf( str, " internal .......... %zu\n", tbman_s_internal_total_alloc( o ) ); st_s_pushf( str, " internal used ....... %zu\n", tbman_s_total_space( o ) ); st_s_pushf( str, " total instances ..... %zu\n", tbman_s_total_instances( o ) ); st_s_pushf( str, " external .......... %zu\n", external_manager_s_total_instances( &o->external_manager ) ); st_s_pushf( str, " internal .......... %zu\n", tbman_s_internal_total_instances( o ) ); st_s_pushf( str, " total references .... %zu\n", tbman_s_total_references( o ) ); st_s_pushf( str, " external .......... %zu\n", external_manager_s_total_references( &o->external_manager ) ); st_s_pushf( str, " internal .......... %zu\n", tbman_s_internal_total_references( o ) ); if( detail_level > 1 ) { for( uz_t i = 0; i < o->size; i++ ) { st_s_pushf( str, "\nblock manager %zu:\n", i ); st_s_push_st_d( str, block_manager_s_status( o->data[ i ], detail_level - 1 ) ); } } return str; } // --------------------------------------------------------------------------------------------------------------------- #include <stdio.h> static void instance_diagnostics( vd_t arg, vd_t ptr, uz_t space ) { printf( "ptr = %p, space = %5zu", ptr, space ); if( bcore_name_try_name( ( ( tp_t* )ptr )[ 0 ] ) ) { printf( ", aware of = '%s'", nameof( ( ( tp_t* )ptr )[ 0 ] ) ); if( bcore_name_try_name( ( ( tp_t* )ptr )[ 1 ] ) ) { printf( ", spect of = '%s'", nameof( ( ( tp_t* )ptr )[ 1 ] ) ); } } printf( "\n" ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_s_instance_disgnostics( bcore_tbman_s* o ) { bcore_tbman_s_for_each_instance( o, instance_diagnostics, NULL ); } // --------------------------------------------------------------------------------------------------------------------- void bcore_tbman_instance_disgnostics( void ) { bcore_tbman_for_each_instance( instance_diagnostics, NULL ); } // --------------------------------------------------------------------------------------------------------------------- /**********************************************************************************************************************/ // Testing and evaluation #include "bcore_spect_inst.h" typedef vd_t (*fp_alloc)( vd_t current_ptr, uz_t current_bytes, uz_t requested_bytes, uz_t* granted_bytes ); // --------------------------------------------------------------------------------------------------------------------- static st_s* tbman_alloc_challenge ( fp_alloc alloc, uz_t table_size, uz_t cycles, uz_t max_alloc, u2_t seed, bl_t cleanup, bl_t verbose ) { st_s* str = st_s_create(); vd_t* data_table = malloc( table_size * sizeof( vd_t ) ); uz_t* size_table = malloc( table_size * sizeof( uz_t ) ); for( uz_t i = 0; i < table_size; i++ ) data_table[ i ] = NULL; for( uz_t i = 0; i < table_size; i++ ) size_table[ i ] = 0; u2_t rval = seed; uz_t alloc_attempts = 0; uz_t realloc_attempts = 0; uz_t free_attempts = 0; uz_t alloc_failures = 0; uz_t realloc_failures = 0; uz_t free_failures = 0; for( uz_t j = 0; j < cycles; j++ ) { for( uz_t i = 0; i < table_size; i++ ) { rval = bcore_xsg_u2( rval ); uz_t idx = rval % table_size; // verify table content if( size_table[ idx ] > 0 ) { u2_t rv = bcore_xsg_u2( idx + 1 ); uint8_t* data = data_table[ idx ]; uz_t sz = size_table[ idx ]; for( uz_t i = 0; i < sz; i++ ) { rv = bcore_xsg_u2( rv ); if( data[ i ] != ( rv & 255 ) ) { ERR( "data failure [%u vs %u].", ( u2_t )data[ i ], ( u2_t )( rv & 255 ) ); } } } if( data_table[ idx ] == NULL ) { rval = bcore_xsg_u2( rval ); uz_t size = pow( ( double )max_alloc, ( rval * pow( 2.0, -32 ) ) ); data_table[ idx ] = alloc( data_table[ idx ], 0, size, &size_table[ idx ] ); alloc_attempts++; alloc_failures += ( size > 0 ) && ( data_table[ idx ] == NULL ); // set new content if( size_table[ idx ] > 0 ) { u2_t rv = bcore_xsg_u2( idx + 1 ); uint8_t* data = data_table[ idx ]; uz_t sz = size_table[ idx ]; for( uz_t i = 0; i < sz; i++ ) data[ i ] = ( ( rv = bcore_xsg_u2( rv ) ) & 255 ); } } else { rval = bcore_xsg_u2( rval ); if( rval & 32 ) { data_table[ idx ] = alloc( data_table[ idx ], size_table[ idx ], 0, &size_table[ idx ] ); // free free_attempts++; free_failures += ( data_table[ idx ] != NULL ); } else { rval = bcore_xsg_u2( rval ); uz_t size = pow( ( double )max_alloc, rval * pow( 2.0, -32 ) ); uz_t new_size = 0; data_table[ idx ] = alloc( data_table[ idx ], size_table[ idx ], size, &new_size ); // realloc // verify old table content (only when size > sz - stdlib realloc does not seem to retain data otherwise) if( size > size_table[ idx ] ) { if( data_table[ idx ] != NULL && size_table[ idx ] > 0 ) { u2_t rv = bcore_xsg_u2( idx + 1 ); uint8_t* data = data_table[ idx ]; uz_t sz = size_table[ idx ]; for( uz_t i = 0; i < sz; i++ ) { rv = bcore_xsg_u2( rv ); if( data[ i ] != ( rv & 255 ) ) { ERR( "data failure [%u vs %u].", ( u2_t )data[ i ], ( u2_t )( rv & 255 ) ); } } } } size_table[ idx ] = new_size; //( data_table[ idx ] != NULL ) ? size : 0; realloc_attempts++; realloc_failures += ( size > 0 ) && ( data_table[ idx ] == NULL ); // set new content if( size_table[ idx ] > 0 ) { u2_t rv = bcore_xsg_u2( idx + 1 ); uint8_t* data = data_table[ idx ]; uz_t sz = size_table[ idx ]; for( uz_t i = 0; i < sz; i++ ) data[ i ] = ( ( rv = bcore_xsg_u2( rv ) ) & 255 ); } } } } } uz_t allocated_table_size = 0; for( uz_t i = 0; i < table_size; i++ ) allocated_table_size += ( data_table[ i ] != NULL ); if( verbose ) { st_s_pushf( str, "cycles ............... %zu\n", cycles ); st_s_pushf( str, "max alloc ............ %zu\n", max_alloc ); st_s_pushf( str, "Instances\n" ); st_s_pushf( str, " total .............. %zu\n", table_size ); st_s_pushf( str, " allocated .......... %zu\n", allocated_table_size ); st_s_pushf( str, "Alloc\n" ); st_s_pushf( str, " attempts .......... %zu\n", alloc_attempts ); st_s_pushf( str, " failures .......... %zu\n", alloc_failures ); st_s_pushf( str, "Realloc\n" ); st_s_pushf( str, " attempts .......... %zu\n", realloc_attempts ); st_s_pushf( str, " failures .......... %zu\n", realloc_failures ); st_s_pushf( str, "Free\n" ); st_s_pushf( str, " attempts .......... %zu\n", free_attempts ); st_s_pushf( str, " failures .......... %zu\n", free_failures ); } // speed test { clock_t time = clock(); for( uz_t j = 0; j < cycles; j++ ) { for( uz_t i = 0; i < table_size; i++ ) { rval = bcore_xsg_u2( rval ); uz_t idx = rval % table_size; if( data_table[ idx ] == NULL ) { uz_t size = pow( ( double )max_alloc, rval * pow( 2.0, -32 ) ); data_table[ idx ] = alloc( data_table[ idx ], 0, size, &size_table[ idx ] ); } else { data_table[ idx ] = alloc( data_table[ idx ], size_table[ idx ], 0, &size_table[ idx ] ); // free } } } time = clock() - time; st_s_pushf( str, "speed test alloc-free: %5.3gs\n", ( double )time / ( CLOCKS_PER_SEC * cycles * table_size ) ); } // speed test { clock_t time = clock(); for( uz_t j = 0; j < cycles; j++ ) { for( uz_t i = 0; i < table_size; i++ ) { rval = bcore_xsg_u2( rval ); uz_t idx = rval % table_size; rval = bcore_xsg_u2( rval ); uz_t size = pow( ( double )max_alloc, rval * pow( 2.0, -32 ) ); data_table[ idx ] = alloc( data_table[ idx ], size_table[ idx ], size, &size_table[ idx ] ); // realloc } } time = clock() - time; st_s_pushf( str, "speed test realloc: %5.3gs\n", ( double )time / ( CLOCKS_PER_SEC * cycles * table_size ) ); } // cleanup if( cleanup ) for( uz_t i = 0; i < table_size; i++ ) data_table[ i ] = alloc( data_table[ i ], size_table[ i ], 0, NULL ); free( size_table ); free( data_table ); return str; } // --------------------------------------------------------------------------------------------------------------------- static void tbman_s_quicktest( void ) { uz_t table_size = 200; uz_t cycles = 1; uz_t max_alloc = 4096; uz_t seed = 5479; st_s_discard( tbman_alloc_challenge( bcore_tbman_bn_alloc, table_size, cycles, max_alloc, seed, true, false ) ); } // --------------------------------------------------------------------------------------------------------------------- /// testing reference control static st_s* tbman_s_rctest( void ) { st_s* log = st_s_createf( "== tbman_s_rctest " ); st_s_push_char_n( log, '=', 80 - log->size ); st_s_push_char( log, '\n' ); typedef struct myclass { st_s name1; st_s* name2; u3_t v1; u3_t* v2; } myclass; tp_t t_myclass = bcore_flect_type_parse_sc( "{ st_s name1; st_s => name2; u3_t v1; u3_t => v2; }" ); bcore_inst_t_discard( t_myclass, bcore_inst_t_create( t_myclass ) ); // cycle once to get all perspectives alive myclass* obj1 = bcore_inst_t_create( t_myclass ); myclass* obj2 = bcore_inst_t_create( t_myclass ); uz_t arr_size = 100000; myclass* obj_arr = bcore_tbman_malloc( sizeof( myclass ) * arr_size ); for( uz_t i = 0; i < arr_size; i++ ) { bcore_inst_t_init( t_myclass, (bcore_inst*)&obj_arr[ i ] ); st_s_pushf( &obj_arr[ i ].name1, "Hi!" ); obj_arr[ i ].name2 = st_s_createf( "Ho!" ); } obj_arr = bcore_tbman_fork( obj_arr ); bcore_tbman_release_arg_arr( ( fp_down_arg )bcore_inst_p_down, bcore_inst_s_get_typed( t_myclass ), obj_arr, arr_size, sizeof( myclass ) ); vd_t* ref_arr1 = bcore_tbman_u_alloc( sizeof( vd_t ), NULL, arr_size, NULL ); vd_t* ref_arr2 = bcore_tbman_u_alloc( sizeof( vd_t ), NULL, arr_size, NULL ); { clock_t time = clock(); for( uz_t i = 0; i < arr_size; i++ ) { ref_arr1[ i ] = bcore_tbman_fork( &obj_arr[ i ].name1 ); } time = clock() - time; st_s_pushf( log, "fork 1 ..... %zuns\n", ( uz_t )( ( ( double )time * 1E9 ) / ( CLOCKS_PER_SEC * arr_size ) ) ); } { clock_t time = clock(); for( uz_t i = 0; i < arr_size; i++ ) { ref_arr2[ i ] = bcore_tbman_fork( &obj_arr[ i ].name1 ); } time = clock() - time; st_s_pushf( log, "fork 2 ..... %zuns\n", ( uz_t )( ( ( double )time * 1E9 ) / ( CLOCKS_PER_SEC * arr_size ) ) ); } st_s* obj2_name1 = bcore_tbman_fork( &obj2->name1 ); st_s_pushf( obj2_name1, "Hi!" ); bcore_tbman_release_arg( ( fp_down_arg )bcore_inst_p_down, bcore_inst_s_get_typed( t_myclass ), obj1 ); bcore_tbman_release_arg( ( fp_down_arg )bcore_inst_p_down, bcore_inst_s_get_typed( t_myclass ), obj2 ); bcore_tbman_release( obj2_name1 ); st_s_pushf( log, "obj_arr references %zu\n", bcore_tbman_references( obj_arr ) ); { clock_t time = clock(); for( uz_t i = 0; i < arr_size; i++ ) { bcore_tbman_release( ref_arr1[ i ] ); } time = clock() - time; st_s_pushf( log, "release 1 .. %zuns\n", ( uz_t )( ( ( double )time * 1E9 ) / ( CLOCKS_PER_SEC * arr_size ) ) ); } { clock_t time = clock(); for( uz_t i = 0; i < arr_size; i++ ) { bcore_tbman_release( ref_arr2[ i ] ); } time = clock() - time; st_s_pushf( log, "release 2 .. %zuns\n", ( uz_t )( ( ( double )time * 1E9 ) / ( CLOCKS_PER_SEC * arr_size ) ) ); } st_s_pushf( log, "obj_arr references %zu\n", bcore_tbman_references( obj_arr ) ); bcore_tbman_release( obj_arr ); st_s_pushf( log, "obj_arr references %zu\n", bcore_tbman_references( obj_arr ) ); bcore_tbman_release( ref_arr1 ); bcore_tbman_release( ref_arr2 ); st_s_push_char_n( log, '=', 80 ); st_s_push_char( log, '\n' ); st_s_push_st_d( log, bcore_tbman_s_status( tbman_s_g, 1 ) ); return log; } // --------------------------------------------------------------------------------------------------------------------- static st_s* tbman_s_memtest( void ) { st_s* log = st_s_createf( "== tbman_s_memtest " ); st_s_push_char_n( log, '=', 80 - log->size ); st_s_push_char( log, '\n' ); uz_t table_size = 100000; uz_t cycles = 5; uz_t max_alloc = 65536; uz_t seed = 1237; { st_s_pushf( log, "\nbcore_internal_alloc:\n"); st_s_push_st_d( log, tbman_alloc_challenge( bcore_tbman_bn_alloc, table_size, cycles, max_alloc, seed, true, false ) ); st_s_push_st_d( log, bcore_tbman_s_status( tbman_s_g, 1 ) ); // st_s_push_st_d( log, bcore_btree_vd_s_status( m->internal_btree ) ); } { st_s_pushf( log, "\nbcore_external_alloc:\n"); st_s_push_st_d( log, tbman_alloc_challenge( bcore_tbman_external_bn_alloc, table_size, cycles, max_alloc, seed, true, false ) ); } st_s_push_char_n( log, '=', 80 ); st_s_push_char( log, '\n' ); return log; } // --------------------------------------------------------------------------------------------------------------------- vd_t tbman_s_thread_func( vd_t arg ) { st_s* log = st_s_create(); uz_t table_size = 10000; uz_t cycles = 5; uz_t max_alloc = 65536; uz_t seed = 1237; st_s_push_st_d( log, tbman_alloc_challenge( bcore_tbman_bn_alloc, table_size, cycles, max_alloc, seed, true, false ) ); // st_s_push_st_d( log, tbman_alloc_challenge( bcore_tbman_external_bn_alloc, table_size, cycles, max_alloc, seed, true, false ) ); return log; } // --------------------------------------------------------------------------------------------------------------------- static st_s* tbman_s_thread_test( void ) { st_s* log = st_s_create(); bcore_thread_s th = bcore_thread_call( tbman_s_thread_func, NULL ); { st_s* log_l = bcore_thread_join( th ); st_s_push_fa( log, "single thread:\n#<st_s*>\n", log_l ); st_s_discard( log_l ); } bcore_thread_s th1 = bcore_thread_call( tbman_s_thread_func, NULL ); bcore_thread_s th2 = bcore_thread_call( tbman_s_thread_func, NULL ); bcore_thread_s th3 = bcore_thread_call( tbman_s_thread_func, NULL ); bcore_thread_s th4 = bcore_thread_call( tbman_s_thread_func, NULL ); { st_s* log_l = bcore_thread_join( th1 ); st_s_push_fa( log, "thread1:\n#<st_s*>\n", log_l ); st_s_discard( log_l ); } { st_s* log_l = bcore_thread_join( th2 ); st_s_push_fa( log, "thread2:\n#<st_s*>\n", log_l ); st_s_discard( log_l ); } { st_s* log_l = bcore_thread_join( th3 ); st_s_push_fa( log, "thread3:\n#<st_s*>\n", log_l ); st_s_discard( log_l ); } { st_s* log_l = bcore_thread_join( th4 ); st_s_push_fa( log, "thread4:\n#<st_s*>\n", log_l ); st_s_discard( log_l ); } return log; } // --------------------------------------------------------------------------------------------------------------------- static void tbman_s_instance_test( void ) { for( uz_t size = 1; size < 10000000; size *= 2 ) { uz_t space = 0; vd_t ptr = bcore_tbman_bn_alloc( NULL, 0, size, &space ); uz_t instance_space = 0; vd_t instance_root = NULL; bcore_tbman_get_instance( ( u0_t* )ptr + ( size >> 1 ), &instance_root, &instance_space ); ASSERT( instance_root == ptr ); ASSERT( instance_space == space ); bcore_tbman_free( ptr ); } } // --------------------------------------------------------------------------------------------------------------------- typedef struct diagnostic_s { bcore_tbman_s* man; vd_t* ptr_arr; uz_t* spc_arr; sz_t size; } diagnostic_s; static void tbman_s_diagnostic_test_callback( vd_t arg, vd_t ptr, uz_t space ) { diagnostic_s* d = arg; bl_t found = false; for( sz_t i = 0; i < d->size; i++ ) { if( ptr == d->ptr_arr[ i ] ) { found = true; ASSERT( space == d->spc_arr[ i ] ); } } ASSERT( found ); bcore_tbman_s_b_alloc( d->man, ptr, 0, NULL ); } static void tbman_s_diagnostic_test( void ) { diagnostic_s diag; diag.man = bcore_tbman_s_create_default(); diag.size = 1000; diag.ptr_arr = bcore_malloc( sizeof( vd_t ) * diag.size ); diag.spc_arr = bcore_malloc( sizeof( sz_t ) * diag.size ); u2_t rval = 1234; for( sz_t i = 0; i < diag.size; i++ ) { rval = bcore_xsg_u2( rval ); sz_t size = rval % 20000; diag.ptr_arr[ i ] = bcore_tbman_s_b_alloc( diag.man, NULL, size, &diag.spc_arr[ i ] ); } ASSERT( bcore_tbman_s_total_instances( diag.man ) == diag.size ); // the callback function frees memory bcore_tbman_s_for_each_instance( diag.man, tbman_s_diagnostic_test_callback, &diag ); ASSERT( bcore_tbman_s_total_granted_space( diag.man ) == 0 ); ASSERT( bcore_tbman_s_total_instances( diag.man ) == 0 ); diag.ptr_arr = bcore_free( diag.ptr_arr ); diag.spc_arr = bcore_free( diag.spc_arr ); bcore_tbman_s_discard( diag.man ); } // --------------------------------------------------------------------------------------------------------------------- /**********************************************************************************************************************/ // signal // --------------------------------------------------------------------------------------------------------------------- vd_t bcore_tbman_signal_handler( const bcore_signal_s* o ) { switch( bcore_signal_s_handle_type( o, typeof( "bcore_tbman" ) ) ) { case TYPEOF_init0: { tbman_open(); } break; case TYPEOF_init1: { tbman_s_quicktest(); // system critical test } break; case TYPEOF_down0: { s2_t verbosity = o->object ? *( s2_t* )o->object : 0; if( verbosity >= 0 ) { uz_t space = bcore_tbman_total_granted_space(); if( space > 0 ) { uz_t instances = bcore_tbman_total_instances(); uz_t references = bcore_tbman_total_references(); st_s_print_d( bcore_tbman_s_status( tbman_s_g, 1 ) ); WRN ( "Leaking memory .... %zu bytes\n" " instances .... %zu\n" " references ... %zu\n", space, instances, references ); } } tbman_close(); } break; case TYPEOF_selftest: { st_s* log = st_s_create(); tbman_s_diagnostic_test(); tbman_s_instance_test(); st_s_push_st_d( log, tbman_s_thread_test() ); st_s_push_st_d( log, tbman_s_rctest() ); st_s_push_st_d( log, tbman_s_memtest() ); return log; } break; default: break; } return NULL; } // --------------------------------------------------------------------------------------------------------------------- /**********************************************************************************************************************/
36.569123
153
0.483942
[ "object" ]
c2e60d836a60ca49ae52ea00ebd32490218d8a10
31,835
h
C
tensorflow_fold/llgtm/graph.h
shkarupa-alex/fold
0e7ca14832a14a5f2009d4e0424783a80e7d7a2c
[ "Apache-2.0" ]
2,020
2017-02-07T18:43:35.000Z
2022-03-19T11:54:04.000Z
tensorflow_fold/llgtm/graph.h
shkarupa-alex/fold
0e7ca14832a14a5f2009d4e0424783a80e7d7a2c
[ "Apache-2.0" ]
103
2017-02-08T11:07:27.000Z
2021-04-25T19:01:01.000Z
tensorflow_fold/llgtm/graph.h
shkarupa-alex/fold
0e7ca14832a14a5f2009d4e0424783a80e7d7a2c
[ "Apache-2.0" ]
346
2017-02-07T20:45:43.000Z
2022-03-02T15:11:11.000Z
/* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Interface for building and executing graphs of tensor operations. // // LLGTM uses a define-by-run semantics. A model is a C++ program that // performs a sequence of tensor operations. The C++ code may interleave // tensor operations with control-flow, loops, functions, recursion, I/O etc. // Each time a tensor operation is performed, a node is added to the Graph, // which allows gradients of the tensor operations to be computed later. // // See examples folder for API usage examples. // // See design doc at https://go/llgtm-doc for more information. #ifndef TENSORFLOW_FOLD_LLGTM_GRAPH_H_ #define TENSORFLOW_FOLD_LLGTM_GRAPH_H_ #include <memory> #include <iostream> #include <vector> #include "tensorflow_fold/llgtm/device.h" #include "tensorflow_fold/llgtm/gradients.h" #include "tensorflow_fold/llgtm/graph_implementation.h" #include "tensorflow_fold/llgtm/platform/platform.h" #include "tensorflow_fold/llgtm/tensor.h" #include "tensorflow_fold/llgtm/tensor_opcodes.h" #include "tensorflow_fold/llgtm/tensor_ops.h" #include "tensorflow_fold/llgtm/util.h" #include "absl/types/span.h" namespace llgtm { class GraphEvaluator; // A Graph serves as a factory for building a Tensor AST. The AST is a // directed acyclic graph. Tensor AST nodes must always be created as part of // a Graph, which encapsulates the AST, and manages memory for both the AST // nodes, and for intermediate results. class Graph { public: // InputList is used to pass a list of inputs to some operations. // It is guaranteed to support operator[], and be constructable from // std::initializer_list. Clients should not rely on other operations. using InputList = GraphImplementation::InputList; template<class DT> using InputListT = GraphImplementation::InputListT<DT>; Graph() = delete; Graph(const Graph& g) = delete; Graph(Graph&& g) = default; explicit Graph(GraphEvaluator* evaluator, GraphImplementation* impl, uint64 seed, bool is_custom_seed, DeviceID device) : evaluator_(evaluator), implementation_(impl), seed_(seed), is_custom_seed_(is_custom_seed), device_(device) {} ~Graph(); Graph& operator=(const Graph& g) = delete; Graph& operator=(Graph&& g) = default; // Create a tuple of the given size, with null tensors. // Intended mainly for internal use, as the gradient of multi-output tensors. TensorBase Tuple(int num_tensors, DeviceID device) { TensorBase* inputs = allocate_inputs(num_tensors); return emplace_node_base<nodes::Tuple>(num_tensors, inputs, device); } // Create a tuple of tensors. TensorBase Tuple(InputList tensors) { TensorBase* inputs = make_inputs(tensors); DeviceID device = tensors.empty() ? kDeviceIDUnspecified : tensors[0].device(); return emplace_node_base<nodes::Tuple>(tensors.size(), inputs, device); } // Get the i^th output of a multi-output tensor. TensorBase GetOutput(TensorBase a, int i) { if (a.is_tuple()) { // For tuples, just return the original tensor. return a.sub_expression(i); } else { CHECK(a.get()->is_valid_output_index(i)); // We pre-allocated GetOutput nodes for multi-output nodes. nodes::TensorNodeBase* node = nodes_[a.get()->output_id(i)]; DCHECK(node->opcode() == kOpGetOutput); DCHECK_EQ(node->sub_expression(0).get(), a.get()); return TensorBase(node); } } // Create a new constant value, from existing data. // The value does not assume ownership of data, and may or may not copy it. // Callers should not attempt to change data until the graph has executed. template<typename DT> Tensor<DT> Value(const Dimensions& dims, DT* data, DeviceID device = kDeviceIDUnspecified) { auto* otype = make_output_type<DT>(dims); return emplace_node<DT, nodes::TensorValue<DT>>(otype, data, device); } // Return a tensor that represents the value of the given variable. template<typename DT> Tensor<DT> Variable(Variable<DT>* variable, DeviceID device = kDeviceIDUnspecified) { return emplace_node<DT, nodes::TensorVariable<DT>>(variable, device); } // Adds the given tensor to the given variable. // Used by Trainers to apply gradients. template<typename DT> inline void AssignAdd(llgtm::Variable<DT>* variable, Tensor<DT> a) { CHECK_EQ(a.dimensions(), variable->dimensions()); auto* inputs = make_inputs(std::move(a)); emplace_node_base<nodes::AssignAdd<DT>>(inputs, variable); } // Create a new constant value, initialized to zero. template<typename DT> Tensor<DT> Zeros(const Dimensions& dims, DeviceID device = kDeviceIDUnspecified) { auto* otype = make_output_type<DT>(dims); return emplace_node<DT, nodes::Zeros<DT>>(otype, device); } // Create a random constant value with uniform distribution. template<typename DT> Tensor<DT> UniformRandom(const Dimensions& dims, uint64 seed = 0, DeviceID device = kDeviceIDUnspecified) { bool is_custom_seed = seed != 0 || is_custom_seed_; uint64 real_seed = seed == 0 ? this->next_seed() : seed; auto* otype = make_output_type<DT>(dims); return emplace_node<DT, nodes::UniformRandom<DT>>( otype, real_seed, is_custom_seed, device); } // Create a random constant value with normal distribution. template<typename DT> Tensor<DT> NormalRandom(const Dimensions& dims, uint64 seed = 0, DeviceID device = kDeviceIDUnspecified) { bool is_custom_seed = seed != 0 || is_custom_seed_; uint64 real_seed = seed == 0 ? this->next_seed() : seed; auto* otype = make_output_type<DT>(dims); return emplace_node<DT, nodes::NormalRandom<DT>>( otype, real_seed, is_custom_seed, device); } // Create a new constant value, initialized to one. template<typename DT> Tensor<DT> Ones(const Dimensions& dims, DeviceID device = kDeviceIDUnspecified) { return this->ConstantFromScalar<DT>(dims, 1, device); } // Create a new constant value, intialized with a lambda. // f(i,j) will be invoked for each element i,j in the matrix. template<typename DT, int R, typename F> Tensor<DT> ConstantFromFunction(const Dimensions& dims, F f, DeviceID device = kDeviceIDUnspecified) { auto* otype = make_output_type<DT>(dims); return emplace_node<DT, nodes::ConstantFromFunction<DT, R, F>>( otype, f, device); } // Initialize a tensor with a constant value. template<typename DT> Tensor<DT> ConstantFromScalar(const Dimensions& dims, DT value, DeviceID device = kDeviceIDUnspecified) { auto* otype = make_output_type<DT>(dims); return emplace_node<DT, nodes::ConstantFromScalar<DT>>( otype, value, device); } // Negate a tensor element-wise. template<typename DT> Tensor<DT> Negative(Tensor<DT> a) { auto* otype = &a.tensor_type(); auto* inputs = make_inputs(std::move(a)); return emplace_node<DT, nodes::Negative<DT>>(inputs, otype); } // Add two tensors element-wise. template<typename DT> Tensor<DT> Add(Tensor<DT> a, Tensor<DT> b) { CHECK_EQ(a.dimensions(), b.dimensions()); auto* otype = &a.tensor_type(); auto* inputs = make_inputs(std::move(a), std::move(b)); return emplace_node<DT, nodes::Add<DT>>(inputs, otype); } // Subtract two tensors element-wise. template<typename DT> Tensor<DT> Subtract(Tensor<DT> a, Tensor<DT> b) { return this->Add(std::move(a), this->Negative<DT>(std::move(b))); } // Invert a tensor element-wise. template<typename DT> Tensor<DT> Reciprocal(Tensor<DT> a) { auto* otype = &a.tensor_type(); auto* inputs = make_inputs(std::move(a)); return emplace_node<DT, nodes::Reciprocal<DT>>(inputs, otype); } // Multiply two tensors element-wise. template<typename DT> Tensor<DT> Multiply(Tensor<DT> a, Tensor<DT> b) { CHECK_EQ(a.dimensions(), b.dimensions()); auto* otype = &a.tensor_type(); auto* inputs = make_inputs(std::move(a), std::move(b)); return emplace_node<DT, nodes::Multiply<DT>>(inputs, otype); } // Divide two tensors element-wise. template<typename DT> Tensor<DT> Divide(Tensor<DT> a, Tensor<DT> b) { return this->Multiply(std::move(a), this->Reciprocal<DT>(std::move(b))); } // Compute element-wise sigmoid of a tensor. template<typename DT> Tensor<DT> Sigmoid(Tensor<DT> a) { auto* otype = &a.tensor_type(); auto* inputs = make_inputs(std::move(a)); return emplace_node<DT, nodes::Sigmoid<DT>>(inputs, otype); } // Compute element-wise hyperbolic tangent of a tensor. template<typename DT> Tensor<DT> Tanh(Tensor<DT> a) { auto* otype = &a.tensor_type(); auto* inputs = make_inputs(std::move(a)); return emplace_node<DT, nodes::Tanh<DT>>(inputs, otype); } // Compute element-wise ReLU of a tensor. template<typename DT> Tensor<DT> Relu(Tensor<DT> a) { auto* otype = &a.tensor_type(); auto* inputs = make_inputs(std::move(a)); return emplace_node<DT, nodes::Relu<DT>>(inputs, otype); } // Compute element-wise first derivative of ReLU of a tensor and multiply // by error. template<typename DT> Tensor<DT> ReluGrad(Tensor<DT> error, Tensor<DT> a) { DCHECK_EQ(a.dimensions(), error.dimensions()); auto* otype = &a.tensor_type(); auto* inputs = make_inputs(std::move(error), std::move(a)); return emplace_node<DT, nodes::ReluGrad<DT>>(inputs, otype); } // Return a tensor with the same number of elements, but different dimensions // and rank. template<typename DT> Tensor<DT> Reshape(Tensor<DT> a, Dimensions dims) { auto* otype = make_output_type<DT>(dims); auto* inputs = make_inputs(std::move(a)); return emplace_node<DT, nodes::Reshape<DT>>(inputs, otype); } // Broadcast a Tensor over the given dimensions. The contents of Tensor 'a' // will be copied/tiled to fill in the larger result tensor. // Broadcast does not change rank; Reshape must be used to change rank. // a.dimension(i) must either be 1, or equal to dims[i] template<typename DT> Tensor<DT> Broadcast(Tensor<DT> a, const Dimensions& dims) { nodes::Broadcast<DT>::CheckBroadcastDimensions(a.dimensions(), dims); auto* otype = make_output_type<DT>(dims); auto* inputs = make_inputs(std::move(a)); return emplace_node<DT, nodes::Broadcast<DT>>(inputs, otype); } // Take the sum of rows or columns. The rank of the tensor stays the same. template<typename DT> Tensor<DT> ReduceSum(Tensor<DT> a, const Dimensions& dims) { nodes::ReduceSum<DT>::CheckReduceDimensions(a.dimensions(), dims); auto* otype = make_output_type<DT>(dims); auto* inputs = make_inputs(std::move(a)); return emplace_node<DT, nodes::ReduceSum<DT>>(inputs, otype); } // Take the sum of rows or columns. The rank of the tensor stays the same. // Indices is a list of dimensions to reduce. For each i in indices, // dimension(i) is changed to 1; this is the same as keep_dims=true in TF. // Note: Dimensions can be initialized with an std::initializer_list, but // the compiler will choose this overload when an initializer list is passed, // because this overload is a "perfect fit". // See also: https://goo.gl/t6ZMMr template<typename DT> Tensor<DT> ReduceSum(Tensor<DT> a, const std::initializer_list<int>& indices) { auto dims = nodes::ReduceSum<DT>::ReducedDimensions( a.dimensions(), indices); return ReduceSum(a, dims); } // Gathers a subset of columns or rows from Tensor 'a', with the indices // given by indices. The dimensions of the output are the same as a, except // that the 'axis' dimension is the same size as 'indices'. // Indices may contain duplicates. template<typename DT> Tensor<DT> Gather(Tensor<int32_t> indices, Tensor<DT> a, int axis = 0) { CHECK_EQ(indices.rank(), 1); CHECK_LE(axis, a.rank()); auto* otype = make_output_type<DT>( nodes::Gather<DT>::OutputDimensions(a.dimensions(), axis, indices.dimension(0))); auto* inputs = make_inputs(std::move(indices), std::move(a)); return emplace_node<DT, nodes::Gather<DT>>(inputs, otype, axis); } // Scatters the values in Tensor 'a' over a larger output tensor. The columns // or rows in 'a' will be copied to the positions given by indices, and all // other values will be initialized to zero. The dimensions of the output // tensor are the same as a, except the 'axis' dimension is num_rows. // Indices may contain duplicates. template<typename DT> Tensor<DT> Scatter(Dimensions::IndexType num_rows, Tensor<int32_t> indices, Tensor<DT> a, int axis = 0) { CHECK_EQ(indices.rank(), 1); CHECK_EQ(indices.dimension(0), a.dimension(axis)); CHECK_LE(axis, a.rank()); auto* otype = make_output_type<DT>( nodes::Gather<DT>::OutputDimensions(a.dimensions(), axis, num_rows)); auto* inputs = make_inputs(std::move(indices), std::move(a)); return emplace_node<DT, nodes::Scatter<DT>>(inputs, otype, axis); } // Transpose (reorder) a tensor according to dim_indices. // dim_indices stores the indices of the transposition and not the resulting // dimensions. template<typename DT> Tensor<DT> Transpose(Tensor<DT> a, const DimensionIndices& dim_indices) { nodes::Transpose<DT>::CheckTransposeIndices(a.dimensions(), dim_indices); auto* otype = make_output_type<DT>( nodes::Transpose<DT>::TransposedDimensions(a.dimensions(), dim_indices)); auto* inputs = make_inputs(std::move(a)); return emplace_node<DT, nodes::Transpose<DT>>(inputs, otype, dim_indices); } template<typename DT> Tensor<DT> Transpose(Tensor<DT> a) { return this->Transpose<DT>(a, { 1, 0 }); } // Multiply two matrices. template<typename DT> Tensor<DT> Matmul(Tensor<DT> a, Tensor<DT> b) { auto* otype = make_output_type<DT>( nodes::Matmul<DT>::ResultDimensions(a.dimensions(), b.dimensions())); auto* inputs = make_inputs(std::move(a), std::move(b)); return emplace_node<DT, nodes::Matmul<DT>>(inputs, otype); } // A concatenation of two or more tensors. The `tensors` Span will be copied // and its memory can be released after calling this method. template<typename DT> Tensor<DT> Concat(InputListT<DT> tensors, int axis) { // Compute new dimensions, and do safety checks (only one output per input // tensor, at least two inputs, and dimensions match). auto* otypes = make_output_type<DT>( nodes::Concat<DT>::ConcatenatedDimensions(tensors, axis)); auto* inputs = make_inputs(tensors); return emplace_node<DT, nodes::Concat<DT>>(tensors.size(), inputs, otypes, axis); } // A concatenation of two tensors. template<typename DT> Tensor<DT> Concat(const Tensor<DT>& a, const Tensor<DT>& b, int axis) { return this->Concat<DT>({ a, b }, axis); } // Split a tensor into multiple parts of given sizes along a given axis. template<typename DT> TensorBase Split(Tensor<DT> a, const absl::Span<const Dimensions::IndexType> in_sizes, int axis, bool copy_sizes = true) { // Copy sizes to arena if requested (default: yes). auto sizes = copy_sizes ? copy_span_to_arena(in_sizes) : in_sizes; auto* output_types = allocate_output_types(sizes.size()); nodes::Split<DT>::InitializeOutputTypes(a.dimensions(), output_types, sizes, axis); auto* inputs = make_inputs(std::move(a)); return emplace_node_base<nodes::Split<DT>>( inputs, output_types, sizes, axis); } // Split a tensor into equally-sized parts along a given axis. template<typename DT> TensorBase Split(Tensor<DT> a, int num_parts, int axis) { CHECK_GE(num_parts, 2); auto* memory = reinterpret_cast<Dimensions::IndexType*>( AllocateInArena(sizeof(Dimensions::IndexType) * num_parts)); absl::Span<Dimensions::IndexType> sizes = absl::MakeSpan(memory, num_parts); Dimensions::IndexType part_size = a.dimension(axis) / num_parts; for (int i = 0; i < num_parts; ++i) { sizes[i] = part_size; } // Last part might be a bit bigger. sizes[num_parts - 1] += a.dimension(axis) % num_parts; return Split(a, sizes, axis); } // Apply softmax to a tensor of rank 1 or rank 2. If the tensor is of rank 2, // then the first dimension is the batch dimension and the second dimension // is being summed over. template<typename DT> Tensor<DT> Softmax(Tensor<DT> a) { static_assert(std::is_floating_point<DT>::value, "Only floating point tensors allowed for Softmax."); auto* otype = &a.tensor_type(); auto* inputs = make_inputs(std::move(a)); return emplace_node<DT, nodes::Softmax<DT>>(inputs, otype); } // Calculate the cross-entropy between two probability distributions `labels` // and `probabilities`. This operation currently supports softmax only. template<typename DT> Tensor<DT> CrossEntropyLoss(Tensor<DT> labels, Tensor<DT> probabilities) { DCHECK_EQ(labels.dimensions(), probabilities.dimensions()); DCHECK_LE(probabilities.dimensions().rank(), 2); TensorOpcode opcode = probabilities.get()->opcode(); auto reduced_dims = nodes::SoftmaxCrossEntropy<DT>::ReducedDimensions( probabilities.dimensions()); auto* otype = make_output_type<DT>(reduced_dims); auto* inputs = make_inputs(std::move(labels), std::move(probabilities)); switch (opcode) { case kOpSoftmax: return emplace_node<DT, nodes::SoftmaxCrossEntropy<DT>>(inputs, otype); default: LOG(FATAL) << "Not implemented: Cross entropy for " << opcode_name(opcode); } } // Calculate the sparse cross-entropy between two probability distributions // `labels` and `probabilities`. I.e., the first distribution assigns `1.0` // to asingle category per batch element. The indices of those categories are // specified by `labels`. This operation currently supports softmax only. template<typename DT> Tensor<DT> SparseCrossEntropyLoss(Tensor<int32_t> labels, Tensor<DT> probabilities) { DCHECK_EQ(labels.dimensions().rank(), probabilities.dimensions().rank() - 1); DCHECK_LE(probabilities.dimensions().rank(), 2); if (probabilities.dimensions().rank() == 2) { // `labels` is a scalar for Rank 1 operations. DCHECK_EQ(labels.dimension(0), probabilities.dimension(0)); } TensorOpcode opcode = probabilities.get()->opcode(); auto* otype = make_output_type<DT>( nodes::SoftmaxCrossEntropy<DT>::ReducedDimensions( probabilities.dimensions())); auto* inputs = make_inputs(std::move(labels), std::move(probabilities)); switch (opcode) { case kOpSoftmax: return emplace_node<DT, nodes::SoftmaxSparseCrossEntropy<DT>>(inputs, otype); default: LOG(FATAL) << "Not implemented: Sparse cross entropy for " << opcode_name(opcode); } } // Calculates the gradient of `SparseCrossEntropy(labels, Softmax(logits))` // in terms of `logits`. template<typename DT> Tensor<DT> SoftmaxSparseCrossEntropyGrad(Tensor<int32_t> labels, Tensor<DT> softmax) { DCHECK_EQ(labels.dimensions().rank(), softmax.dimensions().rank() - 1); DCHECK_LE(softmax.dimensions().rank(), 2); auto* otype = &softmax.tensor_type(); auto* inputs = make_inputs(std::move(labels), std::move(softmax)); return emplace_node<DT, nodes::SoftmaxSparseCrossEntropyGrad<DT>>(inputs, otype); } // Copies a tensor to another device. If the source device equals the // destination device, no copy is performed. template<typename DT> Tensor<DT> CopyToDevice(Tensor<DT> a, DeviceID device) { // TODO(matthiasspringer): Implement block copy of memory. auto* otype = &a.tensor_type(); auto* inputs = make_inputs(std::move(a)); return emplace_node<DT, nodes::CopyToDevice<DT>>(inputs, otype, device); } // Invokes a layer. // An optimizing evaluation engine may JIT-compile code for the layer. TensorBase Layer(class Layer* layer, InputList inputs, DeviceID device = kDeviceIDUnspecified) { return implementation_->Layer(this, layer, inputs, device); } // Evaluate all nodes which have been created up until this point. // Returns the number of nodes which were evaluated. inline int Eval() { return implementation_->Eval(this); } // Compute gradients of the graph with respect to loss. void ComputeGradients(Gradients* gradients, Tensor<float> loss) { gradients->ComputeGradients(this, std::move(loss)); } // Dump a pretty-printed version of the Graph to out. void Dump(std::ostream& out); // Return a Tensor that contains the sum of the gradients for variable v. template<class DT> Tensor<DT> Gradient(const Gradients& gradients, llgtm::Variable<DT>* v) { DCHECK_EQ(gradients.graph(), this); return gradients.Gradient(v); } GraphEvaluator* evaluator() { return evaluator_; } // Request a new seed value for random number generators. Seed values are // deterministic. Initial seed value can be specified upon graph creation. uint64 next_seed() { // Use Lehmer random number generator to generate a new seed. // See also: https://en.wikipedia.org/wiki/Lehmer_random_number_generator. seed_ = (seed_ * 279470273UL) % 4294967291UL; return seed_; } int size() const { return nodes_.size(); } int current_node() const { return current_node_; } nodes::TensorNodeBase* node(int i) { return nodes_[i]; } const nodes::TensorNodeBase* node(int i) const { return nodes_[i]; } // Register a node that may refer to subsequent nodes in the graph. void register_out_of_order_node(nodes::TensorNodeBase* node) { out_of_order_nodes_.push_back(node); } GraphImplementation* graph_implementation() { return implementation_.get(); } DeviceID default_device() const { return device_; } private: friend class GraphImplementation; // Concat::ComputeGradients should be able to access the graph implementation // to allocate memory for `sizes` in the arena. template<typename DT> friend class nodes::Concat; // Split::ComputeGradients should be able to call ConcatTuple. template<typename DT> friend class nodes::Split; TensorBase CopyToDevice(const TensorBase& a, DeviceID device) { // If we hit this line, it is probably a programming error. Users of LLGTM // do not usually work with multi-output nodes, but use GetOutput on the // result of a multi-output operation. LOG(FATAL) << "CopyToDevice not implemented for multi-output nodes."; } void set_current_node(int i) { DCHECK_LE(i, nodes_.size()); current_node_ = i; } void* AllocateInArena(size_t size) { return implementation_->AllocateInArena(size); } // Allocate memory for a node of type T. Does not construct it. template<class NodeType> void* allocate_node_memory() { return AllocateInArena(sizeof(NodeType)); } // Allocate the input expressions for a node. TensorBase* allocate_inputs(int num_inputs) { void* addr = AllocateInArena(sizeof(TensorBase) * num_inputs); return new (addr) TensorBase[num_inputs]; } TensorType* allocate_output_types(int num_outputs) { return reinterpret_cast<TensorType*>( AllocateInArena(sizeof(TensorType) * num_outputs)); } template<typename DT> absl::Span<const DT> copy_span_to_arena( const absl::Span<const DT> input) { size_t bytes = sizeof(Dimensions::IndexType)*input.size(); auto arena_memory = reinterpret_cast<Dimensions::IndexType*>( AllocateInArena(bytes)); memcpy(arena_memory, input.data(), bytes); return absl::MakeConstSpan(arena_memory, input.size()); } template<typename TensorT> TensorT ensure_device_type(DeviceID device, TensorT&& t) { if (t.device() != device) { // Transfer result to another device. CopyToDevice has overloadings for // Tensor<DT> and TensorBase. LOG(INFO) << "Inserting CopyToDevice to " << static_cast<int>(device) << " for Tensor " << t.get()->type_str(); return this->CopyToDevice(t, device); } else { return t; } } // Promotes a node to a given device. Does not promote children. // We usually want to update an entire subtree (including children). // However, this is not the case during node evaluation, because nodes // are evaluated from the leaf upward (increasing node IDs). void promote_node_device_shallow(nodes::TensorNodeBase* t, DeviceID device) { t->set_device(device); } // Promotes a node to a given device, including all children. void promote_node_device_deep(nodes::TensorNodeBase* t, DeviceID device) { for (int i = 0; i < t->num_inputs(); ++i) { auto* subnode = t->sub_expression(i).get(); // Invariant: The device of a child is equal to the device of its // parent. The only exception to this are CopyToDevice nodes. Since we // are promoting an unspecified node, its children's devices must also // be unspecified. (CopyToDevice nodes cannot appear down the path.) DCHECK(subnode->device() == kDeviceIDUnspecified || subnode->device() == device); promote_node_device_deep(subnode, device); } promote_node_device_shallow(t, device); } void promote_input_devices(TensorBase* inputs, int num_inputs) { // First pass: Determine to which device unspecified inputs should be // promoted. DeviceID device_specified = kDeviceIDUnspecified; for (int i = 0; i < num_inputs; ++i) { if (inputs[i].device() != kDeviceIDUnspecified) { if (device_specified == kDeviceIDUnspecified) { // Set all unspecified nodes to device of inputs[i]. device_specified = inputs[i].device(); } else if (inputs[i].device() != device_specified) { LOG(FATAL) << "Input nodes have different devices: " << device_name(inputs[i].device()) << " and " << device_name(device_specified) << "."; } } } // Second pass: Promote unspecified inputs. for (int i = 0; i < num_inputs; ++i) { if (inputs[i].device() != device_specified) { promote_node_device_deep(inputs[i].get(), device_specified); } } } // Return a pointer to allocated inputs, containing t0. TensorBase* make_inputs(TensorBase&& t0) { auto* inputs = allocate_inputs(1); inputs[0] = std::move(t0); return inputs; } // Return a pointer to allocated inputs, containing t0, t1. TensorBase* make_inputs(TensorBase&& t0, TensorBase&& t1) { TensorBase* inputs = allocate_inputs(2); inputs[0] = std::move(t0); inputs[1] = std::move(t1); promote_input_devices(inputs, /*num_inputs=*/ 2); return inputs; } // Copy tensors to the arena, and return a pointer to the allocated array. TensorBase* make_inputs(InputList tensors) { auto* inputs = allocate_inputs(tensors.size()); for (int i = 0; i < tensors.size(); ++i) { inputs[i] = tensors[i]; } promote_input_devices(inputs, tensors.size()); return inputs; } // Copy tensors to the arena, and return a pointer to the allocated array. template<typename DT> TensorBase* make_inputs(InputListT<DT> tensors) { auto* inputs = allocate_inputs(tensors.size()); for (int i = 0; i < tensors.size(); ++i) { inputs[i] = tensors[i]; } promote_input_devices(inputs, tensors.size()); return inputs; } // Allocate the output types for a node. template<typename DT> TensorType* make_output_type(const Dimensions& dimensions) { void* addr = AllocateInArena(sizeof(TensorType)); return new (addr) TensorType(CppTypeToDType<DT>::dtype, dimensions); } void insert_output_nodes(nodes::TensorNodeBase* node) { size_t offset = 0; auto* node_in = make_inputs(TensorBase(node)); for (int i = 0; i < node->num_outputs(); ++i) { auto* mem_ptr = allocate_node_memory<nodes::GetOutput>(); auto* output_node = new (mem_ptr) nodes::GetOutput(node_in, i, offset); output_node->id_ = nodes_.size(); nodes_.push_back(output_node); offset += node->output_type(i).aligned_memory_size(); } } TensorBase insert(nodes::TensorNodeBase* node) { node->id_ = nodes_.size(); nodes_.push_back(node); if (node->has_multiple_outputs() && node->num_outputs() > 0) { insert_output_nodes(node); } return TensorBase(node); } template<class DT> Tensor<DT> insert(nodes::TensorNode<DT>* node) { node->id_ = nodes_.size(); nodes_.push_back(node); return Tensor<DT>(node); } template<class NodeType, typename ...Args> TensorBase emplace_node_base(Args... args) { void* mem_ptr = allocate_node_memory<NodeType>(); auto* node = new (mem_ptr) NodeType(args...); return insert(node); } template<typename DT, class NodeType, typename ...Args> Tensor<DT> emplace_node(Args... args) { void* mem_ptr = allocate_node_memory<NodeType>(); auto* node = new (mem_ptr) NodeType(args...); return insert(node); } // Build a single tensor (concatenation) from a tuple. This concat variant is // used during gradient computation of Split. template<typename DT> Tensor<DT> ConcatTuple(TensorBase* tuple, int axis, const TensorType& output_type) { // Not passing `tuple` as const reference because we can't to invoke the // non-const version of `get` here. DCHECK(tuple->is_tuple()); return emplace_node<DT, nodes::Concat<DT>>(tuple->num_inputs(), tuple->get()->sub_expressions(), &output_type, axis); } GraphEvaluator* evaluator_ = nullptr; // GraphEvaluator for this graph. std::unique_ptr<GraphImplementation> implementation_; std::vector<nodes::TensorNodeBase*> nodes_; // Nodes in the graph. std::vector<nodes::TensorNodeBase*> out_of_order_nodes_; int current_node_ = 0; // Index of first unevaluated node. // Seed value used for the next UniformRandom and NormalRandom (unless // different seed is specified upon node creation). uint64 seed_; // Indicates whether this graph was given a custom seed by the programmer. bool is_custom_seed_; // Device used for new operations, unless device explicitly specified. DeviceID device_; }; } // namespace llgtm #endif // TENSORFLOW_FOLD_LLGTM_GRAPH_H_
39.157442
80
0.671274
[ "vector", "model" ]
c2e7ec3ced6543c27773dc85df6d90556c922304
4,702
h
C
robotCode/jettsonCode/AStarCode.h
PlavaFeniks/UNDLunarRobotics22
70f02c8608f82f414adf37d6de3663bf54ead1ed
[ "MIT" ]
1
2022-02-10T21:38:26.000Z
2022-02-10T21:38:26.000Z
robotCode/jettsonCode/AStarCode.h
PlavaFeniks/UNDLunarRobotics22
70f02c8608f82f414adf37d6de3663bf54ead1ed
[ "MIT" ]
1
2022-03-31T21:43:30.000Z
2022-03-31T21:43:30.000Z
robotCode/jettsonCode/AStarCode.h
PlavaFeniks/UNDLunarRobotics22
70f02c8608f82f414adf37d6de3663bf54ead1ed
[ "MIT" ]
4
2021-09-28T02:19:48.000Z
2022-01-08T13:07:21.000Z
class AStarNode; int calculateDistance(int x, int y, AStarNode* targetNode); int calculateDistance(int x, int y, int targetX, int targetY); AStarNode ***mapOfPit = new AStarNode**[HEIGHT]; //each index is 10cm by 10cm AStarNode* endNode; AStarNode* startNode; std::vector<AStarNode*>openNodes; //vector of input nodes struct TransformationData//used for storing zed position { float tx; float ty; float tz; //https://www.stereolabs.com/docs/api/classsl_1_1Rotation.html float rx; float ry; float rz; } zedCurrent, zedGoal, zedNextGoal; class AStarNode { public: bool fake = true; float gCost = -1; //distance to starting node float hCost = -1; //distance to endNode float fCost = -1; //f = G + H int x,y,z; //position, y|x used for index //OccMapVals int Nobs = 0; //Number of times observed int OBS = 0; //Running value of observation double Pocc = 1.0; //Probability of occupancy int showOcc = 0; //PointCloud Processing float Zsum = 0; int Npoints = 0; float Zval = 0; float Disthere = 0; bool isTraversable = true; bool isClose = false; AStarNode* parent = NULL; AStarNode* child = NULL; AStarNode(int x, int y, int z) { this->x = x; this->y = y; this->z = z; fake = false; } void setXYZ(int x, int y, int z) { this->x = x; this->y = y; this->z = z; } void setGCost(int gCost, AStarNode* endNode) { this->gCost = gCost; hCost = calculateDistance(x, y, endNode); fCost = hCost + gCost; } }; int calculateDistance(int x, int y, AStarNode* targetNode) { int targetX = targetNode->x; int targetY = targetNode->y; float distance = sqrt(pow((targetX - x), 2) + pow((targetY - y), 2)); return (int)(distance*10); } int calculateDistance(int x, int y, int targetX, int targetY) { float distance = sqrt(pow((targetX - x), 2) + pow((targetY - y), 2)); return (int)(distance*10); } void initializeTesselatedMap() { //initialization of map with default values for (int i=0; i< HEIGHT; i++) { mapOfPit[i] = new AStarNode*[WIDTH]; for (int j=0; j<WIDTH; j++) { mapOfPit[i][j] = new AStarNode(j, i, 0); //set 0 to height } } } void resetAStarTesselatedMap() { //sets it up for another path to be plotted for (int i=0; i< HEIGHT; i++) { mapOfPit[i] = new AStarNode*[WIDTH]; for (int j=0; j<WIDTH; j++) { mapOfPit[i][j]->isClose = false; //set 0 to height } } } void definePath(AStarNode* currentNode) //define path from startNode to EndNode { if (currentNode->parent == NULL) { if (currentNode == startNode) cout << "path found\n"; else cout <<"path not found\n"; return; } currentNode->parent->child = currentNode; definePath(currentNode->parent); } void FindPath(AStarNode* startingNode) //A* Algorithm, startNode and end node must be defined { if (endNode->isTraversable == false) {cout << "great one\n";endNode->isTraversable=true;} openNodes.push_back(startNode); AStarNode* current = NULL; int index = 0; while(openNodes.size() != 0) { current = NULL; //sets current to node in openNodes with lowest fCost for (int i=0; i<(int)openNodes.size(); i++) { if (current == NULL) {current = openNodes[i]; index = i;} else if (openNodes[i]->fCost < current->fCost){current = openNodes[i]; index = i;} } if (current->x == endNode->x and current->y == endNode->y) break; current->isClose = true; AStarNode** neighbors = new AStarNode*[8]; //for (int i=0; i<8; i++) {neighbors[i] = NULL;} int x = current->x; int y = current->y; int counter = 0; for (int i=-1; i<=1; i++) { for (int j=-1; j<=1; j++) { int newX = x+i; int newY = y+j; if ((newY==0 and newX==0) or newY<0 or newX<0 or newY>HEIGHT-1 or newX>WIDTH-1) continue; neighbors[counter] = mapOfPit[newY][newX]; counter++; } } for (int i=0; i<8; i++) { if (counter-1 < i) break; AStarNode* neighbor = (AStarNode*)neighbors[i]; if (neighbor == NULL) break; //go to next neighbor if current one doesnt exist if (neighbor->isTraversable == false or neighbor->isClose == true or neighbor->fake == true) continue; //go to next neighbor if current neighbor is not traversable or closed int gCost = current->gCost + calculateDistance(current->x, current->y, neighbor->x, neighbor->y); //add gCost from parent and get distance from child to parent if (neighbor->parent == NULL) { neighbor->parent = current; neighbor->setGCost(gCost, endNode); openNodes.push_back(neighbor); } else if (neighbor->gCost > gCost) { neighbor->parent = current; neighbor->setGCost(gCost, endNode); } } openNodes.erase(openNodes.begin() + index); } cout << "a* complete\n"; definePath(endNode); }
24.362694
176
0.648235
[ "vector" ]
c2f2fc67dfa2b758d6f7ff0de644c6e8897231fc
671
h
C
Engine/Renderer/OpenGL/Drawable/Frustum.h
gitter-badger/ZeloEngine
22a15783d58a9c1d5b2bad30d1544f13ac07ce2b
[ "MIT" ]
null
null
null
Engine/Renderer/OpenGL/Drawable/Frustum.h
gitter-badger/ZeloEngine
22a15783d58a9c1d5b2bad30d1544f13ac07ce2b
[ "MIT" ]
null
null
null
Engine/Renderer/OpenGL/Drawable/Frustum.h
gitter-badger/ZeloEngine
22a15783d58a9c1d5b2bad30d1544f13ac07ce2b
[ "MIT" ]
null
null
null
// Frustum.h // created on 2021/10/20 // author @zoloypzuo #pragma once #include "ZeloPrerequisites.h" #include "ZeloGLPrerequisites.h" class Frustum { private: GLuint vao; glm::vec3 center, u, v, n; float mNear, mFar, fovy, ar; std::vector<GLuint> buffers; public: Frustum(); ~Frustum(); void orient(const glm::vec3 &pos, const glm::vec3 &a, const glm::vec3 &u); void setPerspective(float, float, float, float); glm::mat4 getViewMatrix() const; glm::mat4 getInverseViewMatrix() const; glm::mat4 getProjectionMatrix() const; glm::vec3 getOrigin() const; void render() const; void deleteBuffers(); };
16.775
78
0.652757
[ "render", "vector" ]
6c02f00a996c130ef86463e12bef03280210c2d6
5,486
h
C
util/third_party/emwin/inc/LCD_Protected.h
lenloe1/v2.7
9ac9c4a7bb37987af382c80647f42d84db5f2e1d
[ "Zlib" ]
null
null
null
util/third_party/emwin/inc/LCD_Protected.h
lenloe1/v2.7
9ac9c4a7bb37987af382c80647f42d84db5f2e1d
[ "Zlib" ]
1
2020-08-25T02:36:22.000Z
2020-08-25T02:36:22.000Z
util/third_party/emwin/inc/LCD_Protected.h
lenloe1/v2.7
9ac9c4a7bb37987af382c80647f42d84db5f2e1d
[ "Zlib" ]
1
2020-08-25T01:56:04.000Z
2020-08-25T01:56:04.000Z
/***************************************************************************//** * # License * * The licensor of this software is Silicon Laboratories Inc. Your use of this * software is governed by the terms of Silicon Labs Master Software License * Agreement (MSLA) available at * www.silabs.com/about-us/legal/master-software-license-agreement. This * software is Third Party Software licensed by Silicon Labs from a third party * and is governed by the sections of the MSLA applicable to Third Party * Software and the additional terms set forth below. * ******************************************************************************/ /********************************************************************* * SEGGER Microcontroller GmbH & Co. KG * * Solutions for real time microcontroller applications * ********************************************************************** * * * (c) 1996 - 2016 SEGGER Microcontroller GmbH & Co. KG * * * * Internet: www.segger.com Support: support@segger.com * * * ********************************************************************** ** emWin V5.34 - Graphical user interface for embedded applications ** All Intellectual Property rights in the Software belongs to SEGGER. emWin is protected by international copyright laws. Knowledge of the source code may not be used to write a similar product. This file may only be used in accordance with the following terms: The software has been licensed to Silicon Labs Norway, a subsidiary of Silicon Labs Inc. whose registered office is 400 West Cesar Chavez, Austin, TX 78701, USA solely for the purposes of creating libraries for its ARM Cortex-M3, M4F processor-based devices, sublicensed and distributed under the terms and conditions of the End User License Agreement supplied by Silicon Labs. Full source code is available at: www.segger.com We appreciate your understanding and fairness. ---------------------------------------------------------------------- Licensing information Licensor: SEGGER Software GmbH Licensed to: Silicon Laboratories Norway Licensed SEGGER software: emWin License number: GUI-00140 License model: See Agreement, dated 20th April 2012 Licensed product: - Licensed platform: Cortex M3, Cortex M4F Licensed number of seats: - ---------------------------------------------------------------------- File : LCD_Protected.h Purpose : LCD level - To be used only internally by the GUI ---------------------------------------------------------------------- */ #ifndef LCD_PROTECTED_H #define LCD_PROTECTED_H #include "LCD.h" #if defined(__cplusplus) extern "C" { /* Make sure we have C-declarations in C++ programs */ #endif /********************************************************************* * * Data types */ typedef struct { LCD_COLOR * paColor; I16 NumEntries; } LCD_LUT_INFO; typedef struct { tLCDDEV_DrawPixel * pfDrawPixel; tLCDDEV_DrawHLine * pfDrawHLine; tLCDDEV_DrawVLine * pfDrawVLine; tLCDDEV_FillRect * pfFillRect; tLCDDEV_DrawBitmap * pfDrawBitmap; } LCD_API_LIST; /********************************************************************* * * External data */ extern GUI_CONST_STORAGE U8 LCD_aMirror[256]; extern LCD_PIXELINDEX * LCD__aConvTable; /********************************************************************* * * Misc functions */ void LCD_UpdateColorIndices (void); int LCD_PassingBitmapsAllowed(void); void LCD_EnableCursor (int OnOff); void LCD_SelectLCD (void); void LCD_DrawBitmap(int x0, int y0, int xsize, int ysize, int xMul, int yMul, int BitsPerPixel, int BytesPerLine, const U8 * pPixel, const LCD_PIXELINDEX * pTrans); void LCD__DrawBitmap_1bpp(int x0, int y0, int xsize, int ysize, int xMul, int yMul, int BitsPerPixel, int BytesPerLine, const U8 * pPixel, const LCD_PIXELINDEX * pTrans, int OffData); /********************************************************************* * * Internal used color conversion routines */ tLCDDEV_Index2Color LCD_Index2Color_444_12; tLCDDEV_Index2Color LCD_Index2Color_M444_12; tLCDDEV_Index2Color LCD_Index2Color_444_12_1; tLCDDEV_Index2Color LCD_Index2Color_M444_12_1; tLCDDEV_Index2Color LCD_Index2Color_444_16; tLCDDEV_Index2Color LCD_Index2Color_M444_16; tLCDDEV_Index2Color LCD_Index2Color_555; tLCDDEV_Index2Color LCD_Index2Color_565; tLCDDEV_Index2Color LCD_Index2Color_8666; tLCDDEV_Index2Color LCD_Index2Color_888; tLCDDEV_Index2Color LCD_Index2Color_8888; tLCDDEV_Index2Color LCD_Index2Color_M8888I; tLCDDEV_Index2Color LCD_Index2Color_M555; tLCDDEV_Index2Color LCD_Index2Color_M565; tLCDDEV_Index2Color LCD_Index2Color_M888; tLCDDEV_Color2Index LCD_Color2Index_8666; #if defined(__cplusplus) } #endif #endif /* LCD_PROTECTED_H */ /*************************** End of file ****************************/
37.575342
80
0.556143
[ "model" ]
6c12b84ea4839d42cfcbf25aa8284ffc56863bc5
1,792
h
C
tests/juliet/testcases/CWE134_Uncontrolled_Format_String/s02/CWE134_Uncontrolled_Format_String__char_environment_vprintf_83.h
RanerL/analyzer
a401da4680f163201326881802ee535d6cf97f5a
[ "MIT" ]
28
2017-01-20T15:25:54.000Z
2020-03-17T00:28:31.000Z
testcases/CWE134_Uncontrolled_Format_String/s02/CWE134_Uncontrolled_Format_String__char_environment_vprintf_83.h
mellowCS/cwe_checker_juliet_suite
ae604f6fd94964251fbe88ef04d5287f6c1ffbe2
[ "MIT" ]
1
2021-07-12T02:57:17.000Z
2021-07-16T02:07:29.000Z
testcases/CWE134_Uncontrolled_Format_String/s02/CWE134_Uncontrolled_Format_String__char_environment_vprintf_83.h
mellowCS/cwe_checker_juliet_suite
ae604f6fd94964251fbe88ef04d5287f6c1ffbe2
[ "MIT" ]
2
2019-07-15T19:07:04.000Z
2019-09-07T14:21:04.000Z
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE134_Uncontrolled_Format_String__char_environment_vprintf_83.h Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml Template File: sources-vasinks-83.tmpl.h */ /* * @description * CWE: 134 Uncontrolled Format String * BadSource: environment Read input from an environment variable * GoodSource: Copy a fixed string into data * Sinks: vprintf * GoodSink: vprintf with a format string * BadSink : vprintf without a format string * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif namespace CWE134_Uncontrolled_Format_String__char_environment_vprintf_83 { #ifndef OMITBAD class CWE134_Uncontrolled_Format_String__char_environment_vprintf_83_bad { public: CWE134_Uncontrolled_Format_String__char_environment_vprintf_83_bad(char * dataCopy); ~CWE134_Uncontrolled_Format_String__char_environment_vprintf_83_bad(); private: char * data; }; #endif /* OMITBAD */ #ifndef OMITGOOD class CWE134_Uncontrolled_Format_String__char_environment_vprintf_83_goodG2B { public: CWE134_Uncontrolled_Format_String__char_environment_vprintf_83_goodG2B(char * dataCopy); ~CWE134_Uncontrolled_Format_String__char_environment_vprintf_83_goodG2B(); private: char * data; }; class CWE134_Uncontrolled_Format_String__char_environment_vprintf_83_goodB2G { public: CWE134_Uncontrolled_Format_String__char_environment_vprintf_83_goodB2G(char * dataCopy); ~CWE134_Uncontrolled_Format_String__char_environment_vprintf_83_goodB2G(); private: char * data; }; #endif /* OMITGOOD */ }
27.151515
122
0.786272
[ "object" ]
6c134e28ba73be11e58293944f6de5a5dd1f4289
378
h
C
src/Core/Console/ConsoleVisual.h
bluespeck/OakVR
65d56942af390dc2ab2d969b44285d23bd53f139
[ "MIT" ]
null
null
null
src/Core/Console/ConsoleVisual.h
bluespeck/OakVR
65d56942af390dc2ab2d969b44285d23bd53f139
[ "MIT" ]
null
null
null
src/Core/Console/ConsoleVisual.h
bluespeck/OakVR
65d56942af390dc2ab2d969b44285d23bd53f139
[ "MIT" ]
null
null
null
#pragma once #include "OakVR/Sprite.h" #include <string> namespace oakvr { class ConsoleVisual { public: ConsoleVisual(); auto DrawHistory(std::vector<std::string> vecHistory) -> void; auto DrawCommandline(std::string commandLine, size_t cursorPosition)->void; private: oakvr::render::Sprite m_historyBackground; oakvr::render::Sprite m_cmdLineBackground; }; }
19.894737
77
0.746032
[ "render", "vector" ]
6c144e971b5a25f8898152fbef40d6522ce041c7
5,450
h
C
Engine/01_core/errorHandling/Exceptions.h
TB989/Fierce-Engine
4fa97b55fafdf97ee0b9eb72203425490b7a01c5
[ "Apache-2.0" ]
null
null
null
Engine/01_core/errorHandling/Exceptions.h
TB989/Fierce-Engine
4fa97b55fafdf97ee0b9eb72203425490b7a01c5
[ "Apache-2.0" ]
43
2020-03-01T12:55:12.000Z
2021-07-10T20:51:23.000Z
Engine/01_core/errorHandling/Exceptions.h
TB989/Fierce-Engine
4fa97b55fafdf97ee0b9eb72203425490b7a01c5
[ "Apache-2.0" ]
null
null
null
#pragma once /* Includes: * -Parent class * -Objects: Object myObject; */ #include "02_system/04_render/02_GL/01_Objects/Fierce_GL.h" #include "99_utils/FierceStrings.h" /* SystemIncludes*/ #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <exception> #include "vulkan/vulkan.h" /* Forward declarations: * -Pointers: Pointer* myPointer; * Reference& myReference; * -Functions: Object MyFunction(Object myObject); * Pointer* MyFunction(Pointer* myPointer); * Reference& MyFunction(Reference& myReference); */ enum FIERCE_ERROR { FE_NO_ERROR, FE_WINDOW_ERROR, FE_CONTEXT_ERROR }; class Fierce_Exception :public std::runtime_error { public: Fierce_Exception(std::string message) :runtime_error(message) {} }; inline void CHECK_FIERCE(FIERCE_ERROR result, std::string message) { std::string errorString; switch (result) { case FE_NO_ERROR: return; case FE_WINDOW_ERROR: errorString = "FIERCE Error: FE_WINDOW_ERROR"; break; case FE_CONTEXT_ERROR: errorString = "FIERCE Error: FE_CONTEXT_ERROR"; break; default: errorString = "FIERCE Error: FE_UNKNOWN_ERROR"; } std::wstring temp1 = std::wstring(message.begin(), message.end()); std::wstring temp2 = std::wstring(errorString.begin(), errorString.end()); MessageBox(NULL, temp1.c_str(), temp2.c_str(), MB_ICONERROR); throw Fierce_Exception(message.c_str()); } class GL_Exception :public std::runtime_error { public: GL_Exception(std::string message) :runtime_error(message) {} }; inline void CHECK_GL(GLenum result, std::string message) { std::string errorString; switch (result) { case GL_NO_ERROR: return; case GL_INVALID_ENUM: errorString = "GL Error: GL_INVALID_ENUM"; break; case GL_INVALID_VALUE: errorString = "GL Error: GL_INVALID_VALUE"; break; case GL_INVALID_OPERATION: errorString = "GL Error: GL_INVALID_OPERATION"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: errorString = "GL Error: GL_INVALID_FRAMEBUFFER_OPERATION"; break; case GL_OUT_OF_MEMORY: errorString = "GL Error: GL_OUT_OF_MEMORY"; break; case GL_STACK_UNDERFLOW: errorString = "GL Error: GL_STACK_UNDERFLOW"; break; case GL_STACK_OVERFLOW: errorString = "GL Error: GL_STACK_OVERFLOW"; break; default: errorString = "GL Error: GL_UNKNOWN_ERROR"; } std::wstring temp1 = std::wstring(message.begin(), message.end()); std::wstring temp2 = std::wstring(errorString.begin(), errorString.end()); MessageBox(NULL, temp1.c_str(), temp2.c_str(), MB_ICONERROR); throw GL_Exception(message.c_str()); } class Win_Exception :public std::runtime_error { public: Win_Exception(std::string message) :runtime_error(message) {} }; inline void CHECK_WIN(DWORD result, std::string message) { std::string errorString; switch (result) { case 0: return; default: errorString = "Win Error: ["+std::to_string(result)+"]"; } std::wstring temp1 = std::wstring(message.begin(), message.end()); std::wstring temp2 = std::wstring(errorString.begin(), errorString.end()); MessageBox(NULL, temp1.c_str(), temp2.c_str(), MB_ICONERROR); throw GL_Exception(message.c_str()); } class VK_Exception :public std::runtime_error { public: VK_Exception(std::string message) :runtime_error(message) {} }; inline void CHECK_VK(VkResult result, std::string message) { std::string errorString; switch (result) { case VK_SUCCESS: case VK_NOT_READY: case VK_TIMEOUT: case VK_EVENT_SET: case VK_EVENT_RESET: case VK_INCOMPLETE: case VK_SUBOPTIMAL_KHR: return; case VK_ERROR_OUT_OF_HOST_MEMORY: errorString = "VK Error: VK_ERROR_OUT_OF_HOST_MEMORY"; break; case VK_ERROR_OUT_OF_DEVICE_MEMORY: errorString = "VK Error: VK_ERROR_OUT_OF_DEVICE_MEMORY"; break; case VK_ERROR_INITIALIZATION_FAILED: errorString = "VK Error: VK_ERROR_INITIALIZATION_FAILED"; break; case VK_ERROR_MEMORY_MAP_FAILED: errorString = "VK Error: VK_ERROR_MEMORY_MAP_FAILED"; break; case VK_ERROR_DEVICE_LOST: errorString = "VK Error: VK_ERROR_DEVICE_LOST"; break; case VK_ERROR_EXTENSION_NOT_PRESENT: errorString = "VK Error: VK_ERROR_EXTENSION_NOT_PRESENT"; break; case VK_ERROR_FEATURE_NOT_PRESENT: errorString = "VK Error: VK_ERROR_FEATURE_NOT_PRESENT"; break; case VK_ERROR_LAYER_NOT_PRESENT: errorString = "VK Error: VK_ERROR_LAYER_NOT_PRESENT"; break; case VK_ERROR_INCOMPATIBLE_DRIVER: errorString = "VK Error: VK_ERROR_INCOMPATIBLE_DRIVER"; break; case VK_ERROR_TOO_MANY_OBJECTS: errorString = "VK Error: VK_ERROR_TOO_MANY_OBJECTS"; break; case VK_ERROR_FORMAT_NOT_SUPPORTED: errorString = "VK Error: VK_ERROR_FORMAT_NOT_SUPPORTED"; break; case VK_ERROR_SURFACE_LOST_KHR: errorString = "VK Error: VK_ERROR_SURFACE_LOST_KHR"; break; case VK_ERROR_OUT_OF_DATE_KHR: errorString = "VK Error: VK_ERROR_OUT_OF_DATE_KHR"; break; case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: errorString = "VK Error: VK_ERROR_INCOMPATIBLE_DISPLAY_KHR"; break; case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: errorString = "VK Error: VK_ERROR_NATIVE_WINDOW_IN_USE_KHR"; break; case VK_ERROR_VALIDATION_FAILED_EXT: errorString = "VK Error: VK_ERROR_VALIDATION_FAILED_EXT"; break; default: errorString = "VK Error: VK_UNKNOWN_ERROR"; } std::wstring temp1 = std::wstring(message.begin(), message.end()); std::wstring temp2 = std::wstring(errorString.begin(), errorString.end()); MessageBox(NULL, temp1.c_str(), temp2.c_str(), MB_ICONERROR); throw VK_Exception(message.c_str()); }
28.238342
75
0.754862
[ "object" ]
6c23b85cc0fb83a871bd3b04d24a544619783134
1,174
h
C
guts/guts/tex/texture_loader.h
Emberwalker/ac41001_opengl_cpp
c2f63fb6bb200a44f93e43af00b32a9d7b5df05a
[ "MIT" ]
1
2017-10-31T16:03:47.000Z
2017-10-31T16:03:47.000Z
guts/guts/tex/texture_loader.h
Emberwalker/ac41001_opengl_cpp
c2f63fb6bb200a44f93e43af00b32a9d7b5df05a
[ "MIT" ]
null
null
null
guts/guts/tex/texture_loader.h
Emberwalker/ac41001_opengl_cpp
c2f63fb6bb200a44f93e43af00b32a9d7b5df05a
[ "MIT" ]
null
null
null
#ifndef GUTS_TEX_TEXTURE_LOADER_H #define GUTS_TEX_TEXTURE_LOADER_H #include <string> #include <vector> namespace guts { namespace tex { // C++ lacks a byte type - but an unsigned char is good enough. typedef unsigned char ubyte; enum TextureType { TEXTURE_RGB, TEXTURE_RGBA, TEXTURE_HEIGHTMAP }; // TextureLoader represents a loader for a certain file format e.g. a PNG // texture loader. class TextureLoader { public: virtual ~TextureLoader() = default; // Gets the texture type this loader instance contains. virtual TextureType GetTextureType() = 0; virtual unsigned int GetImageWidth() = 0; virtual unsigned int GetImageHeight() = 0; // Gets the raw components of the image. // GetComponents().size() must be divisible by 3 for RGB sources, or 4 for // RGBA sources. Height maps have no extra size restrictions, as each point is // 1 item. The size must also match up with the width * height of the image. // It is suggested that this value be created when this loader is created, and // then cached. virtual std::vector<ubyte> GetComponents() = 0; }; } // namespace tex } // namespace guts #endif //GUTS_TEX_TEXTURE_LOADER_H
25.521739
80
0.732538
[ "vector" ]
6c23fff58edc7828b526484d07b15d5d2aa1d6b4
7,561
h
C
vectorian/core/cpp/document.h
poke1024/vectorian-2021
5b8a23ca473dd5e6b0ad4baaca75c8a8bf7cc12b
[ "MIT" ]
9
2020-03-02T08:43:55.000Z
2021-07-14T14:54:40.000Z
vectorian/core/cpp/document.h
poke1024/vectorian-2021
5b8a23ca473dd5e6b0ad4baaca75c8a8bf7cc12b
[ "MIT" ]
null
null
null
vectorian/core/cpp/document.h
poke1024/vectorian-2021
5b8a23ca473dd5e6b0ad4baaca75c8a8bf7cc12b
[ "MIT" ]
1
2021-07-14T14:53:33.000Z
2021-07-14T14:53:33.000Z
#ifndef __VECTORIAN_DOCUMENT_H__ #define __VECTORIAN_DOCUMENT_H__ #include "common.h" #include "vocabulary.h" #include "embedding/vectors.h" inline void add_dummy_token(std::vector<Token> &tokens) { Token t; t.id = -1; t.len = 0; t.pos = -1; t.tag = -1; if (tokens.empty()) { t.idx = 0; } else { t.idx = tokens.rbegin()->idx + tokens.rbegin()->len; } // adding a last dummy token with the correct idx is handy. tokens.push_back(t); } class FixedSpans { const size_t m_size; public: FixedSpans(const size_t p_size) : m_size(p_size) { } inline size_t size() const { return m_size; } inline int32_t start(const size_t p_index) const { return p_index; } inline int32_t end(const size_t p_index) const { return p_index + 1; } inline int32_t len(const size_t p_index) const { return 1; } inline int32_t bounded_len(const size_t p_index, const size_t p_size) const { return std::min(p_size, m_size - p_index); } inline int32_t max_len(const size_t p_window_size) const { return p_window_size; } }; class VariableSpans { public: typedef int32_t offset_t; struct Span { offset_t start; offset_t end; }; private: const std::vector<Span> m_spans; offset_t m_max_len; public: VariableSpans(std::vector<Span> &&p_spans) : m_spans(p_spans) { offset_t max_len = 0; for (const auto &s : m_spans) { max_len = std::max(max_len, s.end - s.start); } m_max_len = max_len; } inline size_t size() const { return m_spans.size(); } inline offset_t start(const size_t p_index) const { return m_spans[p_index].start; } inline offset_t end(const size_t p_index) const { return m_spans[p_index].end; } inline offset_t len(const size_t p_index) const { return end(p_index) - start(p_index); } inline offset_t bounded_len(const size_t p_index, const size_t p_size) const { const size_t i1 = std::min(p_index + p_size - 1, m_spans.size() - 1); return end(i1) - start(p_index); } inline offset_t max_len(const size_t p_window_size) const { return m_max_len * p_window_size; } }; class Spans { std::optional<FixedSpans> m_fixed; std::optional<VariableSpans> m_variable; public: Spans(FixedSpans &&p_spans) : m_fixed(p_spans) { } Spans(VariableSpans &&p_spans) : m_variable(p_spans) { } inline size_t size() const { return m_variable.has_value() ? (*m_variable).size() : (*m_fixed).size(); } inline int32_t start(const size_t p_index) const { return m_variable.has_value() ? (*m_variable).start(p_index) : (*m_fixed).start(p_index); } inline int32_t end(const size_t p_index) const { return m_variable.has_value() ? (*m_variable).end(p_index) : (*m_fixed).end(p_index); } inline int32_t len(const size_t p_index) const { return m_variable.has_value() ? (*m_variable).len(p_index) : (*m_fixed).len(p_index); } inline int32_t bounded_len(const size_t p_index, const size_t p_size) const { return m_variable.has_value() ? (*m_variable).bounded_len(p_index, p_size) : (*m_fixed).bounded_len(p_index, p_size); } inline Slice slice(const size_t p_index) const { return Slice{start(p_index), len(p_index)}; } inline int32_t max_len(const size_t p_window_size) const { return m_variable.has_value() ? (*m_variable).max_len(p_window_size) : (*m_fixed).max_len(p_window_size); } template<typename F> void iterate(const SliceStrategy &p_slice_strategy, const F &p_callback) const { const size_t n_slices = size(); size_t token_at = 0; for (size_t slice_id = 0; slice_id < n_slices; slice_id += p_slice_strategy.window_step) { const auto len_s = bounded_len( slice_id, p_slice_strategy.window_size); if (len_s >= 1) { if (!p_callback(slice_id, token_at, len_s)) { break; } } token_at += bounded_len( slice_id, p_slice_strategy.window_step); } } }; typedef std::shared_ptr<Spans> SpansRef; class Booster { const py::array_t<float> m_boost_weights; public: Booster(const py::array_t<float> &p_weights) : m_boost_weights(p_weights) { } inline float get_boost(const size_t p_slice_id) const { const auto weights = m_boost_weights.unchecked<1>(); return weights[p_slice_id]; } }; class Document : public std::enable_shared_from_this<Document>, public ContextualVectorsContainer, public TokenContainer { private: const int64_t m_id; const VocabularyRef m_vocab; TokenVectorRef m_tokens; size_t m_num_dummy_tokens; std::map<std::string, SpansRef> m_spans; const py::dict m_metadata; std::string m_cache_path; public: Document( int64_t p_document_id, // unique index inside corpus VocabularyRef p_vocab, const py::dict &p_spans, const py::dict &p_tokens, const py::dict &p_metadata, const py::dict &p_contextual_embeddings); ResultSetRef find( const QueryRef &p_query, const BoosterRef &p_booster); inline VocabularyRef vocabulary() const { return m_vocab; } std::string __str__() const { return "<vectorian.core.Document " + m_metadata["author"].cast<std::string>() + ", " + m_metadata["title"].cast<std::string>() + ">"; } inline int64_t id() const { return m_id; } const std::string &path() const { return m_cache_path; } const py::dict &metadata() const { return m_metadata; } py::dict py_tokens() const { return to_py_array(m_tokens, n_tokens()); } std::string token_str(size_t i) const { return std::string(m_vocab->id_to_token(m_tokens->at(i).id)); } inline const TokenVectorRef &tokens_vector() const { return m_tokens; } inline size_t n_tokens() const { return m_tokens->size() - m_num_dummy_tokens; } virtual std::tuple<const Token*, size_t> tokens() const { return std::make_tuple(tokens_vector()->data(), n_tokens()); } const SpansRef &spans(const std::string &p_name) const { const auto it = m_spans.find(p_name); if (it == m_spans.end()) { std::ostringstream err; err << "unknown spans " << p_name; throw std::runtime_error(err.str()); } return it->second; } inline size_t max_len(const std::string &p_name, const size_t p_window_size) const { return spans(p_name)->max_len(p_window_size); } py::array_t<int32_t> count_keywords( const py::dict &p_slice_strategy, const py::tuple &p_keywords) const { std::unordered_set<token_t> keywords; keywords.reserve(p_keywords.size()); for (auto x : p_keywords) { const token_t x_id = m_vocab->token_to_id(x.cast<std::string>()); if (x_id >= 0) { keywords.insert(x_id); } } const SliceStrategy slice_strategy(p_slice_strategy); const SpansRef spans = this->spans(slice_strategy.level); const size_t n_spans = spans->size(); const Token *s_tokens = this->tokens_vector()->data(); py::array_t<size_t> counts{static_cast<py::ssize_t>(n_spans)}; auto mutable_counts = counts.mutable_unchecked<1>(); for (size_t i = 0; i < n_spans; i++) { mutable_counts[i] = 0; } spans->iterate(p_slice_strategy, [s_tokens, &keywords, &mutable_counts] ( const size_t slice_id, const size_t token_at, const size_t len_s) { for (size_t i = 0; i < len_s; i++) { const Token &t = s_tokens[token_at + i]; if (keywords.find(t.id) != keywords.end()) { mutable_counts[slice_id] += 1; } } return true; }); return counts; }}; typedef std::shared_ptr<Document> DocumentRef; #endif // __VECTORIAN_DOCUMENT_H__
23.628125
107
0.677688
[ "vector" ]
8fc3ee2733c797d85777a9a80e77bc5c3d7db929
1,128
h
C
libs/androidfw/include/androidfw/PosixUtils.h
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
164
2015-01-05T16:49:11.000Z
2022-03-29T20:40:27.000Z
libs/androidfw/include/androidfw/PosixUtils.h
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
127
2015-01-12T12:02:32.000Z
2021-11-28T08:46:25.000Z
libs/androidfw/include/androidfw/PosixUtils.h
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
1,141
2015-01-01T22:54:40.000Z
2022-02-09T22:08:26.000Z
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <memory> #include <string> #include <vector> namespace android { namespace util { struct ProcResult { int status; std::string stdout; std::string stderr; }; // Fork, exec and wait for an external process. Return nullptr if the process could not be launched, // otherwise a ProcResult containing the external process' exit status and captured stdout and // stderr. std::unique_ptr<ProcResult> ExecuteBinary(const std::vector<std::string>& argv); } // namespace util } // namespace android
30.486486
100
0.739362
[ "vector" ]
8fc724ac69274b910635b9b4b10229f150d6a7db
3,197
h
C
src/store/api/temp_seq.h
jsoniq/jsoniq
f7af29417f809d64d1f0b2622d880bc4d87f2e42
[ "Apache-2.0" ]
94
2015-01-18T09:40:36.000Z
2022-03-02T21:14:55.000Z
src/store/api/temp_seq.h
jsoniq/jsoniq
f7af29417f809d64d1f0b2622d880bc4d87f2e42
[ "Apache-2.0" ]
72
2015-01-05T22:00:31.000Z
2021-07-17T11:35:03.000Z
src/store/api/temp_seq.h
jsoniq/jsoniq
f7af29417f809d64d1f0b2622d880bc4d87f2e42
[ "Apache-2.0" ]
27
2015-01-18T20:20:54.000Z
2020-11-01T18:01:07.000Z
/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ZORBA_STORE_TEMP_SEQ_H #define ZORBA_STORE_TEMP_SEQ_H #include <vector> #include <zorba/config.h> #include "zorbatypes/schema_types.h" #include "store/api/shared_types.h" namespace zorba { namespace store { /** * XQuery Data Model Instance: Logically, implements a "vector&lt;Item_t&gt;" * Used internally to materialize temporary query results */ class TempSeq : public SimpleRCObject { public: virtual ~TempSeq(){} virtual bool isLazy() const = 0; /** * @return Does this TempSeq save an empty sequence? */ virtual bool empty() = 0; /** * */ virtual xs_integer getSize() const = 0; /** * Initializes a temp sequence with the given input iterator */ virtual void init(const store::Iterator_t& iter) = 0; /** * Appends the items from the iterator to the temp sequence */ virtual void append(const Iterator_t& iter) = 0; /** * purge() allows the store to do proper garbage collection. If e.g. a let * has created iterators for all his bindings he has to produce, it can * call purge(). After purge() it is not allowed to ask the XDMInstance * to create further iterators or items. Of course it is allowed to use * the already created iteratos */ virtual void purge() = 0; /** * Similar to purge(), but in contrast it is still allowed to ask for items * or iterators which start with an item higher than the position number upTo * * Starts counting with 1. * * @param upTo boundary for garbage collector */ virtual void purgeUpTo(xs_integer pos) = 0; /** * Gets an item at a certain position. * * Starts counting with 1. * * @param position (first position in XQuery is 1 and not 0!) * @return item */ virtual void getItem(xs_integer pos, Item_t& result) = 0; /** * Returns true if the item at the passed position is available. * * Starts counting with 1. * * @param position * @return */ virtual bool containsItem(xs_integer pos) = 0; /** * Reads the whole Sequence from beginning to end; it is allowed to have several * concurrent iterators on the same TempSeq. * * @return Iterator which iterates over the complete TempSeq * */ virtual Iterator_t getIterator() const = 0; #ifndef NDEBUG /** Debugging aid: method to print the contents of the sequence */ virtual std::string toString() const = 0; #endif }; } // namespace store } // namespace zorba #endif /* ZORBA_STORE_TEMP_SEQ_H */ /* * Local variables: * mode: c++ * End: */ /* vim:set et sw=2 ts=2: */
25.173228
83
0.678761
[ "vector", "model" ]
8fd3abd98a5fb45315387ab71741523a049e5ebe
6,992
h
C
catkin_ws/devel/include/vision_msgs/BoundingBox2D.h
Colin1245/ROS-Theory-Application-Shenlan
49986c83a2c73c7ab4310fd3f010e1b6bc0de786
[ "Apache-2.0" ]
null
null
null
catkin_ws/devel/include/vision_msgs/BoundingBox2D.h
Colin1245/ROS-Theory-Application-Shenlan
49986c83a2c73c7ab4310fd3f010e1b6bc0de786
[ "Apache-2.0" ]
null
null
null
catkin_ws/devel/include/vision_msgs/BoundingBox2D.h
Colin1245/ROS-Theory-Application-Shenlan
49986c83a2c73c7ab4310fd3f010e1b6bc0de786
[ "Apache-2.0" ]
null
null
null
// Generated by gencpp from file vision_msgs/BoundingBox2D.msg // DO NOT EDIT! #ifndef VISION_MSGS_MESSAGE_BOUNDINGBOX2D_H #define VISION_MSGS_MESSAGE_BOUNDINGBOX2D_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <geometry_msgs/Pose2D.h> namespace vision_msgs { template <class ContainerAllocator> struct BoundingBox2D_ { typedef BoundingBox2D_<ContainerAllocator> Type; BoundingBox2D_() : center() , size_x(0.0) , size_y(0.0) { } BoundingBox2D_(const ContainerAllocator& _alloc) : center(_alloc) , size_x(0.0) , size_y(0.0) { (void)_alloc; } typedef ::geometry_msgs::Pose2D_<ContainerAllocator> _center_type; _center_type center; typedef double _size_x_type; _size_x_type size_x; typedef double _size_y_type; _size_y_type size_y; typedef boost::shared_ptr< ::vision_msgs::BoundingBox2D_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::vision_msgs::BoundingBox2D_<ContainerAllocator> const> ConstPtr; }; // struct BoundingBox2D_ typedef ::vision_msgs::BoundingBox2D_<std::allocator<void> > BoundingBox2D; typedef boost::shared_ptr< ::vision_msgs::BoundingBox2D > BoundingBox2DPtr; typedef boost::shared_ptr< ::vision_msgs::BoundingBox2D const> BoundingBox2DConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::vision_msgs::BoundingBox2D_<ContainerAllocator> & v) { ros::message_operations::Printer< ::vision_msgs::BoundingBox2D_<ContainerAllocator> >::stream(s, "", v); return s; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator==(const ::vision_msgs::BoundingBox2D_<ContainerAllocator1> & lhs, const ::vision_msgs::BoundingBox2D_<ContainerAllocator2> & rhs) { return lhs.center == rhs.center && lhs.size_x == rhs.size_x && lhs.size_y == rhs.size_y; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator!=(const ::vision_msgs::BoundingBox2D_<ContainerAllocator1> & lhs, const ::vision_msgs::BoundingBox2D_<ContainerAllocator2> & rhs) { return !(lhs == rhs); } } // namespace vision_msgs namespace ros { namespace message_traits { template <class ContainerAllocator> struct IsFixedSize< ::vision_msgs::BoundingBox2D_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::vision_msgs::BoundingBox2D_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::vision_msgs::BoundingBox2D_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::vision_msgs::BoundingBox2D_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::vision_msgs::BoundingBox2D_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::vision_msgs::BoundingBox2D_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::vision_msgs::BoundingBox2D_<ContainerAllocator> > { static const char* value() { return "9ab41e2a4c8627735e5091a9abd68b02"; } static const char* value(const ::vision_msgs::BoundingBox2D_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x9ab41e2a4c862773ULL; static const uint64_t static_value2 = 0x5e5091a9abd68b02ULL; }; template<class ContainerAllocator> struct DataType< ::vision_msgs::BoundingBox2D_<ContainerAllocator> > { static const char* value() { return "vision_msgs/BoundingBox2D"; } static const char* value(const ::vision_msgs::BoundingBox2D_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::vision_msgs::BoundingBox2D_<ContainerAllocator> > { static const char* value() { return "# A 2D bounding box that can be rotated about its center.\n" "# All dimensions are in pixels, but represented using floating-point\n" "# values to allow sub-pixel precision. If an exact pixel crop is required\n" "# for a rotated bounding box, it can be calculated using Bresenham's line\n" "# algorithm.\n" "\n" "# The 2D position (in pixels) and orientation of the bounding box center.\n" "geometry_msgs/Pose2D center\n" "\n" "# The size (in pixels) of the bounding box surrounding the object relative\n" "# to the pose of its center.\n" "float64 size_x\n" "float64 size_y\n" "\n" "================================================================================\n" "MSG: geometry_msgs/Pose2D\n" "# Deprecated\n" "# Please use the full 3D pose.\n" "\n" "# In general our recommendation is to use a full 3D representation of everything and for 2D specific applications make the appropriate projections into the plane for their calculations but optimally will preserve the 3D information during processing.\n" "\n" "# If we have parallel copies of 2D datatypes every UI and other pipeline will end up needing to have dual interfaces to plot everything. And you will end up with not being able to use 3D tools for 2D use cases even if they're completely valid, as you'd have to reimplement it with different inputs and outputs. It's not particularly hard to plot the 2D pose or compute the yaw error for the Pose message and there are already tools and libraries that can do this for you.\n" "\n" "\n" "# This expresses a position and orientation on a 2D manifold.\n" "\n" "float64 x\n" "float64 y\n" "float64 theta\n" ; } static const char* value(const ::vision_msgs::BoundingBox2D_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::vision_msgs::BoundingBox2D_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.center); stream.next(m.size_x); stream.next(m.size_y); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct BoundingBox2D_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::vision_msgs::BoundingBox2D_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::vision_msgs::BoundingBox2D_<ContainerAllocator>& v) { s << indent << "center: "; s << std::endl; Printer< ::geometry_msgs::Pose2D_<ContainerAllocator> >::stream(s, indent + " ", v.center); s << indent << "size_x: "; Printer<double>::stream(s, indent + " ", v.size_x); s << indent << "size_y: "; Printer<double>::stream(s, indent + " ", v.size_y); } }; } // namespace message_operations } // namespace ros #endif // VISION_MSGS_MESSAGE_BOUNDINGBOX2D_H
28.655738
475
0.735412
[ "object", "vector", "3d" ]
8fd486b5af1b603c49b104d90f86bb6d9c4c40aa
52,691
c
C
core/object.c
charlesdaniels/libagar
099ce716e2ca01a7904b23f22610bf589295f5b5
[ "BSD-2-Clause" ]
null
null
null
core/object.c
charlesdaniels/libagar
099ce716e2ca01a7904b23f22610bf589295f5b5
[ "BSD-2-Clause" ]
null
null
null
core/object.c
charlesdaniels/libagar
099ce716e2ca01a7904b23f22610bf589295f5b5
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2001-2019 Julien Nadeau Carriere <vedge@csoft.net> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Base object class. */ #include <agar/core/core.h> #include <agar/core/config.h> #include <stdarg.h> #include <ctype.h> #include <string.h> #include <agar/config/ag_debug_core.h> AG_ObjectClass agObjectClass = { "AG_Object", sizeof(AG_Object), { 7,3 }, NULL, /* init */ NULL, /* reset */ NULL, /* destroy */ NULL, /* load */ NULL, /* save */ NULL /* edit */ }; #ifdef AG_SERIALIZATION const AG_Version agPropTblVer = { 2, 1 }; int agObjectIgnoreDataErrors = 0; /* Don't fail on a data load failure. */ int agObjectIgnoreUnknownObjs = 0; /* Don't fail on unknown object types. */ int agObjectBackups = 1; /* Backup object save files. */ #endif /* Import inlinables */ #undef AG_INLINE_HEADER #include <agar/core/inline_object.h> /* Initialize an AG_Object instance. */ void AG_ObjectInit(void *p, void *cl) { AG_Object *ob = p; AG_ObjectClass **hier; int i, nHier; #ifdef AG_DEBUG memset(ob->name, '\0', sizeof(ob->name)); #else ob->name[0] = '\0'; #endif #ifdef AG_SERIALIZATION # if defined(_WIN32) || defined(_XBOX) ob->save_pfx = "\\world"; # else ob->save_pfx = "/world"; # endif ob->archivePath = NULL; #endif ob->cls = (cl != NULL) ? (AG_ObjectClass *)cl : &agObjectClass; ob->parent = NULL; ob->root = ob; ob->flags = 0; ob->pvt.attachFn = NULL; ob->pvt.detachFn = NULL; AG_MutexInitRecursive(&ob->pvt.lock); TAILQ_INIT(&ob->events); #ifdef AG_TIMERS TAILQ_INIT(&ob->timers); #endif TAILQ_INIT(&ob->vars); #ifdef AG_SERIALIZATION TAILQ_INIT(&ob->deps); #endif TAILQ_INIT(&ob->children); if (AG_ObjectGetInheritHier(ob, &hier, &nHier) != 0) { AG_FatalError(NULL); } for (i = 0; i < nHier; i++) { if (hier[i]->init != NULL) hier[i]->init(ob); } free(hier); } /* Initialize an AG_Object instance (name argument variant). */ void AG_ObjectInitNamed(void *obj, void *cl, const char *name) { AG_ObjectInit(obj, cl); if (name != NULL) { AG_ObjectSetNameS(obj, name); } else { OBJECT(obj)->flags |= AG_OBJECT_NAME_ONATTACH; } } /* Initialize an AG_Object instance (static variant). */ void AG_ObjectInitStatic(void *obj, void *C) { AG_ObjectInit(obj, C); OBJECT(obj)->flags |= AG_OBJECT_STATIC; } /* * Allocate, initialize and attach a new object instance of the specified * class. */ void * AG_ObjectNew(void *parent, const char *name, AG_ObjectClass *C) { char nameGen[AG_OBJECT_NAME_MAX]; AG_Object *obj; if (name == NULL) { AG_ObjectGenName(parent, C, nameGen, sizeof(nameGen)); } else { if (parent != NULL && AG_ObjectFindChild(parent, name) != NULL) { AG_SetErrorV("E7", _("Existing child object")); return (NULL); } } if ((obj = TryMalloc(C->size)) == NULL) { return (NULL); } AG_ObjectInit(obj, C); AG_ObjectSetNameS(obj, (name != NULL) ? name : (const char *)nameGen); if (parent != NULL) { AG_ObjectAttach(parent, obj); } return (obj); } /* * Restore an object to an initial state prior to deserialization or release. * Dependencies are preserved, but are all assumed to have 0 refcounts. */ void AG_ObjectReset(void *p) { AG_Object *ob = p; int preserveDeps; AG_ObjectClass **hier; int i, nHier; AG_ObjectLock(ob); preserveDeps = (ob->flags & AG_OBJECT_PRESERVE_DEPS); ob->flags |= AG_OBJECT_PRESERVE_DEPS; if (AG_ObjectGetInheritHier(ob, &hier, &nHier) != 0) { AG_FatalError(NULL); } for (i = nHier-1; i >= 0; i--) { if (hier[i]->reset != NULL) hier[i]->reset(ob); } free(hier); if (!preserveDeps) { ob->flags &= ~(AG_OBJECT_PRESERVE_DEPS); } AG_ObjectUnlock(ob); } /* * Recursive function to construct absolute object names. * The object's VFS must be locked. */ static int GenerateObjectPath(void *_Nonnull obj, char *_Nonnull path, AG_Size path_len) { AG_Object *ob = obj; AG_Size name_len, cur_len; int rv = 0; AG_ObjectLock(ob); cur_len = strlen(path); name_len = strlen(ob->name); if (name_len+cur_len+1 > path_len) { AG_SetErrorV("E4", _("Path buffer overflow")); AG_ObjectUnlock(ob); return (-1); } /* Prepend `/ and the object name. */ memmove(&path[name_len+1], path, cur_len+1); /* Move the NUL as well */ path[0] = AG_PATHSEPCHAR; memcpy(&path[1], ob->name, name_len); /* Omit the NUL */ if (ob->parent != ob->root && ob->parent != NULL) { rv = GenerateObjectPath(ob->parent, path, path_len); } AG_ObjectUnlock(ob); return (rv); } /* * Copy the absolute pathname of an object to a fixed-size buffer. * Buffer size must be at least 2 bytes in size. */ int AG_ObjectCopyName(void *obj, char *path, AG_Size path_len) { AG_Object *ob = obj; int rv = 0; if (path_len < 2) { AG_SetErrorV("E5", _("Path buffer overflow")); return (-1); } path[0] = AG_PATHSEPCHAR; path[1] = '\0'; AG_LockVFS(ob); AG_ObjectLock(ob); if (ob == ob->root) { Strlcat(path, ob->name, path_len); } else { rv = GenerateObjectPath(ob, path, path_len); } AG_ObjectUnlock(ob); AG_UnlockVFS(ob); return (rv); } /* * Return a newly allocated string containing the absolute pathname of * an object. */ char * AG_ObjectGetName(void *obj) { AG_Object *ob = obj; AG_Object *pob; char *path; AG_Size pathLen = 1; AG_LockVFS(ob); AG_ObjectLock(ob); for (pob = ob; pob->parent != NULL; pob = pob->parent) { pathLen += strlen(pob->name) + 1; } if ((path = TryMalloc(pathLen+1)) == NULL) { goto fail; } path[0] = AG_PATHSEPCHAR; path[1] = '\0'; if (ob == ob->root) { Strlcat(path, ob->name, pathLen); } else { GenerateObjectPath(ob, path, pathLen); } AG_ObjectUnlock(ob); AG_UnlockVFS(ob); return (path); fail: AG_ObjectUnlock(ob); AG_UnlockVFS(ob); return (NULL); } #ifdef AG_SERIALIZATION /* * Search an object and its children for a dependency upon robj. * The object's VFS must be locked. */ static int FindObjectInUse(void *_Nonnull p, void *_Nonnull robj) _Pure_Attribute_If_Unthreaded { AG_Object *ob = p, *cob; AG_ObjectDep *dep; AG_ObjectLock(ob); TAILQ_FOREACH(dep, &ob->deps, deps) { if (dep->obj == robj && robj != ob) goto used; } TAILQ_FOREACH(cob, &ob->children, cobjs) { if (FindObjectInUse(cob, robj)) goto used; } AG_ObjectUnlock(ob); return (0); used: AG_ObjectUnlock(ob); return (1); } /* * Return 1 if the given object or one of its children is being referenced. * Return value is only valid as long as the VFS is locked. */ int AG_ObjectInUse(void *p) { AG_Object *ob = p, *cob; AG_Object *root; AG_LockVFS(ob); root = AG_ObjectRoot(ob); if (FindObjectInUse(root, ob)) { goto used; } TAILQ_FOREACH(cob, &ob->children, cobjs) { if (AG_ObjectInUse(cob)) goto used; } AG_UnlockVFS(ob); return (0); used: AG_UnlockVFS(ob); return (1); } #endif /* AG_SERIALIZATION */ /* Configure a custom "attach" function. */ void AG_ObjectSetAttachFn(void *p, void (*fn)(struct ag_event *), const char *fmt, ...) { AG_Object *obj = p; AG_ObjectLock(obj); if (fn != NULL) { obj->pvt.attachFn = AG_SetEvent(obj, NULL, fn, NULL); AG_EVENT_GET_ARGS(obj->pvt.attachFn, fmt); } else { obj->pvt.attachFn = NULL; } AG_ObjectUnlock(obj); } /* Configure a custom "detach" function. */ void AG_ObjectSetDetachFn(void *p, void (*fn)(struct ag_event *), const char *fmt, ...) { AG_Object *obj = p; AG_ObjectLock(obj); if (fn != NULL) { obj->pvt.detachFn = AG_SetEvent(obj, NULL, fn, NULL); AG_EVENT_GET_ARGS(obj->pvt.detachFn, fmt); } else { obj->pvt.detachFn = NULL; } AG_ObjectUnlock(obj); } /* Attach an object to another object. */ void AG_ObjectAttach(void *parentp, void *pChld) { AG_Object *parent = parentp; AG_Object *chld = pChld; if (parent == NULL) return; #ifdef AG_DEBUG if (parent == chld) AG_FatalErrorV("E31", "parent == chld"); #endif AG_LockVFS(parent); AG_ObjectLock(parent); AG_ObjectLock(chld); /* * Update the child's "parent" and "root" pointers. If we are using * a custom attach function, we assume that it will follow through. */ chld->parent = parent; chld->root = parent->root; /* Call the attach function if one is defined. */ if (chld->pvt.attachFn != NULL) { chld->pvt.attachFn->fn(chld->pvt.attachFn); goto out; } /* Name the object if it has the name-on-attach flag set. */ if (chld->flags & AG_OBJECT_NAME_ONATTACH) { AG_ObjectGenName(parent, chld->cls, chld->name, sizeof(chld->name)); } /* Attach the object. */ TAILQ_INSERT_TAIL(&parent->children, chld, cobjs); /* Notify both the parent and child objects. */ AG_PostEvent(parent, chld, "attached", NULL); AG_PostEvent(chld, parent, "child-attached", NULL); #ifdef AG_DEBUG_CORE if (chld->name[0] != '\0') { Debug(parent, "Attached child: %s\n", chld->name); } else { Debug(parent, "Attached child: <%p>\n", chld); } if (parent->name[0] != '\0') { Debug(chld, "New parent: %s\n", parent->name); } else { Debug(chld, "New parent: <%p>\n", parent); } #endif /* AG_DEBUG_CORE */ out: AG_ObjectUnlock(chld); AG_ObjectUnlock(parent); AG_UnlockVFS(parent); } /* Detach a child object from its parent. */ void AG_ObjectDetach(void *pChld) { AG_Object *chld = pChld; #ifdef AG_THREADS AG_Object *root = chld->root; #endif AG_Object *parent = chld->parent; #ifdef AG_TIMERS AG_Timer *to, *toNext; #endif #ifdef AG_THREADS AG_LockVFS(root); #endif AG_ObjectLock(parent); AG_ObjectLock(chld); /* Call the detach function if one is defined. */ if (chld->pvt.detachFn != NULL) { chld->pvt.detachFn->fn(chld->pvt.detachFn); goto out; } #ifdef AG_TIMERS /* Cancel any running timer associated with the object. */ AG_LockTiming(); for (to = TAILQ_FIRST(&chld->timers); to != TAILQ_END(&chld->timers); to = toNext) { toNext = TAILQ_NEXT(to, pvt.timers); AG_DelTimer(chld, to); } AG_UnlockTiming(); #endif /* Detach the object. */ TAILQ_REMOVE(&parent->children, chld, cobjs); chld->parent = NULL; chld->root = chld; AG_PostEvent(parent, chld, "detached", NULL); AG_PostEvent(chld, parent, "child-detached", NULL); #ifdef AG_DEBUG_CORE if (chld->name[0] != '\0') { Debug(parent, "Detached child: %s\n", chld->name); } else { Debug(parent, "Detached child: <%p>\n", chld); } if (parent->name[0] != '\0') { Debug(chld, "New parent: NULL\n"); } #endif /* AG_DEBUG_CORE */ out: AG_ObjectUnlock(chld); AG_ObjectUnlock(parent); #ifdef AG_THREADS AG_UnlockVFS(root); #endif } /* Traverse the object tree using a pathname. */ static void *_Nullable _Pure_Attribute FindObjectByName(const AG_Object *_Nonnull parent, const char *_Nonnull name) { char chldName[AG_OBJECT_PATH_MAX]; void *rv; char *s; AG_Object *child; Strlcpy(chldName, name, sizeof(chldName)); if ((s = strchr(chldName, AG_PATHSEPCHAR)) != NULL) { *s = '\0'; } TAILQ_FOREACH(child, &parent->children, cobjs) { if (strcmp(child->name, chldName) != 0) continue; if ((s = strchr(name, AG_PATHSEPCHAR)) != NULL && s[1] != '\0') { rv = FindObjectByName(child, &s[1]); if (rv != NULL) { return (rv); } else { return (NULL); } } return (child); } return (NULL); } /* * Search for the named object (absolute path). * * Returned pointer is guaranteed to be valid as long as the VFS is locked. * If no such object exists, return NULL (without SetError). */ void * AG_ObjectFindS(void *vfsRoot, const char *name) { void *rv; #ifdef AG_DEBUG if (name[0] != AG_PATHSEPCHAR) AG_FatalErrorV("E32", "Not an absolute path"); #endif if (name[0] == AG_PATHSEPCHAR && name[1] == '\0') { return (vfsRoot); } AG_LockVFS(vfsRoot); rv = FindObjectByName(vfsRoot, &name[1]); AG_UnlockVFS(vfsRoot); return (rv); } /* * Search for the named object (absolute path as format string). * * Returned pointer is guaranteed to be valid as long as the VFS is locked. * If no such object exists, return NULL (without SetError). */ void * AG_ObjectFind(void *vfsRoot, const char *fmt, ...) { char path[AG_OBJECT_PATH_MAX]; void *rv; va_list ap; va_start(ap, fmt); Vsnprintf(path, sizeof(path), fmt, ap); va_end(ap); #ifdef AG_DEBUG if (path[0] != AG_PATHSEPCHAR) AG_FatalErrorV("E32", "Not an absolute path"); #endif AG_LockVFS(vfsRoot); rv = FindObjectByName(vfsRoot, &path[1]); AG_UnlockVFS(vfsRoot); return (rv); } /* * Traverse an object's ancestry looking for parent object of the given class. * Return value is only valid as long as VFS is locked. */ void * AG_ObjectFindParent(void *p, const char *name, const char *t) { AG_Object *ob = AGOBJECT(p); AG_LockVFS(p); while (ob != NULL) { AG_Object *po = AGOBJECT(ob->parent); if (po == NULL) { goto fail; } if ((t == NULL || AG_ClassIsNamed(po->cls, t)) && (name == NULL || strcmp(po->name, name) == 0)) { AG_UnlockVFS(p); return ((void *)po); } ob = AGOBJECT(ob->parent); } fail: AG_UnlockVFS(p); return (NULL); } #ifdef AG_SERIALIZATION /* Clear the dependency table. */ void AG_ObjectFreeDeps(AG_Object *ob) { AG_ObjectDep *dep, *ndep; AG_ObjectLock(ob); for (dep = TAILQ_FIRST(&ob->deps); dep != TAILQ_END(&ob->deps); dep = ndep) { ndep = TAILQ_NEXT(dep, deps); free(dep); } TAILQ_INIT(&ob->deps); AG_ObjectUnlock(ob); } /* * Remove any entry in the object's dependency table with a reference count * of zero. Also applies to the object's children. */ void AG_ObjectFreeDummyDeps(AG_Object *ob) { AG_Object *cob; AG_ObjectDep *dep, *ndep; AG_ObjectLock(ob); for (dep = TAILQ_FIRST(&ob->deps); dep != TAILQ_END(&ob->deps); dep = ndep) { ndep = TAILQ_NEXT(dep, deps); if (dep->count == 0) { TAILQ_REMOVE(&ob->deps, dep, deps); free(dep); } } TAILQ_FOREACH(cob, &ob->children, cobjs) { AG_ObjectFreeDummyDeps(cob); } AG_ObjectUnlock(ob); } #endif /* AG_SERIALIZATION */ /* Detach and free all children. None of them must be in use. */ static void FreeChildObject(AG_Object *_Nonnull obj) { AG_Object *cob, *ncob; AG_ObjectLock(obj); for (cob = TAILQ_FIRST(&obj->children); cob != TAILQ_END(&obj->children); cob = ncob) { ncob = TAILQ_NEXT(cob, cobjs); FreeChildObject(cob); } AG_ObjectUnlock(obj); #ifdef AG_DEBUG_CORE if (obj->name[0] != '\0') { Debug(NULL, "Freeing: %s\n", obj->name); } else { Debug(NULL, "Freeing: <%p>\n", obj); } #endif AG_ObjectDetach(obj); AG_ObjectDestroy(obj); } void AG_ObjectFreeChildren(void *p) { AG_Object *pob = p; AG_Object *cob, *ncob; AG_ObjectLock(pob); for (cob = TAILQ_FIRST(&pob->children); cob != TAILQ_END(&pob->children); cob = ncob) { ncob = TAILQ_NEXT(cob, cobjs); FreeChildObject(cob); } TAILQ_INIT(&pob->children); AG_ObjectUnlock(pob); } /* Destroy the object variables. */ void AG_ObjectFreeVariables(void *pObj) { AG_Object *ob = pObj; AG_Variable *V, *Vnext; AG_ObjectLock(ob); for (V = TAILQ_FIRST(&ob->vars); V != TAILQ_END(&ob->vars); V = Vnext) { Vnext = TAILQ_NEXT(V, vars); AG_FreeVariable(V); free(V); } TAILQ_INIT(&ob->vars); AG_ObjectUnlock(ob); } /* Destroy the event handler structures. */ void AG_ObjectFreeEvents(AG_Object *ob) { AG_Event *ev, *evNext; AG_ObjectLock(ob); for (ev = TAILQ_FIRST(&ob->events); ev != TAILQ_END(&ob->events); ev = evNext) { evNext = TAILQ_NEXT(ev, events); free(ev); } TAILQ_INIT(&ob->events); AG_ObjectUnlock(ob); } /* * Release the resources allocated by an object and its children, assuming * that none of them are currently in use. */ void AG_ObjectDestroy(void *p) { AG_Object *ob = p; AG_ObjectClass **hier; int i, nHier; #ifdef AG_DEBUG if (ob->parent != NULL) { AG_Debug(ob, "I'm still attached to %s\n", OBJECT(ob->parent)->name); AG_FatalErrorV("E33", "Object is still attached"); } # ifdef AG_DEBUG_CORE Debug(ob, "Destroying\n"); # endif #endif AG_ObjectFreeChildren(ob); AG_ObjectReset(ob); #ifdef AG_SERIALIZATION AG_ObjectFreeDeps(ob); #endif if (AG_ObjectGetInheritHier(ob, &hier, &nHier) != 0) { AG_FatalError(NULL); } for (i = nHier-1; i >= 0; i--) { if (hier[i]->destroy != NULL) hier[i]->destroy(ob); } free(hier); AG_ObjectFreeVariables(ob); AG_ObjectFreeEvents(ob); AG_MutexDestroy(&ob->pvt.lock); #ifdef AG_SERIALIZATION Free(ob->archivePath); #endif if ((ob->flags & AG_OBJECT_STATIC) == 0) free(ob); } #ifdef AG_SERIALIZATION /* * Copy the full pathname to an object's data file to a fixed-size buffer. * The path is only valid as long as the VFS is locked. */ /* NOTE: Will return data into path even upon failure. */ int AG_ObjectCopyFilename(void *p, char *path, AG_Size pathSize) { char objName[AG_OBJECT_PATH_MAX]; AG_ConfigPathQ *pathGroup = &agConfig->paths[AG_CONFIG_PATH_DATA]; AG_ConfigPath *loadPath; AG_Object *ob = p; AG_ObjectLock(ob); if (ob->archivePath != NULL) { Strlcpy(path, ob->archivePath, pathSize); goto out; } AG_ObjectCopyName(ob, objName, sizeof(objName)); SLIST_FOREACH(loadPath, pathGroup, paths) { Strlcpy(path, loadPath->s, pathSize); if (ob->save_pfx != NULL) { Strlcat(path, ob->save_pfx, pathSize); } Strlcat(path, objName, pathSize); Strlcat(path, AG_PATHSEP, pathSize); Strlcat(path, ob->name, pathSize); Strlcat(path, ".", pathSize); Strlcat(path, ob->cls->name, pathSize); if (AG_FileExists(path)) goto out; } # ifdef AG_VERBOSITY AG_SetError(_("The %s%s%c%s.%s file is not in load-path."), ob->save_pfx != NULL ? ob->save_pfx : "", objName, AG_PATHSEPCHAR, ob->name, ob->cls->name); # else AG_SetErrorS("E5"); # endif AG_ObjectUnlock(ob); return (-1); out: AG_ObjectUnlock(ob); return (0); } /* * Copy the full pathname of an object's data dir to a fixed-size buffer. * The path is only valid as long as the VFS is locked. */ int AG_ObjectCopyDirname(void *p, char *path, AG_Size pathSize) { char tmpPath[AG_PATHNAME_MAX]; char objName[AG_OBJECT_PATH_MAX]; AG_ConfigPathQ *pathGroup = &agConfig->paths[AG_CONFIG_PATH_DATA]; AG_ConfigPath *loadPath; AG_Object *ob = p; AG_ObjectLock(ob); AG_ObjectCopyName(ob, objName, sizeof(objName)); SLIST_FOREACH(loadPath, pathGroup, paths) { Strlcpy(tmpPath, loadPath->s, sizeof(tmpPath)); if (ob->save_pfx != NULL) { Strlcat(tmpPath, ob->save_pfx, sizeof(tmpPath)); } Strlcat(tmpPath, objName, sizeof(tmpPath)); if (AG_FileExists(tmpPath)) { Strlcpy(path, tmpPath, pathSize); goto out; } } #ifdef AG_VERBOSITY AG_SetError(_("The %s directory is not in load-path."), objName); #else AG_SetErrorS("E6"); #endif AG_ObjectUnlock(ob); return (-1); out: AG_ObjectUnlock(ob); return (0); } /* * Load an object's data into memory and mark it resident. If the object * is either marked non-persistent or no data can be found in storage, * just mark the object resident. */ int AG_ObjectPageIn(void *p) { AG_Object *ob = p; int dataFound; AG_ObjectLock(ob); if (!OBJECT_RESIDENT(ob) && AG_ObjectLoadData(ob, &dataFound) == -1) { if (dataFound == 0) { ob->flags |= AG_OBJECT_RESIDENT; AG_ObjectUnlock(ob); return (0); } else { AG_ObjectUnlock(ob); return (-1); } } AG_ObjectUnlock(ob); return (0); } /* * If the given object is persistent and no longer referenced, save * its data and free it from memory. The object must be resident. */ int AG_ObjectPageOut(void *p) { AG_Object *ob = p; AG_ObjectLock(ob); if (!OBJECT_PERSISTENT(ob)) { goto out; } if (!AG_ObjectInUse(ob)) { if (AG_FindEventHandler(ob->root, "object-page-out") != NULL) { AG_PostEvent(ob, ob->root, "object-page-out", NULL); } else { if (AG_ObjectSave(ob) == -1) goto fail; } if ((ob->flags & AG_OBJECT_REMAIN_DATA) == 0) { AG_ObjectReset(ob); ob->flags &= ~(AG_OBJECT_RESIDENT); } } out: AG_ObjectUnlock(ob); return (0); fail: AG_ObjectUnlock(ob); return (-1); } /* Load both the generic part and the dataset of an object from file. */ int AG_ObjectLoadFromFile(void *p, const char *path) { AG_Object *ob = p; int dataFound; AG_LockVFS(ob); AG_ObjectLock(ob); if (AG_ObjectLoadGenericFromFile(ob, path) == -1 || AG_ObjectResolveDeps(ob) == -1 || AG_ObjectLoadDataFromFile(ob, &dataFound, path) == -1) { goto fail; } AG_ObjectUnlock(ob); AG_UnlockVFS(ob); return (0); fail: AG_ObjectUnlock(ob); AG_UnlockVFS(ob); return (-1); } int AG_ObjectLoad(void *p) { return AG_ObjectLoadFromFile(p, NULL); } int AG_ObjectLoadData(void *p, int *dataFound) { return AG_ObjectLoadDataFromFile(p, dataFound, NULL); } int AG_ObjectLoadGeneric(void *p) { return AG_ObjectLoadGenericFromFile(p, NULL); } /* * Resolve the encoded dependencies of an object and its children. * The object's VFS must be locked. */ int AG_ObjectResolveDeps(void *p) { AG_Object *ob = p, *cob; AG_ObjectDep *dep; AG_ObjectLock(ob); TAILQ_FOREACH(dep, &ob->deps, deps) { if (dep->obj != NULL) { continue; } if ((dep->obj = AG_ObjectFindS(ob->root, dep->path)) == NULL) { #ifdef AG_VERBOSITY AG_SetError(_("%s: Cannot resolve dependency `%s'"), ob->name, dep->path); #else AG_SetErrorS("E6"); #endif goto fail; } #ifdef AG_DEBUG_CORE Debug(ob, "Dependency: %p (%s)\n", dep->obj, dep->obj->name); #endif free(dep->path); dep->path = NULL; } TAILQ_FOREACH(cob, &ob->children, cobjs) { AG_ObjectLock(cob); if (!OBJECT_PERSISTENT(cob)) { AG_ObjectUnlock(cob); continue; } if (AG_ObjectResolveDeps(cob) == -1) { AG_ObjectUnlock(cob); goto fail; } AG_ObjectUnlock(cob); } AG_ObjectUnlock(ob); return (0); fail: AG_ObjectUnlock(ob); return (-1); } /* Read an Agar archive header. */ int AG_ObjectReadHeader(AG_DataSource *ds, AG_ObjectHeader *oh) { /* Signature and version data */ if (AG_ReadVersion(ds, agObjectClass.name, &agObjectClass.ver, &oh->ver) == -1) return (-1); /* Class hierarchy and module references */ if (oh->ver.minor >= 2) { AG_ObjectClassSpec *cs = &oh->cs; char *c; AG_CopyString(cs->hier, ds, sizeof(cs->hier)); #ifdef AG_ENABLE_DSO AG_CopyString(cs->libs, ds, sizeof(cs->libs)); #else AG_SkipString(ds); #endif Strlcpy(cs->spec, cs->hier, sizeof(cs->spec)); #ifdef AG_ENABLE_DSO if (cs->libs[0] != '\0') { Strlcat(cs->spec, "@", sizeof(cs->spec)); Strlcat(cs->spec, cs->libs, sizeof(cs->spec)); } #endif if ((c = strrchr(cs->hier, ':')) != NULL && c[1] != '\0') { Strlcpy(cs->name, &c[1], sizeof(cs->name)); } else { Strlcpy(cs->name, cs->hier, sizeof(cs->name)); } } else { oh->cs.hier[0] = '\0'; oh->cs.spec[0] = '\0'; oh->cs.name[0] = '\0'; #ifdef AG_ENABLE_DSO oh->cs.libs[0] = '\0'; #endif } /* Dataset start offset */ oh->dataOffs = AG_ReadUint32(ds); /* Object flags */ oh->flags = (Uint)AG_ReadUint32(ds); return (0); } /* Load an object dependency table. */ static int ReadDependencyTable(AG_DataSource *_Nonnull ds, AG_Object *_Nonnull ob) { Uint32 i, count; AG_ObjectDep *dep; count = AG_ReadUint32(ds); for (i = 0; i < count; i++) { if ((dep = TryMalloc(sizeof(AG_ObjectDep))) == NULL) { goto fail; } if ((dep->path = AG_ReadString(ds)) == NULL) { free(dep); goto fail; } dep->obj = NULL; dep->count = 0; dep->persistent = 1; TAILQ_INSERT_TAIL(&ob->deps, dep, deps); } return (0); fail: AG_ObjectFreeDeps(ob); return (-1); } /* Return the default datafile path for the given object. */ static int GetDatafile(char *_Nonnull path, AG_Object *_Nonnull ob) { if (ob->archivePath != NULL) { Strlcpy(path, ob->archivePath, AG_PATHNAME_MAX); } else { if (AG_ObjectCopyFilename(ob, path, AG_PATHNAME_MAX) == -1) return (-1); } return (0); } /* Load Object variables. */ int AG_ObjectLoadVariables(void *p, AG_DataSource *ds) { AG_Object *ob = p; Uint count, i, j; /* TODO 2.0 remove this redundant signature */ if (AG_ReadVersion(ds, "AG_PropTbl", &agPropTblVer, NULL) == -1) return (-1); AG_ObjectLock(ob); if (ob->flags & AG_OBJECT_FLOATING_VARS) AG_ObjectFreeVariables(ob); count = (Uint)AG_ReadUint32(ds); #if AG_MODEL != AG_SMALL if (count > AG_OBJECT_MAX_VARIABLES) { AG_SetErrorS(_("Too many variables")); return (-1); } #endif for (i = 0; i < count; i++) { char key[64]; Sint8 code; char *s; if (AG_CopyString(key, ds, sizeof(key)) >= sizeof(key)) { #ifdef AG_VERBOSITY AG_SetError(_("Variable name too long: %s"), key); #else AG_SetErrorS("E8"); #endif goto fail; } code = (Sint8)AG_ReadSint32(ds); /* XXX */ #if 0 Verbose("%s: %s (code %d)\n", ob->name, key, (int)code); #endif for (j = 0; j < AG_VARIABLE_TYPE_LAST; j++) { if (agVariableTypes[j].code == code) break; } if (j == AG_VARIABLE_TYPE_LAST) { #ifdef AG_VERBOSITY AG_SetError(_("Unknown variable code: %u"), (Uint)code); #else AG_SetErrorS("E9"); #endif goto fail; } switch (agVariableTypes[j].typeTgt) { #if AG_MODEL == AG_SMALL case AG_VARIABLE_UINT: AG_SetUint(ob, key, AG_ReadUint16(ds)); break; case AG_VARIABLE_INT: AG_SetInt(ob, key, AG_ReadSint16(ds)); break; #else case AG_VARIABLE_UINT: AG_SetUint(ob, key, (Uint)AG_ReadUint32(ds)); break; case AG_VARIABLE_INT: AG_SetInt(ob, key, (int)AG_ReadSint32(ds)); break; case AG_VARIABLE_ULONG: AG_SetUlong(ob, key, (Ulong)AG_ReadUint64(ds)); break; case AG_VARIABLE_LONG: AG_SetLong(ob, key, (long)AG_ReadSint64(ds)); break; case AG_VARIABLE_UINT32: AG_SetUint32(ob, key, AG_ReadUint32(ds)); break; case AG_VARIABLE_SINT32: AG_SetSint32(ob, key, AG_ReadSint32(ds)); break; #endif /* MD or LG */ case AG_VARIABLE_UINT8: AG_SetUint8(ob, key, AG_ReadUint8(ds)); break; case AG_VARIABLE_SINT8: AG_SetSint8(ob, key, AG_ReadSint8(ds)); break; case AG_VARIABLE_UINT16: AG_SetUint16(ob, key, AG_ReadUint16(ds)); break; case AG_VARIABLE_SINT16: AG_SetSint16(ob, key, AG_ReadSint16(ds)); break; #ifdef AG_HAVE_64BIT case AG_VARIABLE_UINT64: AG_SetUint64(ob, key, AG_ReadUint64(ds)); break; case AG_VARIABLE_SINT64: AG_SetSint64(ob, key, AG_ReadSint64(ds)); break; #endif #ifdef AG_HAVE_FLOAT case AG_VARIABLE_FLOAT: AG_SetFloat(ob, key, AG_ReadFloat(ds)); break; case AG_VARIABLE_DOUBLE: AG_SetDouble(ob, key, AG_ReadDouble(ds)); break; # ifdef AG_HAVE_LONG_DOUBLE case AG_VARIABLE_LONG_DOUBLE: AG_SetLongDouble(ob, key, AG_ReadLongDouble(ds)); break; # endif #endif case AG_VARIABLE_STRING: if ((s = AG_ReadString(ds)) != NULL) { AG_SetStringNODUP(ob, key, s); } else { AG_SetString(ob, key, ""); } break; default: #ifdef AG_VERBOSITY AG_SetError(_("Attempt to load variable of type %s"), agVariableTypes[j].name); #else AG_SetErrorS("E10"); #endif goto fail; } } AG_ObjectUnlock(ob); return (0); fail: AG_ObjectUnlock(ob); return (-1); } /* Save persistent object variables. */ void AG_ObjectSaveVariables(void *pObj, AG_DataSource *ds) { AG_Object *ob = pObj; AG_Offset countOffs; Uint32 count = 0; AG_Variable *V; /* TODO 2.0 remove this redundant signature */ AG_WriteVersion(ds, "AG_PropTbl", &agPropTblVer); countOffs = AG_Tell(ds); AG_WriteUint32(ds, 0); AG_ObjectLock(ob); TAILQ_FOREACH(V, &ob->vars, vars) { const AG_VariableTypeInfo *Vt = &agVariableTypes[V->type]; void *p; if (Vt->code == -1) { Verbose("Save: skipping %s (non-persistent)\n", V->name); continue; } AG_LockVariable(V); AG_WriteString(ds, (char *)V->name); AG_WriteSint32(ds, (Sint32)Vt->code); /* XXX */ p = (agVariableTypes[V->type].indirLvl > 0) ? V->data.p : (void *)&V->data; switch (AG_VARIABLE_TYPE(V)) { #if AG_MODEL == AG_SMALL case AG_VARIABLE_UINT: AG_WriteUint16(ds, *(Uint *)p); break; case AG_VARIABLE_INT: AG_WriteSint16(ds, *(int *)p); break; #else /* MEDIUM or LARGE */ case AG_VARIABLE_UINT: AG_WriteUint32(ds, (Uint32)*(Uint *)p); break; case AG_VARIABLE_INT: AG_WriteSint32(ds, (Sint32)*(int *)p); break; case AG_VARIABLE_ULONG: AG_WriteUint64(ds, (Uint64)*(Ulong *)p); break; case AG_VARIABLE_LONG: AG_WriteSint64(ds, (Sint64)*(long *)p); break; #endif case AG_VARIABLE_UINT8: AG_WriteUint8(ds, *(Uint8 *)p); break; case AG_VARIABLE_SINT8: AG_WriteSint8(ds, *(Sint8 *)p); break; case AG_VARIABLE_UINT16: AG_WriteUint16(ds, *(Uint16 *)p); break; case AG_VARIABLE_SINT16: AG_WriteSint16(ds, *(Sint16 *)p); break; #if AG_MODEL != AG_SMALL case AG_VARIABLE_UINT32: AG_WriteUint32(ds, *(Uint32 *)p); break; case AG_VARIABLE_SINT32: AG_WriteSint32(ds, *(Sint32 *)p); break; #endif #ifdef AG_HAVE_64BIT case AG_VARIABLE_UINT64: AG_WriteUint64(ds, *(Uint64 *)p); break; case AG_VARIABLE_SINT64: AG_WriteSint64(ds, *(Sint64 *)p); break; #endif #ifdef AG_HAVE_FLOAT case AG_VARIABLE_FLOAT: AG_WriteFloat(ds, *(float *)p); break; case AG_VARIABLE_DOUBLE: AG_WriteDouble(ds, *(double *)p); break; # ifdef AG_HAVE_LONG_DOUBLE case AG_VARIABLE_LONG_DOUBLE: AG_WriteLongDouble(ds, *(long double *)p); break; # endif #endif case AG_VARIABLE_STRING: AG_WriteString(ds, V->data.s); break; default: break; } AG_UnlockVariable(V); if (++count > AG_OBJECT_MAX_VARIABLES) { AG_FatalErrorV("E34", "Too many variables to save"); /* break; */ } } AG_ObjectUnlock(ob); AG_WriteUint32At(ds, count, countOffs); } /* * Load an Agar object (or a virtual filesystem of Agar objects) from an * archive file. * * Only the generic part is read, datasets are skipped and dependencies * are left unresolved. */ int AG_ObjectLoadGenericFromFile(void *p, const char *pPath) { AG_Object *ob = p; #if AG_MODEL == AG_SMALL AG_ObjectHeader *oh; #else AG_ObjectHeader oh; #endif char path[AG_PATHNAME_MAX]; AG_DataSource *ds; Uint32 count, i; if (!OBJECT_PERSISTENT(ob)) { AG_SetErrorV("E11", _("Object is non-persistent")); return (-1); } AG_LockVFS(ob); AG_ObjectLock(ob); if (pPath != NULL) { Strlcpy(path, pPath, sizeof(path)); } else { if (GetDatafile(path, ob) == -1) goto fail_unlock; } #ifdef AG_DEBUG_CORE Debug(ob, "Loading generic data from %s\n", path); #endif if ((ds = AG_OpenFile(path, "rb")) == NULL) goto fail_unlock; /* Free any resident dataset in order to clear the dependencies. */ AG_ObjectReset(ob); AG_ObjectFreeDeps(ob); #if AG_MODEL == AG_SMALL if ((oh = TryMalloc(sizeof(AG_ObjectHeader))) == NULL) { goto fail; } if (AG_ObjectReadHeader(ds, oh) == -1) { goto fail; } ob->flags &= ~(AG_OBJECT_SAVED_FLAGS); ob->flags |= oh->flags; free(oh); #else if (AG_ObjectReadHeader(ds, &oh) == -1) { goto fail; } ob->flags &= ~(AG_OBJECT_SAVED_FLAGS); ob->flags |= oh.flags; #endif /* Dependencies, properties */ if (ReadDependencyTable(ds, ob) == -1) goto fail; if (AG_ObjectLoadVariables(ob, ds) == -1) goto fail; /* Load the generic part of the archived child objects. */ count = AG_ReadUint32(ds); for (i = 0; i < count; i++) { char cname[AG_OBJECT_NAME_MAX]; char hier[AG_OBJECT_HIER_MAX]; AG_Object *chld; AG_ObjectClass *C; /* TODO check that there are no duplicate names. */ AG_CopyString(cname, ds, sizeof(cname)); AG_CopyString(hier, ds, sizeof(hier)); /* Look for an existing object of the given name. */ if ((chld = AG_ObjectFindChild(ob, cname)) != NULL) { if (strcmp(chld->cls->hier, hier) != 0) { #ifdef AG_VERBOSITY AG_SetError(_("Archived object `%s' clashes with " "existing object of different type"), cname); #else AG_SetErrorS("E12"); #endif goto fail; } if (!OBJECT_PERSISTENT(chld)) { #ifdef AG_VERBOSITY AG_SetError(_("Archived object `%s' clashes with " "existing non-persistent object"), cname); #else AG_SetErrorS("E13"); #endif goto fail; } if (AG_ObjectLoadGeneric(chld) == -1) { goto fail; } continue; } /* Create a new child object. */ #ifdef AG_ENABLE_DSO C = AG_LoadClass(hier); #else C = AG_LookupClass(hier); #endif if (C == NULL) { #ifdef AG_VERBOSITY AG_SetError("%s: %s", ob->name, AG_GetError()); #else AG_SetErrorS("E14"); #endif if (agObjectIgnoreUnknownObjs) { #ifdef AG_DEBUG_CORE Debug(ob, "%s; ignoring\n", AG_GetError()); #endif continue; } else { goto fail; } goto fail; } if ((chld = TryMalloc(C->size)) == NULL) { goto fail; } AG_ObjectInit(chld, C); AG_ObjectSetNameS(chld, cname); AG_ObjectAttach(ob, chld); if (AG_ObjectLoadGeneric(chld) == -1) goto fail; } AG_CloseFile(ds); AG_ObjectUnlock(ob); AG_UnlockVFS(ob); return (0); fail: AG_ObjectReset(ob); AG_ObjectFreeDeps(ob); AG_CloseFile(ds); fail_unlock: AG_ObjectUnlock(ob); AG_UnlockVFS(ob); return (-1); } /* Load an Agar object dataset from an object archive file. */ int AG_ObjectLoadDataFromFile(void *p, int *dataFound, const char *pPath) { AG_ObjectHeader oh; char path[AG_PATHNAME_MAX]; AG_Object *ob = p; AG_DataSource *ds; AG_Version ver; AG_ObjectClass **hier; int i, nHier; AG_LockVFS(ob); AG_ObjectLock(ob); if (!OBJECT_PERSISTENT(ob)) { goto out; } *dataFound = 1; /* Open the file. */ if (pPath != NULL) { Strlcpy(path, pPath, sizeof(path)); } else { if (GetDatafile(path, ob) == -1) { *dataFound = 0; goto fail_unlock; } } #ifdef AG_DEBUG_CORE Debug(ob, "Loading dataset from %s\n", path); #endif if ((ds = AG_OpenFile(path, "rb")) == NULL) { *dataFound = 0; goto fail_unlock; } if (AG_ObjectReadHeader(ds, &oh) == -1 || AG_Seek(ds, oh.dataOffs, AG_SEEK_SET) == -1 || AG_ReadVersion(ds, ob->cls->name, &ob->cls->ver, &ver) == -1) { goto fail; } if (ob->flags & AG_OBJECT_DEBUG_DATA) { #ifdef AG_DEBUG AG_SetSourceDebug(ds, 1); #else AG_SetErrorV("E15", _("Can't read without DEBUG")); goto fail; #endif } if (AG_ObjectGetInheritHier(ob, &hier, &nHier) == -1) goto fail; AG_ObjectReset(ob); for (i = 0; i < nHier; i++) { #ifdef AG_DEBUG_CORE Debug(ob, "Loading as %s\n", hier[i]->name); #endif if (hier[i]->load == NULL) continue; if (hier[i]->load(ob, ds, &ver) == -1) { #ifdef AG_VERBOSITY AG_SetError("<0x%x>: %s", (Uint)AG_Tell(ds), AG_GetError()); #else AG_SetErrorS("E16"); #endif free(hier); goto fail; } } free(hier); AG_CloseFile(ds); AG_PostEvent(ob, ob->root, "object-post-load-data", "%s", path); out: AG_ObjectUnlock(ob); AG_UnlockVFS(ob); return (0); fail: AG_CloseFile(ds); fail_unlock: AG_ObjectUnlock(ob); AG_UnlockVFS(ob); return (-1); } static void BackupObjectFile(const char *_Nonnull orig) { char path[AG_PATHNAME_MAX]; if (AG_FileExists(orig)) { Strlcpy(path, orig, sizeof(path)); Strlcat(path, ".bak", sizeof(path)); rename(orig, path); } } /* Save the state of an object and its children. */ int AG_ObjectSaveAll(void *p) { AG_Object *obj = p, *cobj; AG_LockVFS(obj); AG_ObjectLock(obj); if (AG_ObjectSave(obj) == -1) { goto fail; } TAILQ_FOREACH(cobj, &obj->children, cobjs) { AG_ObjectLock(cobj); if (!OBJECT_PERSISTENT(cobj)) { AG_ObjectUnlock(cobj); continue; } if (AG_ObjectSaveAll(cobj) == -1) { AG_ObjectUnlock(cobj); goto fail; } AG_ObjectUnlock(cobj); } AG_ObjectUnlock(obj); AG_UnlockVFS(obj); return (0); fail: AG_ObjectUnlock(obj); AG_UnlockVFS(obj); return (-1); } /* Serialize an object to an arbitrary AG_DataSource(3). */ int AG_ObjectSerialize(void *p, AG_DataSource *ds) { AG_Object *ob = p; AG_Offset countOffs, dataOffs; Uint32 count; AG_Object *chld; AG_ObjectDep *dep; AG_ObjectClass **hier; int i, nHier; #ifdef AG_DEBUG int debugSave; #endif AG_ObjectLock(ob); /* Header */ AG_WriteVersion(ds, agObjectClass.name, &agObjectClass.ver); AG_WriteString(ds, ob->cls->hier); #ifdef AG_ENABLE_DSO AG_WriteString(ds, ob->cls->pvt.libs); #else AG_WriteString(ds, ""); #endif dataOffs = AG_Tell(ds); AG_WriteUint32(ds, 0); /* Data offs */ AG_WriteUint32(ds, (Uint32)(ob->flags & AG_OBJECT_SAVED_FLAGS)); /* Interobject dependency table */ countOffs = AG_Tell(ds); AG_WriteUint32(ds, 0); for (dep = TAILQ_FIRST(&ob->deps), count = 0; dep != TAILQ_END(&ob->deps); dep = TAILQ_NEXT(dep, deps)) { char depName[AG_OBJECT_PATH_MAX]; if (!dep->persistent) { continue; } AG_ObjectCopyName(dep->obj, depName, sizeof(depName)); AG_WriteString(ds, depName); count++; } AG_WriteUint32At(ds, count, countOffs); /* Persistent object variables */ AG_ObjectSaveVariables(ob, ds); /* Table of child objects */ if (ob->flags & AG_OBJECT_CHLD_AUTOSAVE) { countOffs = AG_Tell(ds); AG_WriteUint32(ds, 0); count = 0; TAILQ_FOREACH(chld, &ob->children, cobjs) { if (!OBJECT_PERSISTENT(chld)) { continue; } AG_WriteString(ds, chld->name); AG_WriteString(ds, chld->cls->hier); count++; } AG_WriteUint32At(ds, count, countOffs); } else { AG_WriteUint32(ds, 0); } /* Dataset */ AG_WriteUint32At(ds, AG_Tell(ds), dataOffs); AG_WriteVersion(ds, ob->cls->name, &ob->cls->ver); #ifdef AG_DEBUG if (ob->flags & AG_OBJECT_DEBUG_DATA) { debugSave = AG_SetSourceDebug(ds, 1); } else { debugSave = 0; } #endif if (AG_ObjectGetInheritHier(ob, &hier, &nHier) == -1) { goto fail; } for (i = 0; i < nHier; i++) { #ifdef AG_DEBUG_CORE Debug(ob, "Saving as %s\n", hier[i]->name); #endif if (hier[i]->save == NULL) continue; if (hier[i]->save(ob, ds) == -1) { free(hier); goto fail; } } free(hier); #ifdef AG_DEBUG if (ob->flags & AG_OBJECT_DEBUG_DATA) AG_SetSourceDebug(ds, debugSave); #endif AG_ObjectUnlock(ob); return (0); fail: #ifdef AG_DEBUG if (ob->flags & AG_OBJECT_DEBUG_DATA) AG_SetSourceDebug(ds, debugSave); #endif AG_ObjectUnlock(ob); return (-1); } /* * Unserialize single object (not a VFS) from an arbitrary AG_DataSource(3). * To unserialize complete virtual filesystems, see AG_ObjectLoadFromFile(). */ int AG_ObjectUnserialize(void *p, AG_DataSource *ds) { AG_Object *ob = p; AG_ObjectHeader oh; AG_Version ver; AG_ObjectClass **hier = NULL; int i, nHier; #ifdef AG_DEBUG int debugSave; #endif AG_ObjectLock(ob); /* Object header */ if (AG_ObjectReadHeader(ds, &oh) == -1) { goto fail; } ob->flags &= ~(AG_OBJECT_SAVED_FLAGS); ob->flags |= oh.flags; /* Dependencies, properties */ if (ReadDependencyTable(ds, ob) == -1) goto fail; if (AG_ObjectLoadVariables(ob, ds) == -1) goto fail; /* Table of child objects, expected empty. */ if (AG_ReadUint32(ds) != 0) { AG_SetErrorV("E17", "nChildren != 0"); goto fail; } /* Dataset */ if (AG_ReadVersion(ds, ob->cls->name, &ob->cls->ver, &ver) == -1) goto fail; if (ob->flags & AG_OBJECT_DEBUG_DATA) { #ifdef AG_DEBUG debugSave = AG_SetSourceDebug(ds, 1); #else AG_SetErrorV("E15", _("Can't read without DEBUG")); goto fail; #endif } else { #ifdef AG_DEBUG debugSave = 0; #endif } if (AG_ObjectGetInheritHier(ob, &hier, &nHier) == -1) { goto fail_dbg; } for (i = 0; i < nHier; i++) { #ifdef AG_DEBUG_CORE Debug(ob, "Loading as %s\n", hier[i]->name); #endif if (hier[i]->load == NULL) continue; if (hier[i]->load(ob, ds, &ver) == -1) { #ifdef AG_VERBOSITY AG_SetError("<0x%x>: %s", (Uint)AG_Tell(ds), AG_GetError()); #else AG_SetErrorS("E18"); #endif free(hier); goto fail_dbg; } } free(hier); #ifdef AG_DEBUG if (ob->flags & AG_OBJECT_DEBUG_DATA) AG_SetSourceDebug(ds, debugSave); #endif AG_ObjectUnlock(ob); return (0); fail_dbg: #ifdef AG_DEBUG if (ob->flags & AG_OBJECT_DEBUG_DATA) AG_SetSourceDebug(ds, debugSave); #endif fail: AG_ObjectReset(ob); AG_ObjectFreeDeps(ob); AG_ObjectUnlock(ob); return (-1); } /* Archive an object to a file. */ int AG_ObjectSaveToFile(void *p, const char *pPath) { char pathDir[AG_PATHNAME_MAX]; char path[AG_PATHNAME_MAX]; char name[AG_OBJECT_PATH_MAX]; AG_Object *ob = p; AG_DataSource *ds; AG_LockVFS(ob); AG_ObjectLock(ob); if (!OBJECT_PERSISTENT(ob)) { AG_SetErrorV("E19", _("Non-persistent object")); goto fail_unlock; } AG_ObjectCopyName(ob, name, sizeof(name)); if (pPath != NULL) { Strlcpy(path, pPath, sizeof(path)); } else if (ob->archivePath == NULL) { /* Create the save directory if needed. */ AG_GetString(agConfig, "save-path", pathDir, sizeof(pathDir)); if (ob->save_pfx != NULL) { Strlcat(pathDir, ob->save_pfx, sizeof(pathDir)); } Strlcat(pathDir, name, sizeof(pathDir)); if (AG_FileExists(pathDir) == 0 && AG_MkPath(pathDir) == -1) goto fail_unlock; } if (pPath == NULL) { if (ob->archivePath != NULL) { Strlcpy(path, ob->archivePath, sizeof(path)); } else { Strlcpy(path, pathDir, sizeof(path)); Strlcat(path, AG_PATHSEP, sizeof(path)); Strlcat(path, ob->name, sizeof(path)); Strlcat(path, ".", sizeof(path)); Strlcat(path, ob->cls->name, sizeof(path)); } } #ifdef AG_DEBUG_CORE Debug(ob, "Saving object to %s\n", path); #endif if (agObjectBackups) { BackupObjectFile(path); } else { AG_FileDelete(path); } if ((ds = AG_OpenFile(path, "wb")) == NULL) { goto fail_unlock; } if (AG_ObjectSerialize(ob, ds) == -1) { goto fail; } AG_CloseFile(ds); AG_ObjectUnlock(ob); AG_UnlockVFS(ob); return (0); fail: AG_CloseFile(ds); fail_unlock: AG_ObjectUnlock(ob); AG_UnlockVFS(ob); return (-1); } /* Shorthand for AG_ObjectSaveToFile() */ int AG_ObjectSave(void *p) { return AG_ObjectSaveToFile(p, NULL); } /* Load an object from an AG_Db database entry. */ int AG_ObjectLoadFromDB(void *obj, AG_Db *db, const AG_Dbt *key) { AG_DataSource *ds; AG_Dbt val; if (AG_DbGet(db, key, &val) == -1) { return (-1); } if ((ds = AG_OpenCore(val.data, val.size)) == NULL) { return (-1); } if (AG_ObjectUnserialize(obj, ds) == -1) { AG_CloseCore(ds); return (-1); } return (0); } /* Archive an object to an AG_Db database entry. */ int AG_ObjectSaveToDB(void *pObj, AG_Db *db, const AG_Dbt *key) { AG_Object *obj = pObj; AG_DataSource *ds; AG_Dbt dbKey, dbVal; int rv; if ((ds = AG_OpenAutoCore()) == NULL) return (-1); AG_LockVFS(obj); AG_ObjectLock(obj); rv = AG_ObjectSerialize(obj, ds); AG_ObjectUnlock(obj); AG_UnlockVFS(obj); if (rv == -1) goto fail; dbKey.data = obj->name; dbKey.size = strlen(obj->name)+1; dbVal.data = AG_CORE_SOURCE(ds)->data; dbVal.size = AG_CORE_SOURCE(ds)->size; rv = AG_DbPut(db, &dbKey, &dbVal); AG_CloseAutoCore(ds); return (rv); fail: AG_CloseAutoCore(ds); return (-1); } #endif /* AG_SERIALIZATION */ /* * Change the name of an object (C string). * The parent VFS, if any, must be locked. */ void AG_ObjectSetNameS(void *p, const char *name) { AG_Object *ob = p; char *c; AG_ObjectLock(ob); if (name == NULL) { ob->name[0] = '\0'; } else { Strlcpy(ob->name, name, sizeof(ob->name)); for (c = &ob->name[0]; *c != '\0'; c++) { if (*c == '/' || *c == '\\') /* Pathname separator */ *c = '_'; } } AG_ObjectUnlock(ob); } /* * Change the name of an object (format string). * The parent VFS, if any, must be locked. */ void AG_ObjectSetName(void *p, const char *fmt, ...) { AG_Object *ob = p; va_list ap; char *c; AG_ObjectLock(ob); if (fmt != NULL) { va_start(ap, fmt); Vsnprintf(ob->name, sizeof(ob->name), fmt, ap); va_end(ap); } else { ob->name[0] = '\0'; } for (c = &ob->name[0]; *c != '\0'; c++) { if (*c == '/' || *c == '\\') /* Pathname separator */ *c = '_'; } AG_ObjectUnlock(ob); } #ifdef AG_SERIALIZATION /* Add a new dependency or increment the reference count on one. */ AG_ObjectDep * AG_ObjectAddDep(void *p, void *depobj, int persistent) { AG_Object *ob = p; AG_ObjectDep *dep; AG_ObjectLock(ob); AG_ObjectLock(depobj); TAILQ_FOREACH(dep, &ob->deps, deps) { if (dep->obj == depobj) break; } if (dep != NULL) { if (++dep->count > AG_OBJECT_DEP_MAX) dep->count = AG_OBJECT_DEP_MAX; } else { dep = Malloc(sizeof(AG_ObjectDep)); dep->obj = depobj; dep->count = 1; dep->persistent = persistent; TAILQ_INSERT_TAIL(&ob->deps, dep, deps); } AG_ObjectUnlock(depobj); AG_ObjectUnlock(ob); return (dep); } /* Resolve a given dependency. */ int AG_ObjectFindDep(void *p, Uint32 ind, void **objp) { AG_Object *ob = p; AG_ObjectDep *dep; Uint32 i; if (ind == 0) { *objp = NULL; return (0); } else if (ind == 1) { *objp = (void *)ob; return (0); } AG_ObjectLock(ob); for (dep = TAILQ_FIRST(&ob->deps), i = 2; dep != TAILQ_END(&ob->deps); dep = TAILQ_NEXT(dep, deps), i++) { if (i == ind) break; } if (dep == NULL) { AG_SetError(_("Unable to resolve dependency %s:%u."), ob->name, (Uint)ind); AG_ObjectUnlock(ob); return (-1); } *objp = dep->obj; AG_ObjectUnlock(ob); return (0); } /* * Encode an object dependency as a serializable 32-bit integer. The * values 0 and 1 are reserved, 0 is a NULL value and 1 is the object itself. */ Uint32 AG_ObjectEncodeName(void *p, const void *depobjp) { AG_Object *ob = p; const AG_Object *depobj = depobjp; AG_ObjectDep *dep; Uint32 i; if (depobjp == NULL) { return (0); } else if (p == depobjp) { return (1); } AG_ObjectLock(ob); for (dep = TAILQ_FIRST(&ob->deps), i = 2; dep != TAILQ_END(&ob->deps); dep = TAILQ_NEXT(dep, deps), i++) { if ((const AG_Object *)dep->obj == depobj) { AG_ObjectUnlock(ob); return (i); } } AG_ObjectUnlock(ob); AG_FatalErrorV("E35", "Bad dependency"); return (0); } /* * Decrement the reference count on a dependency and remove it if the * reference count reaches 0. */ void AG_ObjectDelDep(void *p, const void *depobj) { AG_Object *ob = p; AG_ObjectDep *dep; AG_ObjectLock(ob); TAILQ_FOREACH(dep, &ob->deps, deps) { if ((const void *)dep->obj == depobj) break; } if (dep == NULL) { goto out; } if (dep->count == AG_OBJECT_DEP_MAX) { /* Wired */ goto out; } if ((dep->count-1) == 0) { if ((ob->flags & AG_OBJECT_PRESERVE_DEPS) == 0) { TAILQ_REMOVE(&ob->deps, dep, deps); free(dep); } else { dep->count = 0; } } else if (dep->count == 0) { AG_FatalErrorV("E36", "Bad refcount"); } else { dep->count--; } out: AG_ObjectUnlock(ob); } #endif /* AG_SERIALIZATION */ #if AG_MODEL != AG_SMALL /* Move an object towards the head of its parent's children list. */ void AG_ObjectMoveUp(void *p) { AG_Object *ob = p, *prev; AG_Object *parent = ob->parent; AG_LockVFS(parent); if (parent != NULL && ob != TAILQ_FIRST(&parent->children)) { prev = TAILQ_PREV(ob, ag_objectq, cobjs); TAILQ_REMOVE(&parent->children, ob, cobjs); TAILQ_INSERT_BEFORE(prev, ob, cobjs); } AG_UnlockVFS(parent); } /* Move an object towards the tail of its parent's children list. */ void AG_ObjectMoveDown(void *p) { AG_Object *ob = p; AG_Object *parent = ob->parent; AG_Object *next = TAILQ_NEXT(ob, cobjs); AG_LockVFS(parent); if (parent != NULL && next != NULL) { TAILQ_REMOVE(&parent->children, ob, cobjs); TAILQ_INSERT_AFTER(&parent->children, next, ob, cobjs); } AG_UnlockVFS(parent); } /* Move an object to the head of its parent's children list. */ void AG_ObjectMoveToHead(void *p) { AG_Object *ob = p; AG_Object *parent = ob->parent; AG_LockVFS(parent); if (parent != NULL) { TAILQ_REMOVE(&parent->children, ob, cobjs); TAILQ_INSERT_HEAD(&parent->children, ob, cobjs); } AG_UnlockVFS(parent); } #endif /* !AG_SMALL */ /* Move an object to the tail of its parent's children list. */ void AG_ObjectMoveToTail(void *p) { AG_Object *ob = p; AG_Object *parent = ob->parent; AG_LockVFS(parent); if (parent != NULL) { TAILQ_REMOVE(&parent->children, ob, cobjs); TAILQ_INSERT_TAIL(&parent->children, ob, cobjs); } AG_UnlockVFS(parent); } #ifdef AG_SERIALIZATION /* * Remove the data files of an object and its children. * The object's VFS must be locked. */ void AG_ObjectUnlinkDatafiles(void *p) { char path[AG_PATHNAME_MAX]; AG_Object *ob = p, *cob; AG_ObjectLock(ob); if (AG_ObjectCopyFilename(ob, path, sizeof(path)) == 0) { AG_FileDelete(path); } TAILQ_FOREACH(cob, &ob->children, cobjs) { AG_ObjectUnlinkDatafiles(cob); } if (AG_ObjectCopyDirname(ob, path, sizeof(path)) == 0) { AG_RmDir(path); } AG_ObjectUnlock(ob); } /* * Check whether the dataset of the given object or any of its children are * different with respect to the last archive. The result is only valid as * long as the object and VFS are locked, and this assumes that no other * application is concurrently accessing the datafiles. */ int AG_ObjectChangedAll(void *p) { AG_Object *ob = p, *cob; AG_LockVFS(ob); AG_ObjectLock(ob); if (AG_ObjectChanged(ob) == 1) { goto changed; } TAILQ_FOREACH(cob, &ob->children, cobjs) { if (AG_ObjectChangedAll(cob) == 1) goto changed; } AG_ObjectUnlock(ob); AG_UnlockVFS(ob); return (0); changed: AG_ObjectUnlock(ob); AG_UnlockVFS(ob); return (1); } /* * Check whether the dataset of the given object is different with respect * to its last archive. The result is only valid as long as the object is * locked, and this assumes no other application is concurrently accessing * the datafiles. */ int AG_ObjectChanged(void *p) { #if AG_MODEL == AG_SMALL char *bufCur = Malloc(AG_BUFFER_MAX); char *bufLast = Malloc(AG_BUFFER_MAX); #else char bufCur[AG_BUFFER_MAX]; char bufLast[AG_BUFFER_MAX]; #endif char pathCur[AG_PATHNAME_MAX]; char pathLast[AG_PATHNAME_MAX]; AG_Object *ob = p; FILE *fLast, *fCur; AG_Size rvLast, rvCur; int rv = 0; AG_ObjectLock(ob); if (!OBJECT_PERSISTENT(ob)) { goto out; } AG_ObjectCopyFilename(ob, pathLast, sizeof(pathLast)); if ((fLast = fopen(pathLast, "r")) == NULL) { rv = 1; goto out; } AG_GetString(agConfig, "tmp-path", pathCur, sizeof(pathCur)); Strlcat(pathCur, AG_PATHSEP, sizeof(pathCur)); Strlcat(pathCur, "_chg.", sizeof(pathCur)); Strlcat(pathCur, ob->name, sizeof(pathCur)); if (AG_ObjectSaveToFile(ob, pathCur) == -1) { fclose(fLast); rv = 1; goto out; } if ((fCur = fopen(pathCur, "r")) == NULL) { fclose(fLast); rv = 1; goto out; } for (;;) { rvLast = fread(bufLast, 1, sizeof(bufLast), fLast); rvCur = fread(bufCur, 1, sizeof(bufCur), fCur); if (rvLast != rvCur || (rvLast > 0 && memcmp(bufLast, bufCur, rvLast) != 0)) { rv = 1; break; } if (feof(fLast)) { if (!feof(fCur)) { rv = 1; } break; } if (feof(fCur)) { if (!feof(fLast)) { rv = 1; } break; } } AG_FileDelete(pathCur); fclose(fCur); fclose(fLast); out: AG_ObjectUnlock(ob); #if AG_MODEL == AG_SMALL free(bufCur); free(bufLast); #endif return (rv); } #endif /* AG_SERIALIZATION */ /* * Generate an object name that is unique in the given parent object. The * name is only guaranteed to remain unique as long as the VFS and parent * object are locked. The class name is used as prefix. */ void AG_ObjectGenName(void *p, AG_ObjectClass *C, char *name, AG_Size len) { AG_Object *pobj = p; Uint i = 0; AG_Object *ch; tryname: Strlcpy(name, C->name, len); Strlcat(name, " #", len); StrlcatUint(name, i, len); if (pobj != NULL) { AG_LockVFS(pobj); TAILQ_FOREACH(ch, &pobj->children, cobjs) { if (strcmp(ch->name, name) == 0) break; } AG_UnlockVFS(pobj); if (ch != NULL) { i++; goto tryname; } } } #if AG_MODEL != AG_SMALL /* Generate a unique object name using the specified prefix. */ void AG_ObjectGenNamePfx(void *p, const char *pfx, char *name, AG_Size len) { AG_Object *pobj = p; Uint i = 1; AG_Object *ch; tryname: Strlcpy(name, pfx, len); StrlcatUint(name, i, len); if (pobj != NULL) { AG_LockVFS(pobj); TAILQ_FOREACH(ch, &pobj->children, cobjs) { if (strcmp(ch->name, name) == 0) break; } AG_UnlockVFS(pobj); if (ch != NULL) { i++; goto tryname; } } } #endif /* !AG_SMALL */
22.479096
88
0.663586
[ "object" ]
8fd6348047f0615bb57b8722b95832898cf4faf9
22,904
h
C
SoulHookDylib/SOHeader.h
fengjixuchui/SoulHook
2db61d432aa816149a5037ed0c7ef4f48580d3d7
[ "MIT" ]
30
2019-06-27T02:34:06.000Z
2022-03-27T13:18:06.000Z
SoulHookDylib/SOHeader.h
fengjixuchui/SoulHook
2db61d432aa816149a5037ed0c7ef4f48580d3d7
[ "MIT" ]
5
2020-12-22T12:51:03.000Z
2021-11-02T09:16:32.000Z
SoulHookDylib/SOHeader.h
fengjixuchui/SoulHook
2db61d432aa816149a5037ed0c7ef4f48580d3d7
[ "MIT" ]
14
2020-09-30T08:12:03.000Z
2021-10-15T03:02:02.000Z
// // SOHeader.h // SoulHook // // Created by miniSeven on 2019/6/24. // Copyright © 2019 fancy. All rights reserved. // #import <UIKit/UIKit.h> #import <WebKit/WebKit.h> #import <AVFoundation/AVFoundation.h> #import "SOHookSettingController.h" #import <objc/runtime.h> #define SO_THEME_COLOR [UIColor colorWithRed:37/255.0 green:212/255.0 blue:208/255.0 alpha:1] CG_INLINE BOOL ExchangeImplementationsInTwoClasses(Class _fromClass, SEL _originSelector, Class _toClass, SEL _newSelector) { if (!_fromClass || !_toClass) { return NO; } Method oriMethod = class_getInstanceMethod(_fromClass, _originSelector); Method newMethod = class_getInstanceMethod(_toClass, _newSelector); if (!newMethod) { return NO; } BOOL isAddedMethod = class_addMethod(_fromClass, _originSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)); if (isAddedMethod) { // 如果 class_addMethod 成功了,说明之前 fromClass 里并不存在 originSelector,所以要用一个空的方法代替它,以避免 class_replaceMethod 后,后续 toClass 的这个方法被调用时可能会 crash IMP oriMethodIMP = method_getImplementation(oriMethod) ?: imp_implementationWithBlock(^(id selfObject) {}); const char *oriMethodTypeEncoding = method_getTypeEncoding(oriMethod) ?: "v@:"; class_replaceMethod(_toClass, _newSelector, oriMethodIMP, oriMethodTypeEncoding); } else { method_exchangeImplementations(oriMethod, newMethod); } return YES; } /// 交换同一个 class 里的 originSelector 和 newSelector 的实现,如果原本不存在 originSelector,则相当于给 class 新增一个叫做 originSelector 的方法 CG_INLINE BOOL ExchangeImplementations(Class _class, SEL _originSelector, SEL _newSelector) { return ExchangeImplementationsInTwoClasses(_class, _originSelector, _class, _newSelector); } CG_INLINE BOOL HasOverrideSuperclassMethod(Class targetClass, SEL targetSelector) { Method method = class_getInstanceMethod(targetClass, targetSelector); if (!method) return NO; Method methodOfSuperclass = class_getInstanceMethod(class_getSuperclass(targetClass), targetSelector); if (!methodOfSuperclass) return YES; return method != methodOfSuperclass; } /** * 用 block 重写某个 class 的指定方法 * @param targetClass 要重写的 class * @param targetSelector 要重写的 class 里的实例方法,注意如果该方法不存在于 targetClass 里,则什么都不做 * @param implementationBlock 该 block 必须返回一个 block,返回的 block 将被当成 targetSelector 的新实现,所以要在内部自己处理对 super 的调用,以及对当前调用方法的 self 的 class 的保护判断(因为如果 targetClass 的 targetSelector 是继承自父类的,targetClass 内部并没有重写这个方法,则我们这个函数最终重写的其实是父类的 targetSelector,所以会产生预期之外的 class 的影响,例如 targetClass 传进来 UIButton.class,则最终可能会影响到 UIView.class),implementationBlock 的参数里第一个为你要修改的 class,也即等同于 targetClass,第二个参数为你要修改的 selector,也即等同于 targetSelector,第三个参数是一个 block,用于获取 targetSelector 原本的实现,由于 IMP 可以直接当成 C 函数调用,所以可利用它来实现“调用 super”的效果,但由于 targetSelector 的参数个数、参数类型、返回值类型,都会影响 IMP 的调用写法,所以这个调用只能由业务自己写。 */ CG_INLINE BOOL OverrideImplementation(Class targetClass, SEL targetSelector, id (^implementationBlock)(__unsafe_unretained Class originClass, SEL originCMD, IMP (^originalIMPProvider)(void))) { Method originMethod = class_getInstanceMethod(targetClass, targetSelector); IMP imp = method_getImplementation(originMethod); BOOL hasOverride = HasOverrideSuperclassMethod(targetClass, targetSelector); // 以 block 的方式达到实时获取初始方法的 IMP 的目的,从而避免先 swizzle 了 subclass 的方法,再 swizzle superclass 的方法,会发现前者调用时不会触发后者 swizzle 后的版本的 bug。 IMP (^originalIMPProvider)(void) = ^IMP(void) { IMP result = NULL; if (hasOverride) { result = imp; } else { // 如果 superclass 里依然没有实现,则会返回一个 objc_msgForward 从而触发消息转发的流程 // https://github.com/Tencent/QMUI_iOS/issues/776 Class superclass = class_getSuperclass(targetClass); result = class_getMethodImplementation(superclass, targetSelector); } // 这只是一个保底,这里要返回一个空 block 保证非 nil,才能避免用小括号语法调用 block 时 crash // 空 block 虽然没有参数列表,但在业务那边被转换成 IMP 后就算传多个参数进来也不会 crash if (!result) { result = imp_implementationWithBlock(^(id selfObject){ // QMUILogWarn(([NSString stringWithFormat:@"%@", targetClass]), @"%@ 没有初始实现,%@\n%@", NSStringFromSelector(targetSelector), selfObject, [NSThread callStackSymbols]); }); } return result; }; if (hasOverride) { method_setImplementation(originMethod, imp_implementationWithBlock(implementationBlock(targetClass, targetSelector, originalIMPProvider))); } else { NSMethodSignature *signature = [targetClass instanceMethodSignatureForSelector:targetSelector]; NSString *typeString = [signature performSelector:NSSelectorFromString([NSString stringWithFormat:@"_%@String", @"type"])]; const char *typeEncoding = method_getTypeEncoding(originMethod) ?: typeString.UTF8String; class_addMethod(targetClass, targetSelector, imp_implementationWithBlock(implementationBlock(targetClass, targetSelector, originalIMPProvider)), typeEncoding); } return YES; } /** * 用 block 重写某个 class 的某个无参数且返回值为 void 的方法,会自动在调用 block 之前先调用该方法原本的实现。 * @param targetClass 要重写的 class * @param targetSelector 要重写的 class 里的实例方法,注意如果该方法不存在于 targetClass 里,则什么都不做,注意该方法必须无参数,返回值为 void * @param implementationBlock targetSelector 的自定义实现,直接将你的实现写进去即可,不需要管 super 的调用。参数 selfObject 代表当前正在调用这个方法的对象,也即 self 指针。 */ CG_INLINE BOOL ExtendImplementationOfVoidMethodWithoutArguments(Class targetClass, SEL targetSelector, void (^implementationBlock)(__kindof NSObject *selfObject)) { return OverrideImplementation(targetClass, targetSelector, ^id(__unsafe_unretained Class originClass, SEL originCMD, IMP (^originalIMPProvider)(void)) { void (^block)(__unsafe_unretained __kindof NSObject *selfObject) = ^(__unsafe_unretained __kindof NSObject *selfObject) { void (*originSelectorIMP)(id, SEL); originSelectorIMP = (void (*)(id, SEL))originalIMPProvider(); originSelectorIMP(selfObject, originCMD); implementationBlock(selfObject); }; #if __has_feature(objc_arc) return block; #else return [block copy]; #endif }); } NS_ASSUME_NONNULL_BEGIN //统计埋点 @interface TalkingData: NSObject //AppId:A52B96856DC**********1B583A45945 channelId:AppStore + (void)sessionStarted:(NSString *)appKey withChannelId:(NSString *)channelId; + (void)initWithAppID:(NSString *)AppId channelID:(NSString *)channelId; @end //统计埋点 @interface KochavaTracker: NSObject //appGUIDString = "kosoul-ios-********"; - (void)configureWithParametersDictionary:(NSDictionary *)dic delegate:(id)delegate; @end //bugly @interface BuglyConfig : NSObject @end @interface Bugly : NSObject + (void)startWithAppId:(NSString *)appId; + (void)startWithAppId:(NSString *)appId config:(BuglyConfig *)config; @end //SmAntiFraud 数美 @interface SmAntiFraud : NSObject - (void)create:(id)opt; - (NSString*)getDeviceId; @end @interface AvatarModifyViewController: UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate> @property (copy, nonatomic) NSString *avatarOriginName; @property (copy, nonatomic) NSString *avatarName; @property (nonatomic, strong) WKWebView *webView; @property (nonatomic, strong, nullable) UIImage *customImage; - (void)updateUserInfWithAvatarName:(NSString *)arg1 originAvatarName:(NSString *)arg2 image:(UIImage *)arg3 originImage:(UIImage *)arg4 svgInfo:(NSString *)arg5; //上传 - (void)uploadToQiniu:(UIImage *)arg1 svginfo:(id)arg2 token:(NSDictionary *)arg3 imageName:(NSString *)arg4 completion:(dispatch_block_t)arg5; - (void)uploadOriginAvatar:(UIImage *)arg1 avatarSVGInfo:(id)arg2; - (void)uploadAvatar:(UIImage *)arg1 avatarSVGInfo:(id)arg2; - (void)viewDidLoad; //add - (void)customAction:(UIButton *)sender; - (void)cancelAction:(UIButton *)sender; - (void)confirmAction:(UIButton *)sender; - (UIImage *)resizeImage:(CGSize)size; @end @interface IMPTextMsg : NSObject @property(copy, nonatomic) NSString *text; @end @interface IMPMsgCommand : NSObject @property (strong, nonatomic) id commonMessage; @property (strong, nonatomic) id expressionMessage; @property (strong, nonatomic) id extChatMessage; @property (strong, nonatomic) NSMutableDictionary *extMap; @property (readonly, nonatomic) unsigned long long extMap_Count; @property (strong, nonatomic) id fingerGuessMessage; @property (copy, nonatomic) NSString *from; @property (readonly, nonatomic) int msgOneOfCase; @property (strong, nonatomic) id musicMessage; @property (copy, nonatomic) NSString *notice; @property (strong, nonatomic) id picMessage; @property (strong, nonatomic) id picMessages; @property (strong, nonatomic) id positionMessage; @property (strong, nonatomic) id repostMessge; @property (strong, nonatomic) id rollDiceMessage; @property (strong, nonatomic) id sensitiveWordMessage; @property (strong, nonatomic) id shareTagMessage; @property (nonatomic) int snapChat; @property (strong, nonatomic) id snapChatMessage; @property (strong, nonatomic) id soulmateCardMessage; @property (strong, nonatomic) IMPTextMsg *textMsg; @property (nonatomic) long long timestamp; @property (copy, nonatomic) NSString *to; @property (nonatomic) int type; @property (strong, nonatomic) id unReadCountMessage; @property (strong, nonatomic) id userCardMessage; @property (strong, nonatomic) id userExpressionMessage; @property (strong, nonatomic) id videoMessage; @property (strong, nonatomic) id voiceChatMessage; @property (strong, nonatomic) id voiceMessage; @end @interface IMPCommandMessage : NSObject @property (copy, nonatomic) NSString *acceptedMsgId; @property (strong, nonatomic) id ackCommand; @property (strong, nonatomic) id chatRoomCommand; @property (nonatomic) int clientType; @property (copy, nonatomic) NSString *cmdId; @property (readonly, nonatomic) int cmdOneOfCase; @property (copy, nonatomic) NSString *crc; @property (copy, nonatomic) NSString *encryptedUserId; @property (strong, nonatomic) id finCommand; @property (strong, nonatomic) IMPMsgCommand *msgCommand; @property (strong, nonatomic) id msgFin; @property (strong, nonatomic) id notifyCommand; @property (strong, nonatomic) id orderCommand; @property (strong, nonatomic) id pshCommand; @property (strong, nonatomic) id pushMessage; @property (strong, nonatomic) id reportCommand; @property (strong, nonatomic) id respCommand; @property (copy, nonatomic) NSString *soulId; @property (strong, nonatomic) id syncCommand; @property (strong, nonatomic) id syncFin; @property (strong, nonatomic) id transCommand; @property (nonatomic) int type; @end //SoulSocket -> SocketService -> ChatTransCenter (deliverMessageListToIMService:) //-> NBIMService(deliverMessageListToIMService:) //收到消息 先走 pushMessageToExtor 再走 receiveMessage,hook后者 cmdmsg.type = 8(recall)时 将此cmd置空 @interface ChatTransCenter : NSObject - (void)receiveMessage:(NSArray *)arg1; - (void)pushMessageToExtor:(NSArray *)arg1; - (void)sendCommandsMessage:(id)arg1 completion:(id)arg2; @end @interface ImageIMModel : NSObject @property (nonatomic) long long mark; @property (nonatomic, copy) NSString *url; @end @interface VoiceIMModel : NSObject @property (nonatomic, copy) NSString *remoteURL; @end @interface VideoIMModel : NSObject @property (nonatomic) long long mark; @property (nonatomic, copy) NSString *url; @end @interface SOChatMessageModel : NSObject @property (nonatomic) BOOL snap; //flash @property (strong, nonatomic) ImageIMModel *imageIMModel; @property (strong, nonatomic) VoiceIMModel *voiceIMModel; @property (strong, nonatomic) VideoIMModel *videoIMModel; @end @interface SOPrivateChatTableViewCell : UITableViewCell @property (nonatomic, strong) SOChatMessageModel *model; @end @interface SOUserDefinedEmoticonTableViewCell : SOPrivateChatTableViewCell - (void)tapIamge; @end @interface SOChatFlashPhotoMessageTableViewCell : SOPrivateChatTableViewCell { UIImageView *imageView; UIVisualEffectView *lookBeforeBgView; UIView *lookAferBgView; UIImageView *iconImage; UILabel *titleLabel; UILabel *photoMarklabel; } - (void)tapFlashPhoto; @end @interface SOChatPhotoMessageTableViewCell : SOPrivateChatTableViewCell - (void)tapIamge; @end @interface SOChatAudioMessageTableViewCell : SOPrivateChatTableViewCell - (void)run; @end @interface SOChatVideoMessageTableViewCell : SOPrivateChatTableViewCell - (void)tap; - (void)UpdateSubclassingUIWithChatMessageModel:(id)arg1; @end @interface SOLookFlashPhotoView : UIView - (id)initWithFrame:(CGRect)arg1 WithImage:(NSData *)arg2 andIsSelf:(BOOL)arg3; - (void)tapImage:(id)arg1; - (void)longPressBgView:(UILongPressGestureRecognizer *)arg1; - (void)tapbgView:(UITapGestureRecognizer *)arg1; @end //表情键盘 @interface SOCollectEmoticonView : UIView @property (nonatomic, copy) void (^diceBlock)(void); @property (nonatomic, copy) void (^fingerBlock)(void); - (void)fingerAction:(UIButton *)sender; - (void)diceAction:(UIButton *)sender; - (void)collectionView:(UICollectionView *)arg1 didSelectItemAtIndexPath:(NSIndexPath *)arg2; @end //设置页 @interface SOSettingsVC : UIViewController - (void)so_rightItemWithTitle:(id)arg1; - (void)rightItemClick:(id)arg1; @end @interface SOBuildMessageManager : NSObject + (id)buildRollDiceMessageTo:(NSString *)arg1 info:(NSString *)arg2; + (id)buildFingerGuessMessageTo:(NSString *)arg1 info:(NSString *)arg2; + (id)buildTextIMMessage:(NSString *)text to:(NSString *)toId senstive:(int)arg3 messageExt:(id)arg4; @end @interface SOUserInfoViewController : UIViewController //@property (nonatomic) BOOL isMySoulmate; @property (nonatomic) BOOL isCanCreatSoulMate; //@property (nonatomic, copy) void (^intiveSoulmateBlock)(void); //@property (nonatomic, copy) void (^cancelSoulmateBlock)(void); - (void)cancelSoulMate; - (void)tableView:(UITableView *)arg1 didSelectRowAtIndexPath:(NSIndexPath *)arg2; @end @interface AppShell : UIResponder - (void)displayAdvert; // AppDelegate已经没有这个方法了 放在AppShell中了 @end @interface HeaderTwoViewController : UIViewController @property (nonatomic, copy) NSString *headImageName; - (void)confirmClick:(id)arg1; @end @interface SOHTTPSessionManager : NSObject - (void)handleRequestSuccess:(id)arg1 task:(id)arg2 withSuccessHandler:(dispatch_block_t)arg3 withFailureHandler:(dispatch_block_t)arg4 withFinishHandler:(dispatch_block_t)arg5; @end @interface SOReleaseViewController : UIViewController - (void)tagEditContainerViewDidLocationItemClick:(id)arg1; @end @interface SoulIMMessage : NSObject @property (copy, nonatomic) NSArray *imageArray; @property (copy, nonatomic) NSString *media; @property (strong, nonatomic) id textIMModel;//TextIMModel @property (nonatomic) BOOL fromMine; @property (strong, nonatomic) NSError *error; @property (copy, nonatomic) NSString *notice; @property (copy, nonatomic) NSString *sessionId; @property (copy, nonatomic) NSDictionary *extMap; @property (strong, nonatomic) id unreadModel;//UnReadIMModel @property (strong, nonatomic) id commenModel;//CommonIMModel @property (strong, nonatomic) id musicShareModel; //MusicShareIMModel @property (strong, nonatomic) id loationshareModel; //LocationShareIMModel @property (strong, nonatomic) id shareTagModel; //ShareTagModel @property (strong, nonatomic) id extModel; // ExtModel @property (strong, nonatomic) id callVoiceIMModel; // CallVoiceIMModel @property (strong, nonatomic) id fingerDiceIMModel; // FingerDiceIMModel @property (strong, nonatomic) id voiceIMModel; // VoiceIMModel @property (strong, nonatomic) id imageModel; // ImageIMModel @property (strong, nonatomic) id videoModel; // VideoIMModel @property (nonatomic) long long snap; @property (nonatomic) long long isTagetRcDone; @property (nonatomic) long long localId; @property (copy, nonatomic) NSString *targetId; @property (copy, nonatomic) NSString *msgId; @property (copy, nonatomic) NSString *fromUid; @property (copy, nonatomic) NSString *toUid; @property (copy, nonatomic) NSDictionary *data; @property (nonatomic) int type; @end @interface SOChatListViewController : UIViewController @property (strong, nonatomic) NSMutableArray *dataArr; @end @interface SOChatListModel : NSObject @property (nonatomic) BOOL isChatManuscript; @property (nonatomic) BOOL isSelectedShare; @property (nonatomic) BOOL isSelected; @property (copy, nonatomic) NSString *birthday; @property (nonatomic) BOOL isMutualFollow; @property (copy, nonatomic) NSString *signatrue; @property (copy, nonatomic) NSString *comeFromStr; @property (copy, nonatomic) NSString *birthDay; @property (nonatomic) long long lastMessageTime; @property (nonatomic) int unreadMessagesCount; @property (copy, nonatomic) NSString *soulmateStr; @property (copy, nonatomic) NSString *contentStr; @property (copy, nonatomic) NSString *alicsStr; @property (copy, nonatomic) NSString *headIcon; @property (copy, nonatomic) NSString *headBGColor; @property (copy, nonatomic) NSString *userID; @end @interface SOMovieVC : UIViewController @property (nonatomic) BOOL isFlashVideo; @end @interface ScrollerWebController : UIViewController <UIWebViewDelegate> @property (strong, nonatomic) UIWebView *webView; @property (copy, nonatomic) NSString *url; - (void)actionForStartNetworkRequst:(id)arg1 callBack:(dispatch_block_t)arg2; - (void)webViewDidFinishLoad:(UIWebView *)webView; - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error; @end @interface NBIMService : NSObject + (id)sharedInstance; @property (strong, nonatomic) ChatTransCenter *chatCenter; @end @interface TextIMModel : NSObject @property(nonatomic) long long sensitive; @property(copy, nonatomic) NSString *text; @end typedef void (^progressBlock)(NSProgress *downloadProgress); typedef void (^successBlock)(NSURLSessionDataTask *task, id _Nullable responseObject); typedef void (^failureBlock)(NSURLSessionDataTask * _Nullable task, NSError *error); @interface AFHTTPSessionManager : NSObject - (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method URLString:(NSString *)URLString parameters:(id)parameters headers:(nullable NSDictionary <NSString *, NSString *> *)headers uploadProgress:(nullable progressBlock) uploadProgress downloadProgress:(nullable progressBlock) downloadProgress success:(successBlock)success failure:(failureBlock)failure; @end @interface SOPrivateChatViewController : UIViewController { UIMenuItem *_revokeflagMenuItem; } @property (nonatomic, copy) NSString *chatId; //对方id @property (nonatomic, strong) UIView *customNavBar; //SAPrivateChatNavBar @property (nonatomic, strong) UIMenuController *menuController; - (void)_showMenuViewIndexPath:(id)arg1; - (void)moreAction:(UIButton *)sender; @end @interface NewTabBarController : UITabBarController @end @interface SOWatermarkOperation : NSObject - (id)makeWatermarkPhotoImageWithImage:(id)arg1 watermark:(id)arg2; - (id)makeWatermarkPhotoImageWithImage:(id)arg1; @end @interface FeelingViewController : UIViewController @property (nonatomic, strong) UITableView *tableView; - (void)scrollViewDidScroll:(UITableView *)scrollView; - (void)myMeetingViewDidTap; - (void)kuakuaWellDidTap; - (void)clickHiddenTag; - (void)updateMeSignature:(nullable UIButton *)arg1; - (void)updateHeadImageView:(nullable UIImageView *)arg1 bgHeadColor:(nullable UIImageView *)arg2; - (void)updateBgImageView:(nullable UIImageView *)arg1; @end @interface StrangerViewController : UIViewController @property (nonatomic, strong) id nav; //SOCustomNav; @property (nonatomic, strong) NSMutableArray *dataArray; @property (nonatomic, strong) UITableView *tableView; @property (nonatomic, strong) NSDictionary *avatarModel; //暂存数据用 @property (nonatomic, copy) NSString *userID; - (void)filterAction:(UIButton *)sender; - (void)endRefresh; @end @interface SOWebItemModel : NSObject @property(nonatomic, copy) NSString *url; @property(nonatomic, strong) NSMutableDictionary *params; @property(nonatomic, assign) long long urlType; @property(nonatomic, copy) NSString *title; @property(nonatomic, copy) NSString *userId; //@property(nonatomic, copy) void (^avatarChangeBlock)(void); //@property(nonatomic, copy) void (^avatarRegisterChangeBlock)(void); //@property(nonatomic, copy) void (^makeFaceFinishNotPayBlock)(void); @end @interface SOUserBridgeManager : NSObject @property(nonatomic, strong, nullable) UIImage *customImage; - (UIImage *)resizeImage:(UIImage *)img size:(CGSize)size; @end @interface SOWebItemViewController : UIViewController <UINavigationControllerDelegate,UIImagePickerControllerDelegate> @property(strong, nonatomic) SOWebItemModel *model; @property(strong, nonatomic) UIView *webView; @property(strong, nonatomic) SOUserBridgeManager *userBridge; - (void)customAction:(UIButton *)sender; - (UIImage *)resizeImage:(UIImage *)img size:(CGSize)size; @end @interface SOPersonalInfoVC : UIViewController - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; @end @interface SoulChatLimitGiftViewController : UIViewController @property(nonatomic, copy) void (^cancelBlock)(void); - (void)clickCancelButtonAction:(id)arg1; @end @interface SOPost : NSObject @property (nonatomic, assign) long long officialTag; @property (nonatomic, copy) NSString *content; @end @interface SOTopicInfoViewController : UIViewController @property(nonatomic, copy) void (^deletePostBlock)(void); @end @interface BellNotifyInfoModel : NSObject @property (nonatomic, copy) NSString *officialTag; @end @interface SOMainSquareViewController : UIViewController - (void)noNameController:(UIButton *)sender; @end @interface SOMusicPlayerModel : NSObject @property (copy, nonatomic) NSString *url; @end /// 悬浮播放器 @interface SOMusicPlayerView : UIView @property (nonatomic, strong) UIView *musicInfoView; @property (nonatomic, strong) SOMusicPlayerModel *musicPlayerModel; @property (nonatomic, strong) UIButton *screenBtn; @property (nonatomic, strong) UIButton *downloadBtn; - (void)createMusicMusicInfoView; - (void)spreadMusicFloatsView; - (void)foldMusicFloatsView; - (void)clickDownloadBtn; @end /// toast @interface UIView (Toast) - (void)makeToast:(NSString *)message; @end NS_ASSUME_NONNULL_END //SOSettingsVC
32.955396
570
0.762138
[ "model" ]
8fda2f8a4bbb9f1b8d7f13fdaa4cd561a7eb1372
1,137
h
C
inc/cmdline/cmdline.h
Kerisa/EzvizLocalProcess
77c72413bbdb862c221af042967d99d44e82fe9f
[ "MIT" ]
null
null
null
inc/cmdline/cmdline.h
Kerisa/EzvizLocalProcess
77c72413bbdb862c221af042967d99d44e82fe9f
[ "MIT" ]
null
null
null
inc/cmdline/cmdline.h
Kerisa/EzvizLocalProcess
77c72413bbdb862c221af042967d99d44e82fe9f
[ "MIT" ]
null
null
null
#pragma once #include <map> #include <string> #include <vector> class CmdLineParser { public: class Param { public: std::string mKey; std::vector<std::string> mValues; size_t mValueCount{ 0 }; bool mRequirement{ false }; Param() = default; Param(const std::string& key) : mKey(key) {} Param(const std::string& key, int valueCount, bool req) : mKey(key), mValueCount(valueCount), mRequirement(req) {} std::string GetValue0() const { return !mValues.empty() ? mValues[0] : std::string(); } }; public: CmdLineParser() {} void AddPartern(const std::string& key, size_t valueCount, bool requirement); void AddHelp(const std::string& str); const CmdLineParser::Param& GetValue(const std::string& key); const std::string& HelpInfo(); bool Parse(size_t argc, char** argv); private: std::map<std::string, Param> mKeyValue; std::vector<std::string> mValue; std::string mHelpInfo; };
29.153846
119
0.554969
[ "vector" ]
8fdbcfc5f289affc7d6b1a2633ef281f2ad4a64f
957
h
C
panda_simulator_examples/include/objectscanner.h
doterkuile/panda_simulator
cb4fb319617256578396e8f05afd8373d888594c
[ "Apache-2.0" ]
null
null
null
panda_simulator_examples/include/objectscanner.h
doterkuile/panda_simulator
cb4fb319617256578396e8f05afd8373d888594c
[ "Apache-2.0" ]
null
null
null
panda_simulator_examples/include/objectscanner.h
doterkuile/panda_simulator
cb4fb319617256578396e8f05afd8373d888594c
[ "Apache-2.0" ]
null
null
null
#ifndef OBJECTSCANNER_H #define OBJECTSCANNER_H #include <ros/ros.h> #include <iostream> #include "sensor_msgs/JointState.h" #include "franka_core_msgs/JointCommand.h" #include "franka_core_msgs/RobotState.h" class ObjectScanner { public: ObjectScanner(ros::NodeHandle &nh); void jointCallback(const sensor_msgs::JointState &inputMsg); void robotCallback(const franka_core_msgs::RobotState &inputMsg); void sendToNeutral(); bool receivedJointPositions(); private: void configParams(); ros::NodeHandle nh_; ros::Publisher pubJoint_; ros::Subscriber subJoint_; ros::Subscriber subRobot_; std::string jointSubTopic_; std::string robotSubTopic_; std::string jointPubTopic_; std::vector<std::string> jointNames_; std::vector<double> neutralPosition_; std::vector<double> jointVelocities_; std::vector<double> jointPositions_; bool receivedPositions_; }; #endif // OBJECTSCANNER_H
22.785714
69
0.739812
[ "vector" ]
8ff2338a0c0147993a613cee49ab7dd02e0678f1
21,041
h
C
aws-cpp-sdk-awstransfer/include/aws/awstransfer/model/ListedAccess.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-awstransfer/include/aws/awstransfer/model/ListedAccess.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-awstransfer/include/aws/awstransfer/model/ListedAccess.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/awstransfer/Transfer_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/awstransfer/model/HomeDirectoryType.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace Transfer { namespace Model { /** * <p>Lists the properties for one or more specified associated * accesses.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/transfer-2018-11-05/ListedAccess">AWS * API Reference</a></p> */ class AWS_TRANSFER_API ListedAccess { public: ListedAccess(); ListedAccess(Aws::Utils::Json::JsonView jsonValue); ListedAccess& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The landing directory (folder) for a user when they log in to the server * using the client.</p> <p>A <code>HomeDirectory</code> example is * <code>/bucket_name/home/mydirectory</code>.</p> */ inline const Aws::String& GetHomeDirectory() const{ return m_homeDirectory; } /** * <p>The landing directory (folder) for a user when they log in to the server * using the client.</p> <p>A <code>HomeDirectory</code> example is * <code>/bucket_name/home/mydirectory</code>.</p> */ inline bool HomeDirectoryHasBeenSet() const { return m_homeDirectoryHasBeenSet; } /** * <p>The landing directory (folder) for a user when they log in to the server * using the client.</p> <p>A <code>HomeDirectory</code> example is * <code>/bucket_name/home/mydirectory</code>.</p> */ inline void SetHomeDirectory(const Aws::String& value) { m_homeDirectoryHasBeenSet = true; m_homeDirectory = value; } /** * <p>The landing directory (folder) for a user when they log in to the server * using the client.</p> <p>A <code>HomeDirectory</code> example is * <code>/bucket_name/home/mydirectory</code>.</p> */ inline void SetHomeDirectory(Aws::String&& value) { m_homeDirectoryHasBeenSet = true; m_homeDirectory = std::move(value); } /** * <p>The landing directory (folder) for a user when they log in to the server * using the client.</p> <p>A <code>HomeDirectory</code> example is * <code>/bucket_name/home/mydirectory</code>.</p> */ inline void SetHomeDirectory(const char* value) { m_homeDirectoryHasBeenSet = true; m_homeDirectory.assign(value); } /** * <p>The landing directory (folder) for a user when they log in to the server * using the client.</p> <p>A <code>HomeDirectory</code> example is * <code>/bucket_name/home/mydirectory</code>.</p> */ inline ListedAccess& WithHomeDirectory(const Aws::String& value) { SetHomeDirectory(value); return *this;} /** * <p>The landing directory (folder) for a user when they log in to the server * using the client.</p> <p>A <code>HomeDirectory</code> example is * <code>/bucket_name/home/mydirectory</code>.</p> */ inline ListedAccess& WithHomeDirectory(Aws::String&& value) { SetHomeDirectory(std::move(value)); return *this;} /** * <p>The landing directory (folder) for a user when they log in to the server * using the client.</p> <p>A <code>HomeDirectory</code> example is * <code>/bucket_name/home/mydirectory</code>.</p> */ inline ListedAccess& WithHomeDirectory(const char* value) { SetHomeDirectory(value); return *this;} /** * <p>The type of landing directory (folder) you want your users' home directory to * be when they log into the server. If you set it to <code>PATH</code>, the user * will see the absolute Amazon S3 bucket or EFS paths as is in their file transfer * protocol clients. If you set it <code>LOGICAL</code>, you need to provide * mappings in the <code>HomeDirectoryMappings</code> for how you want to make * Amazon S3 or EFS paths visible to your users.</p> */ inline const HomeDirectoryType& GetHomeDirectoryType() const{ return m_homeDirectoryType; } /** * <p>The type of landing directory (folder) you want your users' home directory to * be when they log into the server. If you set it to <code>PATH</code>, the user * will see the absolute Amazon S3 bucket or EFS paths as is in their file transfer * protocol clients. If you set it <code>LOGICAL</code>, you need to provide * mappings in the <code>HomeDirectoryMappings</code> for how you want to make * Amazon S3 or EFS paths visible to your users.</p> */ inline bool HomeDirectoryTypeHasBeenSet() const { return m_homeDirectoryTypeHasBeenSet; } /** * <p>The type of landing directory (folder) you want your users' home directory to * be when they log into the server. If you set it to <code>PATH</code>, the user * will see the absolute Amazon S3 bucket or EFS paths as is in their file transfer * protocol clients. If you set it <code>LOGICAL</code>, you need to provide * mappings in the <code>HomeDirectoryMappings</code> for how you want to make * Amazon S3 or EFS paths visible to your users.</p> */ inline void SetHomeDirectoryType(const HomeDirectoryType& value) { m_homeDirectoryTypeHasBeenSet = true; m_homeDirectoryType = value; } /** * <p>The type of landing directory (folder) you want your users' home directory to * be when they log into the server. If you set it to <code>PATH</code>, the user * will see the absolute Amazon S3 bucket or EFS paths as is in their file transfer * protocol clients. If you set it <code>LOGICAL</code>, you need to provide * mappings in the <code>HomeDirectoryMappings</code> for how you want to make * Amazon S3 or EFS paths visible to your users.</p> */ inline void SetHomeDirectoryType(HomeDirectoryType&& value) { m_homeDirectoryTypeHasBeenSet = true; m_homeDirectoryType = std::move(value); } /** * <p>The type of landing directory (folder) you want your users' home directory to * be when they log into the server. If you set it to <code>PATH</code>, the user * will see the absolute Amazon S3 bucket or EFS paths as is in their file transfer * protocol clients. If you set it <code>LOGICAL</code>, you need to provide * mappings in the <code>HomeDirectoryMappings</code> for how you want to make * Amazon S3 or EFS paths visible to your users.</p> */ inline ListedAccess& WithHomeDirectoryType(const HomeDirectoryType& value) { SetHomeDirectoryType(value); return *this;} /** * <p>The type of landing directory (folder) you want your users' home directory to * be when they log into the server. If you set it to <code>PATH</code>, the user * will see the absolute Amazon S3 bucket or EFS paths as is in their file transfer * protocol clients. If you set it <code>LOGICAL</code>, you need to provide * mappings in the <code>HomeDirectoryMappings</code> for how you want to make * Amazon S3 or EFS paths visible to your users.</p> */ inline ListedAccess& WithHomeDirectoryType(HomeDirectoryType&& value) { SetHomeDirectoryType(std::move(value)); return *this;} /** * <p>Specifies the Amazon Resource Name (ARN) of the IAM role that controls your * users' access to your Amazon S3 bucket or EFS file system. The policies attached * to this role determine the level of access that you want to provide your users * when transferring files into and out of your Amazon S3 bucket or EFS file * system. The IAM role should also contain a trust relationship that allows the * server to access your resources when servicing your users' transfer * requests.</p> */ inline const Aws::String& GetRole() const{ return m_role; } /** * <p>Specifies the Amazon Resource Name (ARN) of the IAM role that controls your * users' access to your Amazon S3 bucket or EFS file system. The policies attached * to this role determine the level of access that you want to provide your users * when transferring files into and out of your Amazon S3 bucket or EFS file * system. The IAM role should also contain a trust relationship that allows the * server to access your resources when servicing your users' transfer * requests.</p> */ inline bool RoleHasBeenSet() const { return m_roleHasBeenSet; } /** * <p>Specifies the Amazon Resource Name (ARN) of the IAM role that controls your * users' access to your Amazon S3 bucket or EFS file system. The policies attached * to this role determine the level of access that you want to provide your users * when transferring files into and out of your Amazon S3 bucket or EFS file * system. The IAM role should also contain a trust relationship that allows the * server to access your resources when servicing your users' transfer * requests.</p> */ inline void SetRole(const Aws::String& value) { m_roleHasBeenSet = true; m_role = value; } /** * <p>Specifies the Amazon Resource Name (ARN) of the IAM role that controls your * users' access to your Amazon S3 bucket or EFS file system. The policies attached * to this role determine the level of access that you want to provide your users * when transferring files into and out of your Amazon S3 bucket or EFS file * system. The IAM role should also contain a trust relationship that allows the * server to access your resources when servicing your users' transfer * requests.</p> */ inline void SetRole(Aws::String&& value) { m_roleHasBeenSet = true; m_role = std::move(value); } /** * <p>Specifies the Amazon Resource Name (ARN) of the IAM role that controls your * users' access to your Amazon S3 bucket or EFS file system. The policies attached * to this role determine the level of access that you want to provide your users * when transferring files into and out of your Amazon S3 bucket or EFS file * system. The IAM role should also contain a trust relationship that allows the * server to access your resources when servicing your users' transfer * requests.</p> */ inline void SetRole(const char* value) { m_roleHasBeenSet = true; m_role.assign(value); } /** * <p>Specifies the Amazon Resource Name (ARN) of the IAM role that controls your * users' access to your Amazon S3 bucket or EFS file system. The policies attached * to this role determine the level of access that you want to provide your users * when transferring files into and out of your Amazon S3 bucket or EFS file * system. The IAM role should also contain a trust relationship that allows the * server to access your resources when servicing your users' transfer * requests.</p> */ inline ListedAccess& WithRole(const Aws::String& value) { SetRole(value); return *this;} /** * <p>Specifies the Amazon Resource Name (ARN) of the IAM role that controls your * users' access to your Amazon S3 bucket or EFS file system. The policies attached * to this role determine the level of access that you want to provide your users * when transferring files into and out of your Amazon S3 bucket or EFS file * system. The IAM role should also contain a trust relationship that allows the * server to access your resources when servicing your users' transfer * requests.</p> */ inline ListedAccess& WithRole(Aws::String&& value) { SetRole(std::move(value)); return *this;} /** * <p>Specifies the Amazon Resource Name (ARN) of the IAM role that controls your * users' access to your Amazon S3 bucket or EFS file system. The policies attached * to this role determine the level of access that you want to provide your users * when transferring files into and out of your Amazon S3 bucket or EFS file * system. The IAM role should also contain a trust relationship that allows the * server to access your resources when servicing your users' transfer * requests.</p> */ inline ListedAccess& WithRole(const char* value) { SetRole(value); return *this;} /** * <p>A unique identifier that is required to identify specific groups within your * directory. The users of the group that you associate have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Amazon Web Services * Transfer Family. If you know the group name, you can view the SID values by * running the following command using Windows PowerShell.</p> <p> * <code>Get-ADGroup -Filter {samAccountName -like "<i>YourGroupName</i>*"} * -Properties * | Select SamAccountName,ObjectSid</code> </p> <p>In that command, * replace <i>YourGroupName</i> with the name of your Active Directory group.</p> * <p>The regex used to validate this parameter is a string of characters * consisting of uppercase and lowercase alphanumeric characters with no spaces. * You can also include underscores or any of the following characters: =,.@:/-</p> */ inline const Aws::String& GetExternalId() const{ return m_externalId; } /** * <p>A unique identifier that is required to identify specific groups within your * directory. The users of the group that you associate have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Amazon Web Services * Transfer Family. If you know the group name, you can view the SID values by * running the following command using Windows PowerShell.</p> <p> * <code>Get-ADGroup -Filter {samAccountName -like "<i>YourGroupName</i>*"} * -Properties * | Select SamAccountName,ObjectSid</code> </p> <p>In that command, * replace <i>YourGroupName</i> with the name of your Active Directory group.</p> * <p>The regex used to validate this parameter is a string of characters * consisting of uppercase and lowercase alphanumeric characters with no spaces. * You can also include underscores or any of the following characters: =,.@:/-</p> */ inline bool ExternalIdHasBeenSet() const { return m_externalIdHasBeenSet; } /** * <p>A unique identifier that is required to identify specific groups within your * directory. The users of the group that you associate have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Amazon Web Services * Transfer Family. If you know the group name, you can view the SID values by * running the following command using Windows PowerShell.</p> <p> * <code>Get-ADGroup -Filter {samAccountName -like "<i>YourGroupName</i>*"} * -Properties * | Select SamAccountName,ObjectSid</code> </p> <p>In that command, * replace <i>YourGroupName</i> with the name of your Active Directory group.</p> * <p>The regex used to validate this parameter is a string of characters * consisting of uppercase and lowercase alphanumeric characters with no spaces. * You can also include underscores or any of the following characters: =,.@:/-</p> */ inline void SetExternalId(const Aws::String& value) { m_externalIdHasBeenSet = true; m_externalId = value; } /** * <p>A unique identifier that is required to identify specific groups within your * directory. The users of the group that you associate have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Amazon Web Services * Transfer Family. If you know the group name, you can view the SID values by * running the following command using Windows PowerShell.</p> <p> * <code>Get-ADGroup -Filter {samAccountName -like "<i>YourGroupName</i>*"} * -Properties * | Select SamAccountName,ObjectSid</code> </p> <p>In that command, * replace <i>YourGroupName</i> with the name of your Active Directory group.</p> * <p>The regex used to validate this parameter is a string of characters * consisting of uppercase and lowercase alphanumeric characters with no spaces. * You can also include underscores or any of the following characters: =,.@:/-</p> */ inline void SetExternalId(Aws::String&& value) { m_externalIdHasBeenSet = true; m_externalId = std::move(value); } /** * <p>A unique identifier that is required to identify specific groups within your * directory. The users of the group that you associate have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Amazon Web Services * Transfer Family. If you know the group name, you can view the SID values by * running the following command using Windows PowerShell.</p> <p> * <code>Get-ADGroup -Filter {samAccountName -like "<i>YourGroupName</i>*"} * -Properties * | Select SamAccountName,ObjectSid</code> </p> <p>In that command, * replace <i>YourGroupName</i> with the name of your Active Directory group.</p> * <p>The regex used to validate this parameter is a string of characters * consisting of uppercase and lowercase alphanumeric characters with no spaces. * You can also include underscores or any of the following characters: =,.@:/-</p> */ inline void SetExternalId(const char* value) { m_externalIdHasBeenSet = true; m_externalId.assign(value); } /** * <p>A unique identifier that is required to identify specific groups within your * directory. The users of the group that you associate have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Amazon Web Services * Transfer Family. If you know the group name, you can view the SID values by * running the following command using Windows PowerShell.</p> <p> * <code>Get-ADGroup -Filter {samAccountName -like "<i>YourGroupName</i>*"} * -Properties * | Select SamAccountName,ObjectSid</code> </p> <p>In that command, * replace <i>YourGroupName</i> with the name of your Active Directory group.</p> * <p>The regex used to validate this parameter is a string of characters * consisting of uppercase and lowercase alphanumeric characters with no spaces. * You can also include underscores or any of the following characters: =,.@:/-</p> */ inline ListedAccess& WithExternalId(const Aws::String& value) { SetExternalId(value); return *this;} /** * <p>A unique identifier that is required to identify specific groups within your * directory. The users of the group that you associate have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Amazon Web Services * Transfer Family. If you know the group name, you can view the SID values by * running the following command using Windows PowerShell.</p> <p> * <code>Get-ADGroup -Filter {samAccountName -like "<i>YourGroupName</i>*"} * -Properties * | Select SamAccountName,ObjectSid</code> </p> <p>In that command, * replace <i>YourGroupName</i> with the name of your Active Directory group.</p> * <p>The regex used to validate this parameter is a string of characters * consisting of uppercase and lowercase alphanumeric characters with no spaces. * You can also include underscores or any of the following characters: =,.@:/-</p> */ inline ListedAccess& WithExternalId(Aws::String&& value) { SetExternalId(std::move(value)); return *this;} /** * <p>A unique identifier that is required to identify specific groups within your * directory. The users of the group that you associate have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Amazon Web Services * Transfer Family. If you know the group name, you can view the SID values by * running the following command using Windows PowerShell.</p> <p> * <code>Get-ADGroup -Filter {samAccountName -like "<i>YourGroupName</i>*"} * -Properties * | Select SamAccountName,ObjectSid</code> </p> <p>In that command, * replace <i>YourGroupName</i> with the name of your Active Directory group.</p> * <p>The regex used to validate this parameter is a string of characters * consisting of uppercase and lowercase alphanumeric characters with no spaces. * You can also include underscores or any of the following characters: =,.@:/-</p> */ inline ListedAccess& WithExternalId(const char* value) { SetExternalId(value); return *this;} private: Aws::String m_homeDirectory; bool m_homeDirectoryHasBeenSet; HomeDirectoryType m_homeDirectoryType; bool m_homeDirectoryTypeHasBeenSet; Aws::String m_role; bool m_roleHasBeenSet; Aws::String m_externalId; bool m_externalIdHasBeenSet; }; } // namespace Model } // namespace Transfer } // namespace Aws
54.369509
145
0.702248
[ "model" ]
8ff94ed340146708ef678dc2a8329a3d27051d52
1,899
h
C
src/ml/algebra.h
gpi-yama/idash2021
151086c8bb1098ccf01e37ab8e1e558d3d3e21cf
[ "MIT" ]
null
null
null
src/ml/algebra.h
gpi-yama/idash2021
151086c8bb1098ccf01e37ab8e1e558d3d3e21cf
[ "MIT" ]
null
null
null
src/ml/algebra.h
gpi-yama/idash2021
151086c8bb1098ccf01e37ab8e1e558d3d3e21cf
[ "MIT" ]
null
null
null
#pragma once #include "../common.h" namespace capsuleGene { class AlgebraUtils { public: static std::vector<double> generate_unit_vec(const int num, const int slot_size, const double value); /** * @brief sum for ctxt. please set num as negative if you want to sum to 0idx. * * @param enc_vec * @param num * @return Ciphertext */ static Ciphertext rotate_and_sum_in_col(const Ciphertext &x, const int num, const std::shared_ptr<Evaluator> evaluator, const std::shared_ptr<GaloisKeys> gal_keys); /** * @brief multiply two ctxt * * @param x * @param y * @param evaluator evaluator * @param rel_keys relin key * @return Ciphertext */ static Ciphertext multiply(const Ciphertext &x, const Ciphertext &y, const std::shared_ptr<Evaluator> evaluator, const std::shared_ptr<RelinKeys> rel_keys); /** * @brief multiply ctxt and vector * * @param x * @param y * @param evaluator * @param rel_keys * @param encoder * @param scale * @return Ciphertext */ static Ciphertext multiply(const Ciphertext &x, const std::vector<double> &y, const std::shared_ptr<Evaluator> evaluator, const std::shared_ptr<RelinKeys> rel_keys, const std::shared_ptr<CKKSEncoder> encoder, double scale); /** * @brief add ctxt and vector * * @param x * @param y * @param evaluator * @param rel_keys * @param encoder * @param scale * @return Ciphertext */ static Ciphertext add(Ciphertext &x, const std::vector<double> &y, const std::shared_ptr<Evaluator> evaluator, const std::shared_ptr<CKKSEncoder> encoder); }; }
33.315789
231
0.579252
[ "vector" ]
8900de5b32a7016aedbe2abce286330339f13a52
3,320
h
C
pmem-mariadb/storage/rocksdb/rdb_io_watchdog.h
wc222/pmdk-examples
64aadc3a70471c469ac8e214eb1e04ff47cf18ff
[ "BSD-3-Clause" ]
1
2019-10-31T08:25:52.000Z
2019-10-31T08:25:52.000Z
pmem-mariadb/storage/rocksdb/rdb_io_watchdog.h
WSCWDA/pmdk-examples
c3d079e52cd18b0e14836ef42bad9a995336bf90
[ "BSD-3-Clause" ]
1
2021-02-24T05:26:44.000Z
2021-02-24T05:26:44.000Z
pmem-mariadb/storage/rocksdb/rdb_io_watchdog.h
isabella232/pmdk-examples
be7a5a18ba7bb8931e512f6d552eadf820fa2235
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2017, Facebook, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #pragma once /* C++ standard header files */ #include <atomic> #include <signal.h> #include <stdlib.h> #include <string> #include <string.h> #include <time.h> #include <vector> /* MySQL header files */ #include "./my_global.h" #include "./my_stacktrace.h" /* MyRocks header files */ #include "./rdb_utils.h" namespace myrocks { // Rdb_io_watchdog does not support Windows ATM. #ifdef HAVE_TIMER_DELETE class Rdb_io_watchdog { const int RDB_IO_WRITE_BUFFER_SIZE = 4096; const char *const RDB_IO_DUMMY_FILE_NAME = "myrocks_io_watchdog_write_file"; private: timer_t m_io_check_timer, m_io_check_watchdog_timer; std::atomic<bool> m_io_in_progress; std::vector<std::string> m_dirs_to_check; uint32_t m_write_timeout; mysql_mutex_t m_reset_mutex; char *m_buf; int check_write_access(const std::string &dirname) const; void io_check_callback(union sigval timer_data); void expire_io_callback(union sigval timer_data); int stop_timers() { int ret = 0; if (m_io_check_watchdog_timer) { ret = timer_delete(m_io_check_watchdog_timer); if (!ret) { m_io_check_watchdog_timer = nullptr; } } if (m_io_check_timer && !ret) { ret = timer_delete(m_io_check_timer); if (!ret) { m_io_check_timer = nullptr; } } return ret; } static void io_check_callback_wrapper(union sigval timer_data) { Rdb_io_watchdog *io_watchdog = static_cast<Rdb_io_watchdog *>(timer_data.sival_ptr); DBUG_ASSERT(io_watchdog != nullptr); io_watchdog->io_check_callback(timer_data); } static void expire_io_callback_wrapper(union sigval timer_data) { Rdb_io_watchdog *io_watchdog = static_cast<Rdb_io_watchdog *>(timer_data.sival_ptr); DBUG_ASSERT(io_watchdog != nullptr); io_watchdog->expire_io_callback(timer_data); } public: explicit Rdb_io_watchdog(const std::vector<std::string> &directories) : m_io_check_timer(nullptr), m_io_check_watchdog_timer(nullptr), m_io_in_progress(false), m_dirs_to_check(std::move(directories)), m_buf(nullptr) { DBUG_ASSERT(m_dirs_to_check.size() > 0); mysql_mutex_init(0, &m_reset_mutex, MY_MUTEX_INIT_FAST); } ~Rdb_io_watchdog() { // We're shutting down. Ignore errors possibly coming from timer deletion. static_cast<void>(stop_timers()); mysql_mutex_destroy(&m_reset_mutex); free(m_buf); } int reset_timeout(const uint32_t &write_timeout); Rdb_io_watchdog(const Rdb_io_watchdog &) = delete; Rdb_io_watchdog &operator=(const Rdb_io_watchdog &) = delete; }; #endif } // namespace myrocks
28.135593
79
0.725
[ "vector" ]
8915e61094f4e65594e17f705c98fc0bfd9d4bd1
3,117
c
C
src/watcher.c
bitptr/argonaut
f2dd9afd90717e5cd5f6024d0c26aea89905a5ea
[ "BSD-3-Clause" ]
null
null
null
src/watcher.c
bitptr/argonaut
f2dd9afd90717e5cd5f6024d0c26aea89905a5ea
[ "BSD-3-Clause" ]
null
null
null
src/watcher.c
bitptr/argonaut
f2dd9afd90717e5cd5f6024d0c26aea89905a5ea
[ "BSD-3-Clause" ]
null
null
null
#ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef HAVE_KQUEUE #include <sys/types.h> #include <sys/event.h> #include <sys/time.h> #include <err.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <gtk/gtk.h> #include "store.h" struct thread_data { GtkListStore *model; char *dir; }; gpointer watch_dir_func(gpointer); gboolean thr_repopulate(gpointer); static struct thread_data *thread_data_new(GtkListStore *, char *); static void thread_data_free(struct thread_data *); /* * Start a thread that watches a directory; update the model when this * directory changes. */ void watch_dir(GtkListStore *model, char *dir) { GThread *watcher_thr; struct thread_data *thr_d; thr_d = thread_data_new(model, dir); watcher_thr = g_thread_new("watcher", watch_dir_func, thr_d); g_thread_unref(watcher_thr); } /* * Watch a directory; when it changes, update the model. * * This runs in a non-main thread. */ gpointer watch_dir_func(gpointer data) { int kq, fd, ret; struct kevent kev; char *dir; struct thread_data *thr_d; thr_d = (struct thread_data *)data; dir = thr_d->dir; if ((fd = open(dir, O_RDONLY)) == -1) err(1, "open"); if ((kq = kqueue()) == -1) err(1, "kqueue"); EV_SET(&kev, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE, 0, NULL); if (kevent(kq, &kev, 1, NULL, 0, NULL) == -1) err(1, "kevent"); for (;;) { ret = kevent(kq, NULL, 0, &kev, 1, NULL); if (ret == -1) err(1, "kevent"); if (ret == 0) break; g_idle_add(thr_repopulate, data); } thread_data_free(data); if (close(fd) == -1) err(1, "close"); return NULL; } /* * Update the model. When done, remove this function from the list of sources * to run when idle. * * RETURN: False, to indicate that the function should be run only once. */ gboolean thr_repopulate(gpointer data) { GtkListStore *model; char *dir; struct thread_data *thr_d; thr_d = (struct thread_data *)data; model = thr_d->model; dir = thr_d->dir; gtk_list_store_clear(model); if (populate(model, dir) == -1) errx(66, "failed to populate icon model from %s", dir); return G_SOURCE_REMOVE; } /* * Construct a new thread_data structure storing the given model and dir. * * RETURN: The new thread_data structure. Deallocate it with * thread_data_free(). */ struct thread_data * thread_data_new(GtkListStore *model, char *dir) { struct thread_data *thr_d; size_t dir_len, cpy_len; dir_len = strlen(dir); if ((thr_d = (struct thread_data*)malloc(sizeof(struct thread_data))) == NULL) err(1, "malloc"); thr_d->model = model; if ((thr_d->dir = (char *)calloc(dir_len, sizeof(char))) == NULL) err(1, "malloc"); cpy_len = strlcpy(thr_d->dir, dir, dir_len+1); if (cpy_len < dir_len) err(1, "strlcpy"); return thr_d; } /* * Clean up the given thread_data structure. */ void thread_data_free(struct thread_data *thr_d) { free(thr_d->dir); free(thr_d); } #else /* * This file needs a "translation unit" - it needs anything for the compiler to * compile. */ int unused; #endif
18.553571
79
0.673404
[ "model" ]
89167816ed6ed70be46ac81bce2c782601222de9
3,765
c
C
Psychtoolbox/PsychContributed/WinJoystickMex.c
dcnieho/Psychtoolbox-3
f0797eeb39781e617d5b544401b9668864857837
[ "MIT" ]
357
2015-01-09T02:48:04.000Z
2022-03-27T12:24:34.000Z
Psychtoolbox/PsychContributed/WinJoystickMex.c
dcnieho/Psychtoolbox-3
f0797eeb39781e617d5b544401b9668864857837
[ "MIT" ]
344
2015-01-02T03:23:05.000Z
2022-03-11T19:22:25.000Z
Psychtoolbox/PsychContributed/WinJoystickMex.c
dcnieho/Psychtoolbox-3
f0797eeb39781e617d5b544401b9668864857837
[ "MIT" ]
250
2015-01-16T04:02:15.000Z
2022-03-27T12:24:59.000Z
/*------------------------------------------------------------------------------ WinJoystickMex.c -- A simple Matlab/Octave MEX file for query of joysticks on Microsoft Windows. On Matlab, compile with: mex -v -g WinJoystickMex.c winmm.lib On Octave, compile with: mex -v -g WinJoystickMex.c -lwinmm ------------------------------------------------------------------------------ WinJoystickMex.c is Copyright (C) 2009-2012 Mario Kleiner This program is licensed under the MIT license. A copy of the license can be found in the License.txt file inside the Psychtoolbox-3 top level folder. ------------------------------------------------------------------------------*/ /* Windows includes: */ #include <windows.h> /* Matlab includes: */ #include "mex.h" /* This is the main entry point from Matlab: */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[]) { JOYINFO joy; // Struct into which joystick state is returned. MMRESULT rc; // Return code of function. unsigned int cmd; double* out; // Get our name for output: const char* me = mexFunctionName(); if(nrhs < 1) { mexPrintf("WinJoystickMex: A simple Matlab/Octave MEX file for query of simple joysticks on Microsoft Windows\n\n"); mexPrintf("(C) 2009-2012 by Mario Kleiner -- Licensed to you under the MIT license.\n"); mexPrintf("This file is part of Psychtoolbox-3 but should also work independently.\n"); mexPrintf("\n"); mexPrintf("Usage:\n\n"); mexPrintf("[x, y, z, buttons] = %s(joystickId);\n", me); mexPrintf("- Query joystick device 'joystickId'. This can be any number between 0 and 15.\n"); mexPrintf("0 is the first connected joystick, 1 the 2nd, etc...\n"); mexPrintf("x, y and z are the current x, y and z coordinate of the joystick.\n"); mexPrintf("buttons is a 4-element vector, each element being zero if the corresponding button is released,\n"); mexPrintf("one if the corresponding button is pressed.\n\n\n"); return; } /* First argument must be the joystick id: */ cmd = (unsigned int) mxGetScalar(prhs[0]); /* Call joystick function: */ if ((rc = joyGetPos((UINT) cmd, &joy)) != JOYERR_NOERROR) { // Failed! mexPrintf("For failed joystick call with 'joystickId' = %i.\n", cmd); switch((int) rc) { case MMSYSERR_NODRIVER: mexErrMsgTxt("The joystick driver is not present or active on this system! [MMSYSERR_NODRIVER]"); break; case JOYERR_NOCANDO: mexErrMsgTxt("Some system service for joystick support is not present or active on this system! [JOYERR_NOCANDO]"); break; case MMSYSERR_INVALPARAM: case JOYERR_PARMS: mexErrMsgTxt("Invalid 'joystickId' passed! [MMSYSERR_INVALPARAM or JOYERR_PARMS]"); break; case JOYERR_UNPLUGGED: mexErrMsgTxt("The specified joystick is not connected to the system! [JOYERR_UNPLUGGED]"); break; default: mexPrintf("Return code of failed joystick call is %i.\n", rc); mexErrMsgTxt("Unknown error! See return code above."); } } // Return X pos: plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); *(mxGetPr(plhs[0])) = (double) joy.wXpos; // Return Y pos: plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL); *(mxGetPr(plhs[1])) = (double) joy.wYpos; // Return Z pos: plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL); *(mxGetPr(plhs[2])) = (double) joy.wZpos; // Return 4-element button state vector: plhs[3] = mxCreateDoubleMatrix(1, 4, mxREAL); out = mxGetPr(plhs[3]); out[0] = (joy.wButtons & JOY_BUTTON1) ? 1 : 0; out[1] = (joy.wButtons & JOY_BUTTON2) ? 1 : 0; out[2] = (joy.wButtons & JOY_BUTTON3) ? 1 : 0; out[3] = (joy.wButtons & JOY_BUTTON4) ? 1 : 0; // Done. return; }
34.861111
120
0.625764
[ "vector" ]
8917eed1fc2bc2dec0702e531956e1e9b309ced9
3,668
h
C
Plugins/AdvKitPlugin/Source/AdvKitRuntime/Classes/Actions/Movement/AdvKitCA_PhysicsTransition.h
crimsonstrife/velorum-defunct
1a6e1eab9057293da2aa045eff021d069df54c5e
[ "CC0-1.0" ]
null
null
null
Plugins/AdvKitPlugin/Source/AdvKitRuntime/Classes/Actions/Movement/AdvKitCA_PhysicsTransition.h
crimsonstrife/velorum-defunct
1a6e1eab9057293da2aa045eff021d069df54c5e
[ "CC0-1.0" ]
null
null
null
Plugins/AdvKitPlugin/Source/AdvKitRuntime/Classes/Actions/Movement/AdvKitCA_PhysicsTransition.h
crimsonstrife/velorum-defunct
1a6e1eab9057293da2aa045eff021d069df54c5e
[ "CC0-1.0" ]
null
null
null
// Copyright 2015 Pascal Krabbe #pragma once #include "Object.h" #include "Actions/AdvKitCharacterActionSingleAnimation.h" #include "Player/AdvKitCharacterMovementComponent.h" #include "AdvKitCA_PhysicsTransition.generated.h" /** @brief Helper struct since UE4 does not support TMap properties. This handles configuring the transition * mapping to set which actions take care of which physics mode transition. */ USTRUCT() struct FAdvKitPhysicsTransition { GENERATED_USTRUCT_BODY(); UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Transitions") /** Mode to transition from */ EAdvKitMovementMode FromMode; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Transitions") /** Mode to transition to */ EAdvKitMovementMode ToMode; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Transitions") /** Action to take when going FromMode -> ToMode*/ TSubclassOf<UAdvKitCharacterAction> TransitionAction; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Transitions") /** Action to take when going ToMode -> FromMode */ TSubclassOf<UAdvKitCharacterAction> ReverseAction; }; /** * @brief This action is responsible for redirecting to sub actions that take care of movement mode * changes. */ UCLASS(abstract, hidecategories = Action) class ADVKITRUNTIME_API UAdvKitCA_PhysicsTransition : public UAdvKitCharacterAction { GENERATED_BODY() public: /** * Constructor */ UAdvKitCA_PhysicsTransition(const FObjectInitializer& ObjectInitializer); protected: /** Flag to enable debug output for transitions */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Transitions") bool bLogDebug; /** Configuration map for the transition action */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Transitions") TArray<FAdvKitPhysicsTransition> DefaultTransitionActions; //TODO replace uint8 with EAdvKitMovementMode (currently unsupported (4.9)) /** Actual transition map, configured based upon the configured DefaultTranstionActions array */ TMap < uint8, TMap<uint8, TSubclassOf<UAdvKitCharacterAction> > > TransitionMap; public: //Begin UActorComponent Interface virtual void InitializeComponent() override; //End UActorComponent Interface /** Begin UAdvKitCharacterAction Interface */ virtual FAdvKitActionResponse Start_Implementation(class UAdvKitCharacterAction_Arguments* Arguments = NULL, UAdvKitCharacterAction* InterruptedOther = NULL) override; virtual FAdvKitActionResponse Stop_Implementation(const UAdvKitCharacterAction* InterruptedBy = NULL) override; virtual bool CanBeInterruptedBy_Implementation(const UAdvKitCharacterAction* Other) const override; virtual TArray<TSubclassOf<UAdvKitCharacterAction>> GetAdditionalRequiredActions_Implementation() override; /** End UAdvKitCharacterAction Interface */ /** * Create arguments for the physics transition action * @param From Movement mode to transition from * @param To Movement mode to transition to * @param SubArguments Arguments to supply to the chosen redirection action * @return Arguments object containing given parameters */ static class UAdvKitCharacterAction_Arguments* MakeArguments(EAdvKitMovementMode From, EAdvKitMovementMode To, UAdvKitCharacterAction_Arguments* SubArguments = NULL); protected: /** * Adds a new transition to the transitions map * @param FromMode Movement mode to transition from * @param ToMode Movement mode to transition to * @param TransitionAction Action to take care of the transition */ virtual void AddTransiton(EAdvKitMovementMode FromMode, EAdvKitMovementMode ToMode, TSubclassOf<UAdvKitCharacterAction> TransitionAction); };
38.208333
168
0.801799
[ "object" ]
891d37ef6458a4c1dd195d5290c7d6760516896a
863
h
C
all/native/rastertiles/ElevationDecoder.h
Akylas/mobile-sdk
744040d87344ee76b4ad14281d9467da1b5f0788
[ "BSD-3-Clause" ]
null
null
null
all/native/rastertiles/ElevationDecoder.h
Akylas/mobile-sdk
744040d87344ee76b4ad14281d9467da1b5f0788
[ "BSD-3-Clause" ]
null
null
null
all/native/rastertiles/ElevationDecoder.h
Akylas/mobile-sdk
744040d87344ee76b4ad14281d9467da1b5f0788
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2016 CartoDB. All rights reserved. * Copying and using this code is allowed only according * to license terms, as given in https://cartodb.com/terms/ */ #ifndef _CARTO_ELEVATIONDECODER_H_ #define _CARTO_ELEVATIONDECODER_H_ #include "graphics/Color.h" #include <memory> #include <string> #include <mutex> #include <map> #include <vector> #include <cglib/mat.h> #include <mapnikvt/Map.h> namespace carto { /** * Abstract base class for raster elevation decoders. */ class ElevationDecoder { public: /** * Constructs an ElevationDecoder. */ ElevationDecoder(); virtual ~ElevationDecoder(); virtual std::array<float, 4> getVectorTileScales() const = 0; virtual std::array<double, 4> getColorComponentCoefficients() const = 0; }; } #endif
20.547619
80
0.655852
[ "vector" ]
892414d45d2c099200a6cbaf62d0f302a0a4d1ab
534
h
C
lib/variable/include/scipp/variable/misc_operations.h
nvaytet/scipp
f14f56ed19cccb4162d55b1123df7225eeedb395
[ "BSD-3-Clause" ]
43
2019-04-08T14:13:11.000Z
2022-02-08T06:09:35.000Z
lib/variable/include/scipp/variable/misc_operations.h
nvaytet/scipp
f14f56ed19cccb4162d55b1123df7225eeedb395
[ "BSD-3-Clause" ]
1,342
2019-03-30T07:06:08.000Z
2022-03-28T13:12:47.000Z
lib/variable/include/scipp/variable/misc_operations.h
nvaytet/scipp
f14f56ed19cccb4162d55b1123df7225eeedb395
[ "BSD-3-Clause" ]
12
2019-06-13T08:56:12.000Z
2021-11-04T08:24:18.000Z
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2021 Scipp contributors (https://github.com/scipp) /// @file /// @author Simon Heybrock #pragma once #include "scipp-variable_export.h" #include "scipp/variable/variable.h" namespace scipp::variable::geometry { [[nodiscard]] SCIPP_VARIABLE_EXPORT Variable position(const Variable &x, const Variable &y, const Variable &z); } // namespace scipp::variable::geometry
31.411765
73
0.597378
[ "geometry" ]
89281c6f7e3b50d0b941ee037af68f35eefde9f8
2,375
h
C
avogadro/qtopengl/activeobjects.h
serk12/avogadrolibs
f2dd0fda7e0d2ca4a0586354ea253cc05242f022
[ "BSD-3-Clause" ]
244
2015-09-09T15:08:54.000Z
2022-03-30T17:44:21.000Z
avogadro/qtopengl/activeobjects.h
serk12/avogadrolibs
f2dd0fda7e0d2ca4a0586354ea253cc05242f022
[ "BSD-3-Clause" ]
670
2015-05-08T18:59:38.000Z
2022-03-29T19:47:08.000Z
avogadro/qtopengl/activeobjects.h
serk12/avogadrolibs
f2dd0fda7e0d2ca4a0586354ea253cc05242f022
[ "BSD-3-Clause" ]
129
2015-01-28T01:18:36.000Z
2022-03-17T08:50:25.000Z
/* This source file is part of the Avogadro project. It is released under the 3-Clause BSD License, see "LICENSE". */ #ifndef AVOGADRO_QTOPENGL_ACTIVEOBJECTS_H #define AVOGADRO_QTOPENGL_ACTIVEOBJECTS_H #include "avogadroqtopenglexport.h" #include <QtCore/QObject> // #include "glwidget.h" #include <QtCore/QPointer> class QWidget; namespace Avogadro { namespace QtGui { class Molecule; } namespace QtOpenGL { class GLWidget; /** * @class ActiveObjects activeobjects.h <avogadro/qtopengl/activeobjects.h> * @brief Singleton to provide access to active objects. * * This class provides access to the active objects in the running application. * If you write an application using the Avogadro libraries you need to keep * this class updated with changes in active objects in order for built in * features to work as expected. * * All returned objects are owned by the running application, nullptr indicates * that there is no currently active object of that type. */ class AVOGADROQTOPENGL_EXPORT ActiveObjects : public QObject { Q_OBJECT public: /** Return a reference to the singleton instance that can be queried. */ static ActiveObjects& instance(); /** Get the active GLWidget. **/ GLWidget* activeGLWidget() const; /** * Get the active widget (more general, could be GLWidget, vtkGLWidget, etc). */ QWidget* activeWidget() const; /** * Get the active molecule. */ QtGui::Molecule* activeMolecule() const; public slots: /** Set the active GLWidget. */ void setActiveGLWidget(GLWidget* glWidget); /** Set the active widget (GLWidget, vtkGLWidget, etc). */ void setActiveWidget(QWidget* widget); /** Set the active widget (GLWidget, vtkGLWidget, etc). */ void setActiveMolecule(QtGui::Molecule* molecule); signals: /** The active GL widget changed. */ void activeGLWidgetChanged(GLWidget* glWidget); /** The active widget changed (GLWidget, vtkGLWidget, etc). */ void activeWidgetChanged(QWidget* widget); /** The active molecule changed. */ void activeMoleculeChanged(QtGui::Molecule* molecule); private: ActiveObjects(); ~ActiveObjects() override; Q_DISABLE_COPY(ActiveObjects) GLWidget* m_glWidget = nullptr; QWidget* m_widget = nullptr; QtGui::Molecule* m_molecule = nullptr; }; } // namespace QtOpenGL } // namespace Avogadro #endif // AVOGADRO_QTOPENGL_ACTIVEOBJECTS_H
26.685393
79
0.737684
[ "object" ]
892d124bff3d96863f33af0f330137923624e477
486
h
C
configuration.h
williamwu88/Flying-Stickman
d11c05e87bde481200ed1f3aaf5a0f4e4982d9ae
[ "MIT" ]
null
null
null
configuration.h
williamwu88/Flying-Stickman
d11c05e87bde481200ed1f3aaf5a0f4e4982d9ae
[ "MIT" ]
null
null
null
configuration.h
williamwu88/Flying-Stickman
d11c05e87bde481200ed1f3aaf5a0f4e4982d9ae
[ "MIT" ]
null
null
null
#pragma once #include <vector> struct ObstacleConfig { double width; double height; double offset_x; double position_y; int colour_red; int colour_green; int colour_blue; }; class Configuration { public: virtual ~Configuration() = default; virtual unsigned int getWorldWidth() = 0; virtual unsigned int getWorldHeight() = 0; virtual std::vector<ObstacleConfig*> getObstacleData() = 0; protected: virtual void setupConfig() = 0; };
17.357143
63
0.683128
[ "vector" ]
892e06ac39d00cb62d5a0811d007b79f7df21f15
33,441
c
C
copaas/src/occipaas_link.c
MarouenMechtri/compatibleone
6e1be42ba023bb64421073d139dc57bb0386b180
[ "Apache-2.0" ]
1
2015-02-28T21:25:54.000Z
2015-02-28T21:25:54.000Z
copaas/src/occipaas_link.c
MarouenMechtri/compatibleone
6e1be42ba023bb64421073d139dc57bb0386b180
[ "Apache-2.0" ]
null
null
null
copaas/src/occipaas_link.c
MarouenMechtri/compatibleone
6e1be42ba023bb64421073d139dc57bb0386b180
[ "Apache-2.0" ]
null
null
null
/* -------------------------------------------------------------------- */ /* ACCORDS PLATFORM */ /* (C) 2011 by Iain James Marshall (Prologue) <ijm667@hotmail.com> */ /* -------------------------------------------------------------------- */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------- */ /* STRUKT WARNING : this file has been generated and should not be modified by hand */ #ifndef _occipaas_link_c_ #define _occipaas_link_c_ #include "paas_link.h" /* ---------------------------- */ /* o c c i _ p a a s _ l i n k */ /* ---------------------------- */ /* -------------------------------------------------------------------- */ /* o c c i c a t e g o r y m a n a g e m e n t s t r u c t u r e */ /* -------------------------------------------------------------------- */ struct paas_link * allocate_paas_link(); struct paas_link * liberate_paas_link(struct paas_link * optr); private pthread_mutex_t list_paas_link_control=PTHREAD_MUTEX_INITIALIZER; private struct occi_kind_node * paas_link_first = (struct occi_kind_node *) 0; private struct occi_kind_node * paas_link_last = (struct occi_kind_node *) 0; public struct occi_kind_node * occi_first_paas_link_node() { return( paas_link_first ); } public struct occi_kind_node * occi_last_paas_link_node() { return( paas_link_last ); } /* ---------------------------------------------- */ /* o c c i c a t e g o r y d r o p n o d e */ /* ---------------------------------------------- */ private struct occi_kind_node * ll_drop_paas_link_node(struct occi_kind_node * nptr) { if ( nptr ) { if (!( nptr->previous )) paas_link_first = nptr->next; else nptr->previous->next = nptr->next; if (!( nptr->next )) paas_link_last = nptr->previous; else nptr->next->previous = nptr->previous; liberate_occi_kind_node( nptr ); } return((struct occi_kind_node *)0); } private struct occi_kind_node * drop_paas_link_node(struct occi_kind_node * nptr) { pthread_mutex_lock( &list_paas_link_control ); nptr = ll_drop_paas_link_node( nptr ); pthread_mutex_unlock( &list_paas_link_control ); return(nptr); } /* -------------------------------------------------- */ /* o c c i c a t e g o r y l o c a t e n o d e */ /* -------------------------------------------------- */ private struct occi_kind_node * ll_locate_paas_link_node(char * id) { struct occi_kind_node * nptr; struct paas_link * pptr; for ( nptr = paas_link_first; nptr != (struct occi_kind_node *) 0; nptr = nptr->next ) { if (!( pptr = nptr->contents )) continue; else if (!( pptr->id )) continue; else if (!( strcmp(pptr->id,id) )) break; } return( nptr ); } private struct occi_kind_node * locate_paas_link_node(char * id) { struct occi_kind_node * nptr; pthread_mutex_lock( &list_paas_link_control ); nptr = ll_locate_paas_link_node(id); pthread_mutex_unlock( &list_paas_link_control ); return( nptr ); } /* -------------------------------------------- */ /* o c c i c a t e g o r y a d d n o d e */ /* -------------------------------------------- */ private struct occi_kind_node * ll_add_paas_link_node(int mode) { struct occi_kind_node * nptr; struct paas_link * pptr; if (!( nptr = allocate_occi_kind_node() )) return( nptr ); else { if (!( nptr->contents = allocate_paas_link())) return( liberate_occi_kind_node(nptr) ); if (!( pptr = nptr->contents )) return( liberate_occi_kind_node(nptr) ); else if (( mode != 0 ) && (!( pptr->id = occi_allocate_uuid()))) return( liberate_occi_kind_node(nptr) ); else { if (!( nptr->previous = paas_link_last )) paas_link_first = nptr; else nptr->previous->next = nptr; paas_link_last = nptr; return( nptr ); } } } private struct occi_kind_node * add_paas_link_node(int mode) { struct occi_kind_node * nptr; pthread_mutex_lock( &list_paas_link_control ); nptr = ll_add_paas_link_node( mode ); pthread_mutex_unlock( &list_paas_link_control ); return(nptr); } /* ------------------------------------------------------------------------------------------ */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d a u t o l o a d */ /* ------------------------------------------------------------------------------------------ */ private char*autosave_paas_link_name="paas_link.xml"; private void autoload_paas_link_nodes() { char * fn=autosave_paas_link_name; struct occi_kind_node * nptr; struct paas_link * pptr; struct xml_element * document; struct xml_element * eptr; struct xml_element * vptr; struct xml_atribut * aptr; if (!( document = document_parse_file(fn))) return; if ((eptr = document_element(document,"paas_links")) != (struct xml_element *) 0) { for (vptr=eptr->first; vptr != (struct xml_element *) 0; vptr=vptr->next) { if (!( vptr->name )) continue; else if ( strcmp( vptr->name, "paas_link" ) ) continue; else if (!( nptr = add_paas_link_node(0))) break; else if (!( pptr = nptr->contents )) break; if ((aptr = document_atribut( vptr, "id" )) != (struct xml_atribut *) 0) pptr->id = document_atribut_string(aptr); if ((aptr = document_atribut( vptr, "name" )) != (struct xml_atribut *) 0) pptr->name = document_atribut_string(aptr); if ((aptr = document_atribut( vptr, "type" )) != (struct xml_atribut *) 0) pptr->type = document_atribut_string(aptr); if ((aptr = document_atribut( vptr, "expression" )) != (struct xml_atribut *) 0) pptr->expression = document_atribut_string(aptr); if ((aptr = document_atribut( vptr, "state" )) != (struct xml_atribut *) 0) pptr->state = document_atribut_value(aptr); } } document = document_drop( document ); return; } /* ------------------------------------------------------------------------------------------ */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d a u t o s a v e */ /* ------------------------------------------------------------------------------------------ */ public void set_autosave_paas_link_name(char * fn) { autosave_paas_link_name = fn; return; } public void autosave_paas_link_nodes() { char * fn=autosave_paas_link_name; struct occi_kind_node * nptr; struct paas_link * pptr; FILE * h; pthread_mutex_lock( &list_paas_link_control ); if (( h = fopen(fn,"w")) != (FILE *) 0) { fprintf(h,"<paas_links>\n"); for ( nptr = paas_link_first; nptr != (struct occi_kind_node *) 0; nptr = nptr->next ) { if (!( pptr = nptr->contents )) continue; fprintf(h,"<paas_link\n"); fprintf(h," id=%c",0x0022); fprintf(h,"%s",(pptr->id?pptr->id:"")); fprintf(h,"%c",0x0022); fprintf(h," name=%c",0x0022); fprintf(h,"%s",(pptr->name?pptr->name:"")); fprintf(h,"%c",0x0022); fprintf(h," type=%c",0x0022); fprintf(h,"%s",(pptr->type?pptr->type:"")); fprintf(h,"%c",0x0022); fprintf(h," expression=%c",0x0022); fprintf(h,"%s",(pptr->expression?pptr->expression:"")); fprintf(h,"%c",0x0022); fprintf(h," state=%c",0x0022); fprintf(h,"%u",pptr->state); fprintf(h,"%c",0x0022); fprintf(h," />\n"); } fprintf(h,"</paas_links>\n"); fclose(h); } pthread_mutex_unlock( &list_paas_link_control ); return; } /* ------------------------------------------------------------------------------------------ */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d s e t f i e l d */ /* ------------------------------------------------------------------------------------------ */ private void set_paas_link_field( struct occi_category * cptr,void * optr, char * nptr, char * vptr) { struct paas_link * pptr; char prefix[1024]; if (!( pptr = optr )) return; sprintf(prefix,"%s.%s.",cptr->domain,cptr->id); if (!( strncmp( nptr, prefix, strlen(prefix) ) )) { nptr += strlen(prefix); if (!( strcmp( nptr, "name" ) )) pptr->name = allocate_string(vptr); if (!( strcmp( nptr, "type" ) )) pptr->type = allocate_string(vptr); if (!( strcmp( nptr, "expression" ) )) pptr->expression = allocate_string(vptr); if (!( strcmp( nptr, "state" ) )) pptr->state = atoi(vptr); } return; } /* -------------------------------------------------- */ /* o c c i c a t e g o r y f i l t e r i n f o */ /* -------------------------------------------------- */ private struct paas_link * filter_paas_link_info( struct occi_category * optr, struct rest_request * rptr, struct rest_response * aptr) { struct paas_link * pptr; if (!( pptr = allocate_paas_link())) return( pptr ); else if (!( occi_process_atributs(optr, rptr, aptr, pptr, set_paas_link_field) )) return( liberate_paas_link(pptr)); else return( pptr ); } /* -------------------------------------------------- */ /* o c c i c a t e g o r y f i l t e r p a s s */ /* -------------------------------------------------- */ private int pass_paas_link_filter( struct paas_link * pptr,struct paas_link * fptr) { if (( fptr->id ) && (strlen( fptr->id ) != 0)) { if (!( pptr->id )) return(0); else if ( strcmp(pptr->id,fptr->id) != 0) return(0); } if (( fptr->name ) && (strlen( fptr->name ) != 0)) { if (!( pptr->name )) return(0); else if ( strcmp(pptr->name,fptr->name) != 0) return(0); } if (( fptr->type ) && (strlen( fptr->type ) != 0)) { if (!( pptr->type )) return(0); else if ( strcmp(pptr->type,fptr->type) != 0) return(0); } if (( fptr->expression ) && (strlen( fptr->expression ) != 0)) { if (!( pptr->expression )) return(0); else if ( strcmp(pptr->expression,fptr->expression) != 0) return(0); } if (( fptr->state ) && ( pptr->state != fptr->state )) return(0); return(1); } /* ---------------------------------------------------------------------------------------- */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d r e s p o n s e */ /* ---------------------------------------------------------------------------------------- */ private struct rest_response * paas_link_occi_response( struct occi_category * optr, struct rest_client * cptr, struct rest_request * rptr, struct rest_response * aptr, struct paas_link * pptr) { struct rest_header * hptr; sprintf(cptr->buffer,"occi.core.id=%s",pptr->id); if (!( hptr = rest_response_header( aptr, "X-OCCI-Attribute",cptr->buffer) )) return( rest_html_response( aptr, 500, "Server Failure" ) ); sprintf(cptr->buffer,"%s.%s.name=%s",optr->domain,optr->id,pptr->name); if (!( hptr = rest_response_header( aptr, "X-OCCI-Attribute",cptr->buffer) )) return( rest_html_response( aptr, 500, "Server Failure" ) ); sprintf(cptr->buffer,"%s.%s.type=%s",optr->domain,optr->id,pptr->type); if (!( hptr = rest_response_header( aptr, "X-OCCI-Attribute",cptr->buffer) )) return( rest_html_response( aptr, 500, "Server Failure" ) ); sprintf(cptr->buffer,"%s.%s.expression=%s",optr->domain,optr->id,pptr->expression); if (!( hptr = rest_response_header( aptr, "X-OCCI-Attribute",cptr->buffer) )) return( rest_html_response( aptr, 500, "Server Failure" ) ); sprintf(cptr->buffer,"%s.%s.state=%u",optr->domain,optr->id,pptr->state); if (!( hptr = rest_response_header( aptr, "X-OCCI-Attribute",cptr->buffer) )) return( rest_html_response( aptr, 500, "Server Failure" ) ); if ( occi_render_links( aptr, pptr->id ) != 0) return( rest_html_response( aptr, 500, "Server Link Failure" ) ); else if (!( occi_success( aptr ) )) return( rest_response_status( aptr, 500, "Server Failure" ) ); else return( rest_response_status( aptr, 200, "OK" ) ); } /* ---------------------------------------------------------------------------------------- */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d g e t i t e m */ /* ---------------------------------------------------------------------------------------- */ private struct rest_response * paas_link_get_item( struct occi_category * optr, struct rest_client * cptr, struct rest_request * rptr, struct rest_response * aptr, char * id) { struct rest_header * hptr; struct occi_interface * iptr; struct occi_kind_node * nptr; struct paas_link * pptr; iptr = optr->callback; if (!( nptr = locate_paas_link_node(id))) return( rest_html_response( aptr, 404, "Not Found") ); else if (!( pptr = nptr->contents )) return( rest_html_response( aptr, 404, "Not Found") ); if (( iptr ) && (iptr->retrieve)) (*iptr->retrieve)(optr,nptr); autosave_paas_link_nodes(); return( paas_link_occi_response(optr,cptr,rptr,aptr,pptr)); } /* ------------------------------------------------------------------------------------------ */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d p o s t l i n k */ /* ------------------------------------------------------------------------------------------ */ private struct rest_response * paas_link_post_link( struct occi_category * optr, struct rest_client * cptr, struct rest_request * rptr, struct rest_response * aptr,char * id) { struct rest_header * hptr; struct occi_interface * iptr; struct occi_kind_node * nptr; struct paas_link * pptr; char * reqhost; if (!( nptr = locate_paas_link_node(id))) return( rest_html_response( aptr, 404, "Not Found") ); else if (!( pptr = nptr->contents )) return( rest_html_response( aptr, 404, "Not Found") ); else return( rest_html_response( aptr, 400, "Bad Request") ); } /* -------------------------------------------------------------------------------------------- */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d p o s t m i x i n */ /* -------------------------------------------------------------------------------------------- */ private struct rest_response * paas_link_post_mixin( struct occi_category * optr, struct rest_client * cptr, struct rest_request * rptr, struct rest_response * aptr,char * id) { struct rest_header * hptr; struct occi_interface * iptr; struct occi_kind_node * nptr; struct paas_link * pptr; char * reqhost; if (!( nptr = locate_paas_link_node(id))) return( rest_html_response( aptr, 404, "Not Found") ); else if (!( pptr = nptr->contents )) return( rest_html_response( aptr, 404, "Not Found") ); else return( rest_html_response( aptr, 400, "Bad Request")); } /* ---------------------------------------------------------------------------------------------- */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d p o s t a c t i o n */ /* ---------------------------------------------------------------------------------------------- */ private struct rest_response * paas_link_post_action( struct occi_category * optr, struct rest_client * cptr, struct rest_request * rptr, struct rest_response * aptr,char * id) { struct rest_header * hptr; struct occi_interface * iptr; struct occi_action * fptr; struct occi_kind_node * nptr; struct paas_link * pptr; char * reqhost; char * mptr; if (!( nptr = locate_paas_link_node(id))) return( rest_html_response( aptr, 404, "Not Found") ); else if (!( pptr = nptr->contents )) return( rest_html_response( aptr, 404, "Not Found") ); mptr = (rptr->parameters+strlen("action=")); for ( fptr=optr->firstact; fptr != (struct occi_action *) 0; fptr = fptr->next ) if (!( strncmp( mptr, fptr->name, strlen( fptr->name )) )) return( occi_invoke_action(fptr,optr,cptr,rptr,aptr,pptr) ); return( rest_html_response( aptr, 400, "Incorrect Action Request")); } /* ------------------------------------------------------------------------------------------ */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d p o s t i t e m */ /* ------------------------------------------------------------------------------------------ */ private struct rest_response * paas_link_post_item( struct occi_category * optr, struct rest_client * cptr, struct rest_request * rptr, struct rest_response * aptr) { struct rest_header * hptr; struct occi_interface * iptr; struct occi_kind_node * nptr; struct paas_link * pptr; char * reqhost; iptr = optr->callback; if (!( reqhost = rest_request_host( rptr ) )) return( rest_html_response( aptr, 400, "Bad Request" ) ); if (!( nptr = add_paas_link_node(1))) return( rest_html_response( aptr, 500, "Server Failure") ); else if (!( pptr = nptr->contents )) return( rest_html_response( aptr, 500, "Server Failure") ); if (!( occi_process_atributs( optr, rptr,aptr, pptr, set_paas_link_field ) )) return( rest_html_response( aptr, 500, "Server Failure") ); if (( iptr ) && (iptr->create)) (*iptr->create)(optr,nptr); autosave_paas_link_nodes(); sprintf(cptr->buffer,"%s%s%s",reqhost,optr->location,pptr->id); if (!( hptr = rest_response_header( aptr, "X-OCCI-Location",cptr->buffer) )) return( rest_html_response( aptr, 500, "Server Failure" ) ); else if (!( occi_success( aptr ) )) return( rest_response_status( aptr, 500, "Server Failure" ) ); else return( rest_response_status( aptr, 200, "OK" ) ); } /* ---------------------------------------------------------------------------------------- */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d p u t i t e m */ /* ---------------------------------------------------------------------------------------- */ private struct rest_response * paas_link_put_item( struct occi_category * optr, struct rest_client * cptr, struct rest_request * rptr, struct rest_response * aptr,char * id) { struct rest_header * hptr; struct occi_interface * iptr; struct occi_kind_node * nptr; struct paas_link * pptr; iptr = optr->callback; if (!( nptr = locate_paas_link_node(id))) return( rest_html_response( aptr, 404, "Not Found") ); else if (!( pptr = nptr->contents )) return( rest_html_response( aptr, 404, "Not Found") ); if (!( occi_process_atributs(optr,rptr,aptr, pptr, set_paas_link_field ) )) return( rest_html_response( aptr, 500, "Server Failure") ); if (( iptr ) && (iptr->update)) (*iptr->update)(optr,nptr); autosave_paas_link_nodes(); return( paas_link_occi_response(optr,cptr,rptr,aptr,pptr)); } /* ------------------------------------------------------------------------------------------ */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d h e a d i t e m */ /* ------------------------------------------------------------------------------------------ */ private struct rest_response * paas_link_head_item( struct occi_category * optr, struct rest_client * cptr, struct rest_request * rptr, struct rest_response * aptr,char * id) { struct rest_header * hptr; struct occi_kind_node * nptr; struct paas_link * pptr; if (!( nptr = locate_paas_link_node(id))) return( rest_html_response( aptr, 404, "Not Found") ); else if (!( pptr = nptr->contents )) return( rest_html_response( aptr, 404, "Not Found") ); else return( rest_html_response( aptr, 400, "Bad Request") ); } /* ---------------------------------------------------------------------------------------------- */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d d e l e t e i t e m */ /* ---------------------------------------------------------------------------------------------- */ private struct rest_response * paas_link_delete_item( struct occi_category * optr, struct rest_client * cptr, struct rest_request * rptr, struct rest_response * aptr, char * id) { struct rest_header * hptr; struct occi_interface * iptr; struct occi_kind_node * nptr; struct paas_link * pptr; iptr = optr->callback; if (!( nptr = locate_paas_link_node(id))) return( rest_html_response( aptr, 404, "Not Found") ); if (( iptr ) && (iptr->delete)) (*iptr->delete)(optr,nptr); drop_paas_link_node( nptr ); autosave_paas_link_nodes(); if (!( occi_success( aptr ) )) return( rest_response_status( aptr, 500, "Server Failure" ) ); else return( rest_response_status( aptr, 200, "OK" ) ); } /* ---------------------------------------------------------------------------------------- */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d g e t l i s t */ /* ---------------------------------------------------------------------------------------- */ private struct rest_response * paas_link_get_list( struct occi_category * optr, struct rest_client * cptr, struct rest_request * rptr, struct rest_response * aptr) { struct rest_header * hptr; struct occi_kind_node * sptr; struct paas_link * pptr; struct paas_link * fptr; char * reqhost; if (!( reqhost = rest_request_host( rptr ) )) return( rest_html_response( aptr, 400, "Bad Request" ) ); else if (!( fptr = filter_paas_link_info( optr, rptr, aptr ) )) return( rest_html_response( aptr, 400, "Bad Request" ) ); for ( sptr = paas_link_first; sptr != (struct occi_kind_node *) 0; sptr = sptr->next ) { if (!( pptr = sptr->contents )) continue; if (!( pass_paas_link_filter( pptr, fptr ) )) continue; sprintf(cptr->buffer,"%s%s%s",reqhost,optr->location,pptr->id); if (!( hptr = rest_response_header( aptr, "X-OCCI-Location",cptr->buffer) )) return( rest_html_response( aptr, 500, "Server Failure" ) ); } if (!( occi_success( aptr ) )) return( rest_response_status( aptr, 500, "Server Failure" ) ); else return( rest_response_status( aptr, 200, "OK" ) ); } /* -------------------------------------------------------------------------------------------- */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d d e l e t e a l l */ /* -------------------------------------------------------------------------------------------- */ private struct rest_response * paas_link_delete_all( struct occi_category * optr, struct rest_client * cptr, struct rest_request * rptr, struct rest_response * aptr) { struct rest_header * hptr; struct occi_interface * iptr; struct occi_kind_node * nptr; struct occi_kind_node * sptr; struct paas_link * pptr; struct paas_link * fptr; iptr = optr->callback; if (!( fptr = filter_paas_link_info( optr, rptr, aptr ) )) return( rest_html_response( aptr, 400, "Bad Request" ) ); nptr=paas_link_first; while (nptr != (struct occi_kind_node *) 0) { if ((!( pptr = nptr->contents )) || (!( pass_paas_link_filter( pptr, fptr ) ))) { nptr = nptr->next; continue; } else { if (( iptr ) && (iptr->delete)) { (*iptr->delete)(optr,nptr); } sptr = nptr->next; drop_paas_link_node( nptr ); nptr = sptr; } } autosave_paas_link_nodes(); if (!( occi_success( aptr ) )) return( rest_response_status( aptr, 500, "Server Failure" ) ); else return( rest_response_status( aptr, 200, "OK" ) ); } /* ------------------------------------------------------------------------------ */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d g e t */ /* ------------------------------------------------------------------------------ */ private struct rest_response * occi_paas_link_get(void * vptr, struct rest_client * cptr, struct rest_request * rptr) { struct rest_response * aptr; struct rest_header * hptr; struct occi_category * optr; char * ctptr; char * mptr; if (!( hptr = rest_resolve_header( rptr->first, "Content-Type" ) )) ctptr = "text/occi"; else ctptr = hptr->value; if (!( optr = vptr )) return( rest_bad_request(vptr,cptr,rptr) ); if(!(aptr = rest_allocate_response( cptr ))) return( aptr ); else if (!(strcmp( rptr->object, optr->location ) )) return( paas_link_get_list( optr, cptr, rptr, aptr ) ); else if (!(strncmp( rptr->object, optr->location, strlen(optr->location) ) )) return( paas_link_get_item( optr, cptr, rptr, aptr,rptr->object+strlen(optr->location) ) ); else return( rest_html_response( aptr, 400, "Bad Request") ); } /* -------------------------------------------------------------------------------- */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d h e a d */ /* -------------------------------------------------------------------------------- */ private struct rest_response * occi_paas_link_head(void * vptr, struct rest_client * cptr, struct rest_request * rptr) { struct rest_response * aptr; struct rest_header * hptr; struct occi_category * optr; char * ctptr; char * mptr; if (!( hptr = rest_resolve_header( rptr->first, "Content-Type" ) )) ctptr = "text/occi"; else ctptr = hptr->value; if (!( optr = vptr )) return( rest_bad_request(vptr,cptr,rptr) ); if(!(aptr = rest_allocate_response( cptr ))) return( aptr ); else if (!(strncmp( rptr->object, optr->location, strlen(optr->location) ) )) return( paas_link_head_item( optr, cptr, rptr, aptr,rptr->object+strlen(optr->location) ) ); else return( rest_html_response( aptr, 400, "Bad Request") ); } /* -------------------------------------------------------------------------------- */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d p o s t */ /* -------------------------------------------------------------------------------- */ private struct rest_response * occi_paas_link_post(void * vptr, struct rest_client * cptr, struct rest_request * rptr) { struct rest_response * aptr; struct rest_header * hptr; struct occi_category * optr; char * ctptr; char * mptr; if (!( hptr = rest_resolve_header( rptr->first, "Content-Type" ) )) ctptr = "text/occi"; else ctptr = hptr->value; if (!( optr = vptr )) return( rest_bad_request(vptr,cptr,rptr) ); if(!(aptr = rest_allocate_response( cptr ))) return( aptr ); else if (!( strcmp( rptr->object, optr->location ) )) return( paas_link_post_item( optr, cptr, rptr, aptr ) ); else if ( strncmp( rptr->object, optr->location,strlen(optr->location)) != 0) return( rest_html_response( aptr, 400, "Bad Request") ); else if (!( rptr->parameters )) return( rest_html_response( aptr, 400, "Bad Request") ); else if (!( strncmp( rptr->parameters, "action=", strlen("action=")) )) return( paas_link_post_action( optr, cptr, rptr, aptr,rptr->object+strlen(optr->location) ) ); else if (!( strncmp( rptr->parameters, "mixin=", strlen("mixin=")) )) return( paas_link_post_mixin( optr, cptr, rptr, aptr,rptr->object+strlen(optr->location) ) ); else if (!( strncmp( rptr->parameters, "link=", strlen("link=")) )) return( paas_link_post_link( optr, cptr, rptr, aptr,rptr->object+strlen(optr->location) ) ); else return( rest_html_response( aptr, 400, "Bad Request") ); } /* ------------------------------------------------------------------------------ */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d p u t */ /* ------------------------------------------------------------------------------ */ private struct rest_response * occi_paas_link_put(void * vptr, struct rest_client * cptr, struct rest_request * rptr) { struct rest_response * aptr; struct rest_header * hptr; struct occi_category * optr; char * ctptr; char * mptr; if (!( hptr = rest_resolve_header( rptr->first, "Content-Type" ) )) ctptr = "text/occi"; else ctptr = hptr->value; if (!( optr = vptr )) return( rest_bad_request(vptr,cptr,rptr) ); if(!(aptr = rest_allocate_response( cptr ))) return( aptr ); else if (!(strncmp( rptr->object, optr->location, strlen(optr->location) ) )) return( paas_link_put_item( optr, cptr, rptr, aptr,rptr->object+strlen(optr->location) ) ); else return( rest_html_response( aptr, 400, "Bad Request") ); } /* ------------------------------------------------------------------------------------ */ /* o c c i c a t e g o r y r e s t i n t e r f a c e m e t h o d d e l e t e */ /* ------------------------------------------------------------------------------------ */ private struct rest_response * occi_paas_link_delete(void * vptr, struct rest_client * cptr, struct rest_request * rptr) { struct rest_response * aptr; struct rest_header * hptr; struct occi_category * optr; char * ctptr; char * mptr; if (!( hptr = rest_resolve_header( rptr->first, "Content-Type" ) )) ctptr = "text/occi"; else ctptr = hptr->value; if (!( optr = vptr )) return( rest_bad_request(vptr,cptr,rptr) ); if(!(aptr = rest_allocate_response( cptr ))) return( aptr ); else if (!(strcmp( rptr->object, optr->location ) )) return( paas_link_delete_all( optr, cptr, rptr, aptr ) ); else if (!(strncmp( rptr->object, optr->location, strlen(optr->location) ) )) return( paas_link_delete_item( optr, cptr, rptr, aptr,rptr->object+strlen(optr->location) ) ); else return( rest_html_response( aptr, 400, "Bad Request") ); } /* -------------------------------------------------------------------------------- */ /* o c c i c a t e g o r y r e s t i n t e r f a c e r e d i r e c t i o n */ /* -------------------------------------------------------------------------------- */ private void redirect_occi_paas_link_mt( struct rest_interface * iptr ) { iptr->get = occi_paas_link_get; iptr->post = occi_paas_link_post; iptr->put = occi_paas_link_put; iptr->delete = occi_paas_link_delete; iptr->head = occi_paas_link_head; return; } /* ------------------------------------ */ /* c r u d d e l e t e a c t i o n */ /* ------------------------------------ */ private struct rest_response * delete_action_paas_link(struct occi_category * optr, struct rest_client * cptr, struct rest_request * rptr, struct rest_response * aptr, void * vptr ) { aptr = liberate_rest_response( aptr ); return( occi_paas_link_delete(optr,cptr,rptr)); } /* ------------------------------------------ */ /* o c c i c a t e g o r y b u i l d e r */ /* ------------------------------------------ */ /* occi category rest instance builder for : occi_paas_link */ public struct occi_category * occi_paas_link_builder(char * a,char * b) { char * c="http://scheme.compatibleone.fr/scheme/compatible#"; char * d="kind"; char * e="http://scheme.ogf.org/occi/resource#"; char * f="CompatibleOne OCCI resource paas_link"; struct occi_category * optr; if (!( optr = occi_create_category(a,b,c,d,e,f) )) { return(optr); } else { redirect_occi_paas_link_mt(optr->interface); if (!( optr = occi_add_attribute(optr, "name",0,0) )) return(optr); if (!( optr = occi_add_attribute(optr, "type",0,0) )) return(optr); if (!( optr = occi_add_attribute(optr, "expression",0,0) )) return(optr); if (!( optr = occi_add_attribute(optr, "state",0,0) )) return(optr); if (!( optr = occi_add_action( optr,"DELETE","",delete_action_paas_link))) return( optr ); autoload_paas_link_nodes(); return(optr); } } /* -------------------------------------------- */ /* p a a s _ l i n k _ o c c i _ h e a d e r s */ /* -------------------------------------------- */ public struct rest_header * paas_link_occi_headers(struct paas_link * sptr) { struct rest_header * first=(struct rest_header *) 0; struct rest_header * last=(struct rest_header *) 0; struct rest_header * hptr=(struct rest_header *) 0; char buffer[8192]; if (!( sptr )) return(0); if (!( hptr = allocate_rest_header())) return(hptr); else if (!( hptr->previous = last)) first = hptr; else hptr->previous->next = hptr; last = hptr; if (!( hptr->name = allocate_string("Category"))) return(first); sprintf(buffer,"paas_link; scheme='http://scheme.compatibleone.fr/scheme/compatible#'; class='kind';\r\n"); if (!( hptr->value = allocate_string(buffer))) return(first); if (!( hptr = allocate_rest_header())) return(first); else if (!( hptr->previous = last)) first = hptr; else hptr->previous->next = hptr; last = hptr; if (!( hptr->name = allocate_string("X-OCCI-Attribute"))) return(first); sprintf(buffer,"occi.paas_link.name='%s'\r\n",(sptr->name?sptr->name:"")); if (!( hptr->value = allocate_string(buffer))) return(first); if (!( hptr = allocate_rest_header())) return(first); else if (!( hptr->previous = last)) first = hptr; else hptr->previous->next = hptr; last = hptr; if (!( hptr->name = allocate_string("X-OCCI-Attribute"))) return(first); sprintf(buffer,"occi.paas_link.type='%s'\r\n",(sptr->type?sptr->type:"")); if (!( hptr->value = allocate_string(buffer))) return(first); if (!( hptr = allocate_rest_header())) return(first); else if (!( hptr->previous = last)) first = hptr; else hptr->previous->next = hptr; last = hptr; if (!( hptr->name = allocate_string("X-OCCI-Attribute"))) return(first); sprintf(buffer,"occi.paas_link.expression='%s'\r\n",(sptr->expression?sptr->expression:"")); if (!( hptr->value = allocate_string(buffer))) return(first); if (!( hptr = allocate_rest_header())) return(first); else if (!( hptr->previous = last)) first = hptr; else hptr->previous->next = hptr; last = hptr; if (!( hptr->name = allocate_string("X-OCCI-Attribute"))) return(first); sprintf(buffer,"occi.paas_link.state='%u'\r\n",sptr->state); if (!( hptr->value = allocate_string(buffer))) return(first); return(first); } #endif /* _occipaas_link_c_ */
41.958595
120
0.561317
[ "object" ]