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
b77a71f1c5d05cfb3a01ad95ac122dbd42f2759d
10,986
c
C
test/command-source_unit.c
williamcroberts/tpm2-abrmd
221784228f5d0d479a0de8153a452b10ab546bc8
[ "BSD-2-Clause" ]
null
null
null
test/command-source_unit.c
williamcroberts/tpm2-abrmd
221784228f5d0d479a0de8153a452b10ab546bc8
[ "BSD-2-Clause" ]
null
null
null
test/command-source_unit.c
williamcroberts/tpm2-abrmd
221784228f5d0d479a0de8153a452b10ab546bc8
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2017, Intel Corporation * 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 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. */ #include <glib.h> #include <errno.h> #include <error.h> #include <fcntl.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/select.h> #include <unistd.h> #include <setjmp.h> #include <cmocka.h> #include "connection-manager.h" #include "sink-interface.h" #include "source-interface.h" #include "command-attrs.h" #include "command-source.h" #include "tpm2-command.h" typedef struct source_test_data { ConnectionManager *manager; CommandAttrs *command_attrs; CommandSource *source; Connection *connection; gboolean match; } source_test_data_t; Connection* __wrap_connection_manager_lookup_fd (ConnectionManager *manager, gint fd_in) { g_debug ("__wrap_connection_manager_lookup_fd"); return CONNECTION (mock ()); } int __wrap_read_data (int fd, size_t *index, uint8_t *buf, size_t count) { g_debug ("__wrap_read_data"); memcpy (&buf[*index], mock_type(uint8_t*), count); *index = mock_type (size_t); return mock_type (int); } void __wrap_sink_enqueue (Sink *sink, GObject *obj) { Tpm2Command **command; g_debug ("__wrap_sink_enqueue"); command = (Tpm2Command**)mock (); *command = TPM2_COMMAND (obj); g_object_ref (*command); } /* command_source_allocate_test begin * Test to allcoate and destroy a CommandSource. */ static void command_source_allocate_test (void **state) { source_test_data_t *data = (source_test_data_t *)*state; data->command_attrs = command_attrs_new (); data->source = command_source_new (data->manager, data->command_attrs); assert_non_null (data->source); } static void command_source_allocate_setup (void **state) { source_test_data_t *data; data = calloc (1, sizeof (source_test_data_t)); data->manager = connection_manager_new (TPM_HT_TRANSIENT); *state = data; } static void command_source_allocate_teardown (void **state) { source_test_data_t *data = (source_test_data_t*)*state; g_object_unref (data->source); g_object_unref (data->manager); free (data); } /* command_source_allocate end */ /* command_source_start_test * This is a basic usage flow test. Can it be started, canceled and joined. * We're testing the underlying pthread usage ... mostly. */ void command_source_start_test (void **state) { source_test_data_t *data; gint ret; data = (source_test_data_t*)*state; thread_start(THREAD (data->source)); sleep (1); ret = thread_cancel (THREAD (data->source)); assert_int_equal (ret, 0); ret = thread_join (THREAD (data->source)); assert_int_equal (ret, 0); } static void command_source_start_setup (void **state) { source_test_data_t *data; data = calloc (1, sizeof (source_test_data_t)); data->manager = connection_manager_new (TPM_HT_TRANSIENT); if (data->manager == NULL) g_error ("failed to allocate new connection_manager"); data->command_attrs = command_attrs_new (); data->source = command_source_new (data->manager, data->command_attrs); if (data->source == NULL) g_error ("failed to allocate new command_source"); *state = data; } static void command_source_start_teardown (void **state) { source_test_data_t *data = (source_test_data_t*)*state; g_object_unref (data->source); g_object_unref (data->manager); g_object_unref (data->command_attrs); free (data); } /* command_source_start_test end */ /* command_source_connection_insert_test begin * In this test we create a connection source and all that that entails. We then * create a new connection and insert it into the connection manager. We then signal * to the source that there's a new connection in the manager by sending data to * it over the send end of the wakeup pipe "wakeup_send_fd". We then check the * receive_fdset in the source structure to be sure the receive end of the * connection pipe is set. This is how we know that the source is now watching * for data from the new connection. */ static void command_source_wakeup_setup (void **state) { source_test_data_t *data; data = calloc (1, sizeof (source_test_data_t)); data->manager = connection_manager_new (MAX_CONNECTIONS_DEFAULT); data->command_attrs = command_attrs_new (); data->source = command_source_new (data->manager, data->command_attrs); *state = data; } static void command_source_connection_insert_test (void **state) { struct source_test_data *data = (struct source_test_data*)*state; CommandSource *source = data->source; HandleMap *handle_map; Connection *connection; gint ret, receive_fd, send_fd; /* */ handle_map = handle_map_new (TPM_HT_TRANSIENT, MAX_ENTRIES_DEFAULT); connection = connection_new (&receive_fd, &send_fd, 5, handle_map); g_object_unref (handle_map); assert_false (FD_ISSET (connection->receive_fd, &source->receive_fdset)); ret = thread_start(THREAD (source)); assert_int_equal (ret, 0); connection_manager_insert (data->manager, connection); sleep (1); assert_true (FD_ISSET (connection->receive_fd, &source->receive_fdset)); connection_manager_remove (data->manager, connection); thread_cancel (THREAD (source)); thread_join (THREAD (source)); } /* command_source_sesion_insert_test end */ /* command_source_connection_test start */ static void command_source_connection_setup (void **state) { source_test_data_t *data; data = calloc (1, sizeof (source_test_data_t)); data->manager = connection_manager_new (TPM_HT_TRANSIENT); data->command_attrs = command_attrs_new (); data->source = command_source_new (data->manager, data->command_attrs); *state = data; } static void command_source_connection_teardown (void **state) { source_test_data_t *data = (source_test_data_t*)*state; thread_cancel (THREAD (data->source)); thread_join (THREAD (data->source)); g_object_unref (data->source); g_object_unref (data->manager); free (data); } /** * A test: Test the command_source_connection_responder function. We do this * by creating a new Connection object, associating it with a new * Tpm2Command object (that we populate with a command body), and then * calling the command_source_connection_responder. * This function will in turn call the connection_manager_lookup_fd, * tpm2_command_new_from_fd, before finally calling the sink_enqueue function. * We mock these 3 functions to control the flow through the function under * test. * The most tricky bit to this is the way the __wrap_sink_enqueue function * works. Since this thing has no return value we pass it a reference to a * Tpm2Command pointer. It sets this to the Tpm2Command that it receives. * We determine success /failure for this test by verifying that the * sink_enqueue function receives the same Tpm2Command that we passed to * the command under test (command_source_connection_responder). */ static void command_source_process_client_fd_test (void **state) { struct source_test_data *data = (struct source_test_data*)*state; HandleMap *handle_map; Connection *connection; Tpm2Command *command_out; gint fds[2] = { 0, }; guint8 data_in [] = { 0x80, 0x01, 0x0, 0x0, 0x0, 0x17, 0x0, 0x0, 0x01, 0x7a, 0x0, 0x0, 0x0, 0x06, 0x0, 0x0, 0x01, 0x0, 0x0, 0x0, 0x0, 0x7f, 0x0a }; handle_map = handle_map_new (TPM_HT_TRANSIENT, MAX_ENTRIES_DEFAULT); connection = connection_new (&fds[0], &fds[1], 0, handle_map); g_object_unref (handle_map); /* prime wraps */ will_return (__wrap_connection_manager_lookup_fd, connection); /* setup read of header */ will_return (__wrap_read_data, &data_in [0]); will_return (__wrap_read_data, 10); will_return (__wrap_read_data, 0); /* setup read of body */ will_return (__wrap_read_data, &data_in [10]); will_return (__wrap_read_data, sizeof (data_in) - 10); will_return (__wrap_read_data, 0); will_return (__wrap_sink_enqueue, &command_out); process_client_fd (data->source, 0); assert_memory_equal (tpm2_command_get_buffer (command_out), data_in, sizeof (data_in)); g_object_unref (command_out); } /* command_source_connection_test end */ int main (int argc, char* argv[]) { const UnitTest tests[] = { unit_test_setup_teardown (command_source_allocate_test, command_source_allocate_setup, command_source_allocate_teardown), unit_test_setup_teardown (command_source_start_test, command_source_start_setup, command_source_start_teardown), unit_test_setup_teardown (command_source_connection_insert_test, command_source_wakeup_setup, command_source_start_teardown), unit_test_setup_teardown (command_source_process_client_fd_test, command_source_connection_setup, command_source_connection_teardown), }; return run_tests (tests); }
34.438871
84
0.684963
[ "object" ]
b77d70d15d05c0e52ed91f00d64740e95f7ac37a
9,444
c
C
fatfs.sup/fatfs_sup.c
magore/esp8266_ili9341
03e96928f0ab20a9c3b91552d221cf41eb2ba40c
[ "Cube", "NTP", "X11" ]
34
2015-06-24T18:16:58.000Z
2021-11-02T13:52:44.000Z
fatfs.sup/fatfs_sup.c
magore/esp8266_ili9341
03e96928f0ab20a9c3b91552d221cf41eb2ba40c
[ "Cube", "NTP", "X11" ]
5
2016-11-05T19:16:45.000Z
2022-02-13T16:50:42.000Z
fatfs.sup/fatfs_sup.c
magore/esp8266_ili9341
03e96928f0ab20a9c3b91552d221cf41eb2ba40c
[ "Cube", "NTP", "X11" ]
20
2015-08-07T22:59:06.000Z
2022-03-08T15:01:27.000Z
/** @file fatfs/disk.c @brief Allocate, Free and display FILINFO structurs, getfattime(), display error messages @par Copyright &copy; 2014-2017 Mike Gore, All rights reserved. GPL License @see http://github.com/magore/hp85disk @see http://github.com/magore/hp85disk/COPYRIGHT.md for specific Copyright details @par Credit: part of FatFs avr example project (C)ChaN, 2013. @par Copyright &copy; 2013 ChaN. @par You are free to use this code under the terms of GPL please retain a copy of this notice in any code you use it in. This 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. This software 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, see <http://www.gnu.org/licenses/>. */ #include "user_config.h" #include "fatfs.sup/fatfs.h" #ifdef AVR #include <stdlib.h> #endif #include "printf/mathio.h" #include "lib/time.h" ///@brief FatFs Drive Volumes FATFS Fatfs[_VOLUMES]; /* File system object for each logical drive */ #if _MULTI_PARTITION != 0 /// @brief FatFs multiple partition drives const PARTITION Drives[] = { { 0,0 } , { 0,1 } }; #endif #if FATFS_DEBUG > 0 ///@brief FatFs Error Messages /// /// - Credit: part of FatFs avr example project (C)ChaN, 2013 static const char *err_msg[] = { "OK", "DISK_ERR", "INT_ERR", "NOT_READY", "NO_FILE", "NO_PATH", "INVALID_NAME", "DENIED", "EXIST", "INVALID_OBJECT", "WRITE_PROTECTED", "INVALID_DRIVE", "NOT_ENABLED", "NO_FILE_SYSTEM", "MKFS_ABORTED", "TIMEOUT", "LOCKED", "NOT_ENOUGH_CORE", "TOO_MANY_OPEN_FILES", "INVALID_PARAMETER", NULL }; #endif /// @brief FAT time structer reference. /// @see rtc.h /// @see http://lxr.free-electrons.com/source/fs/fat/misc.c /// @verbatim /// typedef struct /// { /// WORD year; /* 2000..2099 */ /// BYTE month; /* 1..12 */ /// BYTE mday; /* 1.. 31 */ /// BYTE wday; /* 1..7 */ /// BYTE hour; /* 0..23 */ /// BYTE min; /* 0..59 */ /// BYTE sec; /* 0..59 */ /// } RTC; /// @endverbatim /// @brief Convert Linux POSIX tm_t * to FAT32 time. /// /// @param[in] t: POSIX struct tm * to convert. /// /// @return FAT32 time. MEMSPACE uint32_t tm_to_fat(tm_t *t) { uint32_t fat; /* Pack date and time into a uint32_t variable */ fat = ((uint32_t)(t->tm_year - 80) << 25) | (((uint32_t)t->tm_mon+1) << 21) | (((uint32_t)t->tm_mday) << 16) | ((uint32_t)t->tm_hour << 11) | ((uint32_t)t->tm_min << 5) | ((uint32_t)t->tm_sec >> 1); return(fat); } /// @brief Read time and convert to FAT32 time. /// /// @return FAT32 time. /// @see tm_to_fat(). MEMSPACE DWORD get_fattime (void) { time_t t; /* Get GMT time */ time(&t); return( tm_to_fat(localtime(&t))); } /// @brief display FatFs return code as ascii string /// /// Credit: Part of FatFs avr example project (C)ChaN, 2013 /// @param[in] rc: FatFs status return code /// @return void MEMSPACE void put_rc (int rc) { #if FATFS_DEBUG > 0 char *ptr; if(rc > 19) ptr = "INVALID ERROR MESSAGE"; else ptr = (char *) err_msg[(int)rc]; printf("rc=%u FR_%s\n", rc, ptr); #else printf("rc=%u\n", rc); #endif } ///@brief Total file space used DWORD AccSize; ///@brief Total number or Files and Directories WORD AccFiles, AccDirs; /// @brief Use were FILINFO structure can be share in many functions /// See: fatfs_alloc_filinfo(), fatfs_scan_files() and fatfs_ls() /// @brief Allocate FILINFO structure and optional long file name buffer /// /// @param[in] allocate: If allocate is true use calloc otherwise return static __filinfo /// @see fatfs_free_filinfo() /// @see fatfs_scan_files() /// @see fatfs_ls() /// @return FILINFO * on success /// @return NULL on error /// @brief Compute space used, number of directories and files contained under a specified directory /// /// - Credit: part of FatFs avr example project (C)ChaN, 2013 /// /// @param[in] path: /// @see f_opendir() /// @see f_readdir() /// @see AccDirs: Total number of directories /// @see AccFiles: Total number of Files /// @see AccSize: Total size of all files /// @return 0 if no error /// @return FafFs error code MEMSPACE int fatfs_scan_files ( char* path /* Pointer to the working buffer with start path */ ) { DIR dirs; FRESULT fr; int i; FILINFO info; fr = f_opendir(&dirs, path); if (fr == FR_OK) { while (((fr = f_readdir(&dirs, &info)) == FR_OK) && info.fname[0]) { if (info.fattrib & AM_DIR) { AccDirs++; i = strlen(path); path[i] = '/'; strcpy(path+i+1, info.fname); fr = fatfs_scan_files(path); path[i] = 0; if (fr != FR_OK) break; } else { // xprintf(PSTR("%s/%s\n"), path, info.fname); AccFiles++; AccSize += info.fsize; } #ifdef ESP8266 optimistic_yield(1000); wdt_reset(); #endif } } return fr; } /// @brief return a string with the file system type /// @param[in] type: file system type /// @return string with file system type MEMSPACE char *fatfs_fstype(int type) { char *ptr; switch(type) { case FS_FAT12: ptr = "FAT12"; break; case FS_FAT16: ptr = "FAT16"; break; case FS_FAT32: ptr = "FAT32"; break; case FS_EXFAT: ptr = "EXFAT"; break; default: ptr = "UNKNOWN"; break; } return(ptr); } /// @brief Compute space used, number of directories and files contained used by a drive /// /// - Credit: part of FatFs avr example project (C)ChaN, 2013 /// /// @param[in] ptr: Drive path like "/" /// @see f_getfree() drive free space /// @see fatfs_scan_files() /// @see AccDirs: Total number of directories /// @see AccFiles: Total number of Files /// @see AccSize: Total size of all files /// @return void MEMSPACE void fatfs_status(char *ptr) { long p2; int res; FATFS *fs; char label[24+2]; DWORD vsn; // volume serial number while(*ptr == ' ' || *ptr == '\t') ++ptr; printf("fatfs status:%s\n",ptr); res = f_getfree(ptr, (DWORD*)&p2, &fs); if (res) { put_rc(res); return; } printf("FAT type = %s\n", fatfs_fstype(fs->fs_type)); printf("Bytes/Cluster = %lu\n", (DWORD)fs->csize * 512); printf("Number of FATs = %u\n", fs->n_fats); printf("Root DIR entries = %u\n", fs->n_rootdir); printf("Sectors/FAT = %lu\n", fs->fsize); printf("Number of clusters = %lu\n", fs->n_fatent - 2); printf("FAT start (lba) = %lu\n", fs->fatbase); printf("DIR start (lba,clustor) = %lu\n", fs->dirbase); printf("Data start (lba) = %lu\n", fs->database); #if _USE_LABEL res = f_getlabel(ptr, label, (DWORD*)&vsn); if (res) { put_rc(res); return; } printf("Volume name = %s\n", label[0] ? label : "<blank>"); printf("Volume S/N = %04X-%04X\n", (WORD)((DWORD)vsn >> 16), (WORD)(vsn & 0xFFFF)); #endif AccSize = AccFiles = AccDirs = 0; res = fatfs_scan_files(ptr); if (res) { put_rc(res); return; } printf("%u files, %lu bytes.\n%u folders.\n" "%lu KB total disk space.\n%lu KB available.\n", AccFiles, AccSize, AccDirs, (fs->n_fatent - 2) * fs->csize / 2, p2 * fs->csize / 2 ); } /// @brief Display FILINFO structure in a readable format /// /// - Credit: part of FatFs avr example project (C)ChaN, 2013. /// - Example: /// @verbatim /// ----A 2014/10/16 00:39 14 test2.txt /// D---- 2014/10/12 21:29 0 tmp /// @endverbatim /// /// @param[in] : FILINFO pointer /// @return void MEMSPACE void fatfs_filinfo_list(FILINFO *info) { char attrs[6]; if(info->fname[0] == 0) { printf("fatfs_filinfo_list: empty\n"); return; } attrs[0] = (info->fattrib & AM_DIR) ? 'D' : '-'; attrs[1] = (info->fattrib & AM_RDO) ? 'R' : '-'; attrs[2] = (info->fattrib & AM_HID) ? 'H' : '-'; attrs[3] = (info->fattrib & AM_SYS) ? 'S' : '-'; attrs[4] = (info->fattrib & AM_ARC) ? 'A' : '-'; attrs[5] = 0; printf("%s %u/%02u/%02u %02u:%02u %9lu %s", attrs, (info->fdate >> 9) + 1980, (info->fdate >> 5) & 15, info->fdate & 31, (info->ftime >> 11), (info->ftime >> 5) & 63, info->fsize, info->fname); printf("\n"); }
26.52809
101
0.558556
[ "object" ]
b77f9f31063396cab82301bbef80a77bb00c9c2a
55,540
c
C
os/sysbits.c
packages-swi-to-yap/yap-6.3
8b1eab04eb14a55bcf7e733f2cc42c69808caa5c
[ "Artistic-1.0-Perl", "ClArtistic" ]
null
null
null
os/sysbits.c
packages-swi-to-yap/yap-6.3
8b1eab04eb14a55bcf7e733f2cc42c69808caa5c
[ "Artistic-1.0-Perl", "ClArtistic" ]
null
null
null
os/sysbits.c
packages-swi-to-yap/yap-6.3
8b1eab04eb14a55bcf7e733f2cc42c69808caa5c
[ "Artistic-1.0-Perl", "ClArtistic" ]
null
null
null
/************************************************************************* * * * YAP Prolog * * * * Yap Prolog was developed at NCCUP - Universidade do Porto * * * * Copyright L.Damas, V.S.Costa and Universidade do Porto 1985-1997 * * * ************************************************************************** * * * File: sysbits.c * * Last rev: 4/03/88 * * mods: * * comments: very much machine dependent routines * * * *************************************************************************/ #ifdef SCCS static char SccsId[] = "%W% %G%"; #endif #include "sysbits.h" /// File Error Handler static void FileError(yap_error_number type, Term where, const char *format, ...) { if (trueLocalPrologFlag(FILEERRORS_FLAG)) { va_list ap; va_start(ap, format); /* now build the error string */ Yap_Error(type, TermNil, format, ap); va_end(ap); } } static Int p_sh(USES_REGS1); static Int p_shell(USES_REGS1); static Int p_system(USES_REGS1); static Int p_mv(USES_REGS1); static Int p_dir_sp(USES_REGS1); static Int p_getenv(USES_REGS1); static Int p_putenv(USES_REGS1); static Term do_glob(const char *spec, bool ok_to); #ifdef MACYAP static int chdir(char *); /* #define signal skel_signal */ #endif /* MACYAP */ static const char *expandVars(const char *spec, char *u); void exit(int); static void freeBuffer(const void *ptr) { CACHE_REGS if (ptr == NULL || ptr == LOCAL_FileNameBuf || ptr == LOCAL_FileNameBuf2) return; free((void *)ptr); } #ifdef _WIN32 void Yap_WinError(char *yap_error) { char msg[256]; /* Error, we could not read time */ FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), msg, 256, NULL); Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, TermNil, "%s at %s", msg, yap_error); } #endif /* __WINDOWS__ */ #define is_valid_env_char(C) \ (((C) >= 'a' && (C) <= 'z') || ((C) >= 'A' && (C) <= 'Z') || (C) == '_') #if __ANDROID__ AAssetManager *Yap_assetManager; void *Yap_openAssetFile(const char *path) { const char *p = path + 8; AAsset *asset = AAssetManager_open(Yap_assetManager, p, AASSET_MODE_UNKNOWN); return asset; } bool Yap_isAsset(const char *path) { if (Yap_assetManager == NULL) return false; return path[0] == '/' && path[1] == 'a' && path[2] == 's' && path[3] == 's' && path[4] == 'e' && path[5] == 't' && path[6] == 's' && (path[7] == '/' || path[7] == '\0'); } bool Yap_AccessAsset(const char *name, int mode) { AAssetManager *mgr = Yap_assetManager; const char *bufp = name + 7; if (bufp[0] == '/') bufp++; if ((mode & W_OK) == W_OK) { return false; } // directory works if file exists AAssetDir *assetDir = AAssetManager_openDir(mgr, bufp); if (assetDir) { AAssetDir_close(assetDir); return true; } return false; } bool Yap_AssetIsFile(const char *name) { AAssetManager *mgr = Yap_assetManager; const char *bufp = name + 7; if (bufp[0] == '/') bufp++; // check if file is a directory. AAsset *asset = AAssetManager_open(mgr, bufp, AASSET_MODE_UNKNOWN); if (!asset) return false; AAsset_close(asset); return true; } bool Yap_AssetIsDir(const char *name) { AAssetManager *mgr = Yap_assetManager; const char *bufp = name + 7; if (bufp[0] == '/') bufp++; // check if file is a directory. AAssetDir *assetDir = AAssetManager_openDir(mgr, bufp); if (!assetDir) { return false; } AAssetDir_close(assetDir); AAsset *asset = AAssetManager_open(mgr, bufp, AASSET_MODE_UNKNOWN); if (!asset) return true; AAsset_close(asset); return false; } int64_t Yap_AssetSize(const char *name) { AAssetManager *mgr = Yap_assetManager; const char *bufp = name + 7; if (bufp[0] == '/') bufp++; AAsset *asset = AAssetManager_open(mgr, bufp, AASSET_MODE_UNKNOWN); if (!asset) return -1; off64_t len = AAsset_getLength64(asset); AAsset_close(asset); return len; } #endif /// is_directory: verifies whether an expanded file name /// points at a readable directory static bool is_directory(const char *FileName) { #ifdef __ANDROID__ if (Yap_isAsset(FileName)) { return Yap_AssetIsDir(FileName); } #endif #ifdef __WINDOWS__ DWORD dwAtts = GetFileAttributes(FileName); if (dwAtts == INVALID_FILE_ATTRIBUTES) return false; return (dwAtts & FILE_ATTRIBUTE_DIRECTORY); #elif HAVE_LSTAT struct stat buf; if (lstat(FileName, &buf) == -1) { /* return an error number */ return false; } return S_ISDIR(buf.st_mode); #else Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, "stat not available in this configuration"); return false; #endif } bool Yap_Exists(const char *f) { #if _WIN32 if (_access(f, 0) == 0) return true; if (errno == EINVAL) { Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, "bad flags to access"); } return false; #elif HAVE_ACCESS if (access(f, F_OK) == 0) return true; if (errno == EINVAL) { Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, "bad flags to access"); } return false; #else Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, "access not available in this configuration"); return false; #endif } static int dir_separator(int ch) { #ifdef MAC return (ch == ':'); #elif ATARI || _MSC_VER return (ch == '\\'); #elif defined(__MINGW32__) || defined(__CYGWIN__) return (ch == '\\' || ch == '/'); #else return (ch == '/'); #endif } int Yap_dir_separator(int ch) { return dir_separator(ch); } #if __WINDOWS__ #include <psapi.h> char *libdir = NULL; #endif bool Yap_IsAbsolutePath(const char *p0) { // verify first if expansion is needed: ~/ or $HOME/ const char *p = expandVars(p0, LOCAL_FileNameBuf); bool nrc; #if _WIN32 || __MINGW32__ nrc = !PathIsRelative(p); #else nrc = (p[0] == '/'); #endif return nrc; } #define isValidEnvChar(C) \ (((C) >= 'a' && (C) <= 'z') || ((C) >= 'A' && (C) <= 'Z') || (C) == '_') // this is necessary because // support for ~expansion at the beginning // systems like Android do not do this. static const char *PlExpandVars(const char *source, const char *root, char *result) { CACHE_REGS const char *src = source; if (!result) result = malloc(YAP_FILENAME_MAX + 1); if (strlen(source) >= YAP_FILENAME_MAX) { Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, TermNil, "%s in true_file-name is larger than the buffer size (%d bytes)", source, strlen(source)); } /* step 1: eating home information */ if (source[0] == '~') { if (dir_separator(source[1]) || source[1] == '\0') { char *s; src++; #if defined(_WIN32) s = getenv("HOMEDRIVE"); if (s != NULL) strncpy(result, getenv("HOMEDRIVE"), YAP_FILENAME_MAX); // s = getenv("HOMEPATH"); #else s = getenv("HOME"); #endif if (s != NULL) strncpy(result, s, YAP_FILENAME_MAX); strcat(result, src); return result; } else { #if HAVE_GETPWNAM struct passwd *user_passwd; char *res = result; src++; while (!dir_separator((*res = *src)) && *res != '\0') res++, src++; res[0] = '\0'; if ((user_passwd = getpwnam(result)) == NULL) { FileError(SYSTEM_ERROR_OPERATING_SYSTEM, MkAtomTerm(Yap_LookupAtom(source)), "User %s does not exist in %s", result, source); return NULL; } strncpy(result, user_passwd->pw_dir, YAP_FILENAME_MAX); strcat(result, src); #else FileError( SYSTEM_ERROR_OPERATING_SYSTEM, MkAtomTerm(Yap_LookupAtom(source)), "User %s cannot be found in %s, missing getpwnam", result, source); return NULL; #endif } return result; } // do VARIABLE expansion else if (source[0] == '$') { /* follow SICStus expansion rules */ char v[YAP_FILENAME_MAX + 1]; int ch; char *s, *res; src = source + 1; if (src[0] == '{') { res = v; src++; while ((*res = (ch = *src++)) && isValidEnvChar(ch) && ch != '}') { res++; } if (ch == '}') { // {...} // done res[0] = '\0'; } } else { res = v; while ((*res = (ch = *src++)) && isValidEnvChar(ch) && ch != '}') { res++; } src--; res[0] = '\0'; } if ((s = (char *)getenv(v))) { strcpy(result, s); strcat(result, src); } else strcpy(result, src); } else { size_t tocp = strlen(src); if (root) { tocp = strlen(root) + 1; } if (tocp > YAP_FILENAME_MAX) { Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, MkStringTerm(src), "path too long"); return NULL; } if (root) { strncpy(result, root, YAP_FILENAME_MAX); strncat(result, "/", YAP_FILENAME_MAX); strncat(result, source, YAP_FILENAME_MAX); } else { strncpy(result, source, strlen(src) + 1); } } return result; } #if _WIN32 // straightforward conversion from Unix style to WIN style // check cygwin path.cc for possible improvements static char *unix2win(const char *source, char *target, int max) { char *s = target; const char *s0 = source; char *s1; int ch; if (s == NULL) s = malloc(YAP_FILENAME_MAX + 1); s1 = s; // win32 syntax // handle drive notation, eg //a/ if (s0[0] == '\0') { s[0] = '.'; s[1] = '\0'; return s; } if (s0[0] == '/' && s0[1] == '/' && isalpha(s0[2]) && s0[3] == '/') { s1[0] = s0[2]; s1[1] = ':'; s1[2] = '\\'; s0 += 4; s1 += 3; } while ((ch = *s1++ = *s0++)) { if (ch == '$') { s1[-1] = '%'; ch = *s0; // handle $(....) if (ch == '{') { s0++; while ((ch = *s0++) != '}') { *s1++ = ch; if (ch == '\0') return FALSE; } *s1++ = '%'; } else { while (((ch = *s1++ = *s0++) >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch == '-') || (ch >= '0' && ch <= '9') || (ch == '_')) ; s1[-1] = '%'; *s1++ = ch; if (ch == '\0') { s1--; s0--; } } } else if (ch == '/') s1[-1] = '\\'; } return s; } #endif static char *OsPath(const char *p, char *buf) { return (char *)p; } static char *PrologPath(const char *Y, char *X) { return (char *)Y; } #if _WIN32 #define HAVE_BASENAME 1 #define HAVE_REALPATH 1 #endif static bool ChDir(const char *path) { bool rc = false; char qp[FILENAME_MAX + 1]; const char *qpath = Yap_AbsoluteFile(path, qp, true); #ifdef __ANDROID__ if (GLOBAL_AssetsWD) { freeBuffer(GLOBAL_AssetsWD); GLOBAL_AssetsWD = NULL; } if (Yap_isAsset(qpath)) { AAssetManager *mgr = Yap_assetManager; const char *ptr = qpath + 8; AAssetDir *d; if (ptr[0] == '/') ptr++; d = AAssetManager_openDir(mgr, ptr); if (d) { GLOBAL_AssetsWD = malloc(strlen(qpath) + 1); strcpy(GLOBAL_AssetsWD, qpath); AAssetDir_close(d); return true; } return false; } else { GLOBAL_AssetsWD = NULL; } #endif #if _WIN32 rc = true; if (qpath != NULL && qpath[0] && (rc = (SetCurrentDirectory(qpath) != 0)) == 0) { Yap_WinError("SetCurrentDirectory failed"); } #else rc = (chdir(qpath) == 0); #endif if (qpath != qp && qpath != LOCAL_FileNameBuf && qpath != LOCAL_FileNameBuf2) free((char *)qpath); return rc; } static const char *myrealpath(const char *path, char *out) { if (!out) out = LOCAL_FileNameBuf; #if _WIN32 DWORD retval = 0; // notice that the file does not need to exist retval = GetFullPathName(path, YAP_FILENAME_MAX, out, NULL); if (retval == 0) { Yap_WinError("Generating a full path name for a file"); return NULL; } return out; #elif HAVE_REALPATH { char *rc = realpath(path, NULL); if (rc) { return rc; } // rc = NULL; if (errno == ENOENT || errno == EACCES) { char base[YAP_FILENAME_MAX + 1]; strncpy(base, path, YAP_FILENAME_MAX - 1); rc = realpath(dirname(base), out); if (rc) { // base may haave been destroyed const char *b = basename((char *)path); size_t e = strlen(rc); size_t bs = strlen(b); if (rc != out && rc != base) { rc = realloc(rc, e + bs + 2); } #if _WIN32 if (rc[e - 1] != '\\' && rc[e - 1] != '/') { rc[e] = '\\'; rc[e + 1] = '\0'; } #else if (rc[e - 1] != '/') { rc[e] = '/'; rc[e + 1] = '\0'; } #endif strcat(rc, b); return rc; } } } #endif out = malloc(strlen(path) + 1); strcpy(out, path); return out; } static const char *expandVars(const char *spec, char *u) { CACHE_REGS #if _WIN32 || defined(__MINGW32__) char *out; // first pass, remove Unix style stuff if ((out = unix2win(spec, u, YAP_FILENAME_MAX)) == NULL) return NULL; spec = u; #endif bool ok_to = LOCAL_PrologMode && !(LOCAL_PrologMode & BootMode); if (ok_to) { Term t = do_glob(spec, true); if (IsPairTerm(t)) return RepAtom(AtomOfTerm(HeadOfTerm(t)))->StrOfAE; return NULL; } return spec; } /** * generate absolute path, if ok first expand SICStus Prolog style * * @param[in] spec the file path, including `~` and `$`. * @param[in] ok where to process `~` and `$`. * * @return tmp, or NULL, in malloced memory */ const char *Yap_AbsoluteFile(const char *spec, char *rc0, bool ok) { const char *rc; const char *spec1; const char *spec2; char rc1[YAP_FILENAME_MAX + 1]; /// spec gothe original spec; /// rc0 may be an outout buffer /// rc1 the internal buffer /// /// PlExpandVars #if _WIN32 char rc2[YAP_FILENAME_MAX]; if ((rc = unix2win(spec, rc2, YAP_FILENAME_MAX)) == NULL) { return NULL; } spec1 = rc; #else spec1 = spec; #endif /// spec gothe original spec; /// rc1 the internal buffer if (ok) { const char *q = PlExpandVars(spec1, NULL, rc1); if (!q) spec2 = spec1; else spec2 = q; } else { spec2 = spec1; } rc = myrealpath(spec2, rc0); return rc; } static Term /* Expand the string for the program to run. */ do_glob(const char *spec, bool glob_vs_wordexp) { CACHE_REGS char u[YAP_FILENAME_MAX + 1]; const char *espec = u; if (spec == NULL) { return TermNil; } #if _WIN32 { WIN32_FIND_DATA find; HANDLE hFind; CELL *dest; Term tf; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; _splitpath(spec, drive, dir, fname, ext); _makepath(u, drive, dir, fname, ext); // first pass, remove Unix style stuff hFind = FindFirstFile(u, &find); if (hFind == INVALID_HANDLE_VALUE) { return TermNil; } else { tf = AbsPair(HR); _makepath(u, drive, dir, find.cFileName, NULL); HR[0] = MkAtomTerm(Yap_LookupAtom(u)); HR[1] = TermNil; dest = HR + 1; HR += 2; while (FindNextFile(hFind, &find)) { *dest = AbsPair(HR); _makepath(u, drive, dir, find.cFileName, NULL); HR[0] = MkAtomTerm(Yap_LookupAtom(u)); HR[1] = TermNil; dest = HR + 1; HR += 2; } FindClose(hFind); } return tf; } #elif HAVE_WORDEXP || HAVE_GLOB strncpy(u, spec, sizeof(u)); /* Expand the string for the program to run. */ size_t pathcount; #if HAVE_GLOB glob_t gresult; #endif #if HAVE_WORDEXP wordexp_t wresult; #endif #if HAVE_GLOB || HAVE_WORDEXP char **ss = NULL; int flags = 0, j; #endif if (glob_vs_wordexp) { #if HAVE_GLOB #ifdef GLOB_NOCHECK flags = GLOB_NOCHECK; #else flags = 0; #endif #ifdef GLOB_BRACE flags |= GLOB_BRACE | GLOB_TILDE; #endif switch (glob(espec, flags, NULL, &gresult)) { case 0: /* Successful. */ ss = gresult.gl_pathv; pathcount = gresult.gl_pathc; if (pathcount) { break; } case GLOB_NOMATCH: globfree(&gresult); { return TermNil; } case GLOB_ABORTED: PlIOError(SYSTEM_ERROR_OPERATING_SYSTEM, ARG1, "glob aborted: %sn", strerror(errno)); globfree(&gresult); return TermNil; case GLOB_NOSPACE: Yap_Error(RESOURCE_ERROR_HEAP, ARG1, "glob ran out of space: %sn", strerror(errno)); globfree(&gresult); return TermNil; /* If the error was WRDE_NOSPACE, then perhaps part of the result was allocated. */ default: /* Some other error. */ return TermNil; } #endif } else { #if HAVE_WORDEXP int rc; memset(&wresult, 0, sizeof(wresult)); switch ((rc = wordexp(espec, &wresult, flags))) { case 0: /* Successful. */ ss = wresult.we_wordv; pathcount = wresult.we_wordc; if (pathcount) { break; } else { Term t; t = MkAtomTerm(Yap_LookupAtom(expandVars(espec, NULL))); wordfree(&wresult); return MkPairTerm(t, TermNil); } case WRDE_NOSPACE: /* If the error was WRDE_NOSPACE, then perhaps part of the result was allocated. */ Yap_Error(RESOURCE_ERROR_HEAP, ARG1, "wordexp ran out of space: %s", strerror(errno)); wordfree(&wresult); return TermNil; default: /* Some other error. */ PlIOError(SYSTEM_ERROR_OPERATING_SYSTEM, ARG1, "wordexp failed: %s", strerror(errno)); wordfree(&wresult); return TermNil; } #endif } const char *tmp; Term tf = TermNil; for (j = 0; j < pathcount; j++) { const char *s = ss[pathcount - (j + 1)]; tmp = s; // if (!exists(s)) // continue; Atom a = Yap_LookupAtom(tmp); tf = MkPairTerm(MkAtomTerm(a), tf); } #if HAVE_GLOB if (glob_vs_wordexp) globfree(&gresult); #endif #if HAVE_WORDEXP if (!glob_vs_wordexp) wordfree(&wresult); #endif return tf; #else // just use basic return MkPairTerm(MkAtomTerm(Yap_LookupAtom(espec)), TermNil); #endif } /** * @pred prolog_expanded_file_system_path( +PrologPath, +ExpandVars, -OSPath ) * * Apply basic transformations to paths, and conidtionally apply * traditional SICStus-style variable expansion. * * @param PrologPath the source, may be atom or string * @param ExpandVars expand initial occurrence of ~ or $ * @param Prefix add this path before _PrologPath_ * @param OSPath pathname. * * @return */ static Int real_path(USES_REGS1) { Term t1 = Deref(ARG1); const char *cmd, *rc0; if (IsAtomTerm(t1)) { cmd = RepAtom(AtomOfTerm(t1))->StrOfAE; } else if (IsStringTerm(t1)) { cmd = StringOfTerm(t1); } else { return false; } #if _WIN32 char cmd2[YAP_FILENAME_MAX + 1]; char *rc; if ((rc = unix2win(cmd, cmd2, YAP_FILENAME_MAX)) == NULL) { return false; } cmd = rc; #endif rc0 = myrealpath(cmd, NULL); if (!rc0) { PlIOError(SYSTEM_ERROR_OPERATING_SYSTEM, ARG1, NULL); } return Yap_unify(MkAtomTerm(Yap_LookupAtom(rc0)), ARG2); } #define EXPAND_FILENAME_DEFS() \ PAR("parameter_expansion", isatom, EXPAND_FILENAME_PARAMETER_EXPANSION) \ , PAR("commands", booleanFlag, EXPAND_FILENAME_COMMANDS), \ PAR(NULL, ok, EXPAND_FILENAME_END) #define PAR(x, y, z) z typedef enum expand_filename_enum_choices { EXPAND_FILENAME_DEFS() } expand_filename_enum_choices_t; #undef PAR #define PAR(x, y, z) \ { x, y, z } static const param_t expand_filename_defs[] = {EXPAND_FILENAME_DEFS()}; #undef PAR static Term do_expand_file_name(Term t1, Term opts USES_REGS) { xarg *args; expand_filename_enum_choices_t i; bool use_system_expansion = true; char *tmpe = NULL; const char *spec; Term tf; if (IsVarTerm(t1)) { Yap_Error(INSTANTIATION_ERROR, t1, NULL); return TermNil; } else if (IsAtomTerm(t1)) { spec = AtomTermName(t1); } else if (IsStringTerm(t1)) { spec = StringOfTerm(t1); } else { Yap_Error(TYPE_ERROR_ATOM, t1, NULL); return TermNil; } #if _WIN32 { char *rc; char cmd2[YAP_FILENAME_MAX + 1]; if ((rc = unix2win(spec, cmd2, YAP_FILENAME_MAX)) == NULL) { return false; } spec = rc; } #endif args = Yap_ArgListToVector(opts, expand_filename_defs, EXPAND_FILENAME_END); if (args == NULL) { return TermNil; } tmpe = malloc(YAP_FILENAME_MAX + 1); for (i = 0; i < EXPAND_FILENAME_END; i++) { if (args[i].used) { Term t = args[i].tvalue; switch (i) { case EXPAND_FILENAME_PARAMETER_EXPANSION: if (t == TermProlog) { const char *s = expandVars(spec, LOCAL_FileNameBuf); if (s == NULL) { return TermNil; } strcpy(tmpe, s); } else if (t == TermTrue) { use_system_expansion = true; } else if (t == TermFalse) { use_system_expansion = false; } break; case EXPAND_FILENAME_COMMANDS: if (!use_system_expansion) { use_system_expansion = true; #if 0 // def WRDE_NOCMD if (t == TermFalse) { flags = WRDE_NOCMD; } #endif } case EXPAND_FILENAME_END: break; } } } if (!use_system_expansion) { const char *o = expandVars(spec, NULL); if (!o) return false; return MkPairTerm(MkAtomTerm(Yap_LookupAtom(o)), TermNil); } tf = do_glob(spec, true); return tf; } /* @pred expand_file_name( +Pattern, -ListOfPaths) is det This builtin receives a pattern and expands it into a list of files. In Unix-like systems, YAP applies glob to expand patterns such as '*', '.', and '?'. Further variable expansion may also happen. glob is shell-dependent: som Yap_InitCPred ("absolute_file_system_path", 2, absolute_file_system_path, 0); Yap_InitCPred ("real_path", 2, prolog_realpath, 0); Yap_InitCPred ("true_file_name", 2, true_file_name, SyncPredFlag); Yap_InitCPred ("true_file_name", 3, true_file_name3, SyncPredFlag); e shells allow command execution and brace-expansion. */ static Int expand_file_name(USES_REGS1) { Term tf = do_expand_file_name(Deref(ARG1), TermNil PASS_REGS); if (tf == 0) return false; return Yap_unify(tf, ARG2); } static Int expand_file_name3(USES_REGS1) { Term tf = do_expand_file_name(Deref(ARG1), Deref(ARG2) PASS_REGS); return Yap_unify(tf, ARG3); } /* static char *canoniseFileName( char *path) { #if HAVE_REALPATH && HAVE_BASENAME #if _WIN32 || defined(__MINGW32__) char *o = malloc(YAP_FILENAME_MAX+1); if (!o) return NULL; // first pass, remove Unix style stuff if (unix2win(path, o, YAP_FILENAME_MAX) == NULL) return NULL; path = o; #endif char *rc; if (tmp == NULL) return NULL; rc = myrealpath(path); #if _WIN32 || defined(__MINGW32__) freeBuffer(o); #endif return rc; #endif } */ static Int absolute_file_system_path(USES_REGS1) { Term t = Deref(ARG1); const char *fp; bool rc; char s[MAXPATHLEN + 1]; const char *text = Yap_TextTermToText(t, s, MAXPATHLEN, LOCAL_encoding); if (text == NULL) { return false; } if (!(fp = Yap_AbsoluteFile(RepAtom(AtomOfTerm(t))->StrOfAE, NULL, true))) return false; rc = Yap_unify(Yap_MkTextTerm(fp, LOCAL_encoding, t), ARG2); if (fp != s) freeBuffer((void *)fp); return rc; } static Int prolog_to_os_filename(USES_REGS1) { Term t = Deref(ARG1), t2 = Deref(ARG2); char *fp; char out[MAXPATHLEN + 1]; if (IsVarTerm(t)) { if (IsVarTerm(t2)) { Yap_Error(INSTANTIATION_ERROR, t, "prolog_to_os_filename"); return false; } else if (IsAtomTerm(t2)) { if (!(fp = PrologPath(RepAtom(AtomOfTerm(t2))->StrOfAE, out))) return false; return Yap_unify(ARG1, MkAtomTerm(Yap_LookupAtom(fp))); } else { Yap_Error(TYPE_ERROR_ATOM, t2, "prolog_to_os_filename"); return false; } } else if (!IsAtomTerm(t)) { Yap_Error(TYPE_ERROR_ATOM, t, "prolog_to_os_filename"); return false; } if (!(fp = OsPath(RepAtom(AtomOfTerm(t))->StrOfAE, out))) return false; return Yap_unify(MkAtomTerm(Yap_LookupAtom(fp)), ARG2); } Atom Yap_TemporaryFile(const char *prefix, int *fd) { #if HAVE_MKSTEMP char *tmp = malloc(PATH_MAX); int n; int f; if (tmp == NULL) return NIL; strncpy(tmp, prefix, PATH_MAX - 1); n = strlen(tmp); if (n >= 6 && tmp[n - 1] == 'X' && tmp[n - 2] == 'X' && tmp[n - 3] == 'X' && tmp[n - 4] == 'X' && tmp[n - 5] == 'X' && tmp[n - 6] == 'X') f = mkstemp(tmp); else { strncat(tmp, "XXXXXX", PATH_MAX - 1); f = mkstemp(tmp); } if (fd) *fd = f; return Yap_LookupAtom(tmp); #else return AtomNil; #endif } /** @pred make_directory(+ _Dir_) Create a directory _Dir_. The name of the directory must be an atom. */ static Int make_directory(USES_REGS1) { const char *fd = AtomName(AtomOfTerm(ARG1)); #if defined(__MINGW32__) || _MSC_VER if (_mkdir(fd) == -1) { #else if (mkdir(fd, 0777) == -1) { #endif /* return an error number */ return false; // errno? } return true; } static Int p_rmdir(USES_REGS1) { const char *fd = AtomName(AtomOfTerm(ARG1)); #if defined(__MINGW32__) || _MSC_VER if (_rmdir(fd) == -1) { #else if (rmdir(fd) == -1) { #endif /* return an error number */ return (Yap_unify(ARG2, MkIntTerm(errno))); } return true; } static bool initSysPath(Term tlib, Term tcommons, bool dir_done, bool commons_done) { CACHE_REGS int len; #if __WINDOWS__ { char *dir; if ((dir = Yap_RegistryGetString("library")) && is_directory(dir)) { if (!Yap_unify(tlib, MkAtomTerm(Yap_LookupAtom(dir)))) return FALSE; } dir_done = true; if ((dir = Yap_RegistryGetString("prolog_commons")) && is_directory(dir)) { if (!Yap_unify(tcommons, MkAtomTerm(Yap_LookupAtom(dir)))) return FALSE; } commons_done = true; } if (dir_done && commons_done) return TRUE; #endif strncpy(LOCAL_FileNameBuf, YAP_SHAREDIR, YAP_FILENAME_MAX); strncat(LOCAL_FileNameBuf, "/", YAP_FILENAME_MAX); len = strlen(LOCAL_FileNameBuf); if (!dir_done) { strncat(LOCAL_FileNameBuf, "Yap", YAP_FILENAME_MAX); if (is_directory(LOCAL_FileNameBuf)) { if (!Yap_unify(tlib, MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf)))) return FALSE; dir_done = true; } } if (!commons_done) { LOCAL_FileNameBuf[len] = '\0'; strncat(LOCAL_FileNameBuf, "PrologCommons", YAP_FILENAME_MAX); if (is_directory(LOCAL_FileNameBuf)) { if (!Yap_unify(tcommons, MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf)))) return FALSE; } commons_done = true; } if (dir_done && commons_done) return TRUE; #if __WINDOWS__ { size_t buflen; char *pt; /* couldn't find it where it was supposed to be, let's try using the executable */ if (!GetModuleFileName(NULL, LOCAL_FileNameBuf, YAP_FILENAME_MAX)) { Yap_WinError("could not find executable name"); /* do nothing */ return FALSE; } buflen = strlen(LOCAL_FileNameBuf); pt = LOCAL_FileNameBuf + buflen; while (*--pt != '\\') { /* skip executable */ if (pt == LOCAL_FileNameBuf) { FileError(SYSTEM_ERROR_OPERATING_SYSTEM, TermNil, "could not find executable name"); /* do nothing */ return FALSE; } } while (*--pt != '\\') { /* skip parent directory "bin\\" */ if (pt == LOCAL_FileNameBuf) { FileError(SYSTEM_ERROR_OPERATING_SYSTEM, TermNil, "could not find executable name"); /* do nothing */ return FALSE; } } /* now, this is a possible location for the ROOT_DIR, let's look for a share * directory here */ pt[1] = '\0'; /* grosse */ strncat(LOCAL_FileNameBuf, "lib\\Yap", YAP_FILENAME_MAX); libdir = Yap_AllocCodeSpace(strlen(LOCAL_FileNameBuf) + 1); strncpy(libdir, LOCAL_FileNameBuf, strlen(LOCAL_FileNameBuf) + 1); pt[1] = '\0'; strncat(LOCAL_FileNameBuf, "share", YAP_FILENAME_MAX); } strncat(LOCAL_FileNameBuf, "\\", YAP_FILENAME_MAX); len = strlen(LOCAL_FileNameBuf); strncat(LOCAL_FileNameBuf, "Yap", YAP_FILENAME_MAX); if (!dir_done && is_directory(LOCAL_FileNameBuf)) { if (!Yap_unify(tlib, MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf)))) return FALSE; } dir_done = true; LOCAL_FileNameBuf[len] = '\0'; strncat(LOCAL_FileNameBuf, "PrologCommons", YAP_FILENAME_MAX); if (!commons_done && is_directory(LOCAL_FileNameBuf)) { if (!Yap_unify(tcommons, MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf)))) return FALSE; } commons_done = true; #endif return dir_done && commons_done; } static Int libraries_directories(USES_REGS1) { return initSysPath(ARG1, ARG2, false, false); } static Int system_library(USES_REGS1) { return initSysPath(ARG1, MkVarTerm(), false, true); } static Int commons_library(USES_REGS1) { return initSysPath(MkVarTerm(), ARG1, true, false); } static Int p_dir_sp(USES_REGS1) { #if ATARI || _MSC_VER || defined(__MINGW32__) Term t = MkIntTerm('\\'); Term t2 = MkIntTerm('/'); #else Term t = MkIntTerm('/'); Term t2 = MkIntTerm('/'); #endif return Yap_unify_constant(ARG1, t) || Yap_unify_constant(ARG1, t2); } size_t Yap_InitPageSize(void) { #ifdef _WIN32 SYSTEM_INFO si; GetSystemInfo(&si); return si.dwPageSize; #elif HAVE_UNISTD_H #if defined(__FreeBSD__) || defined(__DragonFly__) return getpagesize(); #elif defined(_AIX) return sysconf(_SC_PAGE_SIZE); #elif !defined(_SC_PAGESIZE) return getpagesize(); #else return sysconf(_SC_PAGESIZE); #endif #else bla bla #endif } /* TrueFileName -> Finds the true name of a file */ #ifdef __MINGW32__ #include <ctype.h> #endif static int volume_header(char *file) { #if _MSC_VER || defined(__MINGW32__) char *ch = file; int c; while ((c = ch[0]) != '\0') { if (isalnum(c)) ch++; else return (c == ':'); } #endif return (FALSE); } int Yap_volume_header(char *file) { return volume_header(file); } const char *Yap_getcwd(const char *cwd, size_t cwdlen) { #if _WIN32 || defined(__MINGW32__) if (GetCurrentDirectory(cwdlen, (char *)cwd) == 0) { Yap_WinError("GetCurrentDirectory failed"); return NULL; } return (char *)cwd; #elif __ANDROID__ if (GLOBAL_AssetsWD) { return strncpy((char *)cwd, (const char *)GLOBAL_AssetsWD, cwdlen); } #endif return getcwd((char *)cwd, cwdlen); } static Int working_directory(USES_REGS1) { char dir[YAP_FILENAME_MAX + 1]; Term t1 = Deref(ARG1), t2; if (!IsVarTerm(t1) && !IsAtomTerm(t1)) { Yap_Error(TYPE_ERROR_ATOM, t1, "working_directory"); } if (!Yap_unify(t1, MkAtomTerm(Yap_LookupAtom(Yap_getcwd(dir, YAP_FILENAME_MAX))))) return false; t2 = Deref(ARG2); if (IsVarTerm(t2)) { Yap_Error(INSTANTIATION_ERROR, t2, "working_directory"); } if (!IsAtomTerm(t2)) { Yap_Error(TYPE_ERROR_ATOM, t2, "working_directory"); } if (t2 == TermEmptyAtom || t2 == TermDot) return true; return ChDir(RepAtom(AtomOfTerm(t2))->StrOfAE); } /** Yap_findFile(): tries to locate a file, no expansion should be performed/ * * * @param isource the proper file * @param idef the default name fo rthe file, ie, startup.yss * @param root the prefix * @param result the output * @param access verify whether the file has access permission * @param ftype saved state, object, saved file, prolog file * @param expand_root expand $ ~, etc * @param in_lib library file * * @return */ const char *Yap_findFile(const char *isource, const char *idef, const char *iroot, char *result, bool access, YAP_file_type_t ftype, bool expand_root, bool in_lib) { char save_buffer[YAP_FILENAME_MAX + 1]; const char *root, *source = isource; int rc = FAIL_RESTORE; int try = 0; while (rc == FAIL_RESTORE) { bool done = false; // { CACHE_REGS __android_log_print(ANDROID_LOG_ERROR, __FUNCTION__, // "try=%d %s %s", try, isource, iroot) ; } switch (try ++) { case 0: // path or file name is given; root = iroot; if (!root && ftype == YAP_BOOT_PL) { root = YAP_PL_SRCDIR; } if (idef || isource) { source = (isource ? isource : idef); } break; case 1: // library directory is given in command line if (in_lib && ftype == YAP_SAVED_STATE) { root = iroot; source = (isource ? isource : idef); } else { done = true; } break; case 2: // use environment variable YAPLIBDIR #if HAVE_GETENV if (in_lib) { if (ftype == YAP_SAVED_STATE || ftype == YAP_OBJ) { root = getenv("YAPLIBDIR"); } else if (ftype == YAP_BOOT_PL) { root = getenv("YAPSHAREDIR"); if (root == NULL) { continue; } else { strncpy(save_buffer, root, YAP_FILENAME_MAX); strncat(save_buffer, "/pl", YAP_FILENAME_MAX); } } source = (isource ? isource : idef); } else #endif done = true; break; case 3: // use compilation variable YAPLIBDIR if (in_lib) { source = (isource ? isource : idef); if (ftype == YAP_PL) { root = YAP_SHAREDIR; } else if (ftype == YAP_BOOT_PL) { root = YAP_SHAREDIR "/pl"; } else { root = YAP_LIBDIR; } } else done = true; break; case 4: // WIN stuff: registry #if __WINDOWS__ if (in_lib) { source = (ftype == YAP_PL || ftype == YAP_QLY ? "library" : "startup"); source = Yap_RegistryGetString(source); root = NULL; } else #endif done = true; break; case 5: // search from the binary #ifndef __ANDROID__ done = true; break; #endif const char *pt = Yap_FindExecutable(); if (pt) { if (ftype == YAP_BOOT_PL) { root = "../../share/Yap/pl"; } else { root = (ftype == YAP_SAVED_STATE || ftype == YAP_OBJ ? "../../lib/Yap" : "../../share/Yap"); } if (Yap_findFile(source, NULL, root, save_buffer, access, ftype, expand_root, in_lib)) root = save_buffer; else done = true; } else { done = true; } source = (isource ? isource : idef); break; case 6: // default, try current directory if (!isource && ftype == YAP_SAVED_STATE) source = idef; root = NULL; break; default: return false; } if (done) continue; // { CACHE_REGS __android_log_print(ANDROID_LOG_ERROR, __FUNCTION__, // "root= %s %s ", root, source) ; } const char *work = PlExpandVars(source, root, result); // expand names in case you have // to add a prefix if (!access || Yap_Exists(work)) { return work; // done } } return NULL; } static Int true_file_name(USES_REGS1) { Term t = Deref(ARG1); const char *s; if (IsVarTerm(t)) { Yap_Error(INSTANTIATION_ERROR, t, "argument to true_file_name unbound"); return FALSE; } if (IsAtomTerm(t)) { s = RepAtom(AtomOfTerm(t))->StrOfAE; } else if (IsStringTerm(t)) { s = StringOfTerm(t); } else { Yap_Error(TYPE_ERROR_ATOM, t, "argument to true_file_name"); return FALSE; } if (!(s = Yap_AbsoluteFile(s, LOCAL_FileNameBuf, true))) return false; return Yap_unify(ARG2, MkAtomTerm(Yap_LookupAtom(s))); } static Int p_expand_file_name(USES_REGS1) { Term t = Deref(ARG1); const char *text, *text2; if (IsVarTerm(t)) { Yap_Error(INSTANTIATION_ERROR, t, "argument to true_file_name unbound"); return FALSE; } text = Yap_TextTermToText(t, NULL, 0, LOCAL_encoding); if (!text) return false; if (!(text2 = PlExpandVars(text, NULL, NULL))) return false; freeBuffer(text); bool rc = Yap_unify(ARG2, Yap_MkTextTerm(text2, LOCAL_encoding, t)); freeBuffer(text2); return rc; } static Int true_file_name3(USES_REGS1) { Term t = Deref(ARG1), t2 = Deref(ARG2); char *root = NULL; if (IsVarTerm(t)) { Yap_Error(INSTANTIATION_ERROR, t, "argument to true_file_name unbound"); return FALSE; } if (!IsAtomTerm(t)) { Yap_Error(TYPE_ERROR_ATOM, t, "argument to true_file_name"); return FALSE; } if (!IsVarTerm(t2)) { if (!IsAtomTerm(t)) { Yap_Error(TYPE_ERROR_ATOM, t2, "argument to true_file_name"); return FALSE; } root = RepAtom(AtomOfTerm(t2))->StrOfAE; } if (!Yap_findFile(RepAtom(AtomOfTerm(t))->StrOfAE, NULL, root, LOCAL_FileNameBuf, false, YAP_PL, false, false)) return FALSE; return Yap_unify(ARG3, MkAtomTerm(Yap_LookupAtom(LOCAL_FileNameBuf))); } /* Executes $SHELL under Prolog */ /** @pred sh Creates a new shell interaction. */ static Int p_sh(USES_REGS1) { /* sh */ #ifdef HAVE_SYSTEM char *shell; shell = (char *)getenv("SHELL"); if (shell == NULL) shell = "/bin/sh"; if (system(shell) < 0) { #if HAVE_STRERROR Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, TermNil, "%s in sh/0", strerror(errno)); #else Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, TermNil, "in sh/0"); #endif return FALSE; } return TRUE; #else #ifdef MSH register char *shell; shell = "msh -i"; system(shell); return (TRUE); #else Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, "sh not available in this configuration"); return (FALSE); #endif /* MSH */ #endif } /** shell(+Command:text, -Status:integer) is det. Run an external command and wait for its completion. */ static Int p_shell(USES_REGS1) { /* '$shell'(+SystCommand) */ const char *cmd; Term t1 = Deref(ARG1); if (IsAtomTerm(t1)) cmd = RepAtom(AtomOfTerm(t1))->StrOfAE; else if (IsStringTerm(t1)) cmd = StringOfTerm(t1); else return FALSE; #if _MSC_VER || defined(__MINGW32__) { int rval = system(cmd); return rval == 0; } return true; #else #if HAVE_SYSTEM char *shell; register int bourne = FALSE; shell = (char *)getenv("SHELL"); if (!strcmp(shell, "/bin/sh")) bourne = TRUE; if (shell == NIL) bourne = TRUE; /* Yap_CloseStreams(TRUE); */ if (bourne) return system(cmd) == 0; else { int status = -1; int child = fork(); if (child == 0) { /* let the children go */ if (!execl(shell, shell, "-c", cmd, NULL)) { exit(-1); } exit(TRUE); } { /* put the father on wait */ int result = child < 0 || /* vsc:I am not sure this is used, Stevens say wait returns an integer. #if NO_UNION_WAIT */ wait((&status)) != child || /* #else wait ((union wait *) (&status)) != child || #endif */ status == 0; return result; } } #else /* HAVE_SYSTEM */ #ifdef MSH register char *shell; shell = "msh -i"; /* Yap_CloseStreams(); */ system(shell); return TRUE; #else Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, "shell not available in this configuration"); return FALSE; #endif #endif /* HAVE_SYSTEM */ #endif /* _MSC_VER */ } /** system(+Command:text). Run an external command. */ static Int p_system(USES_REGS1) { /* '$system'(+SystCommand) */ const char *cmd; Term t1 = Deref(ARG1); if (IsVarTerm(t1)) { Yap_Error(INSTANTIATION_ERROR, t1, "argument to system/1 unbound"); return FALSE; } else if (IsAtomTerm(t1)) { cmd = RepAtom(AtomOfTerm(t1))->StrOfAE; } else if (IsStringTerm(t1)) { cmd = StringOfTerm(t1); } else { if (!Yap_GetName(LOCAL_FileNameBuf, YAP_FILENAME_MAX, t1)) { Yap_Error(TYPE_ERROR_ATOM, t1, "argument to system/1"); return false; } cmd = LOCAL_FileNameBuf; } /* Yap_CloseStreams(TRUE); */ #if _MSC_VER || defined(__MINGW32__) { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); // Start the child process. if (!CreateProcess(NULL, // No module name (use command line) (LPSTR)cmd, // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi) // Pointer to PROCESS_INFORMATION structure ) { Yap_Error(SYSTEM_ERROR_INTERNAL, ARG1, "CreateProcess failed (%d).\n", GetLastError()); return FALSE; } // Wait until child process exits. WaitForSingleObject(pi.hProcess, INFINITE); // Close process and thread handles. CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return TRUE; } return FALSE; #elif HAVE_SYSTEM #if _MSC_VER _flushall(); #endif if (system(cmd)) { #if HAVE_STRERROR Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, t1, "%s in system(%s)", strerror(errno), cmd); #else Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, t1, "in system(%s)", cmd); #endif return FALSE; } return TRUE; #else #ifdef MSH register char *shell; shell = "msh -i"; /* Yap_CloseStreams(); */ system(shell); return (TRUE); #undef command #else Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, "sh not available in this machine"); return (FALSE); #endif #endif /* HAVE_SYSTEM */ } static Int p_mv(USES_REGS1) { /* rename(+OldName,+NewName) */ #if HAVE_LINK int r; char *oldname, *newname; Term t1 = Deref(ARG1); Term t2 = Deref(ARG2); if (IsVarTerm(t1)) { Yap_Error(INSTANTIATION_ERROR, t1, "first argument to rename/2 unbound"); } else if (!IsAtomTerm(t1)) { Yap_Error(TYPE_ERROR_ATOM, t1, "first argument to rename/2 not atom"); } if (IsVarTerm(t2)) { Yap_Error(INSTANTIATION_ERROR, t2, "second argument to rename/2 unbound"); } else if (!IsAtomTerm(t2)) { Yap_Error(TYPE_ERROR_ATOM, t2, "second argument to rename/2 not atom"); } else { oldname = (RepAtom(AtomOfTerm(t1)))->StrOfAE; newname = (RepAtom(AtomOfTerm(t2)))->StrOfAE; if ((r = link(oldname, newname)) == 0 && (r = unlink(oldname)) != 0) unlink(newname); if (r != 0) { #if HAVE_STRERROR Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, t2, "%s in rename(%s,%s)", strerror(errno), oldname, newname); #else Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, t2, "in rename(%s,%s)", oldname, newname); #endif return false; } return true; } #else Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, "rename/2 not available in this machine"); #endif return false; } #ifdef MAC void Yap_SetTextFile(name) char *name; { #ifdef MACC SetFileType(name, 'TEXT'); SetFileSignature(name, 'EDIT'); #else FInfo f; FInfo *p = &f; GetFInfo(name, 0, p); p->fdType = 'TEXT'; #ifdef MPW if (mpwshell) p->fdCreator = 'MPS\0'; #endif #ifndef LIGHT else p->fdCreator = 'EDIT'; #endif SetFInfo(name, 0, p); #endif } #endif /* return YAP's environment */ static Int p_getenv(USES_REGS1) { #if HAVE_GETENV Term t1 = Deref(ARG1), to; char *s, *so; if (IsVarTerm(t1)) { Yap_Error(INSTANTIATION_ERROR, t1, "first arg of getenv/2"); return (FALSE); } else if (!IsAtomTerm(t1)) { Yap_Error(TYPE_ERROR_ATOM, t1, "first arg of getenv/2"); return (FALSE); } else s = RepAtom(AtomOfTerm(t1))->StrOfAE; if ((so = getenv(s)) == NULL) return (FALSE); to = MkAtomTerm(Yap_LookupAtom(so)); return (Yap_unify_constant(ARG2, to)); #else Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, "getenv not available in this configuration"); return (FALSE); #endif } /* set a variable in YAP's environment */ static Int p_putenv(USES_REGS1) { #if HAVE_PUTENV Term t1 = Deref(ARG1), t2 = Deref(ARG2); char *s, *s2, *p0, *p; if (IsVarTerm(t1)) { Yap_Error(INSTANTIATION_ERROR, t1, "first arg to putenv/2"); return (FALSE); } else if (!IsAtomTerm(t1)) { Yap_Error(TYPE_ERROR_ATOM, t1, "first arg to putenv/2"); return (FALSE); } else s = RepAtom(AtomOfTerm(t1))->StrOfAE; if (IsVarTerm(t2)) { Yap_Error(INSTANTIATION_ERROR, t1, "second arg to putenv/2"); return (FALSE); } else if (!IsAtomTerm(t2)) { Yap_Error(TYPE_ERROR_ATOM, t2, "second arg to putenv/2"); return (FALSE); } else s2 = RepAtom(AtomOfTerm(t2))->StrOfAE; while (!(p0 = p = Yap_AllocAtomSpace(strlen(s) + strlen(s2) + 3))) { if (!Yap_growheap(FALSE, MinHeapGap, NULL)) { Yap_Error(RESOURCE_ERROR_HEAP, TermNil, LOCAL_ErrorMessage); return FALSE; } } while ((*p++ = *s++) != '\0') ; p[-1] = '='; while ((*p++ = *s2++) != '\0') ; if (putenv(p0) == 0) return TRUE; #if HAVE_STRERROR Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, TermNil, "in putenv(%s)", strerror(errno), p0); #else Yap_Error(SYSTEM_ERROR_OPERATING_SYSTEM, TermNil, "in putenv(%s)", p0); #endif return FALSE; #else Yap_Error(SYSTEM_ERROR_INTERNAL, TermNil, "putenv not available in this configuration"); return FALSE; #endif } static Int p_host_type(USES_REGS1) { Term out = MkAtomTerm(Yap_LookupAtom(HOST_ALIAS)); return (Yap_unify(out, ARG1)); } static Int p_yap_home(USES_REGS1) { Term out = MkAtomTerm(Yap_LookupAtom(YAP_ROOTDIR)); return (Yap_unify(out, ARG1)); } static Int p_yap_paths(USES_REGS1) { Term out1, out2, out3; const char *env_destdir = getenv("DESTDIR"); char destdir[YAP_FILENAME_MAX + 1]; if (env_destdir) { strncat(destdir, env_destdir, YAP_FILENAME_MAX); strncat(destdir, "/" YAP_LIBDIR, YAP_FILENAME_MAX); out1 = MkAtomTerm(Yap_LookupAtom(destdir)); } else { out1 = MkAtomTerm(Yap_LookupAtom(YAP_LIBDIR)); } if (env_destdir) { strncat(destdir, env_destdir, YAP_FILENAME_MAX); strncat(destdir, "/" YAP_SHAREDIR, YAP_FILENAME_MAX); out2 = MkAtomTerm(Yap_LookupAtom(destdir)); } else { out2 = MkAtomTerm(Yap_LookupAtom(YAP_SHAREDIR)); } if (env_destdir) { strncat(destdir, env_destdir, YAP_FILENAME_MAX); strncat(destdir, "/" YAP_BINDIR, YAP_FILENAME_MAX); out3 = MkAtomTerm(Yap_LookupAtom(destdir)); } else { out3 = MkAtomTerm(Yap_LookupAtom(YAP_BINDIR)); } return (Yap_unify(out1, ARG1) && Yap_unify(out2, ARG2) && Yap_unify(out3, ARG3)); } static Int p_log_event(USES_REGS1) { Term in = Deref(ARG1); Atom at; if (IsVarTerm(in)) return FALSE; if (!IsAtomTerm(in)) return FALSE; at = AtomOfTerm(in); #if DEBUG if (IsWideAtom(at)) fprintf(stderr, "LOG %S\n", RepAtom(at)->WStrOfAE); else if (IsBlob(at)) return FALSE; else fprintf(stderr, "LOG %s\n", RepAtom(at)->StrOfAE); #endif if (IsWideAtom(at) || IsBlob(at)) return FALSE; LOG(" %s ", RepAtom(at)->StrOfAE); return TRUE; } static Int p_env_separator(USES_REGS1) { #if defined(_WIN32) return Yap_unify(MkIntegerTerm(';'), ARG1); #else return Yap_unify(MkIntegerTerm(':'), ARG1); #endif } /* * This is responsable for the initialization of all machine dependant * predicates */ void Yap_InitSysbits(int wid) { CACHE_REGS #if __simplescalar__ { char *pwd = getenv("PWD"); strncpy(GLOBAL_pwd, pwd, YAP_FILENAME_MAX); } #endif Yap_InitWTime(); Yap_InitRandom(); /* let the caller control signals as it sees fit */ Yap_InitOSSignals(worker_id); } static Int p_unix(USES_REGS1) { #ifdef unix return TRUE; #else #ifdef __unix__ return TRUE; #else #ifdef __APPLE__ return TRUE; #else return FALSE; #endif #endif #endif } static Int p_win32(USES_REGS1) { #ifdef _WIN32 return TRUE; #else #ifdef __CYGWIN__ return TRUE; #else return FALSE; #endif #endif } static Int p_ld_path(USES_REGS1) { return Yap_unify(ARG1, MkAtomTerm(Yap_LookupAtom(YAP_LIBDIR))); } static Int p_address_bits(USES_REGS1) { #if SIZEOF_INT_P == 4 return Yap_unify(ARG1, MkIntTerm(32)); #else return Yap_unify(ARG1, MkIntTerm(64)); #endif } #ifdef _WIN32 /* This code is from SWI-Prolog by Jan Wielemaker */ #define wstreq(s, q) (wcscmp((s), (q)) == 0) static HKEY reg_open_key(const wchar_t *which, int create) { HKEY key = HKEY_CURRENT_USER; DWORD disp; LONG rval; while (*which) { wchar_t buf[256]; wchar_t *s; HKEY tmp; for (s = buf; *which && !(*which == '/' || *which == '\\');) *s++ = *which++; *s = '\0'; if (*which) which++; if (wstreq(buf, L"HKEY_CLASSES_ROOT")) { key = HKEY_CLASSES_ROOT; continue; } else if (wstreq(buf, L"HKEY_CURRENT_USER")) { key = HKEY_CURRENT_USER; continue; } else if (wstreq(buf, L"HKEY_LOCAL_MACHINE")) { key = HKEY_LOCAL_MACHINE; continue; } else if (wstreq(buf, L"HKEY_USERS")) { key = HKEY_USERS; continue; } if (RegOpenKeyExW(key, buf, 0L, KEY_READ, &tmp) == ERROR_SUCCESS) { RegCloseKey(key); key = tmp; continue; } if (!create) return NULL; rval = RegCreateKeyExW(key, buf, 0, L"", 0, KEY_ALL_ACCESS, NULL, &tmp, &disp); RegCloseKey(key); if (rval == ERROR_SUCCESS) key = tmp; else return NULL; } return key; } #define MAXREGSTRLEN 1024 static void recover_space(wchar_t *k, Atom At) { if (At->WStrOfAE != k) Yap_FreeCodeSpace((char *)k); } static wchar_t *WideStringFromAtom(Atom KeyAt USES_REGS) { if (IsWideAtom(KeyAt)) { return KeyAt->WStrOfAE; } else { int len = strlen(KeyAt->StrOfAE); int sz = sizeof(wchar_t) * (len + 1); char *chp = KeyAt->StrOfAE; wchar_t *kptr, *k; k = (wchar_t *)Yap_AllocCodeSpace(sz); while (k == NULL) { if (!Yap_growheap(false, sz, NULL)) { Yap_Error(RESOURCE_ERROR_HEAP, MkIntegerTerm(sz), "generating key in win_registry_get_value/3"); return false; } k = (wchar_t *)Yap_AllocCodeSpace(sz); } kptr = k; while ((*kptr++ = *chp++)) ; return k; } } static Int p_win_registry_get_value(USES_REGS1) { DWORD type; BYTE data[MAXREGSTRLEN]; DWORD len = sizeof(data); wchar_t *k, *name; HKEY key; Term Key = Deref(ARG1); Term Name = Deref(ARG2); Atom KeyAt, NameAt; if (IsVarTerm(Key)) { Yap_Error(INSTANTIATION_ERROR, Key, "argument to win_registry_get_value unbound"); return FALSE; } if (!IsAtomTerm(Key)) { Yap_Error(TYPE_ERROR_ATOM, Key, "argument to win_registry_get_value"); return FALSE; } KeyAt = AtomOfTerm(Key); if (IsVarTerm(Name)) { Yap_Error(INSTANTIATION_ERROR, Key, "argument to win_registry_get_value unbound"); return FALSE; } if (!IsAtomTerm(Name)) { Yap_Error(TYPE_ERROR_ATOM, Key, "argument to win_registry_get_value"); return FALSE; } NameAt = AtomOfTerm(Name); k = WideStringFromAtom(KeyAt PASS_REGS); if (!(key = reg_open_key(k, FALSE))) { Yap_Error(EXISTENCE_ERROR_KEY, Key, "argument to win_registry_get_value"); recover_space(k, KeyAt); return FALSE; } name = WideStringFromAtom(NameAt PASS_REGS); if (RegQueryValueExW(key, name, NULL, &type, data, &len) == ERROR_SUCCESS) { RegCloseKey(key); switch (type) { case REG_SZ: recover_space(k, KeyAt); recover_space(name, NameAt); ((wchar_t *)data)[len] = '\0'; return Yap_unify(MkAtomTerm(Yap_LookupMaybeWideAtom((wchar_t *)data)), ARG3); case REG_DWORD: recover_space(k, KeyAt); recover_space(name, NameAt); { DWORD *d = (DWORD *)data; return Yap_unify(MkIntegerTerm((Int)d[0]), ARG3); } default: recover_space(k, KeyAt); recover_space(name, NameAt); return FALSE; } } recover_space(k, KeyAt); recover_space(name, NameAt); return FALSE; } char *Yap_RegistryGetString(char *name) { DWORD type; BYTE data[MAXREGSTRLEN]; DWORD len = sizeof(data); HKEY key; char *ptr; int i; #if SIZEOF_INT_P == 8 if (!(key = reg_open_key(L"HKEY_LOCAL_MACHINE/SOFTWARE/YAP/Prolog64", FALSE))) { return NULL; } #else if (!(key = reg_open_key(L"HKEY_LOCAL_MACHINE/SOFTWARE/YAP/Prolog", FALSE))) { return NULL; } #endif if (RegQueryValueEx(key, name, NULL, &type, data, &len) == ERROR_SUCCESS) { RegCloseKey(key); switch (type) { case REG_SZ: ptr = malloc(len + 2); if (!ptr) return NULL; for (i = 0; i <= len; i++) ptr[i] = data[i]; ptr[len + 1] = '\0'; return ptr; default: return NULL; } } return NULL; } #endif void Yap_InitSysPreds(void) { Yap_InitCPred("log_event", 1, p_log_event, SafePredFlag | SyncPredFlag); Yap_InitCPred("sh", 0, p_sh, SafePredFlag | SyncPredFlag); Yap_InitCPred("$shell", 1, p_shell, SafePredFlag | SyncPredFlag); Yap_InitCPred("system", 1, p_system, SafePredFlag | SyncPredFlag | UserCPredFlag); Yap_InitCPred("$rename", 2, p_mv, SafePredFlag | SyncPredFlag); Yap_InitCPred("$yap_home", 1, p_yap_home, SafePredFlag); Yap_InitCPred("$yap_paths", 3, p_yap_paths, SafePredFlag); Yap_InitCPred("$dir_separator", 1, p_dir_sp, SafePredFlag); Yap_InitCPred("libraries_directories", 2, libraries_directories, 0); Yap_InitCPred("system_library", 1, system_library, 0); Yap_InitCPred("commons_library", 1, commons_library, 0); Yap_InitCPred("$getenv", 2, p_getenv, SafePredFlag); Yap_InitCPred("$putenv", 2, p_putenv, SafePredFlag | SyncPredFlag); Yap_InitCPred("$host_type", 1, p_host_type, SafePredFlag | SyncPredFlag); Yap_InitCPred("$env_separator", 1, p_env_separator, SafePredFlag); Yap_InitCPred("$unix", 0, p_unix, SafePredFlag); Yap_InitCPred("$win32", 0, p_win32, SafePredFlag); Yap_InitCPred("$ld_path", 1, p_ld_path, SafePredFlag); Yap_InitCPred("$address_bits", 1, p_address_bits, SafePredFlag); Yap_InitCPred("$expand_file_name", 2, p_expand_file_name, SyncPredFlag); Yap_InitCPred("expand_file_name", 3, expand_file_name3, SyncPredFlag); Yap_InitCPred("expand_file_name", 2, expand_file_name, SyncPredFlag); Yap_InitCPred("working_directory", 2, working_directory, SyncPredFlag); Yap_InitCPred("prolog_to_os_filename", 2, prolog_to_os_filename, SyncPredFlag); Yap_InitCPred("absolute_file_system_path", 2, absolute_file_system_path, 0); Yap_InitCPred("real_path", 2, real_path, 0); Yap_InitCPred("true_file_name", 2, true_file_name, SyncPredFlag); Yap_InitCPred("true_file_name", 3, true_file_name3, SyncPredFlag); #ifdef _WIN32 Yap_InitCPred("win_registry_get_value", 3, p_win_registry_get_value, 0); #endif Yap_InitCPred("rmdir", 2, p_rmdir, SyncPredFlag); Yap_InitCPred("make_directory", 1, make_directory, SyncPredFlag); }
25.929038
80
0.609129
[ "object" ]
b789b1178d2ac916bc9ff61cd7019ddbdd9b06e8
255,525
c
C
runtime/src/comm/ofi/comm-ofi.c
prashanth018/chapel
f0189208ea3b7c3ffa684d7fc6cc1941b58d2938
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
runtime/src/comm/ofi/comm-ofi.c
prashanth018/chapel
f0189208ea3b7c3ffa684d7fc6cc1941b58d2938
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
runtime/src/comm/ofi/comm-ofi.c
prashanth018/chapel
f0189208ea3b7c3ffa684d7fc6cc1941b58d2938
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright 2020-2021 Hewlett Packard Enterprise Development LP * Copyright 2004-2019 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is 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. */ // // OFI-based implementation of Chapel communication interface. // #include "chplrt.h" #include "chpl-env-gen.h" #include "chpl-comm.h" #include "chpl-comm-callbacks.h" #include "chpl-comm-callbacks-internal.h" #include "chpl-comm-diags.h" #include "chpl-comm-internal.h" #include "chpl-comm-strd-xfer.h" #include "chpl-env.h" #include "chplexit.h" #include "chpl-format.h" #include "chpl-gen-includes.h" #include "chpl-linefile-support.h" #include "chpl-mem.h" #include "chpl-mem-sys.h" #include "chplsys.h" #include "chpl-tasks.h" #include "chpl-topo.h" #include "chpltypes.h" #include "error.h" #include "comm-ofi-internal.h" // Don't get warning macros for chpl_comm_get etc #include "chpl-comm-no-warning-macros.h" #include <assert.h> #include <errno.h> #include <pthread.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/uio.h> /* for struct iovec */ #include <time.h> #include <unistd.h> #ifdef CHPL_COMM_DEBUG #include <ctype.h> #endif #include <rdma/fabric.h> #include <rdma/fi_atomic.h> #include <rdma/fi_cm.h> #include <rdma/fi_domain.h> #include <rdma/fi_endpoint.h> #include <rdma/fi_errno.h> #include <rdma/fi_rma.h> //////////////////////////////////////// // // Data global to all comm-ofi*.c files // // // These are declared extern in comm-ofi-internal.h. // #ifdef CHPL_COMM_DEBUG uint64_t chpl_comm_ofi_dbg_level; FILE* chpl_comm_ofi_dbg_file; #endif int chpl_comm_ofi_abort_on_error; //////////////////////////////////////// // // Libfabric API version // // // This is used to check that the libfabric version the runtime is // linked with in a user program is the same one it was compiled // against. // #define COMM_OFI_FI_VERSION FI_VERSION(FI_MAJOR_VERSION, FI_MINOR_VERSION) //////////////////////////////////////// // // Types and data global just within this file. // static struct fi_info* ofi_info; // fabric interface info static struct fid_fabric* ofi_fabric; // fabric domain static struct fid_domain* ofi_domain; // fabric access domain static struct fid_ep* ofi_txEpScal; // scalable transmit endpoint static struct fid_poll* ofi_amhPollSet; // poll set for AM handler static int pollSetSize = 0; // number of fids in the poll set static struct fid_wait* ofi_amhWaitSet; // wait set for AM handler // // We direct RMA traffic and AM traffic to different endpoints so we can // spread the progress load across all the threads when we're doing // manual progress. // static struct fid_ep* ofi_rxEp; // receive endpoint static struct fid_cq* ofi_rxCQ; // receive endpoint CQ static struct fid_av* ofi_av; // address vector static fi_addr_t* ofi_rxAddrs; // table of remote endpoint addresses #define rxAddr(n) (ofi_rxAddrs[n]) // // Transmit support. // static chpl_bool envPreferScalableTxEp; // env: prefer scalable tx endpoint? static int envCommConcurrency; // env: communication concurrency static ssize_t envMaxHeapSize; // env: max heap size static chpl_bool envOversubscribed; // env over-subscribed? static int numTxCtxs; static int numRxCtxs; struct perTxCtxInfo_t { atomic_bool allocated; // true: in use; false: available chpl_bool bound; // true: bound to an owner (usually a thread) struct fid_ep* txCtx; // transmit context (endpoint, if not scalable) struct fid_cq* txCQ; // completion CQ struct fid_cntr* txCntr; // completion counter (AM handler tx ctx only) struct fid* txCmplFid; // CQ or counter fid // fn: check for tx completions void (*checkTxCmplsFn)(struct perTxCtxInfo_t*); // fn: ensure progress void (*ensureProgressFn)(struct perTxCtxInfo_t*); uint64_t numTxnsOut; // number of transactions in flight now // (and for which we expect CQ events) uint64_t numTxnsSent; // number of transactions ever initiated void* putVisBitmap; // nodes needing forced RMA store visibility void* amoVisBitmap; // nodes needing forced AMO store visibility }; static int tciTabLen; static struct perTxCtxInfo_t* tciTab; static chpl_bool tciTabBindTxCtxs; static size_t txCQLen; // // Memory registration support. // static chpl_bool scalableMemReg; struct memEntry { void* addr; uint64_t base; size_t size; void* desc; uint64_t key; }; #define MAX_MEM_REGIONS 10 typedef struct memEntry (memTab_t)[MAX_MEM_REGIONS]; static memTab_t memTab; static int memTabSize = sizeof(memTab) / sizeof(struct memEntry); static int memTabCount = 0; static memTab_t* memTabMap; static struct fid_mr* ofiMrTab[MAX_MEM_REGIONS]; // // Messaging (AM) support. // #define AM_MAX_EXEC_ON_PAYLOAD_SIZE 1024 struct amRequest_execOn_t { chpl_comm_on_bundle_t hdr; char space[AM_MAX_EXEC_ON_PAYLOAD_SIZE]; }; struct amRequest_execOnLrg_t { chpl_comm_on_bundle_t hdr; void* pPayload; // addr of arg payload on initiator node }; static int numAmHandlers = 1; // // AM request landing zones. // static void* amLZs[2]; static struct iovec ofi_iov_reqs[2]; static struct fi_msg ofi_msg_reqs[2]; static int ofi_msg_i; // // These are the major modes in which we can operate in order to // achieve Chapel MCM conformance. // // To conform to the Chapel MCM we need the following within each task: // - Atomics have to be seen to occur strictly in program order. // - A PUT followed by a GET from the same address must return the PUT // data. // - When a write (AMO or RMA) is following by a tasking construct or an // on-stmt, the written data must be visible to the statement body. // // With libfabric we can meet these requirements using one of a few // different combinations of message ordering settings or, as a last // resort because it performs poorly, the delivery-complete completion // level. Most of the ordering issues have to do with visibility for // the effects of writes, since libfabric's default completion level // for reads (AMO or RMA) guarantees that the retrieved data is stored // before the completion is delivered. When using message orderings we // use fenced operations and/or non-programmatic reads to ensure write // visibility when needed. Such non-programmatic reads may be done // immediately after the writes they to which they apply or may be // delayed until just before the next operation that could depend on // the write visibility. The latter is preferred for performance but // can only be done if the task has a bound transmit context, because // libfabric message ordering applies only to operations on a given // endpoint (or context) pair. Additional commentary throughout the // code has more details where needed. // enum mcmMode_t { mcmm_undef, mcmm_msgOrdFence, // ATOMIC_{RAW,WAR,WAW}, SAS, fences mcmm_msgOrd, // RAW, WAW, SAW, SAS mcmm_dlvrCmplt, // delivery-complete }; static enum mcmMode_t mcmMode; // overall operational mode static const char* mcmModeNames[] = { "undefined", "message-order-fence", "message-order", "delivery-complete", }; //////////////////////////////////////// // // Forward decls // static struct perTxCtxInfo_t* tciAlloc(void); static struct perTxCtxInfo_t* tciAllocForAmHandler(void); static chpl_bool tciAllocTabEntry(struct perTxCtxInfo_t*); static void tciFree(struct perTxCtxInfo_t*); static void waitForCQSpace(struct perTxCtxInfo_t*, size_t); static chpl_comm_nb_handle_t ofi_put(const void*, c_nodeid_t, void*, size_t); static void ofi_put_lowLevel(const void*, void*, c_nodeid_t, uint64_t, uint64_t, size_t, void*, uint64_t, struct perTxCtxInfo_t*); static void do_remote_put_buff(void*, c_nodeid_t, void*, size_t); static chpl_comm_nb_handle_t ofi_get(void*, c_nodeid_t, void*, size_t); static void ofi_get_lowLevel(void*, void*, c_nodeid_t, uint64_t, uint64_t, size_t, void*, uint64_t, struct perTxCtxInfo_t*); static void do_remote_get_buff(void*, c_nodeid_t, void*, size_t); static void do_remote_amo_nf_buff(void*, c_nodeid_t, void*, size_t, enum fi_op, enum fi_datatype); static void amEnsureProgress(struct perTxCtxInfo_t*); static void amCheckRxTxCmpls(chpl_bool*, chpl_bool*, struct perTxCtxInfo_t*); static void checkTxCmplsCQ(struct perTxCtxInfo_t*); static void checkTxCmplsCntr(struct perTxCtxInfo_t*); static size_t readCQ(struct fid_cq*, void*, size_t); static void reportCQError(struct fid_cq*); static void waitForTxnComplete(struct perTxCtxInfo_t*, void* ctx); static void forceMemFxVisOneNode(c_nodeid_t, chpl_bool, chpl_bool, struct perTxCtxInfo_t*); static void forceMemFxVisAllNodes(chpl_bool, chpl_bool, c_nodeid_t, struct perTxCtxInfo_t*); static void forceMemFxVisAllNodes_noTcip(chpl_bool, chpl_bool); static void* allocBounceBuf(size_t); static void freeBounceBuf(void*); static void local_yield(void); static void time_init(void); #ifdef CHPL_COMM_DEBUG static void dbg_catfile(const char*, const char*); #endif //////////////////////////////////////// // // Alignment // #define ALIGN_DN(i, size) ((i) & ~((size) - 1)) #define ALIGN_UP(i, size) ALIGN_DN((i) + (size) - 1, size) //////////////////////////////////////// // // Error checking // static void ofiErrReport(const char*, int, const char*); #define OFI_ERR(exprStr, retVal, errStr) \ do { \ ofiErrReport(exprStr, retVal, errStr); /* may not return */ \ INTERNAL_ERROR_V("OFI error: %s: %s", exprStr, errStr); \ } while (0) #define OFI_CHK(expr) OFI_CHK_1(expr, FI_SUCCESS) #define OFI_CHK_1(expr, want1) \ do { \ int retVal = (expr); \ if (retVal != want1) { \ OFI_ERR(#expr, retVal, fi_strerror(-retVal)); \ } \ } while (0) #define OFI_CHK_2(expr, retVal, want2) \ do { \ retVal = (expr); \ if (retVal != FI_SUCCESS && retVal != want2) { \ OFI_ERR(#expr, retVal, fi_strerror(-retVal)); \ } \ } while (0) #define OFI_CHK_3(expr, retVal, want2, want3) \ do { \ retVal = (expr); \ if (retVal != FI_SUCCESS && retVal != want2 && retVal != want3) { \ OFI_ERR(#expr, retVal, fi_strerror(-retVal)); \ } \ } while (0) #define OFI_CHK_COUNT(expr, retVal) \ do { \ retVal = (expr); \ if (retVal < 0) { \ OFI_ERR(#expr, retVal, fi_strerror(-retVal)); \ } \ } while (0) #define PTHREAD_CHK(expr) CHK_EQ_TYPED(expr, 0, int, "d") //////////////////////////////////////// // // Early declarations for AM handling and progress // // // Ideally these would be declared with related stuff later in the // file, but they're needed earlier than that and with each other, // so they're here instead. // // // Is this the (an) AM handler thread? // static __thread chpl_bool isAmHandler = false; // // Flag used to tell AM handler(s) to exit. // static atomic_bool amHandlersExit; // // Should the AM handler do liveness checks? // static chpl_bool amDoLivenessChecks = false; // // The ofi_rxm provider may return -FI_EAGAIN for read/write/send while // doing on-demand connection when emulating FI_RDM endpoints. The man // page says: "Applications should be aware of this and retry until the // the operation succeeds." Handle this in a generalized way, because // it seems like something we might encounter with other providers as // well. // #define OFI_RIDE_OUT_EAGAIN(tcip, expr) \ do { \ ssize_t _ret; \ if (isAmHandler) { \ do { \ OFI_CHK_2(expr, _ret, -FI_EAGAIN); \ if (_ret == -FI_EAGAIN) { \ (*tcip->ensureProgressFn)(tcip); \ } \ } while (_ret == -FI_EAGAIN \ && !atomic_load_bool(&amHandlersExit)); \ } else { \ do { \ OFI_CHK_2(expr, _ret, -FI_EAGAIN); \ if (_ret == -FI_EAGAIN) { \ (*tcip->ensureProgressFn)(tcip); \ } \ } while (_ret == -FI_EAGAIN); \ } \ } while (0) //////////////////////////////////////// // // Providers // // // provider name in environment // static const char* ofi_provNameEnv = "FI_PROVIDER"; static pthread_once_t provNameOnce = PTHREAD_ONCE_INIT; static const char* provName; static void setProvName(void) { provName = getenv(ofi_provNameEnv); } static const char* getProviderName(void) { PTHREAD_CHK(pthread_once(&provNameOnce, setProvName)); return provName; } // // provider name parsing // static inline chpl_bool isInProvName(const char* s, const char* prov_name) { if (prov_name == NULL) { return false; } char pn[strlen(prov_name) + 1]; strcpy(pn, prov_name); char* tok; char* strSave; for (char* pnPtr = pn; (tok = strtok_r(pnPtr, ";", &strSave)) != NULL; pnPtr = NULL) { if (strcmp(s, tok) == 0) { return true; } } return false; } // // provider type // typedef enum { provType_efa, provType_gni, provType_verbs, provType_rxd, provType_rxm, provType_tcp, provTypeCount } provider_t; // // provider sets // typedef chpl_bool providerSet_t[provTypeCount]; static inline void providerSetSet(providerSet_t* s, provider_t p) { CHK_TRUE(p >= 0 && p < provTypeCount); (*s)[p] = 1; } static inline int providerSetTest(providerSet_t* s, provider_t p) { CHK_TRUE(p >= 0 && p < provTypeCount); return (*s)[p] != 0; } // // providers in use // static pthread_once_t providerInUseOnce = PTHREAD_ONCE_INIT; static providerSet_t providerInUseSet; static void init_providerInUse(void) { if (chpl_numNodes <= 1) { return; } // // We can be using only one primary provider. // const char* pn = ofi_info->fabric_attr->prov_name; if (isInProvName("efa", pn)) { providerSetSet(&providerInUseSet, provType_efa); } else if (isInProvName("gni", pn)) { providerSetSet(&providerInUseSet, provType_gni); } else if (isInProvName("tcp", pn)) { providerSetSet(&providerInUseSet, provType_tcp); } else if (isInProvName("verbs", pn)) { providerSetSet(&providerInUseSet, provType_verbs); } // // We can be using any number of utility providers. // if (isInProvName("ofi_rxd", pn)) { providerSetSet(&providerInUseSet, provType_rxd); } if (isInProvName("ofi_rxm", pn)) { providerSetSet(&providerInUseSet, provType_rxm); } } static chpl_bool providerInUse(provider_t p) { if (ofi_info != NULL) { // Early exit hedge: don't init "in use" info until we have one. PTHREAD_CHK(pthread_once(&providerInUseOnce, init_providerInUse)); } return providerSetTest(&providerInUseSet, p); } // // provider-specific behavior control // static chpl_bool provCtl_sizeAvsByNumEps; // size AVs by numEPs (RxD) static chpl_bool provCtl_readAmoNeedsOpnd; // READ AMO needs operand (RxD) //////////////////////////////////////// // // transaction tracking // // // If we need to wait for an individual transaction's network completion // we give the address of a 'txnDone' flag as the context pointer when we // initiate the transaction, and then just wait for the flag to become // true. We encode this information in the context pointer we pass to // libfabric, and then it hands it back to us in the CQ entry, and then // checkTxCQ() uses that to figure out what to update. // typedef enum { txnTrkId, // no tracking as such, context "ptr" is just an id value txnTrkDone, // *ptr is atomic bool 'done' flag txnTrkTypeCount } txnTrkType_t; #define TXNTRK_TYPE_BITS 1 #define TXNTRK_ADDR_BITS (64 - TXNTRK_TYPE_BITS) #define TXNTRK_TYPE_MASK ((1UL << TXNTRK_TYPE_BITS) - 1UL) #define TXNTRK_ADDR_MASK (~(TXNTRK_TYPE_MASK << TXNTRK_ADDR_BITS)) typedef struct { txnTrkType_t typ; void* ptr; } txnTrkCtx_t; static inline void* txnTrkEncode(txnTrkType_t typ, void* p) { assert((((uint64_t) txnTrkTypeCount - 1UL) & ~TXNTRK_TYPE_MASK) == 0UL); assert((((uint64_t) p) & ~TXNTRK_ADDR_MASK) == 0UL); return (void*) ( ((uint64_t) typ << TXNTRK_ADDR_BITS) | ((uint64_t) p & TXNTRK_ADDR_MASK)); } static inline void* txnTrkEncodeId(intptr_t id) { return txnTrkEncode(txnTrkId, (void*) id); } static inline void* txnTrkEncodeDone(void* pDone) { return txnTrkEncode(txnTrkDone, pDone); } static inline txnTrkCtx_t txnTrkDecode(void* ctx) { const uint64_t u = (uint64_t) ctx; return (txnTrkCtx_t) { .typ = (u >> TXNTRK_ADDR_BITS) & TXNTRK_TYPE_MASK, .ptr = (void*) (u & TXNTRK_ADDR_MASK) }; } //////////////////////////////////////// // // transaction ordering // // // This is a little dummy memory buffer used when we need to do a // remote GET or PUT to enforce ordering. Its contents must _not_ // by considered meaningful, because it can be written to at any // time by any remote node. // static uint32_t* orderDummy; static void* orderDummyMRDesc; struct orderDummyMap_t { uint64_t mrRaddr; uint64_t mrKey; }; static struct orderDummyMap_t* orderDummyMap; //////////////////////////////////////// // // bitmaps // #define bitmapElemWidth 64 #define __bitmapBaseType_t(w) uint##w##_t #define _bitmapBaseType_t(w) __bitmapBaseType_t(w) #define bitmapBaseType_t _bitmapBaseType_t(bitmapElemWidth) struct bitmap_t { size_t len; bitmapBaseType_t map[0]; }; static inline size_t bitmapElemIdx(size_t i) { return i / bitmapElemWidth; } static inline size_t bitmapOff(size_t i) { return i % bitmapElemWidth; } static inline size_t bitmapNumElems(size_t len) { return (((ssize_t) len) - 1) / bitmapElemWidth + 1; } static inline size_t bitmapSizeofMap(size_t len) { return bitmapNumElems(len) * sizeof(bitmapBaseType_t); } static inline size_t bitmapSizeof(size_t len) { return offsetof(struct bitmap_t, map) + bitmapSizeofMap(len); } static inline void bitmapZero(struct bitmap_t* b) { memset(&b->map, 0, bitmapSizeofMap(b->len)); } static inline bitmapBaseType_t bitmapElemBit(size_t i) { return ((bitmapBaseType_t) 1) << bitmapOff(i); } static inline void bitmapClear(struct bitmap_t* b, size_t i) { b->map[bitmapElemIdx(i)] &= ~bitmapElemBit(i); } static inline void bitmapSet(struct bitmap_t* b, size_t i) { b->map[bitmapElemIdx(i)] |= bitmapElemBit(i); } static inline int bitmapTest(struct bitmap_t* b, size_t i) { return (b->map[bitmapElemIdx(i)] & bitmapElemBit(i)) != 0; } #define BITMAP_FOREACH_SET(b, i) \ do { \ size_t _eWid = bitmapElemWidth; \ size_t _eCnt = bitmapNumElems((b)->len); \ size_t _bCnt = (b)->len; \ for (size_t _ei = 0; _ei < _eCnt; _ei++, _bCnt -= _eWid) { \ if ((b)->map[_ei] != 0) { \ size_t _bi_end = (_eWid < _bCnt) ? _eWid : _bCnt; \ for (size_t _bi = 0; _bi < _bi_end; _bi++) { \ if (((b)->map[_ei] & bitmapElemBit(_bi)) != 0) { \ size_t i = _ei * bitmapElemWidth + _bi; #define BITMAP_FOREACH_SET_OR(b1, b2, i) \ do { \ size_t _eWid = bitmapElemWidth; \ size_t _eCnt = bitmapNumElems((b1)->len); \ size_t _bCnt = (b1)->len; \ for (size_t _ei = 0; _ei < _eCnt; _ei++, _bCnt -= _eWid) { \ bitmapBaseType_t _m = (b1)->map[_ei] | (b2)->map[_ei]; \ if (_m != 0) { \ size_t _bi_end = (_eWid < _bCnt) ? _eWid : _bCnt; \ for (size_t _bi = 0; _bi < _bi_end; _bi++) { \ if ((_m & bitmapElemBit(_bi)) != 0) { \ size_t i = _ei * bitmapElemWidth + _bi; #define BITMAP_FOREACH_SET_END } } } } } while (0); static inline struct bitmap_t* bitmapAlloc(size_t len) { struct bitmap_t* b; CHPL_CALLOC_SZ(b, 1, bitmapSizeof(len)); b->len = len; return b; } //////////////////////////////////////// // // task private data // static inline chpl_comm_taskPrvData_t* get_comm_taskPrvdata(void) { chpl_task_infoRuntime_t* infoRuntime; if ((infoRuntime = chpl_task_getInfoRuntime()) != NULL) { return &infoRuntime->comm_data; } if (isAmHandler) { static __thread chpl_comm_taskPrvData_t amHandlerCommData; return &amHandlerCommData; } return NULL; } //////////////////////////////////////// // // task local buffering // // Largest size to use unordered transactions for #define MAX_UNORDERED_TRANS_SZ 1024 // // Maximum number of PUTs/AMOs in a chained transaction list. This // is a provisional value, not yet tuned. // #define MAX_TXNS_IN_FLIGHT 64 #define MAX_CHAINED_AMO_NF_LEN MAX_TXNS_IN_FLIGHT #define MAX_CHAINED_PUT_LEN MAX_TXNS_IN_FLIGHT #define MAX_CHAINED_GET_LEN MAX_TXNS_IN_FLIGHT enum BuffType { amo_nf_buff = 1 << 0, get_buff = 1 << 1, put_buff = 1 << 2 }; // Per task information about non-fetching AMO buffers typedef struct { chpl_bool new; int vi; uint64_t opnd_v[MAX_CHAINED_AMO_NF_LEN]; c_nodeid_t locale_v[MAX_CHAINED_AMO_NF_LEN]; void* object_v[MAX_CHAINED_AMO_NF_LEN]; size_t size_v[MAX_CHAINED_AMO_NF_LEN]; enum fi_op cmd_v[MAX_CHAINED_AMO_NF_LEN]; enum fi_datatype type_v[MAX_CHAINED_AMO_NF_LEN]; uint64_t remote_mr_v[MAX_CHAINED_AMO_NF_LEN]; void* local_mr; } amo_nf_buff_task_info_t; // Per task information about GET buffers typedef struct { chpl_bool new; int vi; void* tgt_addr_v[MAX_CHAINED_GET_LEN]; c_nodeid_t locale_v[MAX_CHAINED_GET_LEN]; uint64_t remote_mr_v[MAX_CHAINED_GET_LEN]; void* src_addr_v[MAX_CHAINED_GET_LEN]; size_t size_v[MAX_CHAINED_GET_LEN]; void* local_mr_v[MAX_CHAINED_GET_LEN]; } get_buff_task_info_t; // Per task information about PUT buffers typedef struct { chpl_bool new; int vi; void* tgt_addr_v[MAX_CHAINED_PUT_LEN]; c_nodeid_t locale_v[MAX_CHAINED_PUT_LEN]; void* src_addr_v[MAX_CHAINED_PUT_LEN]; char src_v[MAX_CHAINED_PUT_LEN][MAX_UNORDERED_TRANS_SZ]; size_t size_v[MAX_CHAINED_PUT_LEN]; uint64_t remote_mr_v[MAX_CHAINED_PUT_LEN]; void* local_mr_v[MAX_CHAINED_PUT_LEN]; } put_buff_task_info_t; // Acquire a task local buffer, initializing if needed static inline void* task_local_buff_acquire(enum BuffType t) { chpl_comm_taskPrvData_t* prvData = get_comm_taskPrvdata(); if (prvData == NULL) return NULL; #define DEFINE_INIT(TYPE, TLS_NAME) \ if (t == TLS_NAME) { \ TYPE* info = prvData->TLS_NAME; \ if (info == NULL) { \ CHPL_CALLOC_SZ(prvData->TLS_NAME, 1, sizeof(TYPE)); \ info = prvData->TLS_NAME; \ info->new = true; \ info->vi = 0; \ } \ return info; \ } DEFINE_INIT(amo_nf_buff_task_info_t, amo_nf_buff); DEFINE_INIT(get_buff_task_info_t, get_buff); DEFINE_INIT(put_buff_task_info_t, put_buff); #undef DEFINE_INIT return NULL; } static void amo_nf_buff_task_info_flush(amo_nf_buff_task_info_t* info); static void get_buff_task_info_flush(get_buff_task_info_t* info); static void put_buff_task_info_flush(put_buff_task_info_t* info); // Flush one or more task local buffers static inline void task_local_buff_flush(enum BuffType t) { chpl_comm_taskPrvData_t* prvData = get_comm_taskPrvdata(); if (prvData == NULL) return; #define DEFINE_FLUSH(TYPE, TLS_NAME, FLUSH_NAME) \ if (t & TLS_NAME) { \ TYPE* info = prvData->TLS_NAME; \ if (info != NULL && info->vi > 0) { \ FLUSH_NAME(info); \ } \ } DEFINE_FLUSH(amo_nf_buff_task_info_t, amo_nf_buff, amo_nf_buff_task_info_flush); DEFINE_FLUSH(get_buff_task_info_t, get_buff, get_buff_task_info_flush); DEFINE_FLUSH(put_buff_task_info_t, put_buff, put_buff_task_info_flush); #undef DEFINE_FLUSH } // Flush and destroy one or more task local buffers static inline void task_local_buff_end(enum BuffType t) { chpl_comm_taskPrvData_t* prvData = get_comm_taskPrvdata(); if (prvData == NULL) return; #define DEFINE_END(TYPE, TLS_NAME, FLUSH_NAME) \ if (t & TLS_NAME) { \ TYPE* info = prvData->TLS_NAME; \ if (info != NULL && info->vi > 0) { \ FLUSH_NAME(info); \ chpl_mem_free(info, 0, 0); \ prvData->TLS_NAME = NULL; \ } \ } DEFINE_END(amo_nf_buff_task_info_t, amo_nf_buff, amo_nf_buff_task_info_flush); DEFINE_END(get_buff_task_info_t, get_buff, get_buff_task_info_flush); DEFINE_END(put_buff_task_info_t, put_buff, put_buff_task_info_flush); #undef END } //////////////////////////////////////// // // Interface: initialization // pthread_t pthread_that_inited; static void init_ofi(void); static void init_ofiFabricDomain(void); static void init_ofiDoProviderChecks(void); static void init_ofiEp(void); static void init_ofiEpTxCtx(int, chpl_bool, struct fi_cq_attr*, struct fi_cntr_attr*); static void init_ofiExchangeAvInfo(void); static void init_ofiForMem(void); static void init_ofiForRma(void); static void init_ofiForAms(void); static void init_ofiConnections(void); static void init_bar(void); static void init_broadcast_private(void); // // forward decls // static chpl_bool mrGetKey(uint64_t*, uint64_t*, int, void*, size_t); static chpl_bool mrGetLocalKey(void*, size_t); static chpl_bool mrGetDesc(void**, void*, size_t); void chpl_comm_init(int *argc_p, char ***argv_p) { chpl_comm_ofi_abort_on_error = (chpl_env_rt_get("COMM_OFI_ABORT_ON_ERROR", NULL) != NULL); time_init(); chpl_comm_ofi_oob_init(); DBG_INIT(); // // Gather run-invariant environment info as early as possible. // envPreferScalableTxEp = chpl_env_rt_get_bool("COMM_OFI_PREFER_SCALABLE_EP", true); envCommConcurrency = chpl_env_rt_get_int("COMM_CONCURRENCY", 0); if (envCommConcurrency < 0) { chpl_warning("CHPL_RT_COMM_CONCURRENCY < 0, ignored", 0, 0); envCommConcurrency = 0; } envMaxHeapSize = chpl_comm_getenvMaxHeapSize(); envOversubscribed = chpl_env_rt_get_bool("OVERSUBSCRIBED", false); // // The user can specify the provider by setting either the Chapel // CHPL_RT_COMM_OFI_PROVIDER environment variable or the libfabric // FI_PROVIDER one, with the former overriding the latter if both // are set. // { const char* s = chpl_env_rt_get("COMM_OFI_PROVIDER", NULL); if (s != NULL) { chpl_env_set(ofi_provNameEnv, s, 1 /*overwrite*/); } } pthread_that_inited = pthread_self(); } void chpl_comm_post_mem_init(void) { DBG_PRINTF(DBG_IFACE_SETUP, "%s()", __func__); chpl_comm_init_prv_bcast_tab(); init_broadcast_private(); } // // No support for gdb for now // int chpl_comm_run_in_gdb(int argc, char* argv[], int gdbArgnum, int* status) { return 0; } // // No support for lldb for now // int chpl_comm_run_in_lldb(int argc, char* argv[], int lldbArgnum, int* status) { return 0; } void chpl_comm_post_task_init(void) { DBG_PRINTF(DBG_IFACE_SETUP, "%s()", __func__); if (chpl_numNodes == 1) return; init_ofi(); init_bar(); } static void init_ofi(void) { init_ofiFabricDomain(); init_ofiDoProviderChecks(); init_ofiEp(); init_ofiExchangeAvInfo(); init_ofiForMem(); init_ofiForRma(); init_ofiForAms(); CHPL_CALLOC(orderDummy, 1); CHK_TRUE(mrGetDesc(&orderDummyMRDesc, orderDummy, sizeof(*orderDummy))); CHPL_CALLOC(orderDummyMap, chpl_numNodes); struct orderDummyMap_t odm; CHK_TRUE(mrGetKey(&odm.mrKey, &odm.mrRaddr, chpl_nodeID, orderDummy, sizeof(*orderDummy))); chpl_comm_ofi_oob_allgather(&odm, orderDummyMap, sizeof(orderDummyMap[0])); init_ofiConnections(); DBG_PRINTF(DBG_CFG, "AM config: recv buf size %zd MiB, %s, responses use %s", ofi_iov_reqs[ofi_msg_i].iov_len / (1L << 20), (ofi_amhPollSet == NULL) ? "explicit polling" : "poll+wait sets", (tciTab[tciTabLen - 1].txCQ != NULL) ? "CQ" : "counter"); if (ofi_txEpScal != NULL) { DBG_PRINTF(DBG_CFG, "per node config: 1 scalable tx ep + %d tx ctx%s (%d bound), " "%d rx ctx%s", numTxCtxs, (numTxCtxs == 1) ? "" : "s", tciTabBindTxCtxs ? chpl_task_getFixedNumThreads() : 0, numRxCtxs, (numRxCtxs == 1) ? "" : "s"); } else { DBG_PRINTF(DBG_CFG, "per node config: %d regular tx ep+ctx%s (%d bound), " "%d rx ctx%s", numTxCtxs, (numTxCtxs == 1) ? "" : "s", tciTabBindTxCtxs ? chpl_task_getFixedNumThreads() : 0, numRxCtxs, (numRxCtxs == 1) ? "" : "s"); } } #ifdef CHPL_COMM_DEBUG struct cfgHint { const char* str; unsigned long int val; }; static chpl_bool getCfgHint(const char* evName, struct cfgHint hintVals[], chpl_bool justOne, uint64_t* pVal) { const char* ev = chpl_env_rt_get(evName, ""); if (strcmp(ev, "") == 0) { return false; } *pVal = 0; char evCopy[strlen(ev) + 1]; strcpy(evCopy, ev); char* p = strtok(evCopy, "|"); while (p != NULL) { int i; for (i = 0; hintVals[i].str != NULL; i++) { if (strcmp(p, hintVals[i].str) == 0) { *pVal |= hintVals[i].val; break; } } if (hintVals[i].str == NULL) { INTERNAL_ERROR_V("unknown config hint val in CHPL_RT_%s: \"%s\"", evName, p); } p = strtok(NULL, "|"); if (justOne && p != NULL) { INTERNAL_ERROR_V("too many config hint vals in CHPL_RT_%s=\"%s\"", evName, ev); } } return true; } static void debugOverrideHints(struct fi_info* hints) { #define CFG_HINT(s) { #s, (uint64_t) (s) } #define CFG_HINT_NULL { NULL, 0ULL } uint64_t val; { struct cfgHint hintVals[] = { CFG_HINT(FI_ATOMIC), CFG_HINT(FI_DIRECTED_RECV), CFG_HINT(FI_FENCE), CFG_HINT(FI_HMEM), CFG_HINT(FI_LOCAL_COMM), CFG_HINT(FI_MSG), CFG_HINT(FI_MULTICAST), CFG_HINT(FI_MULTI_RECV), CFG_HINT(FI_NAMED_RX_CTX), CFG_HINT(FI_READ), CFG_HINT(FI_RECV), CFG_HINT(FI_REMOTE_COMM), CFG_HINT(FI_REMOTE_READ), CFG_HINT(FI_REMOTE_WRITE), CFG_HINT(FI_RMA), CFG_HINT(FI_RMA_EVENT), CFG_HINT(FI_RMA_PMEM), CFG_HINT(FI_SEND), CFG_HINT(FI_SHARED_AV), CFG_HINT(FI_SOURCE), CFG_HINT(FI_SOURCE_ERR), CFG_HINT(FI_TAGGED), CFG_HINT(FI_TRIGGER), CFG_HINT(FI_VARIABLE_MSG), CFG_HINT(FI_WRITE), }; if (getCfgHint("COMM_OFI_HINTS_CAPS", hintVals, false /*justOne*/, &val)) { hints->caps = val; } } { struct cfgHint hintVals[] = { CFG_HINT(FI_COMMIT_COMPLETE), CFG_HINT(FI_COMPLETION), CFG_HINT(FI_DELIVERY_COMPLETE), CFG_HINT(FI_INJECT), CFG_HINT(FI_INJECT_COMPLETE), CFG_HINT(FI_TRANSMIT_COMPLETE), CFG_HINT_NULL, }; if (getCfgHint("COMM_OFI_HINTS_TX_OP_FLAGS", hintVals, false /*justOne*/, &val)) { hints->tx_attr->op_flags = val; } } { struct cfgHint hintVals[] = { CFG_HINT(FI_ORDER_ATOMIC_RAR), CFG_HINT(FI_ORDER_ATOMIC_RAW), CFG_HINT(FI_ORDER_ATOMIC_WAR), CFG_HINT(FI_ORDER_ATOMIC_WAW), CFG_HINT(FI_ORDER_NONE), CFG_HINT(FI_ORDER_RAR), CFG_HINT(FI_ORDER_RAS), CFG_HINT(FI_ORDER_RAW), CFG_HINT(FI_ORDER_RMA_RAR), CFG_HINT(FI_ORDER_RMA_RAW), CFG_HINT(FI_ORDER_RMA_WAR), CFG_HINT(FI_ORDER_RMA_WAW), CFG_HINT(FI_ORDER_SAR), CFG_HINT(FI_ORDER_SAS), CFG_HINT(FI_ORDER_SAW), CFG_HINT(FI_ORDER_WAR), CFG_HINT(FI_ORDER_WAS), CFG_HINT(FI_ORDER_WAW), CFG_HINT_NULL, }; if (getCfgHint("COMM_OFI_HINTS_MSG_ORDER", hintVals, false /*justOne*/, &val)) { hints->tx_attr->msg_order = hints->rx_attr->msg_order = val; } } { struct cfgHint hintVals[] = { CFG_HINT(FI_COMMIT_COMPLETE), CFG_HINT(FI_COMPLETION), CFG_HINT(FI_DELIVERY_COMPLETE), CFG_HINT(FI_MULTI_RECV), CFG_HINT_NULL, }; if (getCfgHint("COMM_OFI_HINTS_RX_OP_FLAGS", hintVals, false /*justOne*/, &val)) { hints->rx_attr->op_flags = val; } } { struct cfgHint hintVals[] = { CFG_HINT(FI_PROGRESS_UNSPEC), CFG_HINT(FI_PROGRESS_AUTO), CFG_HINT(FI_PROGRESS_MANUAL), CFG_HINT_NULL, }; if (getCfgHint("COMM_OFI_HINTS_CONTROL_PROGRESS", hintVals, true /*justOne*/, &val)) { hints->domain_attr->control_progress = (enum fi_progress) val; } if (getCfgHint("COMM_OFI_HINTS_DATA_PROGRESS", hintVals, true /*justOne*/, &val)) { hints->domain_attr->data_progress = (enum fi_progress) val; } } { struct cfgHint hintVals[] = { CFG_HINT(FI_THREAD_UNSPEC), CFG_HINT(FI_THREAD_SAFE), CFG_HINT(FI_THREAD_FID), CFG_HINT(FI_THREAD_DOMAIN), CFG_HINT(FI_THREAD_COMPLETION), CFG_HINT(FI_THREAD_ENDPOINT), CFG_HINT_NULL, }; if (getCfgHint("COMM_OFI_HINTS_THREADING", hintVals, true /*justOne*/, &val)) { hints->domain_attr->threading = (enum fi_threading) val; } } { struct cfgHint hintVals[] = { CFG_HINT(FI_MR_UNSPEC), CFG_HINT(FI_MR_BASIC), CFG_HINT(FI_MR_SCALABLE), CFG_HINT(FI_MR_LOCAL), CFG_HINT(FI_MR_RAW), CFG_HINT(FI_MR_VIRT_ADDR), CFG_HINT(FI_MR_ALLOCATED), CFG_HINT(FI_MR_PROV_KEY), CFG_HINT(FI_MR_MMU_NOTIFY), CFG_HINT(FI_MR_RMA_EVENT), CFG_HINT(FI_MR_ENDPOINT), CFG_HINT(FI_MR_HMEM), CFG_HINT_NULL, }; if (getCfgHint("COMM_OFI_HINTS_MR_MODE", hintVals, false /*justOne*/, &val)) { hints->domain_attr->mr_mode = (int) val; } } #undef CFG_HINT #undef CFG_HINT_NULL } #endif static inline chpl_bool isInProvider(const char* s, struct fi_info* info) { return isInProvName(s, info->fabric_attr->prov_name); } static inline chpl_bool isGoodCoreProvider(struct fi_info* info) { return (!isInProvName("sockets", info->fabric_attr->prov_name) && !isInProvName("tcp", info->fabric_attr->prov_name)); } static inline struct fi_info* findProvInList(struct fi_info* info, chpl_bool accept_ungood_provs, chpl_bool accept_RxD_provs, chpl_bool accept_RxM_provs) { while (info != NULL && ( (!accept_ungood_provs && !isGoodCoreProvider(info)) || (!accept_RxD_provs && isInProvider("ofi_rxd", info)) || (!accept_RxM_provs && isInProvider("ofi_rxm", info)))) { info = info->next; } return (info == NULL) ? NULL : fi_dupinfo(info); } static chpl_bool findProvGivenHints(struct fi_info** p_infoOut, struct fi_info* infoIn, chpl_bool accept_RxD_provs, chpl_bool accept_RxM_provs, enum mcmMode_t mcmm) { struct fi_info* infoList; int ret; OFI_CHK_2(fi_getinfo(COMM_OFI_FI_VERSION, NULL, NULL, 0, infoIn, &infoList), ret, -FI_ENODATA); struct fi_info* info; info = findProvInList(infoList, (getProviderName() != NULL) /*accept_ungood_provs*/, accept_RxD_provs, accept_RxM_provs); DBG_PRINTF_NODE0(DBG_PROV, "** %s desirable provider with %s", (info == NULL) ? "no" : "found", mcmModeNames[mcmm]); if (info == NULL) { *p_infoOut = infoList; return false; } fi_freeinfo(infoList); *p_infoOut = info; return true; } static chpl_bool findProvGivenList(struct fi_info** p_infoOut, struct fi_info* infoIn, chpl_bool accept_RxD_provs, chpl_bool accept_RxM_provs, enum mcmMode_t mcmm) { struct fi_info* info; info = findProvInList(infoIn, true /*accept_ungood_provs*/, accept_RxD_provs, accept_RxM_provs); DBG_PRINTF_NODE0(DBG_PROV, "** %s less-desirable provider with %s", (info == NULL) ? "no" : "found", mcmModeNames[mcmm]); if (info == NULL) { return false; } *p_infoOut = info; return true; } static chpl_bool canBindTxCtxs(struct fi_info* info) { // // This function decides whether we will be able to run with bound // transmit contexts if we choose to use the passed-in provider. // // // We can only support contexts bound to threads if the tasking layer // uses a fixed number of threads. // int fixedNumThreads = chpl_task_getFixedNumThreads(); if (fixedNumThreads <= 0) { return false; } // // Gather invariant info. The simplistic first-time check here is // sufficent because we only get called from single-threaded code // while examining provider candidates. // static chpl_bool haveInvariants = false; if (!haveInvariants) { haveInvariants = true; envPreferScalableTxEp = chpl_env_rt_get_bool("COMM_OFI_PREFER_SCALABLE_EP", true); envCommConcurrency = chpl_env_rt_get_int("COMM_CONCURRENCY", 0); if (envCommConcurrency < 0) { chpl_warning("CHPL_RT_COMM_CONCURRENCY < 0, ignored", 0, 0); envCommConcurrency = 0; } } // // Note for future maintainers: if interoperability between Chapel // and other languages someday results in non-tasking layer threads // calling Chapel code which then tries to communicate across nodes, // then some of this may need adjusting, notably the fixed-threads // logic. // // // Start with the maximum number of transmit contexts/endpoints the // provider could support. Reduce that to allow for one tx context to // be shared among non-worker pthreads including the process itself, // and for one private tx context for each AM handler. If the user // limited communication concurrency via the environment to less than // what's left, reduce further. If this leaves us with at least as // many tx contexts as the tasking layer's fixed thread count then // we'll use bound tx contexts with this provider. // const struct fi_domain_attr* dom_attr = info->domain_attr; int numWorkerTxCtxs = ((envPreferScalableTxEp && dom_attr->max_ep_tx_ctx > 1) ? dom_attr->max_ep_tx_ctx : dom_attr->ep_cnt) - 1 - numAmHandlers; if (envCommConcurrency > 0 && envCommConcurrency < numWorkerTxCtxs) { numWorkerTxCtxs = envCommConcurrency; } return fixedNumThreads <= numWorkerTxCtxs; } // // The find*Prov() functions operate in one of two ways, as selected by // the inputIsHints flag. We call them in some order the first time to // try to find a fabric with a "good" provider, and then if all those // attempts fail we call them again in the same order to find a fabric // with a not-so-good-but-acceptable provider. To save a little time, // we use the candidate list resulting from the first call as the input // for the second one. // // If inputIsHints is true, then infoIn contains basic hints that are to // be adjusted appropriately for the major mode the function tries to // match, and then passed to fi_getinfo() to get a list of candidate // fabrics. If the candidate list contains a fabric instance with a // good provider, output variables *p_infoOut and *p_modeOut are set to // that fabric and the resulting major operational mode, respectively, // and the function returns true. Otherwise, *p_infoOut is set to the // entire candidate list, *p_modeOut is unchanged, and the function // returns false. // // If inputIsHints is false, then infoIn is the candidate list from the // first call. If that list contains a fabric instance with any usable // provider, output variables *p_infoOut and *p_modeOut are set to that // fabric and the resulting major operational mode, respectively, and // the function returns true. Otherwise *p_infoOut and *p_modeOut are // unchanged and the function returns false. // // Each find*Prov() function has companion is*Prov() and setCheck*Prov() // functions. The is*Prov() functions return the corresponding MCM mode // constant iff the given fabric instance has the capabilities that the // find*Prov() function looks for. These functions are used in setting // the MCM conformance mode when the provider is forced rather than // chosen. The setCheck*Prov() functions either add the appropriate // capabilities to existing hints ("set") or determine whether a given // fabric instance has all the capabilities needed ("check"). These // functions are building blocks for both the find*Prov() and is*Prov() // functions, and serve to encapsulate in just one place the specific // capabilities needed for each MCM conformance mode. // typedef chpl_bool (fnFindProv_t)(struct fi_info**, enum mcmMode_t*, struct fi_info*, chpl_bool); static fnFindProv_t findMsgOrderFenceProv; static fnFindProv_t findMsgOrderProv; static fnFindProv_t findDlvrCmpltProv; typedef enum mcmMode_t (fnIsProv_t)(struct fi_info*); static fnIsProv_t isMsgOrderFenceProv; static fnIsProv_t isMsgOrderProv; static fnIsProv_t isDlvrCmpltProv; static struct fi_info* setCheckMsgOrderFenceProv(struct fi_info* info, chpl_bool set) { uint64_t need_caps = FI_ATOMIC | FI_FENCE; uint64_t need_msg_orders = FI_ORDER_ATOMIC_RAW | FI_ORDER_ATOMIC_WAR | FI_ORDER_ATOMIC_WAW | FI_ORDER_SAS; if (set) { info = fi_dupinfo(info); info->caps |= need_caps; info->tx_attr->msg_order = need_msg_orders; info->rx_attr->msg_order = need_msg_orders; return info; } else { // // In addition to needing to be able to support the specific message // ordering settings we require, for message-order-fence mode the // provider has to support bound tx contexts so that we can benefit // from delaying memory visibility. // return ((info->caps & need_caps) == need_caps && (info->tx_attr->msg_order & need_msg_orders) == need_msg_orders && (info->rx_attr->msg_order & need_msg_orders) == need_msg_orders && canBindTxCtxs(info)) ? info : NULL; } } static chpl_bool findMsgOrderFenceProv(struct fi_info** p_infoOut, enum mcmMode_t* p_modeOut, struct fi_info* infoIn, chpl_bool inputIsHints) { // // Try to find a provider that can conform to the MCM using atomic // message orderings plus fences. We try to avoid using either the // RxD or RxM utility providers here, because we really only want // to use atomics where the network can do them natively. // const char* prov_name = getProviderName(); const chpl_bool accept_RxD_provs = isInProvName("ofi_rxd", prov_name); const chpl_bool accept_RxM_provs = isInProvName("ofi_rxm", prov_name); enum mcmMode_t mcmm = mcmm_msgOrdFence; chpl_bool ret; if (inputIsHints) { struct fi_info* infoAdj = setCheckMsgOrderFenceProv(infoIn, true /*set*/); ret = findProvGivenHints(p_infoOut, infoAdj, accept_RxD_provs, accept_RxM_provs, mcmm); fi_freeinfo(infoAdj); } else { ret = findProvGivenList(p_infoOut, infoIn, accept_RxD_provs, accept_RxM_provs, mcmm); } if (ret) { *p_modeOut = mcmm; } return ret; } static enum mcmMode_t isMsgOrderFenceProv(struct fi_info* info) { return (setCheckMsgOrderFenceProv(info, false /*check*/) == info) ? mcmm_msgOrdFence : mcmm_undef; } static struct fi_info* setCheckMsgOrderProv(struct fi_info* info, chpl_bool set) { uint64_t need_msg_orders = FI_ORDER_RAW | FI_ORDER_WAW | FI_ORDER_SAW | FI_ORDER_SAS; if (set) { info = fi_dupinfo(info); info->tx_attr->msg_order = need_msg_orders; info->rx_attr->msg_order = need_msg_orders; return info; } else { return ((info->tx_attr->msg_order & need_msg_orders) == need_msg_orders && (info->rx_attr->msg_order & need_msg_orders) == need_msg_orders) ? info : NULL; } } static chpl_bool findMsgOrderProv(struct fi_info** p_infoOut, enum mcmMode_t* p_modeOut, struct fi_info* infoIn, chpl_bool inputIsHints) { // // Try to find a provider that supports message orderings sufficient // for our MCM, all by themselves. // const char* prov_name = getProviderName(); const chpl_bool accept_RxD_provs = isInProvName("ofi_rxd", prov_name); const chpl_bool accept_RxM_provs = true; enum mcmMode_t mcmm = mcmm_msgOrd; chpl_bool ret; if (inputIsHints) { struct fi_info* infoAdj = setCheckMsgOrderProv(infoIn, true /*set*/); ret = findProvGivenHints(p_infoOut, infoAdj, accept_RxD_provs, accept_RxM_provs, mcmm); fi_freeinfo(infoAdj); } else { ret = findProvGivenList(p_infoOut, infoIn, accept_RxD_provs, accept_RxM_provs, mcmm); } if (ret) { *p_modeOut = mcmm; } return ret; } static enum mcmMode_t isMsgOrderProv(struct fi_info* info) { return (setCheckMsgOrderProv(info, false /*check*/) == info) ? mcmm_msgOrd : mcmm_undef; } static struct fi_info* setCheckDlvrCmpltProv(struct fi_info* info, chpl_bool set) { uint64_t need_op_flags = FI_DELIVERY_COMPLETE; if (set) { info = fi_dupinfo(info); info->tx_attr->op_flags |= need_op_flags; return info; } else { return ((info->tx_attr->op_flags & need_op_flags) == need_op_flags) ? info : NULL; } } static chpl_bool findDlvrCmpltProv(struct fi_info** p_infoOut, enum mcmMode_t* p_modeOut, struct fi_info* infoIn, chpl_bool inputIsHints) { // // Try to find a provider that supports delivery-complete. // const char* prov_name = getProviderName(); const chpl_bool accept_RxD_provs = isInProvName("ofi_rxd", prov_name); const chpl_bool accept_RxM_provs = isInProvName("ofi_rxm", prov_name); enum mcmMode_t mcmm = mcmm_dlvrCmplt; chpl_bool ret; if (inputIsHints) { struct fi_info* infoAdj = setCheckDlvrCmpltProv(infoIn, true /*set*/); ret = findProvGivenHints(p_infoOut, infoAdj, accept_RxD_provs, accept_RxM_provs, mcmm); fi_freeinfo(infoAdj); } else { ret = findProvGivenList(p_infoOut, infoIn, accept_RxD_provs, accept_RxM_provs, mcmm); } if (ret) { *p_modeOut = mcmm; } return ret; } static enum mcmMode_t isDlvrCmpltProv(struct fi_info* info) { return (setCheckDlvrCmpltProv(info, false /*check*/) == info) ? mcmm_dlvrCmplt : mcmm_undef; } static struct fi_info* getBaseProviderHints(chpl_bool* pTxAttrsForced); static void init_ofiFabricDomain(void) { // // Get hints describing our base requirements, the ones that are // independent of which MCM conformance mode we'll eventually use. // chpl_bool txAttrsForced; struct fi_info* hints = getBaseProviderHints(&txAttrsForced); DBG_PRINTF_NODE0(DBG_PROV_HINTS, "====================\n" "initial hints"); DBG_PRINTF_NODE0(DBG_PROV_HINTS, "%s", fi_tostr(hints, FI_TYPE_INFO)); DBG_PRINTF_NODE0(DBG_PROV_HINTS, "===================="); // // Look for a provider that can do one of our message ordering sets // or one that can do delivery-complete. We can't just get all the // providers that match our fundamental needs and then look through // the list to find one that can do what we want, though, because // capabilities that aren't in our hints might not be expressed by // any returned provider. (Providers will not typically volunteer // capabilities that aren't asked for, especially capabilities that // have performance costs.) So here, first see if we get a "good" // core provider using the various hint sets and if that doesn't // succeed, settle for a not-so-good provider. "Good" here means // "neither tcp nor sockets". // // There are some wrinkles: // - Setting either the transaction orderings or the completion type // in manually overridden hints causes those hints to be used as-is, // turning off both the good-provider check and any attempt to find // something sufficient for the MCM. // - Setting the FI_PROVIDER environment variable to manually specify // a provider turns off the good-provider checks. // - We can't accept the RxM utility provider with any core provider // for delivery-complete, because although RxM will match that it // cannot actually do it, and programs will fail. This is a known // bug that can't be fixed without breaking other things: // https://github.com/ofiwg/libfabric/issues/5601 // Explicitly including ofi_rxm in FI_PROVIDER overrides this. // mcmMode = mcmm_undef; // // Take manually overridden hints as forcing provider selection if // they adjust either the transaction orderings or completion type. // Otherwise, just flow those overrides into the selection process // below. // if (txAttrsForced) { int ret; OFI_CHK_2(fi_getinfo(COMM_OFI_FI_VERSION, NULL, NULL, 0, hints, &ofi_info), ret, -FI_ENODATA); if (ret != FI_SUCCESS) { const char* prov_name = getProviderName(); INTERNAL_ERROR_V_NODE0("No (forced) provider for prov_name \"%s\"", (prov_name == NULL) ? "<any>" : prov_name); } } struct { fnFindProv_t* fnFind; fnIsProv_t* fnIs; struct fi_info* infoList; } capTry[] = { { findMsgOrderFenceProv, isMsgOrderFenceProv, NULL }, { findMsgOrderProv, isMsgOrderProv, NULL }, { findDlvrCmpltProv, isDlvrCmpltProv, NULL }, }; size_t capTryLen = sizeof(capTry) / sizeof(capTry[0]); if (ofi_info == NULL) { // Search for a good provider. for (int i = 0; ofi_info == NULL && i < capTryLen; i++) { struct fi_info* info; enum mcmMode_t mcmm; if ((*capTry[i].fnFind)(&info, &mcmm, hints, true /*inputIsHints*/)) { ofi_info = info; mcmMode = mcmm; } else { capTry[i].infoList = info; } } // If necessary, search for a less-good provider. for (int i = 0; ofi_info == NULL && i < capTryLen; i++) { (void) (*capTry[i].fnFind)(&ofi_info, &mcmMode, capTry[i].infoList, false /*inputIsHints*/); } // ofi_info has the result, if any. Free intermediate list(s). for (int i = 0; i < capTryLen && capTry[i].infoList != NULL; i++) { fi_freeinfo(capTry[i].infoList); } } else { // // The capability set, and provider, were forced upon us. Figure out // what capability set we'll be using. // for (int i = 0; mcmMode == mcmm_undef && i < capTryLen; i++) { mcmMode = (*capTry[i].fnIs)(ofi_info); } if (mcmMode == mcmm_undef) { chpl_warning("Forced provider has unknown capability set", 0, 0); } } if (ofi_info == NULL) { // // We didn't find any provider at all. // NOTE: execution ends here. // const char* prov_name = getProviderName(); INTERNAL_ERROR_V_NODE0("No libfabric provider for prov_name \"%s\"", (prov_name == NULL) ? "<any>" : prov_name); } // // If we get here, we have a provider in ofi_info. // fi_freeinfo(hints); if (DBG_TEST_MASK(DBG_PROV_ALL)) { if (chpl_nodeID == 0) { DBG_PRINTF(DBG_PROV_ALL, "====================\n" "matched fabric(s):"); struct fi_info* info; for (info = ofi_info; info != NULL; info = info->next) { DBG_PRINTF(DBG_PROV_ALL, "%s", fi_tostr(ofi_info, FI_TYPE_INFO)); } } } else { DBG_PRINTF_NODE0(DBG_PROV, "====================\n" "matched fabric:"); DBG_PRINTF_NODE0(DBG_PROV, "%s", fi_tostr(ofi_info, FI_TYPE_INFO)); } DBG_PRINTF_NODE0(DBG_PROV | DBG_PROV_ALL, "===================="); if (verbosity >= 2) { if (chpl_nodeID == 0) { void* start; size_t size; chpl_comm_regMemHeapInfo(&start, &size); char buf[10]; printf("COMM=ofi: %s MCM mode, \"%s\" provider, %s fixed heap\n", mcmModeNames[mcmMode], ofi_info->fabric_attr->prov_name, ((size == 0) ? "no" : chpl_snprintf_KMG_z(buf, sizeof(buf), size))); } } // // Create the fabric domain and associated fabric access domain. // OFI_CHK(fi_fabric(ofi_info->fabric_attr, &ofi_fabric, NULL)); OFI_CHK(fi_domain(ofi_fabric, ofi_info, &ofi_domain, NULL)); } static struct fi_info* getBaseProviderHints(chpl_bool* pTxAttrsForced) { // // Build hints describing our base requirements, the ones that are // independent of which MCM conformance mode we'll eventually use: // - capabilities: // - messaging (send/receive), including multi-receive // - RMA // - transactions directed at both self and remote nodes // - on Cray XC, atomics (gni provider doesn't volunteer this) // - tx endpoints: // - completion events // - send-after-send ordering // - rx endpoint ordering same as tx // - RDM endpoints // - "domain" threading model, since we manage thread contention ourselves // - resource management, to improve the odds we hear about exhaustion // - table-style address vectors // - the memory registration modes we can support // const char* prov_name = getProviderName(); struct fi_info* hints; CHK_TRUE((hints = fi_allocinfo()) != NULL); hints->caps = (FI_MSG | FI_MULTI_RECV | FI_RMA | FI_LOCAL_COMM | FI_REMOTE_COMM); if ((strcmp(CHPL_TARGET_PLATFORM, "cray-xc") == 0 && (prov_name == NULL || isInProvName("gni", prov_name))) || chpl_env_rt_get_bool("COMM_OFI_HINTS_CAPS_ATOMIC", false)) { hints->caps |= FI_ATOMIC; } hints->tx_attr->op_flags = FI_COMPLETION; hints->tx_attr->msg_order = FI_ORDER_SAS; hints->rx_attr->msg_order = hints->tx_attr->msg_order; hints->ep_attr->type = FI_EP_RDM; hints->domain_attr->threading = FI_THREAD_DOMAIN; hints->domain_attr->resource_mgmt = FI_RM_ENABLED; hints->domain_attr->av_type = FI_AV_TABLE; hints->domain_attr->mr_mode = ( FI_MR_LOCAL | FI_MR_VIRT_ADDR | FI_MR_PROV_KEY // TODO: avoid pkey bcast? | FI_MR_ENDPOINT); if (chpl_numNodes > 1 && envMaxHeapSize != 0 && !envOversubscribed) { hints->domain_attr->mr_mode |= FI_MR_ALLOCATED; } *pTxAttrsForced = false; #ifdef CHPL_COMM_DEBUG struct fi_info* hintsOrig = fi_dupinfo(hints); debugOverrideHints(hints); *pTxAttrsForced = (hints->tx_attr->op_flags == hintsOrig->tx_attr->op_flags && hints->tx_attr->msg_order == hintsOrig->tx_attr->msg_order) ? false : true; fi_freeinfo(hintsOrig); #endif return hints; } static size_t get_hugepageSize(void); static void init_ofiDoProviderChecks(void) { // // Set/compute various provider-specific things. // if (providerInUse(provType_gni)) { // // gni (Cray XC) // // - Warn if they don't use hugepages. // - Warn if the fixed heap size is larger than what will fit in the // TLB cache. While that may reduce performance it won't affect // function, though, so don't do anything dramatic like reducing // the size to fit. // size_t page_size = get_hugepageSize(); if (page_size == 0) { if (chpl_nodeID == 0) { chpl_warning_explicit("not using hugepages may reduce performance", __LINE__, __FILE__); } page_size = chpl_getSysPageSize(); } const size_t nic_TLB_cache_pages = 512; // not publicly defined const size_t nic_mem_map_limit = nic_TLB_cache_pages * page_size; void* start; size_t size; chpl_comm_impl_regMemHeapInfo(&start, &size); if (size > nic_mem_map_limit) { if (chpl_nodeID == 0) { size_t page_size = chpl_comm_impl_regMemHeapPageSize(); char buf1[20], buf2[20], buf3[20], msg[200]; (void) snprintf(msg, sizeof(msg), "Aries TLB cache can cover %s with %s pages; " "with %s heap,\n" " cache refills may reduce performance", chpl_snprintf_KMG_z(buf1, sizeof(buf1), nic_mem_map_limit), chpl_snprintf_KMG_z(buf2, sizeof(buf2), page_size), chpl_snprintf_KMG_f(buf3, sizeof(buf3), size)); chpl_warning(msg, 0, 0); } } } if (providerInUse(provType_rxd)) { // // ofi_rxd (utility provider with tcp, verbs, possibly others) // // - Based on tracebacks after internal error aborts, RxD seems to // want to record an address per accessing endpoint for at least // some AVs (perhaps just those for which it handles progress?). // It uses the AV attribute 'count' member to size the data // structure in which it stores those. So, that member will need // to account for all transmitting endpoints. // provCtl_sizeAvsByNumEps = true; } // // RxD and perhaps other providers must have a non-NULL buf arg for // fi_fetch_atomic(FI_ATOMIC_READ) or they segfault, even though the // fi_atomic man page says buf is ignored for that operation and may // be NULL. // provCtl_readAmoNeedsOpnd = true; } static void init_ofiEp(void) { // // The AM handler is responsible not only for AM handling and progress // on any RMA it initiates but also progress on inbound RMA, if that // is needed. It uses poll and wait sets to manage this, if it can. // Note: we'll either have both a poll and a wait set, or neither. // // We don't use poll and wait sets with the efa provider because that // doesn't support wait objects. I tried just setting the cq_attr // wait object to FI_WAIT_UNSPEC for all providers, since we don't // reference the wait object explicitly anyway, but then saw hangs // with (at least) the tcp;ofi_rxm provider. // // We don't use poll and wait sets with the gni provider because (1) // it returns -ENOSYS for fi_poll_open() and (2) although a wait set // seems to work properly during execution, we haven't found a way to // avoid getting -FI_EBUSY when we try to close it. // // We don't use poll and wait sets on macOS because the underlying // libfabric support needs epoll, which is from Linux rather than // POSIX and thus not present on macOS. Unfortunately, libfabric has // not (yet?) worked around the lack of epoll because macOS is rather // a secondary platform. One can find comments in the libfabric issue // https://github.com/ofiwg/libfabric/issues/5453 that provide some // background, though that issue is for an unrelated problem. // if (!providerInUse(provType_efa) && !providerInUse(provType_gni) && strcmp(CHPL_TARGET_PLATFORM, "darwin") != 0) { int ret; struct fi_poll_attr pollSetAttr = (struct fi_poll_attr) { .flags = 0, }; OFI_CHK_2(fi_poll_open(ofi_domain, &pollSetAttr, &ofi_amhPollSet), ret, -FI_ENOSYS); if (ret == FI_SUCCESS) { struct fi_wait_attr waitSetAttr = (struct fi_wait_attr) { .wait_obj = FI_WAIT_UNSPEC, }; OFI_CHK_2(fi_wait_open(ofi_fabric, &waitSetAttr, &ofi_amhWaitSet), ret, -FI_ENOSYS); if (ret != FI_SUCCESS) { ofi_amhPollSet = NULL; ofi_amhWaitSet = NULL; } } else { ofi_amhPollSet = NULL; } } // // Compute numbers of transmit and receive contexts, and then create // the transmit context table. // tciTabBindTxCtxs = canBindTxCtxs(ofi_info); if (tciTabBindTxCtxs) { numTxCtxs = chpl_task_getFixedNumThreads() + numAmHandlers + 1; } else { numTxCtxs = chpl_task_getMaxPar() + numAmHandlers + 1; } const chpl_bool useScalEp = envPreferScalableTxEp && ofi_info->domain_attr->max_ep_tx_ctx > 1; if (useScalEp) { ofi_info->ep_attr->tx_ctx_cnt = numTxCtxs; } CHK_TRUE(ofi_info->domain_attr->max_ep_rx_ctx >= numAmHandlers); numRxCtxs = numAmHandlers; tciTabLen = numTxCtxs; CHPL_CALLOC(tciTab, tciTabLen); // // Create transmit contexts. // // // For the CQ lengths, allow for whichever maxOutstanding (AMs or // RMAs) value is larger, plus quite a few for AM responses because // the network round-trip latency ought to be quite a bit more than // our AM handling time, so we want to be able to have many responses // in flight at once. // struct fi_av_attr avAttr = (struct fi_av_attr) { .type = FI_AV_TABLE, .count = chpl_numNodes * 2 /* AM, RMA+AMO */, .name = NULL, .rx_ctx_bits = 0, }; if (provCtl_sizeAvsByNumEps) { // Workaround for RxD peculiarity. avAttr.count *= numTxCtxs; } OFI_CHK(fi_av_open(ofi_domain, &avAttr, &ofi_av, NULL)); if (useScalEp) { // // Use a scalable transmit endpoint and multiple tx contexts. Make // just one address vector, in the first tciTab[] entry. The others // will be synonyms for that one, to make the references easier. // OFI_CHK(fi_scalable_ep(ofi_domain, ofi_info, &ofi_txEpScal, NULL)); OFI_CHK(fi_scalable_ep_bind(ofi_txEpScal, &ofi_av->fid, 0)); } else { // // Use regular transmit endpoints; see below. // } // // Worker TX contexts need completion queues, so they can tell what // kinds of things are completing. // const int numWorkerTxCtxs = tciTabLen - numAmHandlers; struct fi_cq_attr cqAttr; struct fi_cntr_attr cntrAttr; { cqAttr = (struct fi_cq_attr) { .format = FI_CQ_FORMAT_MSG, .size = 100 + MAX_TXNS_IN_FLIGHT, .wait_obj = FI_WAIT_NONE, }; txCQLen = cqAttr.size; for (int i = 0; i < numWorkerTxCtxs; i++) { init_ofiEpTxCtx(i, false /*isAMHandler*/, &cqAttr, NULL); } } // // TX contexts for the AM handler(s) can just use counters, if the // provider supports them. Otherwise, they have to use CQs also. // const enum fi_wait_obj waitObj = (ofi_amhWaitSet == NULL) ? FI_WAIT_NONE : FI_WAIT_SET; if (true /*ofi_info->domain_attr->cntr_cnt == 0*/) { // disable tx counters cqAttr = (struct fi_cq_attr) { .format = FI_CQ_FORMAT_MSG, .size = 100, .wait_obj = waitObj, .wait_cond = FI_CQ_COND_NONE, .wait_set = ofi_amhWaitSet, }; for (int i = numWorkerTxCtxs; i < tciTabLen; i++) { init_ofiEpTxCtx(i, true /*isAMHandler*/, &cqAttr, NULL); } } else { cntrAttr = (struct fi_cntr_attr) { .events = FI_CNTR_EVENTS_COMP, .wait_obj = waitObj, .wait_set = ofi_amhWaitSet, }; for (int i = numWorkerTxCtxs; i < tciTabLen; i++) { init_ofiEpTxCtx(i, true /*isAMHandler*/, NULL, &cntrAttr); } } // // Create receive contexts. // // For the CQ length, allow for an appreciable proportion of the job // to send requests to us at once. // cqAttr = (struct fi_cq_attr) { .size = chpl_numNodes * numWorkerTxCtxs, .format = FI_CQ_FORMAT_DATA, .wait_obj = waitObj, .wait_cond = FI_CQ_COND_NONE, .wait_set = ofi_amhWaitSet, }; cntrAttr = (struct fi_cntr_attr) { .events = FI_CNTR_EVENTS_COMP, .wait_obj = waitObj, .wait_set = ofi_amhWaitSet, }; OFI_CHK(fi_endpoint(ofi_domain, ofi_info, &ofi_rxEp, NULL)); OFI_CHK(fi_ep_bind(ofi_rxEp, &ofi_av->fid, 0)); OFI_CHK(fi_cq_open(ofi_domain, &cqAttr, &ofi_rxCQ, &ofi_rxCQ)); OFI_CHK(fi_ep_bind(ofi_rxEp, &ofi_rxCQ->fid, FI_TRANSMIT | FI_RECV)); OFI_CHK(fi_enable(ofi_rxEp)); // // If we're using poll and wait sets, put all the progress-related // CQs and/or counters in the poll set. // if (ofi_amhPollSet != NULL) { OFI_CHK(fi_poll_add(ofi_amhPollSet, &ofi_rxCQ->fid, 0)); OFI_CHK(fi_poll_add(ofi_amhPollSet, tciTab[tciTabLen - 1].txCmplFid, 0)); pollSetSize = 3; } } static void init_ofiEpTxCtx(int i, chpl_bool isAMHandler, struct fi_cq_attr* cqAttr, struct fi_cntr_attr* cntrAttr) { struct perTxCtxInfo_t* tcip = &tciTab[i]; atomic_init_bool(&tcip->allocated, false); tcip->bound = false; if (ofi_txEpScal == NULL) { OFI_CHK(fi_endpoint(ofi_domain, ofi_info, &tcip->txCtx, NULL)); OFI_CHK(fi_ep_bind(tcip->txCtx, &ofi_av->fid, 0)); } else { OFI_CHK(fi_tx_context(ofi_txEpScal, i, NULL, &tcip->txCtx, NULL)); } if (cqAttr != NULL) { OFI_CHK(fi_cq_open(ofi_domain, cqAttr, &tcip->txCQ, &tcip->checkTxCmplsFn)); tcip->txCmplFid = &tcip->txCQ->fid; OFI_CHK(fi_ep_bind(tcip->txCtx, tcip->txCmplFid, FI_TRANSMIT | FI_RECV)); tcip->checkTxCmplsFn = checkTxCmplsCQ; } else { OFI_CHK(fi_cntr_open(ofi_domain, cntrAttr, &tcip->txCntr, &tcip->checkTxCmplsFn)); tcip->txCmplFid = &tcip->txCntr->fid; OFI_CHK(fi_ep_bind(tcip->txCtx, tcip->txCmplFid, FI_SEND | FI_READ | FI_WRITE)); tcip->checkTxCmplsFn = checkTxCmplsCntr; } OFI_CHK(fi_enable(tcip->txCtx)); tcip->ensureProgressFn = isAMHandler ? amEnsureProgress : tcip->checkTxCmplsFn; } static void init_ofiExchangeAvInfo(void) { // // Exchange addresses with the rest of the nodes. // // // Get everybody else's address. // Note: this assumes all addresses, job-wide, are the same length. // if (DBG_TEST_MASK(DBG_CFG_AV)) { // // Sanity-check our same-address-length assumption. // size_t len = 0; OFI_CHK_1(fi_getname(&ofi_rxEp->fid, NULL, &len), -FI_ETOOSMALL); size_t* lens; CHPL_CALLOC(lens, chpl_numNodes); chpl_comm_ofi_oob_allgather(&len, lens, sizeof(len)); if (chpl_nodeID == 0) { for (int i = 0; i < chpl_numNodes; i++) { CHK_TRUE(lens[i] == len); } } } char* my_addr; char* addrs; size_t my_addr_len = 0; OFI_CHK_1(fi_getname(&ofi_rxEp->fid, NULL, &my_addr_len), -FI_ETOOSMALL); CHPL_CALLOC_SZ(my_addr, my_addr_len, 1); OFI_CHK(fi_getname(&ofi_rxEp->fid, my_addr, &my_addr_len)); CHPL_CALLOC_SZ(addrs, chpl_numNodes, my_addr_len); if (DBG_TEST_MASK(DBG_CFG_AV)) { char nameBuf[128]; size_t nameLen; nameLen = sizeof(nameBuf); (void) fi_av_straddr(ofi_av, my_addr, nameBuf, &nameLen); DBG_PRINTF(DBG_CFG_AV, "my_addrs: %.*s%s", (int) nameLen, nameBuf, (nameLen <= sizeof(nameBuf)) ? "" : "[...]"); } chpl_comm_ofi_oob_allgather(my_addr, addrs, my_addr_len); // // Insert the addresses into the address vector and build up a vector // of remote receive endpoints. // // All the transmit context table entries have address vectors and we // always use the one associated with our tx context. But if we have // a scalable endpoint then all of those AVs are really the same one. // Only when the provider cannot support scalable EPs and we have // multiple actual endpoints are the AVs individualized to those. // size_t numAddrs = chpl_numNodes; CHPL_CALLOC(ofi_rxAddrs, numAddrs); CHK_TRUE(fi_av_insert(ofi_av, addrs, numAddrs, ofi_rxAddrs, 0, NULL) == numAddrs); CHPL_FREE(my_addr); CHPL_FREE(addrs); } static void findMoreMemoryRegions(void); static void init_ofiForMem(void) { void* fixedHeapStart; size_t fixedHeapSize; chpl_comm_impl_regMemHeapInfo(&fixedHeapStart, &fixedHeapSize); // // We default to scalable registration if none of the settings that // force basic registration are present, but the user can override // that by specifying use of a fixed heap. Note that this is to // some extent just a backstop, because if the user does specify a // fixed heap we will have earlier included FI_MR_ALLOCATED in our // hints, which might well have caused the selection of a provider // which requires basic registration. // const uint64_t basicMemRegBits = (FI_MR_BASIC | FI_MR_LOCAL | FI_MR_VIRT_ADDR | FI_MR_ALLOCATED | FI_MR_PROV_KEY); scalableMemReg = ((ofi_info->domain_attr->mr_mode & basicMemRegBits) == 0 && fixedHeapSize == 0); // // With scalable memory registration we just register the whole // address space here; with non-scalable we register each region // individually. Currently with non-scalable we actually only // register a fixed heap. We may do something more complicated // in the future, though. // if (scalableMemReg) { memTab[0].addr = (void*) 0; memTab[0].base = 0; memTab[0].size = SIZE_MAX; memTabCount = 1; } else { if (fixedHeapSize == 0) { INTERNAL_ERROR_V("must specify fixed heap with %s provider", ofi_info->fabric_attr->prov_name); } memTab[0].addr = fixedHeapStart; memTab[0].base = 0; memTab[0].size = fixedHeapSize; memTabCount = 1; findMoreMemoryRegions(); if ((ofi_info->domain_attr->mr_mode & FI_MR_VIRT_ADDR) == 0) { for (int i = 0; i < memTabCount; i++) { memTab[i].base = (uint64_t) memTab[i].addr; } } } const chpl_bool prov_key = ((ofi_info->domain_attr->mr_mode & FI_MR_PROV_KEY) != 0); uint64_t bufAcc = FI_RECV | FI_REMOTE_READ | FI_REMOTE_WRITE; if ((ofi_info->domain_attr->mr_mode & FI_MR_LOCAL) != 0) { bufAcc |= FI_SEND | FI_READ | FI_WRITE; } for (int i = 0; i < memTabCount; i++) { DBG_PRINTF(DBG_MR, "[%d] fi_mr_reg(%p, %#zx, %#" PRIx64 ")", i, memTab[i].addr, memTab[i].size, bufAcc); OFI_CHK(fi_mr_reg(ofi_domain, memTab[i].addr, memTab[i].size, bufAcc, 0, (prov_key ? 0 : i), 0, &ofiMrTab[i], NULL)); memTab[i].desc = fi_mr_desc(ofiMrTab[i]); memTab[i].key = fi_mr_key(ofiMrTab[i]); CHK_TRUE(prov_key || memTab[i].key == i); DBG_PRINTF(DBG_MR, "[%d] key %#" PRIx64, i, memTab[i].key); if ((ofi_info->domain_attr->mr_mode & FI_MR_ENDPOINT) != 0) { OFI_CHK(fi_mr_bind(ofiMrTab[i], &ofi_rxEp->fid, 0)); OFI_CHK(fi_mr_enable(ofiMrTab[i])); } } // // Unless we're doing scalable registration of the entire address // space, share the memory regions around the job. // if (!scalableMemReg) { CHPL_CALLOC(memTabMap, chpl_numNodes); chpl_comm_ofi_oob_allgather(&memTab, memTabMap, sizeof(memTabMap[0])); } } static chpl_bool nextMemMapEntry(void** pAddr, size_t* pSize, char* retPath, size_t retPathSize); static void findMoreMemoryRegions(void) { DBG_CATFILE(DBG_MEMMAP, "/proc/self/maps", NULL); // // Look through /proc/self/maps for memory regions we'd like to // register. So far we just try to register the program's data // segment, heap, and stack. To identify the first of those we // need our program's name, so get that first. // char progName[1000]; ssize_t pnLen = readlink("/proc/self/exe", progName, sizeof(progName)); if (pnLen > 0) { if (pnLen >= sizeof(progName)) { pnLen--; } progName[pnLen] = '\0'; } void* addr; size_t size; char path[1000]; while (memTabCount < memTabSize - 1 && nextMemMapEntry(&addr, &size, path, sizeof(path))) { // // Record this memory region if we want it. Don't record a region // more than once. // chpl_bool seen = false; for (int i = 0; i < memTabCount; i++) { if (addr == memTab[i].addr && size == memTab[i].size) { seen = true; break; } } if (!seen && ((pnLen > 0 && strcmp(path, progName) == 0) || strcmp(path, "[heap]") == 0 || strcmp(path, "[stack]") == 0)) { DBG_PRINTF(DBG_MR, "record mem map region: %p %#zx \"%s\"", addr, size, path); memTab[memTabCount].addr = addr; memTab[memTabCount].size = size; memTabCount++; } } } static chpl_bool nextMemMapEntry(void** pAddr, size_t* pSize, char* retPath, size_t retPathSize) { static FILE* f = NULL; if (f == NULL) { if ((f = fopen("/proc/self/maps", "r")) == NULL) { INTERNAL_ERROR_V("cannot fopen(\"/proc/self/maps\")"); } } while (true) { uint64_t lo_addr; uint64_t hi_addr; char perms[5]; int ch; int scn_cnt; scn_cnt = fscanf(f, "%" SCNx64 "-%" SCNx64 "%4s%*x%*x:%*x%*x", &lo_addr, &hi_addr, perms); if (scn_cnt == EOF) { break; } else if (scn_cnt != 3) { INTERNAL_ERROR_V("unrecognized /proc/self/maps line format"); } // // Skip regions that are not read/write. // if (perms[0] != 'r' || perms[1] != 'w') { while ((ch = fgetc(f)) != EOF && ch != '\n') ; continue; } if (retPath == NULL) { // // Pathname not wanted -- skip the rest of this line. // while ((ch = fgetc(f)) != EOF && ch != '\n') ; } else { // // Pathname wanted -- skip leading white space, then pick up as // many characters as will fit in supplied buffer. // while ((ch = fgetc(f)) == ' ' || ch == '\t') ; int p_idx; for (p_idx = 0; ch != EOF && ch != '\n'; ch = fgetc(f)) { if (p_idx < retPathSize - 1) { retPath[p_idx++] = ch; } } retPath[p_idx] = '\0'; } *pAddr = (void*) (intptr_t) lo_addr; *pSize = hi_addr - lo_addr; return true; } (void) fclose(f); f = NULL; return false; } static int isAtomicValid(enum fi_datatype); static void init_ofiForRma(void) { // // We need to make an initial call to isAtomicValid() to let it // initialize its internals. The datatype here doesn't matter. // (void) isAtomicValid(FI_INT32); } static void init_amHandling(void); static void init_ofiForAms(void) { // // Compute the amount of space we should allow for AM landing zones. // We should have enough that we needn't re-post the multi-receive // buffer more often than, say, every tenth of a second. We know from // the Chapel performance/comm/low-level/many-to-one test that the // comm=ugni AM handler can handle just over 150k "fast" AM requests // in 0.1 sec. Assuming an average AM request size of 256 bytes, a 40 // MiB buffer is enough to give us the desired 0.1 sec lifetime before // it needs renewing. We actually then split this in half and create // 2 half-sized buffers (see below), so reflect that here also. // const size_t amLZSize = ((size_t) 40 << 20) / 2; // // Set the minimum multi-receive buffer space. Make it big enough to // hold a max-sized request from every potential sender, but no more // than 10% of the buffer size. Some providers don't have fi_setopt() // for some ep types, so allow this to fail in that case. But note // that if it does fail and we get overruns we'll die or, worse yet, // silently compute wrong results. // { size_t sz = chpl_numNodes * tciTabLen * sizeof(struct amRequest_execOn_t); if (sz > amLZSize / 10) { sz = amLZSize / 10; } int ret; OFI_CHK_2(fi_setopt(&ofi_rxEp->fid, FI_OPT_ENDPOINT, FI_OPT_MIN_MULTI_RECV, &sz, sizeof(sz)), ret, -FI_ENOSYS); } // // Pre-post multi-receive buffer for inbound AM requests. In reality // set up two of these and swap back and forth between them, to hedge // against receiving "buffer filled and released" events out of order // with respect to the messages stored within them. // CHPL_CALLOC_SZ(amLZs[0], 1, amLZSize); CHPL_CALLOC_SZ(amLZs[1], 1, amLZSize); ofi_iov_reqs[0] = (struct iovec) { .iov_base = amLZs[0], .iov_len = amLZSize, }; ofi_iov_reqs[1] = (struct iovec) { .iov_base = amLZs[1], .iov_len = amLZSize, }; ofi_msg_reqs[0] = (struct fi_msg) { .msg_iov = &ofi_iov_reqs[0], .desc = NULL, .iov_count = 1, .addr = FI_ADDR_UNSPEC, .context = txnTrkEncodeId(__LINE__), .data = 0x0, }; ofi_msg_reqs[1] = (struct fi_msg) { .msg_iov = &ofi_iov_reqs[1], .desc = NULL, .iov_count = 1, .addr = FI_ADDR_UNSPEC, .context = txnTrkEncodeId(__LINE__), .data = 0x0, }; ofi_msg_i = 0; OFI_CHK(fi_recvmsg(ofi_rxEp, &ofi_msg_reqs[ofi_msg_i], FI_MULTI_RECV)); DBG_PRINTF(DBG_AM_BUF, "pre-post fi_recvmsg(AMLZs %p, len %#zx)", ofi_msg_reqs[ofi_msg_i].msg_iov->iov_base, ofi_msg_reqs[ofi_msg_i].msg_iov->iov_len); init_amHandling(); } static void amRequestNop(c_nodeid_t, chpl_bool, struct perTxCtxInfo_t*); static void init_ofiConnections(void) { // // With providers that do dynamic endpoint connection we have seen // fairly dramatic connection overheads under certain circumstances. // As an aid to performance analysis, here we allow for forcing the // endpoint connections to be established early, during startup, // rather than later during timed sections of user code. // if (!providerInUse(provType_tcp) && !providerInUse(provType_verbs)) { return; } if (!chpl_env_rt_get_bool("COMM_OFI_CONNECT_EAGERLY", false)) { return; } // // We do this by firing a no-op AM to every remote node from every // still-inactive tx context. (In effect, this means from all tx // contexts that aren't already bound to AM handlers.) At present we // use blocking AMs for this, but if needed we could delay blocking // until after the last one had been initiated. One way or another, // we need to not return until after all the connections have been // established. // for (c_nodeid_t node = (chpl_nodeID + 1) % chpl_numNodes; node != chpl_nodeID; node = (node + 1) % chpl_numNodes) { for (int i = 0; i < tciTabLen; i++) { struct perTxCtxInfo_t* tcip = &tciTab[i]; if (!tcip->bound) { CHK_TRUE(tciAllocTabEntry(tcip)); while (tcip->txCQ != NULL && tcip->numTxnsOut >= txCQLen) { (*tcip->checkTxCmplsFn)(tcip); } amRequestNop(node, true /*blocking*/, tcip); tciFree(tcip); } } } } void chpl_comm_rollcall(void) { DBG_PRINTF(DBG_IFACE_SETUP, "%s()", __func__); // Initialize diags chpl_comm_diags_init(); chpl_msg(2, "executing on node %d of %d node(s): %s\n", chpl_nodeID, chpl_numNodes, chpl_nodeName()); // // Only node 0 in multi-node programs does liveness checks, and only // after we're sure all the other nodes' AM handlers are running. // if (chpl_numNodes > 1 && chpl_nodeID == 0) { amDoLivenessChecks = true; } } // // Chapel global and private variable support // wide_ptr_t* chpl_comm_broadcast_global_vars_helper(void) { DBG_PRINTF(DBG_IFACE_SETUP, "%s()", __func__); // // Gather the global variables' wide pointers on node 0 into a // buffer, and broadcast the address of that buffer to the other // nodes. // wide_ptr_t* buf; if (chpl_nodeID == 0) { CHPL_CALLOC(buf, chpl_numGlobalsOnHeap); for (int i = 0; i < chpl_numGlobalsOnHeap; i++) { buf[i] = *chpl_globals_registry[i]; } } chpl_comm_ofi_oob_bcast(&buf, sizeof(buf)); return buf; } static void*** chplPrivBcastTabMap; static void init_broadcast_private(void) { // // // Share the nodes' private broadcast tables around. These are // needed by chpl_comm_broadcast_private(), below. // void** pbtMap; size_t pbtSize = chpl_rt_priv_bcast_tab_len * sizeof(chpl_rt_priv_bcast_tab[0]); CHPL_CALLOC(pbtMap, chpl_numNodes * pbtSize); chpl_comm_ofi_oob_allgather(chpl_rt_priv_bcast_tab, pbtMap, pbtSize); CHPL_CALLOC(chplPrivBcastTabMap, chpl_numNodes); for (int i = 0; i < chpl_numNodes; i++) { chplPrivBcastTabMap[i] = &pbtMap[i * chpl_rt_priv_bcast_tab_len]; } } void chpl_comm_broadcast_private(int id, size_t size) { DBG_PRINTF(DBG_IFACE_SETUP, "%s(%d, %zd)", __func__, id, size); for (int i = 0; i < chpl_numNodes; i++) { if (i != chpl_nodeID) { (void) ofi_put(chpl_rt_priv_bcast_tab[id], i, chplPrivBcastTabMap[i][id], size); } } } //////////////////////////////////////// // // Interface: shutdown // static void exit_all(int); static void exit_any(int); static void fini_amHandling(void); static void fini_ofi(void); static void amRequestShutdown(c_nodeid_t); void chpl_comm_pre_task_exit(int all) { DBG_PRINTF(DBG_IFACE_SETUP, "%s(%d)", __func__, all); if (all) { if (chpl_nodeID == 0) { for (int node = 1; node < chpl_numNodes; node++) { amRequestShutdown(node); } } else { chpl_wait_for_shutdown(); } chpl_comm_barrier("chpl_comm_pre_task_exit"); fini_amHandling(); } } void chpl_comm_exit(int all, int status) { DBG_PRINTF(DBG_IFACE_SETUP, "%s(%d, %d)", __func__, all, status); if (all) { exit_all(status); } else { exit_any(status); } } static void exit_all(int status) { fini_ofi(); chpl_comm_ofi_oob_fini(); } static void exit_any(int status) { // // (Over)abundance of caution mode: if exiting unilaterally with the // 'verbs' provider in use, call _exit() now instead of allowing the // usual runtime control flow to call exit() and invoke the atexit(3) // functions. Otherwise we run the risk of segfaulting due to some // broken destructor code in librdmacm. That was fixed years ago by // https://github.com/linux-rdma/rdma-core/commit/9ef8ed2 // but the fix doesn't seem to have made it into general circulation // yet. // // Flush all the stdio FILE streams first, in the hope of not losing // any output. // if (providerInUse(provType_verbs)) { fflush(NULL); _exit(status); } } static void fini_ofi(void) { if (chpl_numNodes <= 1) return; for (int i = 0; i < memTabCount; i++) { OFI_CHK(fi_close(&ofiMrTab[i]->fid)); } if (memTabMap != NULL) { CHPL_FREE(memTabMap); } CHPL_FREE(amLZs[1]); CHPL_FREE(amLZs[0]); CHPL_FREE(ofi_rxAddrs); if (ofi_amhPollSet != NULL) { OFI_CHK(fi_poll_del(ofi_amhPollSet, tciTab[tciTabLen - 1].txCmplFid, 0)); OFI_CHK(fi_poll_del(ofi_amhPollSet, &ofi_rxCQ->fid, 0)); } OFI_CHK(fi_close(&ofi_rxEp->fid)); OFI_CHK(fi_close(&ofi_rxCQ->fid)); for (int i = 0; i < tciTabLen; i++) { OFI_CHK(fi_close(&tciTab[i].txCtx->fid)); OFI_CHK(fi_close(tciTab[i].txCmplFid)); } if (ofi_txEpScal != NULL) { OFI_CHK(fi_close(&ofi_txEpScal->fid)); } OFI_CHK(fi_close(&ofi_av->fid)); if (ofi_amhPollSet != NULL) { OFI_CHK(fi_close(&ofi_amhWaitSet->fid)); OFI_CHK(fi_close(&ofi_amhPollSet->fid)); } OFI_CHK(fi_close(&ofi_domain->fid)); OFI_CHK(fi_close(&ofi_fabric->fid)); fi_freeinfo(ofi_info); } //////////////////////////////////////// // // Interface: Registered memory // static pthread_once_t fixedHeapOnce = PTHREAD_ONCE_INIT; static size_t fixedHeapSize; static void* fixedHeapStart; static pthread_once_t hugepageOnce = PTHREAD_ONCE_INIT; static size_t hugepageSize; static void init_fixedHeap(void); static size_t get_hugepageSize(void); static void init_hugepageSize(void); void chpl_comm_impl_regMemHeapInfo(void** start_p, size_t* size_p) { DBG_PRINTF(DBG_IFACE_SETUP, "%s()", __func__); PTHREAD_CHK(pthread_once(&fixedHeapOnce, init_fixedHeap)); *start_p = fixedHeapStart; *size_p = fixedHeapSize; } static void init_fixedHeap(void) { // // Determine whether or not we'll use a fixed heap, and if so what its // address and size are. Note that this has to be able to run early, // before we've actually selected a provider and set up libfabric, // because it can indirectly be called from memory layer init which // may need to configure itself differently with or without a fixed // heap. // // // Get hints describing our base requirements, the ones that are // independent of which MCM conformance mode we'll eventually use. // chpl_bool txAttrsForced; struct fi_info* hints = getBaseProviderHints(&txAttrsForced); // // If hint construction didn't at least tentatively say we'll use a // fixed heap, we definitely won't. The checks it does are based on // run-invariant info such as environment settings, whether this is // a multi-node program, etc. // if ((hints->domain_attr->mr_mode & FI_MR_ALLOCATED) == 0) { DBG_PRINTF_NODE0(DBG_HEAP, "fixedHeap: base hints say no"); return; } // // Now do further checks. We default to using a fixed heap on Cray XC // and (for now) HPE Cray EX systems unless the user explicitly says // not to. That was checked in base hint construction. On other // platforms, we'll use a fixed heap if the best-performing "good" // provider (not sockets, not tcp, not verbs;ofi_rxd) out of those // that can meet our base requirements has FI_MR_ALLOCATED set to // indicate it wants one. // if (strcmp(CHPL_TARGET_PLATFORM, "cray-xc") != 0 && strcmp(CHPL_TARGET_PLATFORM, "hpe-cray-ex") != 0) { struct fi_info* infoList; int ret; OFI_CHK_2(fi_getinfo(COMM_OFI_FI_VERSION, NULL, NULL, 0, hints, &infoList), ret, -FI_ENODATA); if (infoList == NULL) { // // We found no providers at all, thus none requiring a fixed heap. // DBG_PRINTF_NODE0(DBG_HEAP, "fixedHeap: no, because no providers (?)"); return; } struct fi_info* info; for (info = infoList; info != NULL; info = info->next) { if (isGoodCoreProvider(info) && (!isInProvider("verbs", info) || !isInProvider("ofi_rxd", info))) { break; } } chpl_bool useHeap; if (info == NULL) { DBG_PRINTF_NODE0(DBG_HEAP, "fixedHeap: no, no provider needs it"); useHeap = false; } else if ((info->domain_attr->mr_mode & FI_MR_ALLOCATED) == 0) { DBG_PRINTF_NODE0(DBG_HEAP, "fixedHeap: no, best provider '%s' doesn't need it", info->fabric_attr->prov_name); useHeap = false; } else { DBG_PRINTF_NODE0(DBG_HEAP, "fixedHeap: yes, best provider '%s' needs it", info->fabric_attr->prov_name); useHeap = true; } fi_freeinfo(infoList); if (!useHeap) { return; } } // // If we get this far we'll use a fixed heap. // uint64_t total_memory = chpl_sys_physicalMemoryBytes(); // // Don't use more than 85% of the total memory for heaps. // uint64_t max_heap_memory = (size_t) (0.85 * total_memory); int num_locales_on_node = chpl_comm_ofi_oob_locales_on_node(); size_t max_heap_per_locale = (size_t) (max_heap_memory / num_locales_on_node); // // If the maximum heap size is not specified or it's greater than the maximum heap per // locale, set it to the maximum heap per locale. // ssize_t size = envMaxHeapSize; CHK_TRUE(size != 0); if ((size < 0) || (size > max_heap_per_locale)) { size = max_heap_per_locale; } // // Check for hugepages. On certain systems you really ought to use // them. But if you're on such a system and don't, we'll emit the // message later. // size_t page_size; chpl_bool have_hugepages; if ((page_size = get_hugepageSize()) == 0) { page_size = chpl_getSysPageSize(); have_hugepages = false; } else { have_hugepages = true; } // // We'll make a fixed heap, on whole (huge)pages. // size = ALIGN_UP(size, page_size); // // Work our way down from the starting size in (roughly) 5% steps // until we can actually allocate a heap that size. // size_t decrement; if ((decrement = ALIGN_DN((size_t) (0.05 * size), page_size)) < page_size) { decrement = page_size; } void* start; size += decrement; do { size -= decrement; #ifdef CHPL_COMM_DEBUG if (DBG_TEST_MASK(DBG_HEAP)) { char buf[10]; DBG_PRINTF(DBG_HEAP, "try allocating fixed heap, size %s (%#zx)", chpl_snprintf_KMG_z(buf, sizeof(buf), size), size); } #endif if (have_hugepages) { start = chpl_comm_ofi_hp_get_huge_pages(size); } else { CHK_SYS_MEMALIGN(start, page_size, size); } } while (start == NULL && size > decrement); if (start == NULL) chpl_error("cannot create fixed heap: cannot get memory", 0, 0); chpl_comm_regMemHeapTouch(start, size); #ifdef CHPL_COMM_DEBUG if (DBG_TEST_MASK(DBG_HEAP)) { char buf[10]; DBG_PRINTF(DBG_HEAP, "fixed heap on %spages, start=%p size=%s (%#zx)\n", have_hugepages ? "huge" : "regular ", start, chpl_snprintf_KMG_z(buf, sizeof(buf), size), size); } #endif fixedHeapSize = size; fixedHeapStart = start; } size_t chpl_comm_impl_regMemHeapPageSize(void) { DBG_PRINTF(DBG_IFACE_SETUP, "%s()", __func__); size_t sz; if ((sz = get_hugepageSize()) > 0) return sz; return chpl_getSysPageSize(); } static size_t get_hugepageSize(void) { PTHREAD_CHK(pthread_once(&hugepageOnce, init_hugepageSize)); return hugepageSize; } static void init_hugepageSize(void) { if (chpl_numNodes > 1 && getenv("HUGETLB_DEFAULT_PAGE_SIZE") != NULL) { hugepageSize = chpl_comm_ofi_hp_gethugepagesize(); } DBG_PRINTF(DBG_HUGEPAGES, "setting hugepage info: use hugepages %s, sz %#zx", (hugepageSize > 0) ? "YES" : "NO", hugepageSize); } static inline struct memEntry* getMemEntry(memTab_t* tab, void* addr, size_t size) { char* myAddr = (char*) addr; for (int i = 0; i < memTabCount; i++) { char* tabAddr = (char*) (*tab)[i].addr; char* tabAddrEnd = tabAddr + (*tab)[i].size; if (myAddr >= tabAddr && myAddr + size <= tabAddrEnd) return &(*tab)[i]; } return NULL; } static inline chpl_bool mrGetDesc(void** pDesc, void* addr, size_t size) { chpl_bool ret; void* desc; if (scalableMemReg) { ret = true; desc = NULL; } else { struct memEntry* mr; ret = (mr = getMemEntry(&memTab, addr, size)) != NULL; if (ret) { desc = mr->desc; DBG_PRINTF(DBG_MR_DESC, "mrGetDesc(%p, %zd): desc %p", addr, size, desc); } else { desc = NULL; DBG_PRINTF(DBG_MR_DESC, "mrGetDesc(%p, %zd): no entry", addr, size); } } if (pDesc != NULL) { *pDesc = desc; } return ret; } static inline void* mrLocalize(void** pDesc, const void* addr, size_t size, chpl_bool isSource, const char* what) { void* mrAddr = (void*) addr; if (mrAddr == NULL) { *pDesc = NULL; } else if (!mrGetDesc(pDesc, mrAddr, size)) { mrAddr = allocBounceBuf(size); DBG_PRINTF(DBG_MR_BB, "%s BB: %p", what, mrAddr); CHK_TRUE(mrGetDesc(pDesc, mrAddr, size)); if (isSource) { memcpy(mrAddr, addr, size); } } return mrAddr; } static inline void* mrLocalizeSource(void** pDesc, const void* addr, size_t size, const char* what) { return mrLocalize(pDesc, addr, size, true /*isSource*/, what); } static inline void* mrLocalizeTarget(void** pDesc, const void* addr, size_t size, const char* what) { return mrLocalize(pDesc, addr, size, false /*isSource*/, what); } static inline void mrUnLocalizeSource(void* mrAddr, const void* addr) { if (mrAddr != NULL && mrAddr != addr) { freeBounceBuf(mrAddr); } } static inline void mrUnLocalizeTarget(void* mrAddr, void* addr, size_t size) { if (mrAddr != NULL && mrAddr != addr) { memcpy(addr, mrAddr, size); freeBounceBuf(mrAddr); } } static inline chpl_bool mrGetKey(uint64_t* pKey, uint64_t* pOff, int iNode, void* addr, size_t size) { uint64_t key; uint64_t off; if (scalableMemReg) { key = 0; off = (uint64_t) addr; } else { struct memEntry* mr; if ((mr = getMemEntry(&memTabMap[iNode], addr, size)) == NULL) { DBG_PRINTF(DBG_MR_KEY, "mrGetKey(%d:%p, %zd): no entry", iNode, addr, size); return false; } key = mr->key; off = (uint64_t) addr - mr->base; DBG_PRINTF(DBG_MR_KEY, "mrGetKey(%d:%p, %zd): key %" PRIx64 ", off %" PRIx64, iNode, addr, size, key, off); } if (pKey != NULL) { *pKey = key; *pOff = off; } return true; } static inline chpl_bool mrGetLocalKey(void* addr, size_t size) { return mrGetKey(NULL, NULL, chpl_nodeID, addr, size); } static inline void* mrLocalizeRemote(const void* addr, size_t size, chpl_bool isSource, const char* what) { void* mrAddr = (void*) addr; if (!mrGetLocalKey(mrAddr, size)) { mrAddr = allocBounceBuf(size); DBG_PRINTF(DBG_MR_BB, "%s BB: %p", what, mrAddr); CHK_TRUE(mrGetLocalKey(mrAddr, size)); if (isSource) { memcpy(mrAddr, addr, size); } } return mrAddr; } static inline void* mrLocalizeSourceRemote(const void* addr, size_t size, const char* what) { return mrLocalizeRemote(addr, size, true /*isSource*/, what); } static inline void* mrLocalizeTargetRemote(const void* addr, size_t size, const char* what) { return mrLocalizeRemote(addr, size, false /*isSource*/, what); } //////////////////////////////////////// // // Interface: memory consistency // static void retireDelayedAmDone(chpl_bool); static inline void mcmReleaseOneNode(c_nodeid_t node, struct perTxCtxInfo_t* tcip, const char* dbgOrderStr) { DBG_PRINTF(DBG_ORDER, "dummy GET from %d for %s ordering", (int) node, dbgOrderStr); uint64_t flags = (mcmMode == mcmm_msgOrdFence) ? FI_FENCE : 0; if (tcip->txCQ != NULL) { atomic_bool txnDone; atomic_init_bool(&txnDone, false); void* ctx = txnTrkEncodeDone(&txnDone); ofi_get_lowLevel(orderDummy, orderDummyMRDesc, node, orderDummyMap[node].mrRaddr, orderDummyMap[node].mrKey, sizeof(*orderDummy), ctx, flags, tcip); waitForTxnComplete(tcip, ctx); atomic_destroy_bool(&txnDone); } else { ofi_get_lowLevel(orderDummy, orderDummyMRDesc, node, orderDummyMap[node].mrRaddr, orderDummyMap[node].mrKey, sizeof(*orderDummy), NULL, flags, tcip); waitForTxnComplete(tcip, NULL); } } static void mcmReleaseAllNodes(struct bitmap_t* b1, struct bitmap_t* b2, c_nodeid_t skipNode, struct perTxCtxInfo_t* tcip, const char* dbgOrderStr) { // // Do a transaction do force all outstanding operations' remote // memory effects to be visible, on every node in one bitmap or // either of two bitmaps. The effects of the transactions we do // here don't matter, only their completions. // // TODO: Allow multiple of these transactions outstanding at once, // instead of waiting for each one before firing the next. // if (b1 == NULL) { if (b2 == NULL) { // Nothing to do. } else { BITMAP_FOREACH_SET(b2, node) { if (skipNode < 0 || node != skipNode) { (*tcip->checkTxCmplsFn)(tcip); mcmReleaseOneNode(node, tcip, dbgOrderStr); } } BITMAP_FOREACH_SET_END bitmapZero(b2); } } else { if (b2 == NULL) { BITMAP_FOREACH_SET(b1, node) { if (skipNode < 0 || node != skipNode) { (*tcip->checkTxCmplsFn)(tcip); mcmReleaseOneNode(node, tcip, dbgOrderStr); } } BITMAP_FOREACH_SET_END bitmapZero(b1); } else { BITMAP_FOREACH_SET_OR(b1, b2, node) { if (skipNode < 0 || node != skipNode) { (*tcip->checkTxCmplsFn)(tcip); mcmReleaseOneNode(node, tcip, dbgOrderStr); } } BITMAP_FOREACH_SET_END bitmapZero(b1); bitmapZero(b2); } } } void chpl_comm_impl_unordered_task_fence(void) { DBG_PRINTF(DBG_IFACE_MCM, "%s()", __func__); task_local_buff_end(get_buff | put_buff | amo_nf_buff); } inline void chpl_comm_impl_task_create(void) { DBG_PRINTF(DBG_IFACE_MCM, "%s()", __func__); retireDelayedAmDone(false /*taskIsEnding*/); forceMemFxVisAllNodes_noTcip(true /*checkPuts*/, true /*checkAmos*/); } void chpl_comm_impl_task_end(void) { DBG_PRINTF(DBG_IFACE_MCM, "%s()", __func__); task_local_buff_end(get_buff | put_buff | amo_nf_buff); retireDelayedAmDone(true /*taskIsEnding*/); forceMemFxVisAllNodes_noTcip(true /*checkPuts*/, true /*checkAmos*/); } //////////////////////////////////////// // // Interface: Active Messages // typedef enum { am_opExecOn = CHPL_ARG_BUNDLE_KIND_COMM, // impl-nonspecific on-stmt am_opExecOnLrg, // on-stmt, large arg am_opGet, // do an RMA GET am_opPut, // do an RMA PUT am_opAMO, // do an AMO am_opFree, // free some memory am_opNop, // do nothing; for MCM & liveness am_opShutdown, // signal main process for shutdown } amOp_t; #ifdef CHPL_COMM_DEBUG static inline chpl_bool op_uses_on_bundle(amOp_t op) { return op == am_opExecOn || op == am_opExecOnLrg; } #endif // // Members are packed, potentially differently, in each AM request type // to reduce space requirements. The 'op' member must come first in all // cases, so the AM handler can tell what kind of request it's looking // at. // typedef uint8_t amDone_t; struct amRequest_base_t { chpl_arg_bundle_kind_t op; // operation c_nodeid_t node; // initiator's node amDone_t* pAmDone; // initiator's 'done' flag; may be NULL #ifdef CHPL_COMM_DEBUG uint64_t seq; #endif }; struct amRequest_RMA_t { struct amRequest_base_t b; void* addr; // address on AM target node void* raddr; // address on AM initiator's node size_t size; // number of bytes }; typedef union { int32_t i32; uint32_t u32; chpl_bool32 b32; int64_t i64; uint64_t u64; _real32 r32; _real64 r64; } chpl_amo_datum_t; struct amRequest_AMO_t { struct amRequest_base_t b; enum fi_op ofiOp; // ofi AMO op enum fi_datatype ofiType; // ofi object type int8_t size; // object size (bytes) void* obj; // object address on target node chpl_amo_datum_t opnd; // operand, if needed chpl_amo_datum_t cmpr; // comparand, if needed void* result; // result address on initiator's node }; struct amRequest_free_t { struct amRequest_base_t b; void* p; // address to free, on AM target node }; typedef union { struct amRequest_base_t b; struct amRequest_execOn_t xo; // present only to set the max req size struct amRequest_execOnLrg_t xol; struct amRequest_RMA_t rma; struct amRequest_AMO_t amo; struct amRequest_free_t free; } amRequest_t; struct taskArg_RMA_t { chpl_task_bundle_t hdr; struct amRequest_RMA_t rma; }; #ifdef CHPL_COMM_DEBUG static const char* am_opName(amOp_t); static const char* amo_opName(enum fi_op); static const char* amo_typeName(enum fi_datatype); static const char* am_seqIdStr(amRequest_t*); static const char* am_reqStr(c_nodeid_t, amRequest_t*, size_t); static const char* am_reqStartStr(amRequest_t*); static const char* am_reqDoneStr(amRequest_t*); static void am_debugPrep(amRequest_t*); #endif static void amRequestExecOn(c_nodeid_t, c_sublocid_t, chpl_fn_int_t, chpl_comm_on_bundle_t*, size_t, chpl_bool, chpl_bool); static void amRequestRmaPut(c_nodeid_t, void*, void*, size_t); static void amRequestRmaGet(c_nodeid_t, void*, void*, size_t); static void amRequestAMO(c_nodeid_t, void*, const void*, const void*, void*, int, enum fi_datatype, size_t); static void amRequestFree(c_nodeid_t, void*); static void amRequestNop(c_nodeid_t, chpl_bool, struct perTxCtxInfo_t*); static void amRequestCommon(c_nodeid_t, amRequest_t*, size_t, amDone_t**, chpl_bool, struct perTxCtxInfo_t*); static void amWaitForDone(amDone_t*); static chpl_bool setUpDelayedAmDone(chpl_comm_taskPrvData_t**, void**); void chpl_comm_execute_on(c_nodeid_t node, c_sublocid_t subloc, chpl_fn_int_t fid, chpl_comm_on_bundle_t *arg, size_t argSize, int ln, int32_t fn) { DBG_PRINTF(DBG_IFACE, "%s(%d, %d, %d, %p, %zd)", __func__, (int) node, (int) subloc, (int) fid, arg, argSize); CHK_TRUE(node != chpl_nodeID); // handled by the locale model if (chpl_comm_have_callbacks(chpl_comm_cb_event_kind_executeOn)) { chpl_comm_cb_info_t cb_data = {chpl_comm_cb_event_kind_executeOn, chpl_nodeID, node, .iu.executeOn={subloc, fid, arg, argSize, ln, fn}}; chpl_comm_do_callbacks (&cb_data); } chpl_comm_diags_verbose_executeOn("", node, ln, fn); chpl_comm_diags_incr(execute_on); amRequestExecOn(node, subloc, fid, arg, argSize, false, true); } void chpl_comm_execute_on_nb(c_nodeid_t node, c_sublocid_t subloc, chpl_fn_int_t fid, chpl_comm_on_bundle_t *arg, size_t argSize, int ln, int32_t fn) { DBG_PRINTF(DBG_IFACE, "%s(%d, %d, %d, %p, %zd)", __func__, (int) node, (int) subloc, (int) fid, arg, argSize); CHK_TRUE(node != chpl_nodeID); // handled by the locale model if (chpl_comm_have_callbacks(chpl_comm_cb_event_kind_executeOn_nb)) { chpl_comm_cb_info_t cb_data = {chpl_comm_cb_event_kind_executeOn_nb, chpl_nodeID, node, .iu.executeOn={subloc, fid, arg, argSize, ln, fn}}; chpl_comm_do_callbacks (&cb_data); } chpl_comm_diags_verbose_executeOn("non-blocking", node, ln, fn); chpl_comm_diags_incr(execute_on_nb); amRequestExecOn(node, subloc, fid, arg, argSize, false, false); } void chpl_comm_execute_on_fast(c_nodeid_t node, c_sublocid_t subloc, chpl_fn_int_t fid, chpl_comm_on_bundle_t *arg, size_t argSize, int ln, int32_t fn) { DBG_PRINTF(DBG_IFACE, "%s(%d, %d, %d, %p, %zd)", __func__, (int) node, (int) subloc, (int) fid, arg, argSize); CHK_TRUE(node != chpl_nodeID); // handled by the locale model if (chpl_comm_have_callbacks(chpl_comm_cb_event_kind_executeOn_fast)) { chpl_comm_cb_info_t cb_data = {chpl_comm_cb_event_kind_executeOn_fast, chpl_nodeID, node, .iu.executeOn={subloc, fid, arg, argSize, ln, fn}}; chpl_comm_do_callbacks (&cb_data); } chpl_comm_diags_verbose_executeOn("fast", node, ln, fn); chpl_comm_diags_incr(execute_on_fast); amRequestExecOn(node, subloc, fid, arg, argSize, true, true); } static inline void amRequestExecOn(c_nodeid_t node, c_sublocid_t subloc, chpl_fn_int_t fid, chpl_comm_on_bundle_t* arg, size_t argSize, chpl_bool fast, chpl_bool blocking) { assert(!isAmHandler); CHK_TRUE(!(fast && !blocking)); // handler doesn't expect fast nonblocking retireDelayedAmDone(false /*taskIsEnding*/); arg->comm = (chpl_comm_bundleData_t) { .fast = fast, .fid = fid, .node = chpl_nodeID, .subloc = subloc, .argSize = argSize, }; if (argSize <= sizeof(amRequest_t)) { // // The arg bundle will fit in max-sized AM request; just send it. // arg->kind = am_opExecOn; amRequestCommon(node, (amRequest_t*) arg, argSize, blocking ? (amDone_t**) &arg->comm.pAmDone : NULL, blocking /*yieldDuringTxnWait*/, NULL); } else { // // The arg bundle is too large for an AM request. Send a copy of // the header to the target and have it retrieve the payload part // itself. // // For the nonblocking case we have to make a copy of the caller's // payload because as soon as we return, the caller may destroy // the original. We also make a copy if the original is not in // registered memory and needs to be, in order to save the target // the overhead of doing an AM back to us to PUT the bundle to // itself. // arg->kind = am_opExecOnLrg; amRequest_t req = { .xol = { .hdr = *arg, .pPayload = &arg->payload, }, }; chpl_bool heapCopyArg = !blocking || !mrGetLocalKey(arg, argSize); if (heapCopyArg) { size_t payloadSize = argSize - offsetof(chpl_comm_on_bundle_t, payload); req.xol.pPayload = allocBounceBuf(payloadSize); memcpy(req.xol.pPayload, &arg->payload, payloadSize); } amRequestCommon(node, &req, sizeof(req.xol), blocking ? (amDone_t**) &req.xol.hdr.comm.pAmDone : NULL, blocking /*yieldDuringTxnWait*/, NULL); // // If blocking and we heap-copied the arg, free that now. The // nonblocking case has to be handled from the target side, since // only there do we know when we don't need the copy any more. // if (heapCopyArg && blocking) { freeBounceBuf(req.xol.pPayload); } } } static inline void amRequestRmaPut(c_nodeid_t node, void* addr, void* raddr, size_t size) { assert(!isAmHandler); retireDelayedAmDone(false /*taskIsEnding*/); // // Make sure the local address is remotely accessible. // void* myAddr = mrLocalizeSourceRemote(addr, size, "RMA via AM"); DBG_PRINTF(DBG_RMA | DBG_RMA_WRITE, "PUT %d:%p <= %p, size %zd, via AM GET", (int) node, raddr, myAddr, size); amRequest_t req = { .rma = { .b = { .op = am_opGet, // remote node does GET .node = chpl_nodeID, }, .addr = raddr, .raddr = myAddr, .size = size, }, }; amRequestCommon(node, &req, sizeof(req.rma), &req.b.pAmDone, true /*yieldDuringTxnWait*/, NULL); mrUnLocalizeSource(myAddr, addr); } static inline void amRequestRmaGet(c_nodeid_t node, void* addr, void* raddr, size_t size) { assert(!isAmHandler); retireDelayedAmDone(false /*taskIsEnding*/); // // Make sure the local address is remotely accessible. // void* myAddr = mrLocalizeTargetRemote(addr, size, "RMA via AM"); DBG_PRINTF(DBG_RMA | DBG_RMA_READ, "GET %p <= %d:%p, size %zd, via AM PUT", myAddr, (int) node, raddr, size); amRequest_t req = { .rma = { .b = { .op = am_opPut, // remote node does PUT .node = chpl_nodeID, }, .addr = raddr, .raddr = myAddr, .size = size, }, }; amRequestCommon(node, &req, sizeof(req.rma), &req.b.pAmDone, true /*yieldDuringTxnWait*/, NULL); mrUnLocalizeTarget(myAddr, addr, size); } static inline void amRequestAMO(c_nodeid_t node, void* object, const void* opnd, const void* cmpr, void* result, int ofiOp, enum fi_datatype ofiType, size_t size) { assert(!isAmHandler); DBG_PRINTF((ofiOp == FI_ATOMIC_READ) ? DBG_AMO_READ : DBG_AMO, "AMO via AM: obj %d:%p, opnd <%s>, cmpr <%s>, res %p, " "op %s, typ %s, sz %zd", (int) node, object, DBG_VAL(opnd, ofiType), DBG_VAL(cmpr, ofiType), result, amo_opName(ofiOp), amo_typeName(ofiType), size); struct perTxCtxInfo_t* tcip; CHK_TRUE((tcip = tciAlloc()) != NULL); void* myResult = result; // // If this is a non-fetching atomic and the task is ending (therefore // this is the _downEndCount()) we do it as a regular nonblocking AM. // If it's non-fetching and the task is not ending we may be able to // do it as a blocking AM but delay waiting for the 'done' indicator // until sometime later, when the next thing with MCM implications // comes along. Otherwise, we have to do it as a normal blocking AM. // chpl_bool delayBlocking = false; chpl_comm_taskPrvData_t* prvData = NULL; amDone_t* pAmDone = NULL; if (myResult == NULL) { delayBlocking = setUpDelayedAmDone(&prvData, (void**) &pAmDone); } else { myResult = mrLocalizeTargetRemote(myResult, size, "AMO result"); } amRequest_t req = { .amo = { .b = { .op = am_opAMO, .node = chpl_nodeID, .pAmDone = delayBlocking ? pAmDone : NULL, }, .ofiOp = ofiOp, .ofiType = ofiType, .size = size, .obj = object, .result = myResult, }, }; if (opnd != NULL) { memcpy(&req.amo.opnd, opnd, size); } if (cmpr != NULL) { memcpy(&req.amo.cmpr, cmpr, size); } amRequestCommon(node, &req, sizeof(req.amo), delayBlocking ? NULL : &req.b.pAmDone, true /*yieldDuringTxnWait*/, tcip); mrUnLocalizeTarget(myResult, result, size); tciFree(tcip); } static inline void amRequestFree(c_nodeid_t node, void* p) { amRequest_t req = { .free = { .b = { .op = am_opFree, .node = chpl_nodeID, }, .p = p, }, }; amRequestCommon(node, &req, sizeof(req.free), NULL, false /*yieldDuringTxnWait*/, NULL); } static inline void amRequestNop(c_nodeid_t node, chpl_bool blocking, struct perTxCtxInfo_t* tcip) { amRequest_t req = { .b = { .op = am_opNop, .node = chpl_nodeID, }, }; amRequestCommon(node, &req, sizeof(req.b), blocking ? &req.b.pAmDone : NULL, false /*yieldDuringTxnWait*/, tcip); } static inline void amRequestShutdown(c_nodeid_t node) { assert(!isAmHandler); amRequest_t req = { .b = { .op = am_opShutdown, .node = chpl_nodeID, }, }; amRequestCommon(node, &req, sizeof(req.b), NULL, true /*yieldDuringTxnWait*/, NULL); } typedef void (amReqFn_t)(c_nodeid_t node, amRequest_t* req, size_t reqSize, void* mrDesc, chpl_bool blocking, struct perTxCtxInfo_t* tcip); static amReqFn_t amReqFn_selector; static inline void amRequestCommon(c_nodeid_t node, amRequest_t* req, size_t reqSize, amDone_t** ppAmDone, chpl_bool yieldDuringTxnWait, struct perTxCtxInfo_t* tcip) { // // If blocking, make sure target can RMA PUT the indicator to us. // amDone_t amDone; amDone_t* pAmDone = NULL; if (ppAmDone != NULL) { pAmDone = mrLocalizeTargetRemote(&amDone, sizeof(*pAmDone), "AM done indicator"); *pAmDone = 0; chpl_atomic_thread_fence(memory_order_release); *ppAmDone = pAmDone; } #ifdef CHPL_COMM_DEBUG am_debugPrep(req); #endif struct perTxCtxInfo_t* myTcip = tcip; if (myTcip == NULL) { CHK_TRUE((myTcip = tciAlloc()) != NULL); } void* mrDesc; amRequest_t* myReq = mrLocalizeSource(&mrDesc, req, reqSize, "AM req"); amReqFn_selector(node, myReq, reqSize, mrDesc, (pAmDone != NULL) /*blocking*/, myTcip); if (tcip == NULL) { tciFree(myTcip); } mrUnLocalizeSource(myReq, req); if (pAmDone != NULL) { amWaitForDone(pAmDone); mrUnLocalizeSource(pAmDone, &amDone); // don't need or want target copyout } } static amReqFn_t amReqFn_msgOrdFence; static amReqFn_t amReqFn_msgOrd; static amReqFn_t amReqFn_dlvrCmplt; static inline void amReqFn_selector(c_nodeid_t node, amRequest_t* req, size_t reqSize, void* mrDesc, chpl_bool blocking, struct perTxCtxInfo_t* tcip) { switch (mcmMode) { case mcmm_msgOrdFence: amReqFn_msgOrdFence(node, req, reqSize, mrDesc, blocking, tcip); break; case mcmm_msgOrd: amReqFn_msgOrd(node, req, reqSize, mrDesc, blocking, tcip); break; case mcmm_dlvrCmplt: amReqFn_dlvrCmplt(node, req, reqSize, mrDesc, blocking, tcip); break; default: INTERNAL_ERROR_V("unexpected mcmMode %d", mcmMode); break; } } static ssize_t wrap_fi_send(c_nodeid_t node, amRequest_t* req, size_t reqSize, void* mrDesc, void* ctx, struct perTxCtxInfo_t* tcip); static ssize_t wrap_fi_inject(c_nodeid_t node, amRequest_t* req, size_t reqSize, struct perTxCtxInfo_t* tcip); static ssize_t wrap_fi_sendmsg(c_nodeid_t node, amRequest_t* req, size_t reqSize, void* mrDesc, void* ctx, uint64_t flags, struct perTxCtxInfo_t* tcip); // // Implements amRequestCommon() when MCM mode is message ordering with fences. // static void amReqFn_msgOrdFence(c_nodeid_t node, amRequest_t* req, size_t reqSize, void* mrDesc, chpl_bool blocking, struct perTxCtxInfo_t* tcip) { // // For on-stmts and AMOs that might modify their target variable, MCM // conformance requires us first to ensure that previous AMOs and PUTs // to any node are visible. Similarly, for GETs we have to ensure // that previous AMOs and PUTs to the target node are visible, and for // PUTs we have to ensure that previous AMOs to the target node are // visible. Do that here for all nodes except this op's target. For // that node, we'll use a fenced send instead. // chpl_bool havePutsOut = false; chpl_bool haveAmosOut = false; switch (req->b.op) { case am_opExecOn: case am_opExecOnLrg: forceMemFxVisAllNodes(true /*checkPuts*/, true /*checkAmos*/, node /*skipNode*/, tcip); havePutsOut = (tcip->putVisBitmap != NULL && bitmapTest(tcip->putVisBitmap, node)); haveAmosOut = (tcip->amoVisBitmap != NULL && bitmapTest(tcip->amoVisBitmap, node)); break; case am_opAMO: { chpl_bool amoHasMemFx = (req->amo.ofiOp != FI_ATOMIC_READ); forceMemFxVisAllNodes(amoHasMemFx /*checkPuts*/, true /*checkAmos*/, node /*skipNode*/, tcip); havePutsOut = (amoHasMemFx && tcip->putVisBitmap != NULL && bitmapTest(tcip->putVisBitmap, node)); haveAmosOut = (tcip->amoVisBitmap != NULL && bitmapTest(tcip->amoVisBitmap, node)); } break; case am_opGet: havePutsOut = (tcip->putVisBitmap != NULL && bitmapTest(tcip->putVisBitmap, node)); haveAmosOut = (tcip->amoVisBitmap != NULL && bitmapTest(tcip->amoVisBitmap, node)); break; case am_opPut: haveAmosOut = (tcip->amoVisBitmap != NULL && bitmapTest(tcip->amoVisBitmap, node)); break; } if (havePutsOut || haveAmosOut) { // // Special case: Do a fenced send if we need it for ordering with // respect to some prior operation(s). If we can inject, do so and // just collect the completion later. Otherwise, wait for it here. // if (!blocking && reqSize <= ofi_info->tx_attr->inject_size) { void* ctx = txnTrkEncodeId(__LINE__); uint64_t flags = FI_FENCE | FI_INJECT; (void) wrap_fi_sendmsg(node, req, reqSize, mrDesc, ctx, flags, tcip); } else { atomic_bool txnDone; atomic_init_bool(&txnDone, false); void* ctx = txnTrkEncodeDone(&txnDone); uint64_t flags = FI_FENCE; (void) wrap_fi_sendmsg(node, req, reqSize, mrDesc, ctx, flags, tcip); waitForTxnComplete(tcip, ctx); atomic_destroy_bool(&txnDone); } if (havePutsOut) { bitmapClear(tcip->putVisBitmap, node); } if (haveAmosOut) { bitmapClear(tcip->amoVisBitmap, node); } } else { // // General case. // atomic_bool txnDone; atomic_init_bool(&txnDone, false); void* ctx = txnTrkEncodeDone(&txnDone); (void) wrap_fi_send(node, req, reqSize, mrDesc, ctx, tcip); waitForTxnComplete(tcip, ctx); atomic_destroy_bool(&txnDone); } } // // Implements amRequestCommon() when MCM mode is message ordering. // static void amReqFn_msgOrd(c_nodeid_t node, amRequest_t* req, size_t reqSize, void* mrDesc, chpl_bool blocking, struct perTxCtxInfo_t* tcip) { // // For on-stmts and AMOs that might modify their target variable, MCM // conformance requires us first to ensure that all previous AMOs and // PUTs are visible. Similarly, for GET ops, we have to ensure that // AMOs and PUTs to the same node are visible. And for PUT ops, we // have to ensure that AMOs to the same node are visible. No other AM // operations depend on AMO or PUT visibility. // switch (req->b.op) { case am_opExecOn: case am_opExecOnLrg: forceMemFxVisAllNodes(true /*checkPuts*/, true /*checkAmos*/, -1 /*skipNode*/, tcip); break; case am_opAMO: if (req->amo.ofiOp != FI_ATOMIC_READ) { forceMemFxVisAllNodes(true /*checkPuts*/, true /*checkAmos*/, -1 /*skipNode*/, tcip); } break; case am_opGet: forceMemFxVisOneNode(node, true /*checkPuts*/, true /*checkAmos*/, tcip); break; case am_opPut: forceMemFxVisOneNode(node, false /*checkPuts*/, true /*checkAmos*/, tcip); break; } if (!blocking && reqSize <= ofi_info->tx_attr->inject_size) { // // Special case: injection is the quickest. We use that if this is // a non-blocking AM and the size doesn't exceed the injection size // limit. (We could even inject a small-enough AM request if this // were a blocking AM, but there's no point because we're going to // wait for it to get done on the target anyway.) // (void) wrap_fi_inject(node, req, reqSize, tcip); } else { // // General case. // atomic_bool txnDone; atomic_init_bool(&txnDone, false); void* ctx = txnTrkEncodeDone(&txnDone); (void) wrap_fi_send(node, req, reqSize, mrDesc, ctx, tcip); waitForTxnComplete(tcip, ctx); atomic_destroy_bool(&txnDone); } } // // Implements amRequestCommon() when MCM mode is delivery complete. // static void amReqFn_dlvrCmplt(c_nodeid_t node, amRequest_t* req, size_t reqSize, void* mrDesc, chpl_bool blocking, struct perTxCtxInfo_t* tcip) { atomic_bool txnDone; atomic_init_bool(&txnDone, false); void* ctx = txnTrkEncodeDone(&txnDone); (void) wrap_fi_send(node, req, reqSize, mrDesc, ctx, tcip); waitForTxnComplete(tcip, ctx); atomic_destroy_bool(&txnDone); } static inline ssize_t wrap_fi_send(c_nodeid_t node, amRequest_t* req, size_t reqSize, void* mrDesc, void* ctx, struct perTxCtxInfo_t* tcip) { if (DBG_TEST_MASK(DBG_AM | DBG_AM_SEND) || (req->b.op == am_opAMO && DBG_TEST_MASK(DBG_AMO))) { DBG_DO_PRINTF("tx AM send to %d: %s, ctx %p", (int) node, am_reqStr(node, req, reqSize), ctx); } OFI_RIDE_OUT_EAGAIN(tcip, fi_send(tcip->txCtx, req, reqSize, mrDesc, rxAddr(node), ctx)); tcip->numTxnsOut++; tcip->numTxnsSent++; return FI_SUCCESS; } static inline ssize_t wrap_fi_inject(c_nodeid_t node, amRequest_t* req, size_t reqSize, struct perTxCtxInfo_t* tcip) { if (DBG_TEST_MASK(DBG_AM | DBG_AM_SEND) || (req->b.op == am_opAMO && DBG_TEST_MASK(DBG_AMO))) { DBG_DO_PRINTF("tx AM send inject to %d: %s", (int) node, am_reqStr(node, req, reqSize)); } // TODO: How quickly/often does local resource throttling happen? OFI_RIDE_OUT_EAGAIN(tcip, fi_inject(tcip->txCtx, req, reqSize, rxAddr(node))); tcip->numTxnsSent++; return FI_SUCCESS; } static inline ssize_t wrap_fi_sendmsg(c_nodeid_t node, amRequest_t* req, size_t reqSize, void* mrDesc, void* ctx, uint64_t flags, struct perTxCtxInfo_t* tcip) { const struct iovec msg_iov = { .iov_base = req, .iov_len = reqSize }; const struct fi_msg msg = { .msg_iov = &msg_iov, .desc = mrDesc, .iov_count = 1, .addr = rxAddr(node), .context = ctx }; if (DBG_TEST_MASK(DBG_AM | DBG_AM_SEND) || (req->b.op == am_opAMO && DBG_TEST_MASK(DBG_AMO))) { DBG_DO_PRINTF("tx AM send msg to %d: %s, ctx %p, flags %#" PRIx64, (int) node, am_reqStr(node, req, reqSize), ctx, flags); } OFI_RIDE_OUT_EAGAIN(tcip, fi_sendmsg(tcip->txCtx, &msg, flags)); tcip->numTxnsOut++; tcip->numTxnsSent++; return FI_SUCCESS; } static inline void amWaitForDone(amDone_t* pAmDone) { // // Wait for completion indicator. // DBG_PRINTF(DBG_AM | DBG_AM_SEND, "waiting for amDone indication in %p", pAmDone); while (!*(volatile amDone_t*) pAmDone) { local_yield(); } DBG_PRINTF(DBG_AM | DBG_AM_SEND, "saw amDone indication in %p", pAmDone); } static inline chpl_bool setUpDelayedAmDone(chpl_comm_taskPrvData_t** pPrvData, void** ppAmDone) { // // Set up to record the completion of a delayed-blocking AM. // chpl_comm_taskPrvData_t* prvData; if ((*pPrvData = prvData = get_comm_taskPrvdata()) == NULL) { return false; } if (prvData->taskIsEnding) { // // This AMO is for our _downEndCount(). We don't care when that is // done because we won't do anything after it, and our parent only // cares about the effect on the endCount. Therefore, send back // *ppAmDone==NULL to make our caller do a regular non-blocking AM. // *ppAmDone = NULL; return true; } // // Otherwise, this will be an actual delayed-blocking AM, and we'll // use the task-private 'done' indicator for it. // *ppAmDone = &prvData->amDone; prvData->amDone = 0; chpl_atomic_thread_fence(memory_order_release); prvData->amDonePending = true; return true; } static inline void retireDelayedAmDone(chpl_bool taskIsEnding) { // // Wait for the completion of any delayed-blocking AM. // chpl_comm_taskPrvData_t* prvData = get_comm_taskPrvdata(); if (prvData != NULL) { if (prvData->amDonePending) { amWaitForDone((amDone_t*) &prvData->amDone); prvData->amDonePending = false; } if (taskIsEnding) { prvData->taskIsEnding = true; } } } //////////////////////////////////////// // // Handler-side active message support // static int numAmHandlersActive; static pthread_cond_t amStartStopCond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t amStartStopMutex = PTHREAD_MUTEX_INITIALIZER; static void amHandler(void*); static void processRxAmReq(struct perTxCtxInfo_t*); static void amHandleExecOn(chpl_comm_on_bundle_t*); static void amWrapExecOnBody(void*); static void amHandleExecOnLrg(chpl_comm_on_bundle_t*); static void amWrapExecOnLrgBody(struct amRequest_execOnLrg_t*); static void amWrapGet(struct taskArg_RMA_t*); static void amWrapPut(struct taskArg_RMA_t*); static void amHandleAMO(struct amRequest_AMO_t*); static void amPutDone(c_nodeid_t, amDone_t*); static void amCheckLiveness(void); static void doCpuAMO(void*, const void*, const void*, void*, enum fi_op, enum fi_datatype, size_t size); static void init_amHandling(void) { // // Sanity checks. // { chpl_comm_taskPrvData_t pd; CHK_TRUE(sizeof(pd.amDone) >= sizeof(amDone_t)); } // // Start AM handler thread(s). Don't proceed from here until at // least one is running. // atomic_init_bool(&amHandlersExit, false); PTHREAD_CHK(pthread_mutex_lock(&amStartStopMutex)); for (int i = 0; i < numAmHandlers; i++) { CHK_TRUE(chpl_task_createCommTask(amHandler, NULL) == 0); } PTHREAD_CHK(pthread_cond_wait(&amStartStopCond, &amStartStopMutex)); PTHREAD_CHK(pthread_mutex_unlock(&amStartStopMutex)); } static void fini_amHandling(void) { if (chpl_numNodes <= 1) return; // // Tear down the AM handler thread(s). On node 0, don't proceed from // here until the last one has finished. // PTHREAD_CHK(pthread_mutex_lock(&amStartStopMutex)); atomic_store_bool(&amHandlersExit, true); PTHREAD_CHK(pthread_cond_wait(&amStartStopCond, &amStartStopMutex)); PTHREAD_CHK(pthread_mutex_unlock(&amStartStopMutex)); atomic_destroy_bool(&amHandlersExit); } // // The AM handler runs this. // static __thread struct perTxCtxInfo_t* amTcip; static void amHandler(void* argNil) { struct perTxCtxInfo_t* tcip; CHK_TRUE((tcip = tciAllocForAmHandler()) != NULL); amTcip = tcip; isAmHandler = true; DBG_PRINTF(DBG_AM, "AM handler running"); // // Count this AM handler thread as running. The creator thread // wants to be released as soon as at least one AM handler thread // is running, so if we're the first, do that. // PTHREAD_CHK(pthread_mutex_lock(&amStartStopMutex)); if (++numAmHandlersActive == 1) PTHREAD_CHK(pthread_cond_signal(&amStartStopCond)); PTHREAD_CHK(pthread_mutex_unlock(&amStartStopMutex)); // // Process AM requests and watch transmit responses arrive. // while (!atomic_load_bool(&amHandlersExit)) { chpl_bool hadRxEvent, hadTxEvent; amCheckRxTxCmpls(&hadRxEvent, &hadTxEvent, tcip); if (hadRxEvent) { processRxAmReq(tcip); } else if (!hadTxEvent) { // // No activity; avoid CPU monopolization. // int ret; OFI_CHK_3(fi_wait(ofi_amhWaitSet, 100 /*ms*/), ret, -FI_EINTR, -FI_ETIMEDOUT); } if (amDoLivenessChecks) { amCheckLiveness(); } } // // Un-count this AM handler thread. Whoever told us to exit wants to // be released once all the AM handler threads are done, so if we're // the last, do that. // PTHREAD_CHK(pthread_mutex_lock(&amStartStopMutex)); if (--numAmHandlersActive == 0) PTHREAD_CHK(pthread_cond_signal(&amStartStopCond)); PTHREAD_CHK(pthread_mutex_unlock(&amStartStopMutex)); DBG_PRINTF(DBG_AM, "AM handler done"); } static void processRxAmReq(struct perTxCtxInfo_t* tcip) { // // Process requests received on the AM request endpoint. // struct fi_cq_data_entry cqes[5]; const size_t maxEvents = sizeof(cqes) / sizeof(cqes[0]); ssize_t ret; CHK_TRUE((ret = fi_cq_read(ofi_rxCQ, cqes, maxEvents)) > 0 || ret == -FI_EAGAIN || ret == -FI_EAVAIL); if (ret == -FI_EAVAIL) { reportCQError(ofi_rxCQ); } const size_t numEvents = (ret == -FI_EAGAIN) ? 0 : ret; for (int i = 0; i < numEvents; i++) { if ((cqes[i].flags & FI_RECV) != 0) { // // This event is for an inbound AM request. Handle it. // amRequest_t* req = (amRequest_t*) cqes[i].buf; DBG_PRINTF(DBG_AM_BUF, "CQ rx AM req @ buffer offset %zd, sz %zd, seqId %s", (char*) req - (char*) ofi_iov_reqs[ofi_msg_i].iov_base, cqes[i].len, am_seqIdStr(req)); DBG_PRINTF(DBG_AM | DBG_AM_RECV, "rx AM req: %s", am_reqStr(chpl_nodeID, req, cqes[i].len)); switch (req->b.op) { case am_opExecOn: if (req->xo.hdr.comm.fast) { amWrapExecOnBody(&req->xo.hdr); } else { amHandleExecOn(&req->xo.hdr); } break; case am_opExecOnLrg: amHandleExecOnLrg(&req->xol.hdr); break; case am_opGet: { struct taskArg_RMA_t arg = { .hdr.kind = CHPL_ARG_BUNDLE_KIND_TASK, .rma = req->rma, }; chpl_task_startMovedTask(FID_NONE, (chpl_fn_p) amWrapGet, &arg, sizeof(arg), c_sublocid_any, chpl_nullTaskID); } break; case am_opPut: { struct taskArg_RMA_t arg = { .hdr.kind = CHPL_ARG_BUNDLE_KIND_TASK, .rma = req->rma, }; chpl_task_startMovedTask(FID_NONE, (chpl_fn_p) amWrapPut, &arg, sizeof(arg), c_sublocid_any, chpl_nullTaskID); } break; case am_opAMO: amHandleAMO(&req->amo); break; case am_opFree: CHPL_FREE(req->free.p); break; case am_opNop: DBG_PRINTF(DBG_AM | DBG_AM_RECV, "%s", am_reqDoneStr(req)); if (req->b.pAmDone != NULL) { amPutDone(req->b.node, req->b.pAmDone); } break; case am_opShutdown: chpl_signal_shutdown(); break; default: INTERNAL_ERROR_V("unexpected AM op %d", (int) req->b.op); break; } } if ((cqes[i].flags & FI_MULTI_RECV) != 0) { // // Multi-receive buffer filled; post the other one. // ofi_msg_i = 1 - ofi_msg_i; OFI_CHK(fi_recvmsg(ofi_rxEp, &ofi_msg_reqs[ofi_msg_i], FI_MULTI_RECV)); DBG_PRINTF(DBG_AM_BUF, "re-post fi_recvmsg(AMLZs %p, len %#zx)", ofi_msg_reqs[ofi_msg_i].msg_iov->iov_base, ofi_msg_reqs[ofi_msg_i].msg_iov->iov_len); } CHK_TRUE((cqes[i].flags & ~(FI_MSG | FI_RECV | FI_MULTI_RECV)) == 0); } } static void amHandleExecOn(chpl_comm_on_bundle_t* req) { chpl_comm_bundleData_t* comm = &req->comm; chpl_task_startMovedTask(comm->fid, (chpl_fn_p) amWrapExecOnBody, req, comm->argSize, comm->subloc, chpl_nullTaskID); } static inline void amWrapExecOnBody(void* p) { DBG_PRINTF(DBG_AM | DBG_AM_RECV, "%s", am_reqStartStr(p)); chpl_comm_bundleData_t* comm = &((chpl_comm_on_bundle_t*) p)->comm; chpl_ftable_call(comm->fid, p); forceMemFxVisAllNodes_noTcip(true /*checkPuts*/, true /*checkAmos*/); DBG_PRINTF(DBG_AM | DBG_AM_RECV, "%s", am_reqDoneStr(p)); if (comm->pAmDone != NULL) { amPutDone(comm->node, comm->pAmDone); } } static inline void amHandleExecOnLrg(chpl_comm_on_bundle_t* req) { struct amRequest_execOnLrg_t* xol = (struct amRequest_execOnLrg_t*) req; xol->hdr.kind = am_opExecOn; // was am_opExecOnLrg, to direct us here chpl_task_startMovedTask(FID_NONE, (chpl_fn_p) amWrapExecOnLrgBody, xol, sizeof(*xol), xol->hdr.comm.subloc, chpl_nullTaskID); } static void amWrapExecOnLrgBody(struct amRequest_execOnLrg_t* xol) { DBG_PRINTF(DBG_AM | DBG_AM_RECV, "%s", am_reqStartStr((amRequest_t*) xol)); // // TODO: We could stack-allocate "bundle" here, if it was small enough // (TBD) not to create the potential for stack overflow. Some // systems have fast enough networks that saving the dynamic // alloc should be performance-visible. // // // The bundle header is in our argument, but we have to retrieve the // payload from the initiating side. // chpl_comm_bundleData_t* comm = &xol->hdr.comm; c_nodeid_t node = comm->node; chpl_comm_on_bundle_t* bundle; CHPL_CALLOC_SZ(bundle, 1, comm->argSize); *bundle = xol->hdr; size_t payloadSize = comm->argSize - offsetof(chpl_comm_on_bundle_t, payload); CHK_TRUE(mrGetKey(NULL, NULL, node, xol->pPayload, payloadSize)); (void) ofi_get(&bundle->payload, node, xol->pPayload, payloadSize); // // Iff this is a nonblocking executeOn, now that we have the payload // we can free the copy of it on the initiating side. In the blocking // case the initiator will free it if that is necessary, since they // have to wait for the whole executeOn to complete anyway. We save // some time here by not waiting for a network response. Either we or // someone else will consume that completion later. In the meantime // we can go ahead with the executeOn body. // if (comm->pAmDone == NULL) { amRequestFree(node, xol->pPayload); } // // Now we can finally call the body function. // chpl_ftable_call(bundle->comm.fid, bundle); forceMemFxVisAllNodes_noTcip(true /*checkPuts*/, true /*checkAmos*/); DBG_PRINTF(DBG_AM | DBG_AM_RECV, "%s", am_reqDoneStr((amRequest_t*) xol)); if (comm->pAmDone != NULL) { amPutDone(node, comm->pAmDone); } CHPL_FREE(bundle); } static void amWrapGet(struct taskArg_RMA_t* tsk_rma) { struct amRequest_RMA_t* rma = &tsk_rma->rma; DBG_PRINTF(DBG_AM | DBG_AM_RECV, "%s", am_reqStartStr((amRequest_t*) rma)); CHK_TRUE(mrGetKey(NULL, NULL, rma->b.node, rma->raddr, rma->size)); (void) ofi_get(rma->addr, rma->b.node, rma->raddr, rma->size); DBG_PRINTF(DBG_AM | DBG_AM_RECV, "%s", am_reqDoneStr((amRequest_t*) rma)); amPutDone(rma->b.node, rma->b.pAmDone); } static void amWrapPut(struct taskArg_RMA_t* tsk_rma) { struct amRequest_RMA_t* rma = &tsk_rma->rma; DBG_PRINTF(DBG_AM | DBG_AM_RECV, "%s", am_reqStartStr((amRequest_t*) rma)); CHK_TRUE(mrGetKey(NULL, NULL, rma->b.node, rma->raddr, rma->size)); (void) ofi_put(rma->addr, rma->b.node, rma->raddr, rma->size); // // Note: the RMA bytes must be visible in target memory before the // 'done' indicator is. // DBG_PRINTF(DBG_AM | DBG_AM_RECV, "%s", am_reqDoneStr((amRequest_t*) rma)); amPutDone(rma->b.node, rma->b.pAmDone); } static void amHandleAMO(struct amRequest_AMO_t* amo) { DBG_PRINTF(DBG_AM | DBG_AM_RECV, "%s", am_reqStartStr((amRequest_t*) amo)); assert(amo->b.node != chpl_nodeID); // should be handled on initiator chpl_amo_datum_t result; size_t resSize = amo->size; doCpuAMO(amo->obj, &amo->opnd, &amo->cmpr, &result, amo->ofiOp, amo->ofiType, amo->size); if (amo->result != NULL) { CHK_TRUE(mrGetKey(NULL, NULL, amo->b.node, amo->result, resSize)); (void) ofi_put(&result, amo->b.node, amo->result, resSize); // // Note: the result must be visible in target memory before the // 'done' indicator is. // } DBG_PRINTF(DBG_AM | DBG_AM_RECV, "%s", am_reqDoneStr((amRequest_t*) amo)); if (amo->b.pAmDone != NULL) { amPutDone(amo->b.node, amo->b.pAmDone); } } static inline void amPutDone(c_nodeid_t node, amDone_t* pAmDone) { static __thread amDone_t* amDone = NULL; static __thread void* mrDesc; if (amDone == NULL) { amDone = allocBounceBuf(1); *amDone = 1; CHK_TRUE(mrGetDesc(&mrDesc, amDone, sizeof(amDone))); } struct perTxCtxInfo_t* tcip = amTcip; // NULL if not AM handler task/thread if (tcip == NULL) { CHK_TRUE((tcip = tciAlloc()) != NULL); } // // Send the 'done' indicator. If necessary, first make sure the // memory effects of all communication ops done by this AM are // visible. We and the AM's initiator are the same Chapel task, // for purposes of MCM conformance, and the memory effects of the // AM must be visible to that initiator by the time it sees the // 'done' indicator. In the delivery-complete mode everything is // already visible. In the message-order mode we don't have to // force PUT visibility because this 'done' is also a PUT and we // use write-after-write message ordering, but we do have to force // AMO visibility. In message-order-fence mode we have to force // both PUT and AMO visibility. // if (mcmMode != mcmm_dlvrCmplt) { forceMemFxVisAllNodes(mcmMode == mcmm_msgOrdFence /*checkPuts*/, true /*checkAmos*/, -1 /*skipNode*/, tcip); } uint64_t mrKey = 0; uint64_t mrRaddr = 0; CHK_TRUE(mrGetKey(&mrKey, &mrRaddr, node, pAmDone, sizeof(*pAmDone))); ofi_put_lowLevel(amDone, mrDesc, node, mrRaddr, mrKey, sizeof(*pAmDone), txnTrkEncodeId(__LINE__), FI_INJECT, tcip); if (amTcip == NULL) { tciFree(tcip); } } static inline void amCheckLiveness(void) { // // Only node 0 does liveness checks. It cycles through the others, // checking to make sure we can AM to them. To minimize overhead, we // try not to do a liveness check any more frequently than about every // 10 seconds and we also try not to make time calls much more often // than that, because they're expensive. A "liveness check" is really // just a check that we can send a no-op AM without an unrecoverable // error resulting. That's sufficient to get us an -EMFILE return if // we run up against the open file limit, for example. // const double timeInterval = 10.0; static __thread double lastTime = 0.0; static __thread int countInterval = 10000; static __thread int count; if (lastTime == 0.0) { // // The first time we've been called, initialize. // lastTime = chpl_comm_ofi_time_get(); count = countInterval; } else if (--count == 0) { // // After the first time, do the "liveness" checks and adjust the // counter interval as needed. // double time = chpl_comm_ofi_time_get(); double timeRatio = (time - lastTime) / timeInterval; const double minTimeRatio = 3.0 / 4.0; const double maxTimeRatio = 4.0 / 3.0; if (timeRatio < minTimeRatio) { timeRatio = minTimeRatio; } else if (timeRatio > maxTimeRatio) { timeRatio = maxTimeRatio; } countInterval /= timeRatio; static __thread c_nodeid_t node = 1; if (--node == 0) { node = chpl_numNodes - 1; } amRequestNop(node, false /*blocking*/, amTcip); count = countInterval; lastTime = time; } } //////////////////////////////////////// // // Interface: RMA // chpl_comm_nb_handle_t chpl_comm_put_nb(void* addr, c_nodeid_t node, void* raddr, size_t size, int32_t commID, int ln, int32_t fn) { chpl_comm_put(addr, node, raddr, size, commID, ln, fn); return NULL; } chpl_comm_nb_handle_t chpl_comm_get_nb(void* addr, c_nodeid_t node, void* raddr, size_t size, int32_t commID, int ln, int32_t fn) { chpl_comm_get(addr, node, raddr, size, commID, ln, fn); return NULL; } int chpl_comm_test_nb_complete(chpl_comm_nb_handle_t h) { chpl_comm_diags_incr(test_nb); // fi_cq_readfrom? return ((void*) h) == NULL; } void chpl_comm_wait_nb_some(chpl_comm_nb_handle_t* h, size_t nhandles) { chpl_comm_diags_incr(wait_nb); size_t i; // fi_cq_readfrom? for( i = 0; i < nhandles; i++ ) { CHK_TRUE(h[i] == NULL); } } int chpl_comm_try_nb_some(chpl_comm_nb_handle_t* h, size_t nhandles) { chpl_comm_diags_incr(try_nb); size_t i; // fi_cq_readfrom? for( i = 0; i < nhandles; i++ ) { CHK_TRUE(h[i] == NULL); } return 0; } void chpl_comm_put(void* addr, c_nodeid_t node, void* raddr, size_t size, int32_t commID, int ln, int32_t fn) { DBG_PRINTF(DBG_IFACE, "%s(%p, %d, %p, %zd, %d)", __func__, addr, (int) node, raddr, size, (int) commID); retireDelayedAmDone(false /*taskIsEnding*/); // // Sanity checks, self-communication. // CHK_TRUE(addr != NULL); CHK_TRUE(raddr != NULL); if (size == 0) { return; } if (node == chpl_nodeID) { memmove(raddr, addr, size); return; } // Communications callback support if (chpl_comm_have_callbacks(chpl_comm_cb_event_kind_put)) { chpl_comm_cb_info_t cb_data = {chpl_comm_cb_event_kind_put, chpl_nodeID, node, .iu.comm={addr, raddr, size, commID, ln, fn}}; chpl_comm_do_callbacks (&cb_data); } chpl_comm_diags_verbose_rdma("put", node, size, ln, fn, commID); chpl_comm_diags_incr(put); (void) ofi_put(addr, node, raddr, size); } void chpl_comm_get(void* addr, int32_t node, void* raddr, size_t size, int32_t commID, int ln, int32_t fn) { DBG_PRINTF(DBG_IFACE, "%s(%p, %d, %p, %zd, %d)", __func__, addr, (int) node, raddr, size, (int) commID); retireDelayedAmDone(false /*taskIsEnding*/); // // Sanity checks, self-communication. // CHK_TRUE(addr != NULL); CHK_TRUE(raddr != NULL); if (size == 0) { return; } if (node == chpl_nodeID) { memmove(addr, raddr, size); return; } // Communications callback support if (chpl_comm_have_callbacks(chpl_comm_cb_event_kind_get)) { chpl_comm_cb_info_t cb_data = {chpl_comm_cb_event_kind_get, chpl_nodeID, node, .iu.comm={addr, raddr, size, commID, ln, fn}}; chpl_comm_do_callbacks (&cb_data); } chpl_comm_diags_verbose_rdma("get", node, size, ln, fn, commID); chpl_comm_diags_incr(get); (void) ofi_get(addr, node, raddr, size); } void chpl_comm_put_strd(void* dstaddr_arg, size_t* dststrides, c_nodeid_t dstnode, void* srcaddr_arg, size_t* srcstrides, size_t* count, int32_t stridelevels, size_t elemSize, int32_t commID, int ln, int32_t fn) { DBG_PRINTF(DBG_IFACE, "%s(%p, %p, %d, %p, %p, %p, %d, %zd, %d)", __func__, dstaddr_arg, dststrides, (int) dstnode, srcaddr_arg, srcstrides, count, (int) stridelevels, elemSize, (int) commID); put_strd_common(dstaddr_arg, dststrides, dstnode, srcaddr_arg, srcstrides, count, stridelevels, elemSize, 1, NULL, commID, ln, fn); } void chpl_comm_get_strd(void* dstaddr_arg, size_t* dststrides, c_nodeid_t srcnode, void* srcaddr_arg, size_t* srcstrides, size_t* count, int32_t stridelevels, size_t elemSize, int32_t commID, int ln, int32_t fn) { DBG_PRINTF(DBG_IFACE, "%s(%p, %p, %d, %p, %p, %p, %d, %zd, %d)", __func__, dstaddr_arg, dststrides, (int) srcnode, srcaddr_arg, srcstrides, count, (int) stridelevels, elemSize, (int) commID); get_strd_common(dstaddr_arg, dststrides, srcnode, srcaddr_arg, srcstrides, count, stridelevels, elemSize, 1, NULL, commID, ln, fn); } void chpl_comm_getput_unordered(c_nodeid_t dstnode, void* dstaddr, c_nodeid_t srcnode, void* srcaddr, size_t size, int32_t commID, int ln, int32_t fn) { DBG_PRINTF(DBG_IFACE, "%s(%d, %p, %d, %p, %zd, %d)", __func__, (int) dstnode, dstaddr, (int) srcnode, srcaddr, size, (int) commID); assert(dstaddr != NULL); assert(srcaddr != NULL); if (size == 0) return; if (dstnode == chpl_nodeID && srcnode == chpl_nodeID) { retireDelayedAmDone(false /*taskIsEnding*/); memmove(dstaddr, srcaddr, size); return; } if (dstnode == chpl_nodeID) { chpl_comm_get_unordered(dstaddr, srcnode, srcaddr, size, commID, ln, fn); } else if (srcnode == chpl_nodeID) { chpl_comm_put_unordered(srcaddr, dstnode, dstaddr, size, commID, ln, fn); } else { if (size <= MAX_UNORDERED_TRANS_SZ) { char buf[MAX_UNORDERED_TRANS_SZ]; chpl_comm_get(buf, srcnode, srcaddr, size, commID, ln, fn); chpl_comm_put(buf, dstnode, dstaddr, size, commID, ln, fn); } else { // Note, we do not expect this case to trigger, but if it does we may // want to do on-stmt to src node and then transfer char* buf = chpl_mem_alloc(size, CHPL_RT_MD_COMM_PER_LOC_INFO, 0, 0); chpl_comm_get(buf, srcnode, srcaddr, size, commID, ln, fn); chpl_comm_put(buf, dstnode, dstaddr, size, commID, ln, fn); chpl_mem_free(buf, 0, 0); } } } void chpl_comm_get_unordered(void* addr, c_nodeid_t node, void* raddr, size_t size, int32_t commID, int ln, int32_t fn) { DBG_PRINTF(DBG_IFACE, "%s(%p, %d, %p, %zd, %d)", __func__, addr, (int) node, raddr, size, (int) commID); retireDelayedAmDone(false /*taskIsEnding*/); // // Sanity checks, self-communication. // CHK_TRUE(addr != NULL); CHK_TRUE(raddr != NULL); if (size == 0) { return; } if (node == chpl_nodeID) { memmove(addr, raddr, size); return; } // Communications callback support if (chpl_comm_have_callbacks(chpl_comm_cb_event_kind_get)) { chpl_comm_cb_info_t cb_data = {chpl_comm_cb_event_kind_get, chpl_nodeID, node, .iu.comm={addr, raddr, size, commID, ln, fn}}; chpl_comm_do_callbacks (&cb_data); } chpl_comm_diags_verbose_rdma("unordered get", node, size, ln, fn, commID); chpl_comm_diags_incr(get); do_remote_get_buff(addr, node, raddr, size); } void chpl_comm_put_unordered(void* addr, c_nodeid_t node, void* raddr, size_t size, int32_t commID, int ln, int32_t fn) { DBG_PRINTF(DBG_IFACE, "%s(%p, %d, %p, %zd, %d)", __func__, addr, (int) node, raddr, size, (int) commID); retireDelayedAmDone(false /*taskIsEnding*/); // // Sanity checks, self-communication. // CHK_TRUE(addr != NULL); CHK_TRUE(raddr != NULL); if (size == 0) { return; } if (node == chpl_nodeID) { memmove(raddr, addr, size); return; } // Communications callback support if (chpl_comm_have_callbacks(chpl_comm_cb_event_kind_put)) { chpl_comm_cb_info_t cb_data = {chpl_comm_cb_event_kind_put, chpl_nodeID, node, .iu.comm={addr, raddr, size, commID, ln, fn}}; chpl_comm_do_callbacks (&cb_data); } chpl_comm_diags_verbose_rdma("unordered put", node, size, ln, fn, commID); chpl_comm_diags_incr(put); do_remote_put_buff(addr, node, raddr, size); } void chpl_comm_getput_unordered_task_fence(void) { DBG_PRINTF(DBG_IFACE_MCM, "%s()", __func__); task_local_buff_flush(get_buff | put_buff); } //////////////////////////////////////// // // Internal communication support // static struct perTxCtxInfo_t* tciAllocCommon(chpl_bool); static struct perTxCtxInfo_t* findFreeTciTabEntry(chpl_bool); static __thread struct perTxCtxInfo_t* _ttcip; static inline struct perTxCtxInfo_t* tciAlloc(void) { return tciAllocCommon(false /*bindToAmHandler*/); } static inline struct perTxCtxInfo_t* tciAllocForAmHandler(void) { return tciAllocCommon(true /*bindToAmHandler*/); } static inline struct perTxCtxInfo_t* tciAllocCommon(chpl_bool bindToAmHandler) { if (_ttcip != NULL) { // // If the last tx context we used is bound to our thread or can be // re-allocated, use that. // if (_ttcip->bound) { DBG_PRINTF(DBG_TCIPS, "realloc bound tciTab[%td]", _ttcip - tciTab); return _ttcip; } if (tciAllocTabEntry(_ttcip)) { DBG_PRINTF(DBG_TCIPS, "realloc tciTab[%td]", _ttcip - tciTab); return _ttcip; } } // // Find a tx context that isn't busy and use that one. If this is // for either the AM handler or a tasking layer fixed worker thread, // bind it permanently. // _ttcip = findFreeTciTabEntry(bindToAmHandler); if (bindToAmHandler || (tciTabBindTxCtxs && chpl_task_isFixedThread())) { _ttcip->bound = true; _ttcip->putVisBitmap = bitmapAlloc(chpl_numNodes); if ((ofi_info->caps & FI_ATOMIC) != 0) { _ttcip->amoVisBitmap = bitmapAlloc(chpl_numNodes); } } DBG_PRINTF(DBG_TCIPS, "alloc%s tciTab[%td]", _ttcip->bound ? " bound" : "", _ttcip - tciTab); return _ttcip; } static struct perTxCtxInfo_t* findFreeTciTabEntry(chpl_bool bindToAmHandler) { // // Find a tx context that isn't busy. Note that tx contexts for // AM handlers and other threads come out of different blocks of // the table. // const int numWorkerTxCtxs = tciTabLen - numAmHandlers; struct perTxCtxInfo_t* tcip; if (bindToAmHandler) { // // AM handlers use tciTab[numWorkerTxCtxs .. tciTabLen - 1]. For // now we only support a single AM handler, so this is simple. If // we ever have more, the CHK_FALSE will force us to revisit this. // tcip = &tciTab[numWorkerTxCtxs]; CHK_TRUE(tciAllocTabEntry(tcip)); return tcip; } // // Workers use tciTab[0 .. numWorkerTxCtxs - 1]. Search forever for // an entry we can use. Give up (and kill the program) only if we // discover they're all bound, because if that's true we can predict // we'll never find a free one. // static __thread int last_iw = 0; tcip = NULL; do { int iw = last_iw; chpl_bool allBound = true; do { if (++iw >= numWorkerTxCtxs) iw = 0; allBound = allBound && tciTab[iw].bound; if (tciAllocTabEntry(&tciTab[iw])) { tcip = &tciTab[iw]; } } while (tcip == NULL && iw != last_iw); if (tcip == NULL) { CHK_FALSE(allBound); local_yield(); } } while (tcip == NULL); return tcip; } // // This returns true if you successfully allocated the given tciTab // entry and false otherwise. // static inline chpl_bool tciAllocTabEntry(struct perTxCtxInfo_t* tcip) { return(!atomic_exchange_bool(&tcip->allocated, true)); } static inline void tciFree(struct perTxCtxInfo_t* tcip) { // // Bound contexts stay bound. We only release non-bound ones. // if (!tcip->bound) { DBG_PRINTF(DBG_TCIPS, "free tciTab[%td]", tcip - tciTab); atomic_store_bool(&tcip->allocated, false); } } static inline void waitForCQSpace(struct perTxCtxInfo_t* tcip, size_t len) { // // Make sure we have at least the given number of free CQ entries. // if (tcip->txCQ != NULL && txCQLen - tcip->numTxnsOut < len) { (*tcip->checkTxCmplsFn)(tcip); while (txCQLen - tcip->numTxnsOut < len) { sched_yield(); (*tcip->checkTxCmplsFn)(tcip); } } } typedef chpl_comm_nb_handle_t (rmaPutFn_t)(void* myAddr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, struct perTxCtxInfo_t* tcip); static rmaPutFn_t rmaPutFn_selector; static inline chpl_comm_nb_handle_t ofi_put(const void* addr, c_nodeid_t node, void* raddr, size_t size) { // // Don't ask the provider to transfer more than it wants to. // if (size > ofi_info->ep_attr->max_msg_size) { DBG_PRINTF(DBG_RMA | DBG_RMA_WRITE, "splitting large PUT %d:%p <= %p, size %zd", (int) node, raddr, addr, size); size_t chunkSize = ofi_info->ep_attr->max_msg_size; for (size_t i = 0; i < size; i += chunkSize) { if (chunkSize > size - i) { chunkSize = size - i; } (void) ofi_put(&((const char*) addr)[i], node, &((char*) raddr)[i], chunkSize); } return NULL; } DBG_PRINTF(DBG_RMA | DBG_RMA_WRITE, "PUT %d:%p <= %p, size %zd", (int) node, raddr, addr, size); // // If the remote address is directly accessible do an RMA from this // side; otherwise do the opposite RMA from the other side. // chpl_comm_nb_handle_t ret; uint64_t mrKey; uint64_t mrRaddr; if (mrGetKey(&mrKey, &mrRaddr, node, raddr, size)) { struct perTxCtxInfo_t* tcip; CHK_TRUE((tcip = tciAlloc()) != NULL); assert(tcip->txCQ != NULL); // PUTs require a CQ, at least for now waitForCQSpace(tcip, 1); void* mrDesc; void* myAddr = mrLocalizeSource(&mrDesc, addr, size, "PUT src"); ret = rmaPutFn_selector(myAddr, mrDesc, node, mrRaddr, mrKey, size, tcip); mrUnLocalizeSource(myAddr, addr); tciFree(tcip); } else { amRequestRmaPut(node, (void*) addr, raddr, size); ret = NULL; } return ret; } static rmaPutFn_t rmaPutFn_msgOrdFence; static rmaPutFn_t rmaPutFn_msgOrd; static rmaPutFn_t rmaPutFn_dlvrCmplt; static inline chpl_comm_nb_handle_t rmaPutFn_selector(void* myAddr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, struct perTxCtxInfo_t* tcip) { chpl_comm_nb_handle_t ret = NULL; switch (mcmMode) { case mcmm_msgOrdFence: ret = rmaPutFn_msgOrdFence(myAddr, mrDesc, node, mrRaddr, mrKey, size, tcip); break; case mcmm_msgOrd: ret = rmaPutFn_msgOrd(myAddr, mrDesc, node, mrRaddr, mrKey, size, tcip); break; case mcmm_dlvrCmplt: ret = rmaPutFn_dlvrCmplt(myAddr, mrDesc, node, mrRaddr, mrKey, size, tcip); break; default: INTERNAL_ERROR_V("unexpected mcmMode %d", mcmMode); break; } return ret; } static ssize_t wrap_fi_write(const void* addr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, struct perTxCtxInfo_t* tcip); static ssize_t wrap_fi_inject_write(const void* addr, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, struct perTxCtxInfo_t* tcip); static ssize_t wrap_fi_writemsg(const void* addr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, uint64_t flags, struct perTxCtxInfo_t* tcip); // // Implements ofi_put() when MCM mode is message ordering with fences. // static chpl_comm_nb_handle_t rmaPutFn_msgOrdFence(void* myAddr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, struct perTxCtxInfo_t* tcip) { if (tcip->bound && size <= ofi_info->tx_attr->inject_size && (tcip->amoVisBitmap == NULL || !bitmapTest(tcip->amoVisBitmap, node))) { // // Special case: write injection has the least latency. We can use // that if this PUT doesn't need a fence, its size doesn't exceed // the injection size limit, and we have a bound tx context so we // can delay forcing the memory visibility until later. // (void) wrap_fi_inject_write(myAddr, node, mrRaddr, mrKey, size, tcip); } else { atomic_bool txnDone; atomic_init_bool(&txnDone, false); void* ctx = txnTrkEncodeDone(&txnDone); if (tcip->bound && bitmapTest(tcip->amoVisBitmap, node)) { // // Special case: If our last operation was an AMO (which can only // be true with a bound tx context) then we need to do a fenced // PUT to force the AMO to complete before this PUT. We may still // be able to inject the PUT, though. // uint64_t flags = FI_FENCE; if (size <= ofi_info->tx_attr->inject_size) { flags |= FI_INJECT; } (void) wrap_fi_writemsg(myAddr, mrDesc, node, mrRaddr, mrKey, size, ctx, flags, tcip); } else { // // General case. // (void) wrap_fi_write(myAddr, mrDesc, node, mrRaddr, mrKey, size, ctx, tcip); } waitForTxnComplete(tcip, ctx); atomic_destroy_bool(&txnDone); } // // When using message ordering we have to do something after the PUT // to force it into visibility, and on the same tx context as the PUT // itself because libfabric message ordering is specific to endpoint // pairs. With a bound tx context we can do it later, when needed. // Otherwise we have to do it here, before we release the tx context. // if (tcip->bound) { bitmapSet(tcip->putVisBitmap, node); } else { mcmReleaseOneNode(node, tcip, "PUT"); } return NULL; } // // Implements ofi_put() when MCM mode is message ordering. // static chpl_comm_nb_handle_t rmaPutFn_msgOrd(void* myAddr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, struct perTxCtxInfo_t* tcip) { // // When using message ordering we have to do something after the PUT // to force it into visibility, and on the same tx context as the PUT // itself because libfabric message ordering is specific to endpoint // pairs. With a bound tx context we can do it later, when needed. // Otherwise we have to do it here, before we release the tx context. // if (tcip->bound && size <= ofi_info->tx_attr->inject_size) { // // Special case: write injection has the least latency. We can use // that if this PUT's size doesn't exceed the injection size limit // and we have a bound tx context so we can delay forcing the // memory visibility until later. // (void) wrap_fi_inject_write(myAddr, node, mrRaddr, mrKey, size, tcip); } else { // // General case. // atomic_bool txnDone; atomic_init_bool(&txnDone, false); void* ctx = txnTrkEncodeDone(&txnDone); (void) wrap_fi_write(myAddr, mrDesc, node, mrRaddr, mrKey, size, ctx, tcip); waitForTxnComplete(tcip, ctx); atomic_destroy_bool(&txnDone); } if (tcip->bound) { bitmapSet(tcip->putVisBitmap, node); } else { mcmReleaseOneNode(node, tcip, "PUT"); } return NULL; } // // Implements ofi_put() when MCM mode is delivery complete. // static chpl_comm_nb_handle_t rmaPutFn_dlvrCmplt(void* myAddr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, struct perTxCtxInfo_t* tcip) { atomic_bool txnDone; atomic_init_bool(&txnDone, false); void* ctx = txnTrkEncodeDone(&txnDone); (void) wrap_fi_write(myAddr, mrDesc, node, mrRaddr, mrKey, size, ctx, tcip); waitForTxnComplete(tcip, ctx); atomic_destroy_bool(&txnDone); return NULL; } static inline ssize_t wrap_fi_write(const void* addr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, struct perTxCtxInfo_t* tcip) { DBG_PRINTF(DBG_RMA | DBG_RMA_WRITE, "tx write: %d:%#" PRIx64 " <= %p, size %zd, ctx %p", (int) node, mrRaddr, addr, size, ctx); OFI_RIDE_OUT_EAGAIN(tcip, fi_write(tcip->txCtx, addr, size, mrDesc, rxAddr(node), mrRaddr, mrKey, ctx)); tcip->numTxnsOut++; tcip->numTxnsSent++; return FI_SUCCESS; } static inline ssize_t wrap_fi_inject_write(const void* addr, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, struct perTxCtxInfo_t* tcip) { DBG_PRINTF(DBG_RMA | DBG_RMA_WRITE, "tx write inject: %d:%#" PRIx64 " <= %p, size %zd", (int) node, mrRaddr, addr, size); // TODO: How quickly/often does local resource throttling happen? OFI_RIDE_OUT_EAGAIN(tcip, fi_inject_write(tcip->txCtx, addr, size, rxAddr(node), mrRaddr, mrKey)); tcip->numTxnsSent++; return FI_SUCCESS; } static inline ssize_t wrap_fi_writemsg(const void* addr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, uint64_t flags, struct perTxCtxInfo_t* tcip) { struct iovec msg_iov = (struct iovec) { .iov_base = (void*) addr, .iov_len = size }; struct fi_rma_iov rma_iov = (struct fi_rma_iov) { .addr = (uint64_t) mrRaddr, .len = size, .key = mrKey }; struct fi_msg_rma msg = (struct fi_msg_rma) { .msg_iov = &msg_iov, .desc = mrDesc, .iov_count = 1, .addr = rxAddr(node), .rma_iov = &rma_iov, .rma_iov_count = 1, .context = ctx }; DBG_PRINTF(DBG_RMA | DBG_RMA_WRITE, "tx write msg: %d:%#" PRIx64 " <= %p, size %zd, ctx %p, " "flags %#" PRIx64, (int) node, mrRaddr, addr, size, ctx, flags); OFI_RIDE_OUT_EAGAIN(tcip, fi_writemsg(tcip->txCtx, &msg, flags)); tcip->numTxnsOut++; tcip->numTxnsSent++; return FI_SUCCESS; } static inline void ofi_put_lowLevel(const void* addr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, uint64_t flags, struct perTxCtxInfo_t* tcip) { if (flags == FI_INJECT && size <= ofi_info->tx_attr->inject_size) { (void) wrap_fi_inject_write(addr, node, mrRaddr, mrKey, size, tcip); } else if (flags == 0) { (void) wrap_fi_write(addr, mrDesc, node, mrRaddr, mrKey, size, ctx, tcip); } else { (void) wrap_fi_writemsg(addr, mrDesc, node, mrRaddr, mrKey, size, ctx, flags, tcip); } } static void ofi_put_V(int v_len, void** addr_v, void** local_mr_v, c_nodeid_t* locale_v, void** raddr_v, uint64_t* remote_mr_v, size_t* size_v) { DBG_PRINTF(DBG_RMA | DBG_RMA_WRITE | DBG_RMA_UNORD, "put_V(%d): %d:%p <= %p, size %zd, key 0x%" PRIx64, v_len, (int) locale_v[0], raddr_v[0], addr_v[0], size_v[0], remote_mr_v[0]); assert(!isAmHandler); struct perTxCtxInfo_t* tcip; CHK_TRUE((tcip = tciAlloc()) != NULL); // // Make sure we have enough free CQ entries to initiate the entire // batch of transactions. // waitForCQSpace(tcip, v_len); // // Initiate the batch. Record which nodes we PUT to, so that we can // force them to be visible in target memory at the end. // if (tcip->putVisBitmap == NULL) { tcip->putVisBitmap = bitmapAlloc(chpl_numNodes); } for (int vi = 0; vi < v_len; vi++) { (void) wrap_fi_writemsg(addr_v[vi], &local_mr_v[vi], locale_v[vi], (uint64_t) raddr_v[vi], remote_mr_v[vi], size_v[vi], txnTrkEncodeId(__LINE__), ((vi < v_len - 1) ? FI_MORE : 0), tcip); bitmapSet(tcip->putVisBitmap, locale_v[vi]); } // // Enforce Chapel MCM: force all of the above PUTs to appear in // target memory. // mcmReleaseAllNodes(tcip->putVisBitmap, NULL, -1 /*skipNode*/, tcip, "unordered PUT"); tciFree(tcip); } /* *** START OF BUFFERED PUT OPERATIONS *** * * Support for buffered PUT operations. We internally buffer PUT operations and * then initiate them all at once for increased transaction rate. */ // Flush buffered PUTs for the specified task info and reset the counter. static inline void put_buff_task_info_flush(put_buff_task_info_t* info) { if (info->vi > 0) { DBG_PRINTF(DBG_RMA_UNORD, "put_buff_task_info_flush(): info has %d entries", info->vi); ofi_put_V(info->vi, info->src_addr_v, info->local_mr_v, info->locale_v, info->tgt_addr_v, info->remote_mr_v, info->size_v); info->vi = 0; } } static inline void do_remote_put_buff(void* addr, c_nodeid_t node, void* raddr, size_t size) { uint64_t mrKey; uint64_t mrRaddr; put_buff_task_info_t* info; if (size > MAX_UNORDERED_TRANS_SZ || !mrGetKey(&mrKey, &mrRaddr, node, raddr, size) || (info = task_local_buff_acquire(put_buff)) == NULL) { (void) ofi_put(addr, node, raddr, size); return; } void* mrDesc; CHK_TRUE(mrGetDesc(&mrDesc, info->src_v, size)); int vi = info->vi; memcpy(&info->src_v[vi], addr, size); info->src_addr_v[vi] = &info->src_v[vi]; info->locale_v[vi] = node; info->tgt_addr_v[vi] = (void*) mrRaddr; info->size_v[vi] = size; info->remote_mr_v[vi] = mrKey; info->local_mr_v[vi] = mrDesc; info->vi++; DBG_PRINTF(DBG_RMA_UNORD, "do_remote_put_buff(): info[%d] = " "{%p, %d, %p, %zd, %" PRIx64 ", %p}", vi, info->src_addr_v[vi], (int) node, raddr, size, mrKey, mrDesc); // flush if buffers are full if (info->vi == MAX_CHAINED_PUT_LEN) { put_buff_task_info_flush(info); } } /*** END OF BUFFERED PUT OPERATIONS ***/ typedef chpl_comm_nb_handle_t (rmaGetFn_t)(void* myAddr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, struct perTxCtxInfo_t* tcip); static rmaGetFn_t rmaGetFn_selector; static inline chpl_comm_nb_handle_t ofi_get(void* addr, c_nodeid_t node, void* raddr, size_t size) { // // Don't ask the provider to transfer more than it wants to. // if (size > ofi_info->ep_attr->max_msg_size) { DBG_PRINTF(DBG_RMA | DBG_RMA_READ, "splitting large GET %p <= %d:%p, size %zd", addr, (int) node, raddr, size); size_t chunkSize = ofi_info->ep_attr->max_msg_size; for (size_t i = 0; i < size; i += chunkSize) { if (chunkSize > size - i) { chunkSize = size - i; } (void) ofi_get(&((char*) addr)[i], node, &((char*) raddr)[i], chunkSize); } return NULL; } DBG_PRINTF(DBG_RMA | DBG_RMA_READ, "GET %p <= %d:%p, size %zd", addr, (int) node, raddr, size); // // If the remote address is directly accessible do an RMA from this // side; otherwise do the opposite RMA from the other side. // chpl_comm_nb_handle_t ret; uint64_t mrKey; uint64_t mrRaddr; if (mrGetKey(&mrKey, &mrRaddr, node, raddr, size)) { struct perTxCtxInfo_t* tcip; CHK_TRUE((tcip = tciAlloc()) != NULL); waitForCQSpace(tcip, 1); void* mrDesc; void* myAddr = mrLocalizeTarget(&mrDesc, addr, size, "GET tgt"); atomic_bool txnDone; atomic_init_bool(&txnDone, false); void* ctx = (tcip->txCQ == NULL) ? txnTrkEncodeId(__LINE__) : txnTrkEncodeDone(&txnDone); ret = rmaGetFn_selector(myAddr, mrDesc, node, mrRaddr, mrKey, size, ctx, tcip); waitForTxnComplete(tcip, ctx); atomic_destroy_bool(&txnDone); mrUnLocalizeTarget(myAddr, addr, size); tciFree(tcip); } else { amRequestRmaGet(node, addr, raddr, size); ret = NULL; } return ret; } static rmaGetFn_t rmaGetFn_msgOrdFence; static rmaGetFn_t rmaGetFn_msgOrd; static rmaGetFn_t rmaGetFn_dlvrCmplt; static inline chpl_comm_nb_handle_t rmaGetFn_selector(void* myAddr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, struct perTxCtxInfo_t* tcip) { chpl_comm_nb_handle_t ret = NULL; switch (mcmMode) { case mcmm_msgOrdFence: ret = rmaGetFn_msgOrdFence(myAddr, mrDesc, node, mrRaddr, mrKey, size, ctx, tcip); break; case mcmm_msgOrd: ret = rmaGetFn_msgOrd(myAddr, mrDesc, node, mrRaddr, mrKey, size, ctx, tcip); break; case mcmm_dlvrCmplt: ret = rmaGetFn_dlvrCmplt(myAddr, mrDesc, node, mrRaddr, mrKey, size, ctx, tcip); break; default: INTERNAL_ERROR_V("unexpected mcmMode %d", mcmMode); break; } return ret; } static ssize_t wrap_fi_read(void* addr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, struct perTxCtxInfo_t* tcip); static ssize_t wrap_fi_readmsg(void* addr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, uint64_t flags, struct perTxCtxInfo_t* tcip); // // Implements ofi_get() when MCM mode is message ordering with fences. // static chpl_comm_nb_handle_t rmaGetFn_msgOrdFence(void* myAddr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, struct perTxCtxInfo_t* tcip) { chpl_bool havePutsOut = tcip->putVisBitmap != NULL && bitmapTest(tcip->putVisBitmap, node); chpl_bool haveAmosOut = tcip->amoVisBitmap != NULL && bitmapTest(tcip->amoVisBitmap, node); if (havePutsOut || haveAmosOut) { // // Special case: If our last operation was a write whose memory // effects might not be visible yet (which can only be true with // a bound tx context) then this GET needs to be fenced to force // that visibility. // (void) wrap_fi_readmsg(myAddr, mrDesc, node, mrRaddr, mrKey, size, ctx, FI_FENCE, tcip); if (havePutsOut) { bitmapClear(tcip->putVisBitmap, node); } if (haveAmosOut) { bitmapClear(tcip->amoVisBitmap, node); } } else { // // General case. // (void) wrap_fi_read(myAddr, mrDesc, node, mrRaddr, mrKey, size, ctx, tcip); } return NULL; } // // Implements ofi_get() when MCM mode is message ordering. // static chpl_comm_nb_handle_t rmaGetFn_msgOrd(void* myAddr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, struct perTxCtxInfo_t* tcip) { // // This GET will force any outstanding PUT to the same node to be // visible. // if (tcip->bound) { if (tcip->putVisBitmap != NULL) { bitmapClear(tcip->putVisBitmap, node); } if (tcip->amoVisBitmap != NULL) { bitmapClear(tcip->amoVisBitmap, node); } } (void) wrap_fi_read(myAddr, mrDesc, node, mrRaddr, mrKey, size, ctx, tcip); return NULL; } // // Implements ofi_get() when MCM mode is delivery complete. // static chpl_comm_nb_handle_t rmaGetFn_dlvrCmplt(void* myAddr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, struct perTxCtxInfo_t* tcip) { (void) wrap_fi_read(myAddr, mrDesc, node, mrRaddr, mrKey, size, ctx, tcip); return NULL; } static inline ssize_t wrap_fi_read(void* addr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, struct perTxCtxInfo_t* tcip) { DBG_PRINTF(DBG_RMA | DBG_RMA_READ, "tx read: %p <= %d:%#" PRIx64 ", size %zd, ctx %p", addr, (int) node, mrRaddr, size, ctx); OFI_RIDE_OUT_EAGAIN(tcip, fi_read(tcip->txCtx, addr, size, mrDesc, rxAddr(node), mrRaddr, mrKey, ctx)); tcip->numTxnsOut++; tcip->numTxnsSent++; return FI_SUCCESS; } static inline ssize_t wrap_fi_readmsg(void* addr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, uint64_t flags, struct perTxCtxInfo_t* tcip) { struct iovec msg_iov = (struct iovec) { .iov_base = addr, .iov_len = size }; struct fi_rma_iov rma_iov = (struct fi_rma_iov) { .addr = (uint64_t) mrRaddr, .len = size, .key = mrKey }; struct fi_msg_rma msg = (struct fi_msg_rma) { .msg_iov = &msg_iov, .desc = mrDesc, .iov_count = 1, .addr = rxAddr(node), .rma_iov = &rma_iov, .rma_iov_count = 1, .context = ctx }; DBG_PRINTF(DBG_RMA | DBG_RMA_READ, "tx read msg: %p <= %d:%#" PRIx64 ", size %zd, ctx %p, " "flags %#" PRIx64, addr, (int) node, mrRaddr, size, ctx, flags); OFI_RIDE_OUT_EAGAIN(tcip, fi_readmsg(tcip->txCtx, &msg, flags)); tcip->numTxnsOut++; tcip->numTxnsSent++; return FI_SUCCESS; } static inline void ofi_get_lowLevel(void* addr, void* mrDesc, c_nodeid_t node, uint64_t mrRaddr, uint64_t mrKey, size_t size, void* ctx, uint64_t flags, struct perTxCtxInfo_t* tcip) { if (flags == 0) { (void) wrap_fi_read(addr, mrDesc, node, mrRaddr, mrKey, size, ctx, tcip); } else { (void) wrap_fi_readmsg(addr, mrDesc, node, mrRaddr, mrKey, size, ctx, flags, tcip); } } static void ofi_get_V(int v_len, void** addr_v, void** local_mr_v, c_nodeid_t* locale_v, void** raddr_v, uint64_t* remote_mr_v, size_t* size_v) { DBG_PRINTF(DBG_RMA | DBG_RMA_READ | DBG_RMA_UNORD, "get_V(%d): %p <= %d:%p, size %zd, key 0x%" PRIx64, v_len, addr_v[0], (int) locale_v[0], raddr_v[0], size_v[0], remote_mr_v[0]); assert(!isAmHandler); struct perTxCtxInfo_t* tcip; CHK_TRUE((tcip = tciAlloc()) != NULL); // // Make sure we have enough free CQ entries to initiate the entire // batch of transactions. // waitForCQSpace(tcip, v_len); for (int vi = 0; vi < v_len; vi++) { struct iovec msg_iov = (struct iovec) { .iov_base = addr_v[vi], .iov_len = size_v[vi] }; struct fi_rma_iov rma_iov = (struct fi_rma_iov) { .addr = (uint64_t) raddr_v[vi], .len = size_v[vi], .key = remote_mr_v[vi] }; struct fi_msg_rma msg = (struct fi_msg_rma) { .msg_iov = &msg_iov, .desc = &local_mr_v[vi], .iov_count = 1, .addr = rxAddr(locale_v[vi]), .rma_iov = &rma_iov, .rma_iov_count = 1, .context = txnTrkEncodeId(__LINE__), .data = 0 }; DBG_PRINTF(DBG_RMA | DBG_RMA_READ, "tx readmsg: %p <= %d:%p, size %zd, key 0x%" PRIx64, msg.msg_iov->iov_base, (int) locale_v[vi], (void*) msg.rma_iov->addr, msg.msg_iov->iov_len, msg.rma_iov->key); tcip->numTxnsOut++; tcip->numTxnsSent++; if (tcip->numTxnsOut < txCQLen && vi < v_len - 1) { // Add another transaction to the group and go on without waiting. OFI_RIDE_OUT_EAGAIN(tcip, fi_readmsg(tcip->txCtx, &msg, FI_MORE)); } else { // Initiate last transaction in group and wait for whole group. OFI_RIDE_OUT_EAGAIN(tcip, fi_readmsg(tcip->txCtx, &msg, 0)); while (tcip->numTxnsOut > 0) { (*tcip->ensureProgressFn)(tcip); } } } tciFree(tcip); } /* *** START OF BUFFERED GET OPERATIONS *** * * Support for buffered GET operations. We internally buffer GET operations and * then initiate them all at once for increased transaction rate. */ // Flush buffered GETs for the specified task info and reset the counter. static inline void get_buff_task_info_flush(get_buff_task_info_t* info) { if (info->vi > 0) { DBG_PRINTF(DBG_RMA_UNORD, "get_buff_task_info_flush(): info has %d entries", info->vi); ofi_get_V(info->vi, info->tgt_addr_v, info->local_mr_v, info->locale_v, info->src_addr_v, info->remote_mr_v, info->size_v); info->vi = 0; } } static inline void do_remote_get_buff(void* addr, c_nodeid_t node, void* raddr, size_t size) { uint64_t mrKey; uint64_t mrRaddr; get_buff_task_info_t* info; if (size > MAX_UNORDERED_TRANS_SZ || !mrGetKey(&mrKey, &mrRaddr, node, raddr, size) || (info = task_local_buff_acquire(get_buff)) == NULL) { (void) ofi_get(addr, node, raddr, size); return; } void* mrDesc; CHK_TRUE(mrGetDesc(&mrDesc, addr, size)); int vi = info->vi; info->tgt_addr_v[vi] = addr; info->locale_v[vi] = node; info->remote_mr_v[vi] = mrKey; info->src_addr_v[vi] = (void*) mrRaddr; info->size_v[vi] = size; info->local_mr_v[vi] = mrDesc; info->vi++; DBG_PRINTF(DBG_RMA_UNORD, "do_remote_get_buff(): info[%d] = " "{%p, %d, %" PRIx64 ", %p, %zd, %p}", vi, addr, (int) node, mrKey, raddr, size, mrDesc); // flush if buffers are full if (info->vi == MAX_CHAINED_GET_LEN) { get_buff_task_info_flush(info); } } /*** END OF BUFFERED GET OPERATIONS ***/ struct amoBundle_t { struct fi_msg_atomic m; struct fi_ioc iovOpnd; void* mrDescOpnd; struct fi_rma_ioc iovObj; struct fi_ioc iovCmpr; void* mrDescCmpr; struct fi_ioc iovRes; void* mrDescRes; c_nodeid_t node; size_t size; }; typedef chpl_comm_nb_handle_t (amoFn_t)(struct amoBundle_t *ab, struct perTxCtxInfo_t* tcip); static amoFn_t amoFn_selector; static chpl_comm_nb_handle_t ofi_amo(c_nodeid_t node, uint64_t object, uint64_t mrKey, const void* opnd, const void* cmpr, void* result, enum fi_op ofiOp, enum fi_datatype ofiType, size_t size) { if (ofiOp == FI_ATOMIC_READ && opnd == NULL && provCtl_readAmoNeedsOpnd) { // // Workaround for bug wherein operand is unused but nevertheless // must not be NULL. // static int64_t dummy; opnd = &dummy; } // // Any or all of these may be NULL but it's clearer and, with inlining, // just as fast to simply make the calls. // void* mrDescOpnd; void* myOpnd = mrLocalizeSource(&mrDescOpnd, opnd, size, "AMO operand"); void* mrDescCmpr; void* myCmpr = mrLocalizeSource(&mrDescCmpr, cmpr, size, "AMO comparand"); void* mrDescRes; void* myRes = mrLocalizeTarget(&mrDescRes, result, size, "AMO result"); struct amoBundle_t ab = { .m = { .msg_iov = &ab.iovOpnd, .desc = &ab.mrDescOpnd, .iov_count = 1, .addr = rxAddr(node), .rma_iov = &ab.iovObj, .rma_iov_count = 1, .datatype = ofiType, .op = ofiOp, }, .iovOpnd = { .addr = myOpnd, .count = 1, }, .mrDescOpnd = mrDescOpnd, .iovObj = { .addr = object, .count = 1, .key = mrKey, }, .iovCmpr = { .addr = myCmpr, .count = 1, }, .mrDescCmpr = mrDescCmpr, .iovRes = { .addr = myRes, .count = 1, }, .mrDescRes = mrDescRes, .node = node, .size = size, }; struct perTxCtxInfo_t* tcip; CHK_TRUE((tcip = tciAlloc()) != NULL); assert(tcip->txCQ != NULL); // AMOs require a CQ, at least for now chpl_comm_nb_handle_t ret; ret = amoFn_selector(&ab, tcip); tciFree(tcip); mrUnLocalizeTarget(myRes, result, size); mrUnLocalizeSource(myCmpr, cmpr); mrUnLocalizeSource(myOpnd, opnd); return ret; } static amoFn_t amoFn_msgOrdFence; static amoFn_t amoFn_msgOrd; static amoFn_t amoFn_dlvrCmplt; static inline chpl_comm_nb_handle_t amoFn_selector(struct amoBundle_t *ab, struct perTxCtxInfo_t* tcip) { chpl_comm_nb_handle_t ret = NULL; switch (mcmMode) { case mcmm_msgOrdFence: ret = amoFn_msgOrdFence(ab, tcip); break; case mcmm_msgOrd: ret = amoFn_msgOrd(ab, tcip); break; case mcmm_dlvrCmplt: ret = amoFn_dlvrCmplt(ab, tcip); break; default: INTERNAL_ERROR_V("unexpected mcmMode %d", mcmMode); break; } return ret; } static ssize_t wrap_fi_inject_atomic(struct amoBundle_t* ab, struct perTxCtxInfo_t* tcip); static ssize_t wrap_fi_atomicmsg(struct amoBundle_t* ab, uint64_t flags, struct perTxCtxInfo_t* tcip); // // Implements ofi_amo() when MCM mode is message ordering with fences. // static chpl_comm_nb_handle_t amoFn_msgOrdFence(struct amoBundle_t *ab, struct perTxCtxInfo_t* tcip) { if (ab->iovRes.addr == NULL && tcip->bound && ab->size <= ofi_info->tx_attr->inject_size && (tcip->putVisBitmap == NULL || !bitmapTest(tcip->putVisBitmap, ab->node))) { // // Special case: injection is the quickest. We can use that if // this is a non-fetching operation, we have a bound tx context so // we can delay forcing the memory visibility until later, the size // doesn't exceed the injection size limit, and we don't need a // fence because the last thing we did to the same target node was // not a PUT. // (void) wrap_fi_inject_atomic(ab, tcip); } else { // // If we need a result wait for it; otherwise, we can collect // the completion later and message ordering will ensure MCM // conformance. // atomic_bool txnDone; atomic_init_bool(&txnDone, false); if (ab->iovRes.addr != NULL) { ab->m.context = txnTrkEncodeDone(&txnDone); } if (tcip->bound && tcip->putVisBitmap != NULL && bitmapTest(tcip->putVisBitmap, ab->node)) { // // Special case: If our last operation to the same remote node was // a PUT (which we only see with a bound tx context) then we need // to do a fenced AMO to force the PUT to complete before this // AMO. We may still be able to inject the AMO, however. // uint64_t flags = FI_FENCE; if (ab->size <= ofi_info->tx_attr->inject_size) { flags |= FI_INJECT; } (void) wrap_fi_atomicmsg(ab, flags, tcip); bitmapClear(tcip->putVisBitmap, ab->node); } else { // // General case. // (void) wrap_fi_atomicmsg(ab, 0, tcip); } if (ab->iovRes.addr != NULL) { waitForTxnComplete(tcip, ab->m.context); } atomic_destroy_bool(&txnDone); } // // When using message ordering we have to do something after the // operation to force it into visibility, and on the same tx context // as the operation itself because libfabric message ordering is // specific to endpoint pairs. With a bound tx context we can do it // later, when needed. Otherwise we have to do it now. // if (tcip->bound) { bitmapSet(tcip->amoVisBitmap, ab->node); } else { mcmReleaseOneNode(ab->node, tcip, "AMO"); } return NULL; } // // Implements ofi_amo() when MCM mode is message ordering. // static chpl_comm_nb_handle_t amoFn_msgOrd(struct amoBundle_t *ab, struct perTxCtxInfo_t* tcip) { if (ab->m.op != FI_ATOMIC_READ) { forceMemFxVisAllNodes(true /*checkPuts*/, true /*checkAmos*/, -1 /*skipNode*/, tcip); } if (tcip->bound && ab->iovRes.addr == NULL && ab->size <= ofi_info->tx_attr->inject_size) { // // Special case: injection is the quickest. We can use that if this // is a non-fetching operation, we have a bound tx context so we can // delay forcing the memory visibility until later, and the size // doesn't exceed the injection size limit. // (void) wrap_fi_inject_atomic(ab, tcip); } else { // // General case. // // If we need a result wait for it; otherwise, message ordering will // ensure MCM conformance and we can collect the completion later. // if (ab->iovRes.addr == NULL) { (void) wrap_fi_atomicmsg(ab, 0, tcip); } else { atomic_bool txnDone; atomic_init_bool(&txnDone, false); ab->m.context = txnTrkEncodeDone(&txnDone); (void) wrap_fi_atomicmsg(ab, 0, tcip); waitForTxnComplete(tcip, ab->m.context); atomic_destroy_bool(&txnDone); } } // // When using message ordering we have to do something after the // operation to force it into visibility, and on the same tx context // as the operation itself because libfabric message ordering is // specific to endpoint pairs. With a bound tx context we can do it // later, when needed. Otherwise we have to do it now. // if (tcip->bound) { bitmapSet(tcip->amoVisBitmap, ab->node); } else { mcmReleaseOneNode(ab->node, tcip, "AMO"); } return NULL; } // // Implements ofi_amo() when MCM mode is delivery complete. // static chpl_comm_nb_handle_t amoFn_dlvrCmplt(struct amoBundle_t *ab, struct perTxCtxInfo_t* tcip) { atomic_bool txnDone; atomic_init_bool(&txnDone, false); ab->m.context = txnTrkEncodeDone(&txnDone); (void) wrap_fi_atomicmsg(ab, 0, tcip); waitForTxnComplete(tcip, ab->m.context); atomic_destroy_bool(&txnDone); return NULL; } static inline ssize_t wrap_fi_inject_atomic(struct amoBundle_t* ab, struct perTxCtxInfo_t* tcip) { DBG_PRINTF(DBG_AMO, "tx AMO (inject): obj %d:%#" PRIx64 ", opnd <%s>, " "op %s, typ %s, sz %zd", (int) ab->node, ab->iovObj.addr, DBG_VAL(ab->iovOpnd.addr, ab->m.datatype), amo_opName(ab->m.op), amo_typeName(ab->m.datatype), ab->size); // TODO: How quickly/often does local resource throttling happen? OFI_RIDE_OUT_EAGAIN(tcip, fi_inject_atomic(tcip->txCtx, ab->iovOpnd.addr, 1, ab->m.addr, ab->iovObj.addr, ab->iovObj.key, ab->m.datatype, ab->m.op)); tcip->numTxnsSent++; return FI_SUCCESS; } static inline ssize_t wrap_fi_atomicmsg(struct amoBundle_t* ab, uint64_t flags, struct perTxCtxInfo_t* tcip) { if (ab->iovRes.addr == NULL) { // Non-fetching. DBG_PRINTF(DBG_AMO, "tx AMO (msg): obj %d:%#" PRIx64 ", opnd <%s>, " "op %s, typ %s, sz %zd, ctx %p, flags %#" PRIx64, (int) ab->node, ab->iovObj.addr, DBG_VAL(ab->iovOpnd.addr, ab->m.datatype), amo_opName(ab->m.op), amo_typeName(ab->m.datatype), ab->size, ab->m.context, flags); OFI_CHK(fi_atomicmsg(tcip->txCtx, &ab->m, flags)); } else { // Fetching. if (ab->m.op == FI_CSWAP) { // CSWAP, operand + comparand. DBG_PRINTF(DBG_AMO, "tx AMO (msg): obj %d:%#" PRIx64 ", opnd <%s>, cmpr <%s>, " "op %s, typ %s, res %p, sz %zd, ctx %p, flags %#" PRIx64, (int) ab->node, ab->iovObj.addr, DBG_VAL(ab->iovOpnd.addr, ab->m.datatype), DBG_VAL(ab->iovCmpr.addr, ab->m.datatype), amo_opName(ab->m.op), amo_typeName(ab->m.datatype), ab->iovRes.addr, ab->size, ab->m.context, flags); OFI_CHK(fi_compare_atomicmsg(tcip->txCtx, &ab->m, &ab->iovCmpr, &ab->mrDescCmpr, 1, &ab->iovRes, &ab->mrDescRes, 1, 0)); } else { // Fetching, but no comparand. if (ab->m.op == FI_ATOMIC_READ) { DBG_PRINTF(DBG_AMO_READ, "tx AMO (msg): obj %d:%#" PRIx64 ", " "op %s, typ %s, res %p, sz %zd, ctx %p, flags %#" PRIx64, (int) ab->node, ab->iovObj.addr, amo_opName(ab->m.op), amo_typeName(ab->m.datatype), ab->iovRes.addr, ab->size, ab->m.context, flags); } else { DBG_PRINTF(DBG_AMO, "tx AMO (msg): obj %d:%#" PRIx64 ", opnd <%s>, " "op %s, typ %s, res %p, sz %zd, ctx %p, flags %#" PRIx64, (int) ab->node, ab->iovObj.addr, DBG_VAL(ab->iovOpnd.addr, ab->m.datatype), amo_opName(ab->m.op), amo_typeName(ab->m.datatype), ab->iovRes.addr, ab->size, ab->m.context, flags); } OFI_CHK(fi_fetch_atomicmsg(tcip->txCtx, &ab->m, &ab->iovRes, &ab->mrDescRes, 1, 0)); } } tcip->numTxnsOut++; tcip->numTxnsSent++; return FI_SUCCESS; } static void ofi_amo_nf_V(int v_len, uint64_t* opnd_v, void* local_mr, c_nodeid_t* locale_v, void** object_v, uint64_t* remote_mr_v, size_t* size_v, enum fi_op* cmd_v, enum fi_datatype* type_v) { DBG_PRINTF(DBG_AMO | DBG_AMO_UNORD, "amo_nf_V(%d): obj %d:%p, opnd <%s>, op %s, typ %s, sz %zd, " "key 0x%" PRIx64, v_len, (int) locale_v[0], object_v[0], DBG_VAL(&opnd_v[0], type_v[0]), amo_opName(cmd_v[0]), amo_typeName(type_v[0]), size_v[0], remote_mr_v[0]); assert(!isAmHandler); struct perTxCtxInfo_t* tcip; CHK_TRUE((tcip = tciAlloc()) != NULL); // // Make sure we have enough free CQ entries to initiate the entire // batch of transactions. // waitForCQSpace(tcip, v_len); // // Initiate the batch. Record which nodes we do AMOs to, so that we // can force visibility in target memory at the end. // if (tcip->amoVisBitmap == NULL) { tcip->amoVisBitmap = bitmapAlloc(chpl_numNodes); } for (int vi = 0; vi < v_len; vi++) { struct amoBundle_t ab = { .m = { .msg_iov = &ab.iovOpnd, .desc = &local_mr, .iov_count = 1, .addr = rxAddr(locale_v[vi]), .rma_iov = &ab.iovObj, .rma_iov_count = 1, .datatype = type_v[vi], .op = cmd_v[vi], .context = txnTrkEncodeId(__LINE__), }, .iovOpnd = { .addr = &opnd_v[vi], .count = 1, }, .iovObj = { .addr = (uint64_t) object_v[vi], .count = 1, .key = remote_mr_v[vi], }, .node = locale_v[vi], .size = size_v[vi], }; (void) wrap_fi_atomicmsg(&ab, (vi < v_len - 1) ? FI_MORE : 0, tcip); bitmapSet(tcip->amoVisBitmap, locale_v[vi]); } // // Enforce Chapel MCM: force visibility of the memory effects of all // these AMOs. // mcmReleaseAllNodes(tcip->amoVisBitmap, NULL, -1 /*skipNode*/, tcip, "unordered AMO"); tciFree(tcip); } static void amEnsureProgress(struct perTxCtxInfo_t* tcip) { (*tcip->checkTxCmplsFn)(tcip); // // We only have responsibility for inbound operations if we're doing // manual progress. // if (ofi_info->domain_attr->data_progress != FI_PROGRESS_MANUAL) { return; } (void) amCheckRxTxCmpls(NULL, NULL, tcip); } static void amCheckRxTxCmpls(chpl_bool* pHadRxEvent, chpl_bool* pHadTxEvent, struct perTxCtxInfo_t* tcip) { if (ofi_amhPollSet != NULL) { void* contexts[pollSetSize]; int ret; OFI_CHK_COUNT(fi_poll(ofi_amhPollSet, contexts, pollSetSize), ret); // // Process the CQs/counters that had events. We really only have // to consume completions for our transmit endpoint. If we have // inbound AM messages we'll let the caller know and those can be // dealt with in the main poll loop. For inbound RMA, ensuring // progress is all that's needed, and the poll call itself will // have done that. // for (int i = 0; i < ret; i++) { if (contexts[i] == &ofi_rxCQ) { if (pHadRxEvent != NULL) { *pHadRxEvent = true; } } else if (contexts[i] == &tcip->checkTxCmplsFn) { (*tcip->checkTxCmplsFn)(tcip); if (pHadTxEvent != NULL) { *pHadTxEvent = true; } } else { INTERNAL_ERROR_V("unexpected context %p from fi_poll()", contexts[i]); } } } else { // // The provider can't do poll sets. Consume transmit completions, // and just assume that there may be some inbound operations which // the main loop will handle. Also, avoid CPU monopolization even // if we had events, because we can't actually tell. // sched_yield(); if (pHadRxEvent != NULL) { *pHadRxEvent = true; } (*tcip->checkTxCmplsFn)(tcip); if (pHadTxEvent != NULL) { *pHadTxEvent = true; } } } static void checkTxCmplsCQ(struct perTxCtxInfo_t* tcip) { struct fi_cq_msg_entry cqes[txCQLen]; const size_t cqesSize = sizeof(cqes) / sizeof(cqes[0]); const size_t numEvents = readCQ(tcip->txCQ, cqes, cqesSize); tcip->numTxnsOut -= numEvents; for (int i = 0; i < numEvents; i++) { struct fi_cq_msg_entry* cqe = &cqes[i]; const txnTrkCtx_t trk = txnTrkDecode(cqe->op_context); DBG_PRINTF(DBG_ACK, "CQ ack tx, flags %#" PRIx64 ", ctx %d:%p", cqe->flags, trk.typ, trk.ptr); if (trk.typ == txnTrkDone) { atomic_store_explicit_bool((atomic_bool*) trk.ptr, true, memory_order_release); } else if (trk.typ != txnTrkId) { INTERNAL_ERROR_V("unexpected trk.typ %d", trk.typ); } } } static void checkTxCmplsCntr(struct perTxCtxInfo_t* tcip) { uint64_t count = fi_cntr_read(tcip->txCntr); if (count > tcip->numTxnsSent) { INTERNAL_ERROR_V("fi_cntr_read() %" PRIu64 ", but numTxnsSent %" PRIu64, count, tcip->numTxnsSent); } tcip->numTxnsOut = tcip->numTxnsSent - count; } static inline size_t readCQ(struct fid_cq* cq, void* buf, size_t count) { ssize_t ret; CHK_TRUE((ret = fi_cq_read(cq, buf, count)) > 0 || ret == -FI_EAGAIN || ret == -FI_EAVAIL); if (ret == -FI_EAVAIL) { reportCQError(cq); } return (ret == -FI_EAGAIN) ? 0 : ret; } static void reportCQError(struct fid_cq* cq) { char err_data[ofi_info->domain_attr->max_err_data]; struct fi_cq_err_entry err = (struct fi_cq_err_entry) { .err_data = err_data, .err_data_size = sizeof(err_data) }; fi_cq_readerr(cq, &err, 0); const txnTrkCtx_t trk = txnTrkDecode(err.op_context); if (err.err == FI_ETRUNC) { // // This only happens when reading from the CQ associated with the // inbound AM request multi-receive buffer. // // We ran out of inbound buffer space and a message was truncated. // If the fi_setopt(FI_OPT_MIN_MULTI_RECV) worked and nobody sent // anything larger than that, this shouldn't happen. In any case, // we can't recover, but let's provide some information to help // aid failure analysis. // INTERNAL_ERROR_V("fi_cq_readerr(): AM recv buf FI_ETRUNC: " "flags %#" PRIx64 ", len %zd, olen %zd, ctx %d:%p", err.flags, err.len, err.olen, trk.typ, trk.ptr); } else { char buf[100]; const char* errStr = fi_cq_strerror(cq, err.prov_errno, err.err_data, buf, sizeof(buf)); INTERNAL_ERROR_V("fi_cq_read(): err %d, prov_errno %d, errStr %s, " "ctx %d:%p", err.err, err.prov_errno, errStr, trk.typ, trk.ptr); } } static inline void waitForTxnComplete(struct perTxCtxInfo_t* tcip, void* ctx) { (*tcip->ensureProgressFn)(tcip); const txnTrkCtx_t trk = txnTrkDecode(ctx); if (trk.typ == txnTrkDone) { while (!atomic_load_explicit_bool((atomic_bool*) trk.ptr, memory_order_acquire)) { sched_yield(); (*tcip->ensureProgressFn)(tcip); } } else { while (tcip->numTxnsOut > 0) { sched_yield(); (*tcip->ensureProgressFn)(tcip); } } } static inline void forceMemFxVisOneNode(c_nodeid_t node, chpl_bool checkPuts, chpl_bool checkAmos, struct perTxCtxInfo_t* tcip) { // // Enforce MCM: make sure the memory effects of the operations we've // done on a specific node are actually visible. Note the check for // a bound tx context -- we can't have outstanding network operations // without that. // if (tcip->bound) { chpl_bool havePutsOut = (checkPuts && tcip->putVisBitmap != NULL && bitmapTest(tcip->putVisBitmap, node)); chpl_bool haveAmosOut = (checkAmos && tcip->amoVisBitmap != NULL && bitmapTest(tcip->amoVisBitmap, node)); if (havePutsOut || haveAmosOut) { mcmReleaseOneNode(node, tcip, "PUT"); if (havePutsOut) { bitmapClear(tcip->putVisBitmap, node); } if (haveAmosOut) { bitmapClear(tcip->amoVisBitmap, node); } } } } static inline void forceMemFxVisAllNodes(chpl_bool checkPuts, chpl_bool checkAmos, c_nodeid_t skipNode, struct perTxCtxInfo_t* tcip) { // // Enforce MCM: make sure the memory effects of all the operations // we've done so far, to any node, are actually visible. This is only // needed if we have a bound tx context. Otherwise, we would have // forced visibility at the time of the operation. // if (tcip->bound) { mcmReleaseAllNodes(checkPuts ? tcip->putVisBitmap : NULL, checkAmos ? tcip->amoVisBitmap : NULL, skipNode, tcip, "PUT and/or AMO"); } } static inline void forceMemFxVisAllNodes_noTcip(chpl_bool checkPuts, chpl_bool checkAmos) { // // Enforce MCM: make sure the memory effects of all the operations // we've done so far, to any node, are actually visible. This is only // needed if we're using message ordering (with or without fences) for // MCM conformance. Otherwise, we would have forced visibility at the // time of the operation. // if (chpl_numNodes > 1 && mcmMode != mcmm_dlvrCmplt) { struct perTxCtxInfo_t* tcip; CHK_TRUE((tcip = tciAlloc()) != NULL); forceMemFxVisAllNodes(checkPuts, checkAmos, -1 /*skipNode*/, tcip); tciFree(tcip); } } static void* allocBounceBuf(size_t size) { void* p; CHPL_CALLOC_SZ(p, 1, size); return p; } static void freeBounceBuf(void* p) { CHPL_FREE(p); } static inline void local_yield(void) { #ifdef CHPL_COMM_DEBUG pthread_t pthreadWas = { 0 }; if (chpl_task_isFixedThread()) { pthreadWas = pthread_self(); } #endif // // Our task cannot make progress. Yield, to allow some other task to // free up whatever resource we need. // // DANGER: Don't call this function on a worker thread while holding // a tciTab[] entry, that is, between tcip=tciAlloc() and // tciFree(). If you do and your task switches threads due // to the chpl_task_yield(), we can end up with two threads // using the same tciTab[] entry simultaneously. // chpl_task_yield(); #ifdef CHPL_COMM_DEBUG // // There are things in the comm layer that will break if tasks can // switch threads when they think their thread is a fixed worker. // if (chpl_task_isFixedThread()) { CHK_TRUE(pthread_self() == pthreadWas); } #endif } //////////////////////////////////////// // // Interface: network atomics // static void doAMO(c_nodeid_t, void*, const void*, const void*, void*, int, enum fi_datatype, size_t); // // WRITE // #define DEFN_CHPL_COMM_ATOMIC_WRITE(fnType, ofiType, Type) \ void chpl_comm_atomic_write_##fnType \ (void* desired, c_nodeid_t node, void* object, \ memory_order order, int ln, int32_t fn) { \ DBG_PRINTF(DBG_IFACE_AMO_WRITE, \ "%s(%p, %d, %p, %d, %s)", __func__, \ desired, (int) node, object, \ ln, chpl_lookupFilename(fn)); \ chpl_comm_diags_verbose_amo("amo write", node, ln, fn); \ chpl_comm_diags_incr(amo); \ doAMO(node, object, desired, NULL, NULL, \ FI_ATOMIC_WRITE, ofiType, sizeof(Type)); \ } DEFN_CHPL_COMM_ATOMIC_WRITE(int32, FI_INT32, int32_t) DEFN_CHPL_COMM_ATOMIC_WRITE(int64, FI_INT64, int64_t) DEFN_CHPL_COMM_ATOMIC_WRITE(uint32, FI_UINT32, uint32_t) DEFN_CHPL_COMM_ATOMIC_WRITE(uint64, FI_UINT64, uint64_t) DEFN_CHPL_COMM_ATOMIC_WRITE(real32, FI_FLOAT, _real32) DEFN_CHPL_COMM_ATOMIC_WRITE(real64, FI_DOUBLE, _real64) // // READ // #define DEFN_CHPL_COMM_ATOMIC_READ(fnType, ofiType, Type) \ void chpl_comm_atomic_read_##fnType \ (void* result, c_nodeid_t node, void* object, \ memory_order order, int ln, int32_t fn) { \ DBG_PRINTF(DBG_IFACE_AMO_READ, \ "%s(%p, %d, %p, %d, %s)", __func__, \ result, (int) node, object, \ ln, chpl_lookupFilename(fn)); \ chpl_comm_diags_verbose_amo("amo read", node, ln, fn); \ chpl_comm_diags_incr(amo); \ doAMO(node, object, NULL, NULL, result, \ FI_ATOMIC_READ, ofiType, sizeof(Type)); \ } DEFN_CHPL_COMM_ATOMIC_READ(int32, FI_INT32, int32_t) DEFN_CHPL_COMM_ATOMIC_READ(int64, FI_INT64, int64_t) DEFN_CHPL_COMM_ATOMIC_READ(uint32, FI_UINT32, uint32_t) DEFN_CHPL_COMM_ATOMIC_READ(uint64, FI_UINT64, uint64_t) DEFN_CHPL_COMM_ATOMIC_READ(real32, FI_FLOAT, _real32) DEFN_CHPL_COMM_ATOMIC_READ(real64, FI_DOUBLE, _real64) #define DEFN_CHPL_COMM_ATOMIC_XCHG(fnType, ofiType, Type) \ void chpl_comm_atomic_xchg_##fnType \ (void* desired, c_nodeid_t node, void* object, void* result, \ memory_order order, int ln, int32_t fn) { \ DBG_PRINTF(DBG_IFACE_AMO, \ "%s(%p, %d, %p, %p, %d, %s)", __func__, \ desired, (int) node, object, result, \ ln, chpl_lookupFilename(fn)); \ chpl_comm_diags_verbose_amo("amo xchg", node, ln, fn); \ chpl_comm_diags_incr(amo); \ doAMO(node, object, desired, NULL, result, \ FI_ATOMIC_WRITE, ofiType, sizeof(Type)); \ } DEFN_CHPL_COMM_ATOMIC_XCHG(int32, FI_INT32, int32_t) DEFN_CHPL_COMM_ATOMIC_XCHG(int64, FI_INT64, int64_t) DEFN_CHPL_COMM_ATOMIC_XCHG(uint32, FI_UINT32, uint32_t) DEFN_CHPL_COMM_ATOMIC_XCHG(uint64, FI_UINT64, uint64_t) DEFN_CHPL_COMM_ATOMIC_XCHG(real32, FI_FLOAT, _real32) DEFN_CHPL_COMM_ATOMIC_XCHG(real64, FI_DOUBLE, _real64) #define DEFN_CHPL_COMM_ATOMIC_CMPXCHG(fnType, ofiType, Type) \ void chpl_comm_atomic_cmpxchg_##fnType \ (void* expected, void* desired, c_nodeid_t node, void* object, \ chpl_bool32* result, memory_order succ, memory_order fail, \ int ln, int32_t fn) { \ DBG_PRINTF(DBG_IFACE_AMO, \ "%s(%p, %p, %d, %p, %p, %d, %s)", __func__, \ expected, desired, (int) node, object, result, \ ln, chpl_lookupFilename(fn)); \ chpl_comm_diags_verbose_amo("amo cmpxchg", node, ln, fn); \ chpl_comm_diags_incr(amo); \ Type old_value; \ Type old_expected; \ memcpy(&old_expected, expected, sizeof(Type)); \ doAMO(node, object, desired, &old_expected, &old_value, \ FI_CSWAP, ofiType, sizeof(Type)); \ *result = (chpl_bool32)(old_value == old_expected); \ if (!*result) memcpy(expected, &old_value, sizeof(Type)); \ } DEFN_CHPL_COMM_ATOMIC_CMPXCHG(int32, FI_INT32, int32_t) DEFN_CHPL_COMM_ATOMIC_CMPXCHG(int64, FI_INT64, int64_t) DEFN_CHPL_COMM_ATOMIC_CMPXCHG(uint32, FI_UINT32, uint32_t) DEFN_CHPL_COMM_ATOMIC_CMPXCHG(uint64, FI_UINT64, uint64_t) DEFN_CHPL_COMM_ATOMIC_CMPXCHG(real32, FI_FLOAT, _real32) DEFN_CHPL_COMM_ATOMIC_CMPXCHG(real64, FI_DOUBLE, _real64) #define DEFN_IFACE_AMO_SIMPLE_OP(fnOp, ofiOp, fnType, ofiType, Type) \ void chpl_comm_atomic_##fnOp##_##fnType \ (void* opnd, c_nodeid_t node, void* object, \ memory_order order, int ln, int32_t fn) { \ DBG_PRINTF(DBG_IFACE_AMO, \ "%s(<%s>, %d, %p, %d, %s)", __func__, \ DBG_VAL(opnd, ofiType), (int) node, \ object, ln, chpl_lookupFilename(fn)); \ chpl_comm_diags_verbose_amo("amo " #fnOp, node, ln, fn); \ chpl_comm_diags_incr(amo); \ doAMO(node, object, opnd, NULL, NULL, \ ofiOp, ofiType, sizeof(Type)); \ } \ \ void chpl_comm_atomic_##fnOp##_unordered_##fnType \ (void* opnd, c_nodeid_t node, void* object, \ int ln, int32_t fn) { \ DBG_PRINTF(DBG_IFACE_AMO, \ "%s(<%s>, %d, %p, %d, %s)", __func__, \ DBG_VAL(opnd, ofiType), (int) node, \ object, ln, chpl_lookupFilename(fn)); \ chpl_comm_diags_verbose_amo("amo unord_" #fnOp, node, ln, fn); \ chpl_comm_diags_incr(amo); \ do_remote_amo_nf_buff(opnd, node, object, sizeof(Type), \ ofiOp, ofiType); \ } \ \ void chpl_comm_atomic_fetch_##fnOp##_##fnType \ (void* opnd, c_nodeid_t node, void* object, void* result, \ memory_order order, int ln, int32_t fn) { \ DBG_PRINTF(DBG_IFACE_AMO, \ "%s(<%s>, %d, %p, %p, %d, %s)", __func__, \ DBG_VAL(opnd, ofiType), (int) node, \ object, result, ln, chpl_lookupFilename(fn)); \ chpl_comm_diags_verbose_amo("amo fetch_" #fnOp, node, ln, fn); \ chpl_comm_diags_incr(amo); \ doAMO(node, object, opnd, NULL, result, \ ofiOp, ofiType, sizeof(Type)); \ } DEFN_IFACE_AMO_SIMPLE_OP(and, FI_BAND, int32, FI_INT32, int32_t) DEFN_IFACE_AMO_SIMPLE_OP(and, FI_BAND, int64, FI_INT64, int64_t) DEFN_IFACE_AMO_SIMPLE_OP(and, FI_BAND, uint32, FI_UINT32, uint32_t) DEFN_IFACE_AMO_SIMPLE_OP(and, FI_BAND, uint64, FI_UINT64, uint64_t) DEFN_IFACE_AMO_SIMPLE_OP(or, FI_BOR, int32, FI_INT32, int32_t) DEFN_IFACE_AMO_SIMPLE_OP(or, FI_BOR, int64, FI_INT64, int64_t) DEFN_IFACE_AMO_SIMPLE_OP(or, FI_BOR, uint32, FI_UINT32, uint32_t) DEFN_IFACE_AMO_SIMPLE_OP(or, FI_BOR, uint64, FI_UINT64, uint64_t) DEFN_IFACE_AMO_SIMPLE_OP(xor, FI_BXOR, int32, FI_INT32, int32_t) DEFN_IFACE_AMO_SIMPLE_OP(xor, FI_BXOR, int64, FI_INT64, int64_t) DEFN_IFACE_AMO_SIMPLE_OP(xor, FI_BXOR, uint32, FI_UINT32, uint32_t) DEFN_IFACE_AMO_SIMPLE_OP(xor, FI_BXOR, uint64, FI_UINT64, uint64_t) DEFN_IFACE_AMO_SIMPLE_OP(add, FI_SUM, int32, FI_INT32, int32_t) DEFN_IFACE_AMO_SIMPLE_OP(add, FI_SUM, int64, FI_INT64, int64_t) DEFN_IFACE_AMO_SIMPLE_OP(add, FI_SUM, uint32, FI_UINT32, uint32_t) DEFN_IFACE_AMO_SIMPLE_OP(add, FI_SUM, uint64, FI_UINT64, uint64_t) DEFN_IFACE_AMO_SIMPLE_OP(add, FI_SUM, real32, FI_FLOAT, _real32) DEFN_IFACE_AMO_SIMPLE_OP(add, FI_SUM, real64, FI_DOUBLE, _real64) #define DEFN_IFACE_AMO_SUB(fnType, ofiType, Type, negate) \ void chpl_comm_atomic_sub_##fnType \ (void* opnd, c_nodeid_t node, void* object, \ memory_order order, int ln, int32_t fn) { \ DBG_PRINTF(DBG_IFACE_AMO, \ "%s(<%s>, %d, %p, %d, %s)", __func__, \ DBG_VAL(opnd, ofiType), (int) node, object, \ ln, chpl_lookupFilename(fn)); \ Type myOpnd = negate(*(Type*) opnd); \ chpl_comm_diags_verbose_amo("amo sub", node, ln, fn); \ chpl_comm_diags_incr(amo); \ doAMO(node, object, &myOpnd, NULL, NULL, \ FI_SUM, ofiType, sizeof(Type)); \ } \ \ void chpl_comm_atomic_sub_unordered_##fnType \ (void* opnd, c_nodeid_t node, void* object, \ int ln, int32_t fn) { \ DBG_PRINTF(DBG_IFACE_AMO, \ "%s(<%s>, %d, %p, %d, %s)", __func__, \ DBG_VAL(opnd, ofiType), (int) node, object, \ ln, chpl_lookupFilename(fn)); \ Type myOpnd = negate(*(Type*) opnd); \ chpl_comm_diags_verbose_amo("amo unord_sub", node, ln, fn); \ chpl_comm_diags_incr(amo); \ do_remote_amo_nf_buff(&myOpnd, node, object, sizeof(Type), \ FI_SUM, ofiType); \ } \ \ void chpl_comm_atomic_fetch_sub_##fnType \ (void* opnd, c_nodeid_t node, void* object, void* result, \ memory_order order, int ln, int32_t fn) { \ DBG_PRINTF(DBG_IFACE_AMO, \ "%s(<%s>, %d, %p, %p, %d, %s)", __func__, \ DBG_VAL(opnd, ofiType), (int) node, object, \ result, ln, chpl_lookupFilename(fn)); \ Type myOpnd = negate(*(Type*) opnd); \ chpl_comm_diags_verbose_amo("amo fetch_sub", node, ln, fn); \ chpl_comm_diags_incr(amo); \ doAMO(node, object, &myOpnd, NULL, result, \ FI_SUM, ofiType, sizeof(Type)); \ } #define NEGATE_I32(x) ((x) == INT32_MIN ? (x) : -(x)) #define NEGATE_I64(x) ((x) == INT64_MIN ? (x) : -(x)) #define NEGATE_U_OR_R(x) (-(x)) DEFN_IFACE_AMO_SUB(int32, FI_INT32, int32_t, NEGATE_I32) DEFN_IFACE_AMO_SUB(int64, FI_INT64, int64_t, NEGATE_I64) DEFN_IFACE_AMO_SUB(uint32, FI_UINT32, uint32_t, NEGATE_U_OR_R) DEFN_IFACE_AMO_SUB(uint64, FI_UINT64, uint64_t, NEGATE_U_OR_R) DEFN_IFACE_AMO_SUB(real32, FI_FLOAT, _real32, NEGATE_U_OR_R) DEFN_IFACE_AMO_SUB(real64, FI_DOUBLE, _real64, NEGATE_U_OR_R) void chpl_comm_atomic_unordered_task_fence(void) { DBG_PRINTF(DBG_IFACE_MCM, "%s()", __func__); task_local_buff_flush(amo_nf_buff); } // // internal AMO utilities // static int computeAtomicValid(enum fi_datatype ofiType) { // // At least one provider (ofi_rxm) segfaults if the endpoint given to // fi*atomicvalid() entirely lacks atomic caps. The man page isn't // clear on whether this should work, so just avoid that situation. // if ((ofi_info->tx_attr->caps & FI_ATOMIC) == 0) { return 0; } struct fid_ep* ep = tciTab[0].txCtx; // assume same answer for all endpoints size_t count; // ignored #define my_valid(typ, op) \ (fi_atomicvalid(ep, typ, op, &count) == 0 && count > 0) #define my_fetch_valid(typ, op) \ (fi_fetch_atomicvalid(ep, typ, op, &count) == 0 && count > 0) #define my_compare_valid(typ, op) \ (fi_compare_atomicvalid(ep, typ, op, &count) == 0 && count > 0) // For integral types, all operations matter. if (ofiType == FI_INT32 || ofiType == FI_UINT32 || ofiType == FI_INT64 || ofiType == FI_UINT64) { return ( my_valid(ofiType, FI_SUM) && my_valid(ofiType, FI_BOR) && my_valid(ofiType, FI_BAND) && my_valid(ofiType, FI_BXOR) && my_valid(ofiType, FI_ATOMIC_WRITE) && my_fetch_valid(ofiType, FI_SUM) && my_fetch_valid(ofiType, FI_BOR) && my_fetch_valid(ofiType, FI_BAND) && my_fetch_valid(ofiType, FI_BXOR) && my_fetch_valid(ofiType, FI_ATOMIC_READ) && my_fetch_valid(ofiType, FI_ATOMIC_WRITE) && my_compare_valid(ofiType, FI_CSWAP)); } // // For real types, only sum, read, write, and cswap matter. // return ( my_valid(ofiType, FI_SUM) && my_valid(ofiType, FI_ATOMIC_WRITE) && my_fetch_valid(ofiType, FI_SUM) && my_fetch_valid(ofiType, FI_ATOMIC_READ) && my_fetch_valid(ofiType, FI_ATOMIC_WRITE) && my_compare_valid(ofiType, FI_CSWAP)); #undef my_valid #undef my_fetch_valid #undef my_compare_valid } static int isAtomicValid(enum fi_datatype ofiType) { static chpl_bool inited = false; static int validByType[FI_DATATYPE_LAST]; if (!inited) { validByType[FI_INT32] = computeAtomicValid(FI_INT32); validByType[FI_UINT32] = computeAtomicValid(FI_UINT32); validByType[FI_INT64] = computeAtomicValid(FI_INT64); validByType[FI_UINT64] = computeAtomicValid(FI_UINT64); validByType[FI_FLOAT] = computeAtomicValid(FI_FLOAT); validByType[FI_DOUBLE] = computeAtomicValid(FI_DOUBLE); inited = true; } return validByType[ofiType]; } static inline void doAMO(c_nodeid_t node, void* object, const void* opnd, const void* cmpr, void* result, int ofiOp, enum fi_datatype ofiType, size_t size) { if (chpl_numNodes <= 1) { doCpuAMO(object, opnd, cmpr, result, ofiOp, ofiType, size); return; } retireDelayedAmDone(false /*taskIsEnding*/); uint64_t mrKey; uint64_t mrRaddr; if (!isAtomicValid(ofiType) || !mrGetKey(&mrKey, &mrRaddr, node, object, size)) { // // We can't do the AMO on the network, so do it on the CPU. If the // object is on this node do it directly; otherwise, use an AM. // if (node == chpl_nodeID) { if (ofiOp != FI_ATOMIC_READ) { forceMemFxVisAllNodes_noTcip(true /*checkPuts*/, true /*checkAmos*/); } doCpuAMO(object, opnd, cmpr, result, ofiOp, ofiType, size); } else { amRequestAMO(node, object, opnd, cmpr, result, ofiOp, ofiType, size); } } else { // // The type is supported for network atomics and the object address // is remotely accessible. Do the AMO natively. // ofi_amo(node, mrRaddr, mrKey, opnd, cmpr, result, ofiOp, ofiType, size); } } static inline void doCpuAMO(void* obj, const void* opnd, const void* cmpr, void* result, enum fi_op ofiOp, enum fi_datatype ofiType, size_t size) { CHK_TRUE(size == 4 || size == 8); chpl_amo_datum_t* myOpnd = (chpl_amo_datum_t*) opnd; chpl_amo_datum_t* myCmpr = (chpl_amo_datum_t*) cmpr; #define CPU_INT_ARITH_AMO(_o, _t, _m) \ do { \ if (result == NULL) { \ (void) atomic_fetch_##_o##_##_t((atomic_##_t*) obj, \ myOpnd->_m); \ } else { \ *(_t*) result = atomic_fetch_##_o##_##_t((atomic_##_t*) obj, \ myOpnd->_m); \ } \ } while (0) // // Here we implement AMOs which the NIC cannot or should not do. // switch (ofiOp) { case FI_ATOMIC_WRITE: if (result == NULL) { // // write // if (size == 4) { atomic_store_uint_least32_t(obj, myOpnd->u32); } else { atomic_store_uint_least64_t(obj, myOpnd->u64); } } else { // // exchange // if (size == 4) { *(uint32_t*) result = atomic_exchange_uint_least32_t(obj, myOpnd->u32); } else { *(uint64_t*) result = atomic_exchange_uint_least64_t(obj, myOpnd->u64); } } break; case FI_ATOMIC_READ: if (size == 4) { *(uint32_t*) result = atomic_load_uint_least32_t(obj); } else { *(uint64_t*) result = atomic_load_uint_least64_t(obj); } break; case FI_CSWAP: if (size == 4) { uint32_t myCmprVal = myCmpr->u32; (void) atomic_compare_exchange_strong_uint_least32_t(obj, &myCmprVal, myOpnd->u32); *(uint32_t*) result = myCmprVal; } else { uint64_t myCmprVal = myCmpr->u64; (void) atomic_compare_exchange_strong_uint_least64_t(obj, &myCmprVal, myOpnd->u64); *(uint64_t*) result = myCmprVal; } break; case FI_BAND: if (ofiType == FI_INT32) { CPU_INT_ARITH_AMO(and, int_least32_t, i32); } else if (ofiType == FI_UINT32) { CPU_INT_ARITH_AMO(and, uint_least32_t, u32); } else if (ofiType == FI_INT64) { CPU_INT_ARITH_AMO(and, int_least64_t, i64); } else if (ofiType == FI_UINT64) { CPU_INT_ARITH_AMO(and, uint_least64_t, u64); } else { INTERNAL_ERROR_V("doCpuAMO(): unsupported ofiOp %d, ofiType %d", ofiOp, ofiType); } break; case FI_BOR: if (ofiType == FI_INT32) { CPU_INT_ARITH_AMO(or, int_least32_t, i32); } else if (ofiType == FI_UINT32) { CPU_INT_ARITH_AMO(or, uint_least32_t, u32); } else if (ofiType == FI_INT64) { CPU_INT_ARITH_AMO(or, int_least64_t, i64); } else if (ofiType == FI_UINT64) { CPU_INT_ARITH_AMO(or, uint_least64_t, u64); } else { INTERNAL_ERROR_V("doCpuAMO(): unsupported ofiOp %d, ofiType %d", ofiOp, ofiType); } break; case FI_BXOR: if (ofiType == FI_INT32) { CPU_INT_ARITH_AMO(xor, int_least32_t, i32); } else if (ofiType == FI_UINT32) { CPU_INT_ARITH_AMO(xor, uint_least32_t, u32); } else if (ofiType == FI_INT64) { CPU_INT_ARITH_AMO(xor, int_least64_t, i64); } else if (ofiType == FI_UINT64) { CPU_INT_ARITH_AMO(xor, uint_least64_t, u64); } else { INTERNAL_ERROR_V("doCpuAMO(): unsupported ofiOp %d, ofiType %d", ofiOp, ofiType); } break; case FI_SUM: if (ofiType == FI_INT32) { CPU_INT_ARITH_AMO(add, int_least32_t, i32); } else if (ofiType == FI_UINT32) { CPU_INT_ARITH_AMO(add, uint_least32_t, u32); } else if (ofiType == FI_INT64) { CPU_INT_ARITH_AMO(add, int_least64_t, i64); } else if (ofiType == FI_UINT64) { CPU_INT_ARITH_AMO(add, uint_least64_t, u64); } else if (ofiType == FI_FLOAT) { CPU_INT_ARITH_AMO(add, _real32, r32); } else if (ofiType == FI_DOUBLE) { CPU_INT_ARITH_AMO(add, _real64, r64); } else { INTERNAL_ERROR_V("doCpuAMO(): unsupported ofiOp %d, ofiType %d", ofiOp, ofiType); } break; default: INTERNAL_ERROR_V("doCpuAMO(): unsupported ofiOp %d, ofiType %d", ofiOp, ofiType); } if (DBG_TEST_MASK(DBG_AMO | DBG_AMO_READ)) { if (result == NULL) { DBG_PRINTF(DBG_AMO, "doCpuAMO(%p, %s, %s, %s): now %s", obj, amo_opName(ofiOp), amo_typeName(ofiType), DBG_VAL(myOpnd, ofiType), DBG_VAL((chpl_amo_datum_t*) obj, ofiType)); } else if (ofiOp == FI_ATOMIC_READ) { DBG_PRINTF(DBG_AMO_READ, "doCpuAMO(%p, %s, %s): res %p is %s", obj, amo_opName(ofiOp), amo_typeName(ofiType), result, DBG_VAL(result, ofiType)); } else { DBG_PRINTF(DBG_AMO, "doCpuAMO(%p, %s, %s, %s, %s): now %s, res %p is %s", obj, amo_opName(ofiOp), amo_typeName(ofiType), DBG_VAL(myOpnd, ofiType), DBG_VAL(myCmpr, ofiType), DBG_VAL((chpl_amo_datum_t*) obj, ofiType), result, DBG_VAL(result, (ofiOp == FI_CSWAP) ? FI_INT32 : ofiType)); } } #undef CPU_INT_ARITH_AMO } /* *** START OF NON-FETCHING BUFFERED ATOMIC OPERATIONS *** * * Support for non-fetching buffered atomic operations. We internally buffer * atomic operations and then initiate them all at once for increased * transaction rate. */ // Flush buffered AMOs for the specified task info and reset the counter. static inline void amo_nf_buff_task_info_flush(amo_nf_buff_task_info_t* info) { if (info->vi > 0) { DBG_PRINTF(DBG_AMO_UNORD, "amo_nf_buff_task_info_flush(): info has %d entries", info->vi); ofi_amo_nf_V(info->vi, info->opnd_v, info->local_mr, info->locale_v, info->object_v, info->remote_mr_v, info->size_v, info->cmd_v, info->type_v); info->vi = 0; } } static inline void do_remote_amo_nf_buff(void* opnd, c_nodeid_t node, void* object, size_t size, enum fi_op ofiOp, enum fi_datatype ofiType) { // // "Unordered" is possible only for actual network atomic ops. // if (chpl_numNodes <= 1) { doCpuAMO(object, opnd, NULL, NULL, ofiOp, ofiType, size); return; } retireDelayedAmDone(false /*taskIsEnding*/); uint64_t mrKey; uint64_t mrRaddr; if (!isAtomicValid(ofiType) || !mrGetKey(&mrKey, &mrRaddr, node, object, size)) { if (node == chpl_nodeID) { doCpuAMO(object, opnd, NULL, NULL, ofiOp, ofiType, size); } else { amRequestAMO(node, object, opnd, NULL, NULL, ofiOp, ofiType, size); } return; } amo_nf_buff_task_info_t* info = task_local_buff_acquire(amo_nf_buff); if (info == NULL) { ofi_amo(node, mrRaddr, mrKey, opnd, NULL, NULL, ofiOp, ofiType, size); return; } if (info->new) { // // The AMO operands are stored in a vector in the info, and we only // need one local memory descriptor for that vector. // CHK_TRUE(mrGetDesc(&info->local_mr, info->opnd_v, size)); info->new = false; } int vi = info->vi; info->opnd_v[vi] = size == 4 ? *(uint32_t*) opnd: *(uint64_t*) opnd; info->locale_v[vi] = node; info->object_v[vi] = (void*) mrRaddr; info->size_v[vi] = size; info->cmd_v[vi] = ofiOp; info->type_v[vi] = ofiType; info->remote_mr_v[vi] = mrKey; info->vi++; DBG_PRINTF(DBG_AMO_UNORD, "do_remote_amo_nf_buff(): info[%d] = " "{%p, %d, %p, %zd, %d, %d, %" PRIx64 ", %p}", vi, &info->opnd_v[vi], (int) node, object, size, (int) ofiOp, (int) ofiType, mrKey, info->local_mr); // flush if buffers are full if (info->vi == MAX_CHAINED_AMO_NF_LEN) { amo_nf_buff_task_info_flush(info); } } /*** END OF NON-FETCHING BUFFERED ATOMIC OPERATIONS ***/ //////////////////////////////////////// // // Interface: utility // int chpl_comm_addr_gettable(c_nodeid_t node, void* start, size_t size) { // No way to know if the page is mapped on the remote (without a round trip) return 0; } int32_t chpl_comm_getMaxThreads(void) { // no limit return 0; } //////////////////////////////////////// // // Interface: barriers // // // We do a simple tree-based split-phase barrier, with locale 0 as the // root of the tree. Each of the locales has a barrier_info_t struct, // and knows the address of that struct in its child locales (locales // num_children*my_idx+1 - num_children*my_idx+num_children) and its // parent (locale (my_idx-1)/num_children). Notify and release flags on // all locales start out 0. The notify step consists of each locale // waiting for its children, if it has any, to set the child_notify // flags in its own barrier info struct to 1, and then if it is not // locale 0, setting the child_notify flag corresponding to itself in // its parent's barrier info struct to 1. Thus notification propagates // up from the leaves of the tree to the root. In the wait phase each // locale except locale 0 waits for the parent_release flag in its own // barrier info struct to become 1. Once a locale sees that, it clears // all of the flags in its own struct and then sets the parent_release // flags in both of its existing children to 1. Thus releases propagate // down from locale 0 to the leaves. Once waiting is complete at the // leaves, all of the flags throughout the job are back to 0 and the // process can repeat. // // Note that we can (and do) do other things while waiting for notify // and release flags to be set. In fact we have to task-yield while // doing so, in case the PUTs need to be done via AM for some reason // (unregistered memory, e.g.). // // TODO: vectorize the child PUTs. // #define BAR_TREE_NUM_CHILDREN 64 typedef struct { volatile int child_notify[BAR_TREE_NUM_CHILDREN]; volatile int parent_release; } bar_info_t; static c_nodeid_t bar_childFirst; static c_nodeid_t bar_numChildren; static c_nodeid_t bar_parent; static bar_info_t bar_info; static bar_info_t** bar_infoMap; static void init_bar(void) { bar_childFirst = BAR_TREE_NUM_CHILDREN * chpl_nodeID + 1; if (bar_childFirst >= chpl_numNodes) bar_numChildren = 0; else { bar_numChildren = BAR_TREE_NUM_CHILDREN; if (bar_childFirst + bar_numChildren >= chpl_numNodes) bar_numChildren = chpl_numNodes - bar_childFirst; } bar_parent = (chpl_nodeID - 1) / BAR_TREE_NUM_CHILDREN; CHPL_CALLOC(bar_infoMap, chpl_numNodes); const bar_info_t* p = &bar_info; chpl_comm_ofi_oob_allgather(&p, bar_infoMap, sizeof(p)); } void chpl_comm_barrier(const char *msg) { DBG_PRINTF(DBG_IFACE_SETUP, "%s('%s')", __func__, msg); #ifdef CHPL_COMM_DEBUG chpl_msg(2, "%d: enter barrier for '%s'\n", chpl_nodeID, msg); #endif if (chpl_numNodes == 1) { return; } DBG_PRINTF(DBG_BARRIER, "barrier '%s'", (msg == NULL) ? "" : msg); if (pthread_equal(pthread_self(), pthread_that_inited) || numAmHandlersActive == 0) { // // Either this is the main (chpl_comm_init()ing) thread or // comm layer setup is not complete yet. Use OOB barrier. // chpl_comm_ofi_oob_barrier(); DBG_PRINTF(DBG_BARRIER, "barrier '%s' done via out-of-band", (msg == NULL) ? "" : msg); return; } // // Ensure our outstanding nonfetching AMOs and PUTs are visible. // (Visibility of operations done by other tasks on this node is // the caller's responsibility.) // retireDelayedAmDone(false /*taskIsEnding*/); forceMemFxVisAllNodes_noTcip(true /*checkPuts*/, true /*checkAmos*/); // // Wait for our child locales to notify us that they have reached the // barrier. // DBG_PRINTF(DBG_BARRIER, "BAR wait for %d children", (int) bar_numChildren); for (uint32_t i = 0; i < bar_numChildren; i++) { while (bar_info.child_notify[i] == 0) { local_yield(); } } const int one = 1; if (chpl_nodeID != 0) { // // Notify our parent locale that we have reached the barrier. // c_nodeid_t parChild = (chpl_nodeID - 1) % BAR_TREE_NUM_CHILDREN; DBG_PRINTF(DBG_BARRIER, "BAR notify parent %d", (int) bar_parent); ofi_put(&one, bar_parent, (void*) &bar_infoMap[bar_parent]->child_notify[parChild], sizeof(one)); // // Wait for our parent locale to release us from the barrier. // DBG_PRINTF(DBG_BARRIER, "BAR wait for parental release"); while (bar_info.parent_release == 0) { local_yield(); } } // // Clear all our barrier flags. // for (int i = 0; i < bar_numChildren; i++) bar_info.child_notify[i] = 0; bar_info.parent_release = 0; // // Release our children. // if (bar_numChildren > 0) { for (int i = 0; i < bar_numChildren; i++) { c_nodeid_t child = bar_childFirst + i; DBG_PRINTF(DBG_BARRIER, "BAR release child %d", (int) child); ofi_put(&one, child, (void*) &bar_infoMap[child]->parent_release, sizeof(one)); } } DBG_PRINTF(DBG_BARRIER, "barrier '%s' done via PUTs", (msg == NULL) ? "" : msg); } //////////////////////////////////////// // // Time // static double timeBase; static void time_init(void) { timeBase = chpl_comm_ofi_time_get(); } double chpl_comm_ofi_time_get(void) { struct timespec _ts; (void) clock_gettime(CLOCK_MONOTONIC, &_ts); return ((double) _ts.tv_sec + (double) _ts.tv_nsec * 1e-9) - timeBase; } //////////////////////////////////////// // // Error reporting // // // Here we just handle a few special cases where we think we can be // more informative than usual. If we return, the usual internal // error message will be printed. // static void ofiErrReport(const char* exprStr, int retVal, const char* errStr) { if (retVal == -FI_EMFILE) { // // We've run into the limit on the number of files we can have open // at once. // // Some providers open a lot of files. The tcp provider, as one // example, can open as many as roughly 9 files per node, plus 2 // socket files for each connected endpoint. Because of this, one // can exceed a quite reasonable open-file limit in a job running on // a fairly modest number of many-core locales. Thus for example, // extremeBlock will get -FI_EMFILE with an open file limit of 1024 // when run on 32 24-core locales. Here, try to inform the user // about this without getting overly technical. // INTERNAL_ERROR_V( "OFI error: %s: %s:\n" " The program has reached the limit on the number of files it can\n" " have open at once. This may be because the product of the number\n" " of locales (%d) and the communication concurrency (roughly %d) is\n" " a significant fraction of the open-file limit (%ld). If so,\n" " either setting CHPL_RT_COMM_CONCURRENCY to decrease communication\n" " concurrency or running on fewer locales may allow the program to\n" " execute successfully. Or, you may be able to use `ulimit` to\n" " increase the open file limit and achieve the same result.", exprStr, errStr, (int) chpl_numNodes, numTxCtxs, sysconf(_SC_OPEN_MAX)); } } #ifdef CHPL_COMM_DEBUG //////////////////////////////////////// // // Debugging support // void chpl_comm_ofi_dbg_init(void) { const char* ev; if ((ev = chpl_env_rt_get("COMM_OFI_DEBUG", NULL)) == NULL) { return; } // // Compute the debug level from the keywords in the env var. // { #define OFIDBG_MACRO(_enum, _desc) { #_enum, _desc }, static struct { const char* kw; const char* desc; } dbgCodes[] = { OFI_ALL_DEBUGS(OFIDBG_MACRO) }; static const int dbgCodesLen = sizeof(dbgCodes) / sizeof(dbgCodes[0]); char evc[strlen(ev) + 1]; // non-constant, for strtok() strcpy(evc, ev); // // Loop over comma-separated tokens in the env var. // chpl_comm_ofi_dbg_level = 0; char* tok; char* strSave; for (char* evcPtr = evc; (tok = strtok_r(evcPtr, ",", &strSave)) != NULL; evcPtr = NULL) { // // Users can use lowercase and dashes; table contains uppercase // and underbars, because it defines C symbols. Canonicalize // user's token. // char ctok[strlen(tok)]; for (int i = 0; i < sizeof(ctok); i++) { if (tok[i] == '-') { ctok[i] = '_'; } else { ctok[i] = toupper(tok[i]); } } // // Find user's keyword in table. // int i, iPrefix; for (i = 0, iPrefix = -1; i < dbgCodesLen; i++) { if (strncmp(ctok, dbgCodes[i].kw, sizeof(ctok)) == 0) { if (dbgCodes[i].kw[sizeof(ctok)] == '\0') { break; } else { // Accept a match to the prefix of a keyword iff unambiguous. iPrefix = (iPrefix < 0) ? i : dbgCodesLen; } } } // // Add found debug bit to our set of same, or say "what?". // if (i >= 0 && i < dbgCodesLen) { chpl_comm_ofi_dbg_level |= (uint64_t) 1 << i; } else if (iPrefix >= 0 && iPrefix < dbgCodesLen) { chpl_comm_ofi_dbg_level |= (uint64_t) 1 << iPrefix; } else { // // All nodes exit on error, but only node 0 says why. // if (chpl_nodeID == 0) { if (ctok[0] != '?' && strncmp(ctok, "HELP", sizeof(ctok)) != 0) { printf("Warning: unknown or ambiguous comm=ofi debug keyword " "\"%s\"\n", tok); } // // Print pretty table of debug keywords and descriptions. // printf("Debug keywords (case ignored, -_ equiv) and descriptions\n"); printf("--------------------------------------------------------\n"); int kwLenMax = 0; for (int ic = 0; ic < dbgCodesLen; ic++) { if (strlen(dbgCodes[ic].kw) > kwLenMax) { kwLenMax = strlen(dbgCodes[ic].kw); } } for (int ic = 0; ic < dbgCodesLen; ic++) { char kw[strlen(dbgCodes[ic].kw)]; for (int ik = 0; ik < sizeof(kw); ik++) { if (dbgCodes[ic].kw[ik] == '_') { kw[ik] = '-'; } else { kw[ik] = tolower(dbgCodes[ic].kw[ik]); } } printf("%.*s:%*s %s\n", (int) sizeof(kw), kw, (int) (kwLenMax - sizeof(kw)), "", dbgCodes[ic].desc); } } chpl_comm_ofi_oob_fini(); chpl_exit_any(0); } } } if ((ev = chpl_env_rt_get("COMM_OFI_DEBUG_FNAME", NULL)) == NULL) { chpl_comm_ofi_dbg_file = stdout; } else { char fname[strlen(ev) + 6 + 1]; int fnameLen; fnameLen = snprintf(fname, sizeof(fname), "%s.%d", ev, (int) chpl_nodeID); CHK_TRUE(fnameLen < sizeof(fname)); CHK_TRUE((chpl_comm_ofi_dbg_file = fopen(fname, "w")) != NULL); setbuf(chpl_comm_ofi_dbg_file, NULL); } } char* chpl_comm_ofi_dbg_prefix(void) { static __thread char buf[30]; int len; if (buf[0] == '\0' || DBG_TEST_MASK(DBG_TSTAMP)) { buf[len = 0] = '\0'; if (chpl_nodeID >= 0) len += snprintf(&buf[len], sizeof(buf) - len, "%d", chpl_nodeID); if (chpl_task_getId() == chpl_nullTaskID) len += snprintf(&buf[len], sizeof(buf) - len, ":_"); else len += snprintf(&buf[len], sizeof(buf) - len, ":%ld", (long int) chpl_task_getId()); if (DBG_TEST_MASK(DBG_TSTAMP)) len += snprintf(&buf[len], sizeof(buf) - len, "%s%.9f", ((len == 0) ? "" : ": "), chpl_comm_ofi_time_get()); if (len > 0) len += snprintf(&buf[len], sizeof(buf) - len, ": "); } return buf; } char* chpl_comm_ofi_dbg_val(const void* pV, enum fi_datatype ofiType) { static __thread char buf[5][32]; static __thread int iBuf = 0; char* s = buf[iBuf]; if (pV == NULL) { snprintf(s, sizeof(buf[0]), "NIL"); } else { switch (ofiType) { case FI_INT32: snprintf(s, sizeof(buf[0]), "%" PRId32, *(const int_least32_t*) pV); break; case FI_UINT32: snprintf(s, sizeof(buf[0]), "%#" PRIx32, *(const uint_least32_t*) pV); break; case FI_INT64: snprintf(s, sizeof(buf[0]), "%" PRId64, *(const int_least64_t*) pV); break; case FI_FLOAT: snprintf(s, sizeof(buf[0]), "%.6g", (double) *(const float*) pV); break; case FI_DOUBLE: snprintf(s, sizeof(buf[0]), "%.16g", *(const double*) pV); break; default: snprintf(s, sizeof(buf[0]), "%#" PRIx64, *(const uint_least64_t*) pV); break; } } if (++iBuf >= sizeof(buf) / sizeof(buf[0])) iBuf = 0; return s; } static const char* am_opName(amOp_t op) { switch (op) { case am_opExecOn: return "opExecOn"; case am_opExecOnLrg: return "opExecOnLrg"; case am_opGet: return "opGet"; case am_opPut: return "opPut"; case am_opAMO: return "opAMO"; case am_opFree: return "opFree"; case am_opNop: return "opNop"; case am_opShutdown: return "opShutdown"; default: return "op???"; } } static const char* amo_opName(enum fi_op ofiOp) { switch (ofiOp) { case FI_ATOMIC_WRITE: return "write"; case FI_ATOMIC_READ: return "read"; case FI_CSWAP: return "cswap"; case FI_BAND: return "band"; case FI_BOR: return "bor"; case FI_BXOR: return "bxor"; case FI_SUM: return "sum"; default: return "amoOp???"; } } static const char* amo_typeName(enum fi_datatype ofiType) { switch (ofiType) { case FI_INT32: return "int32"; case FI_UINT32: return "uint32"; case FI_INT64: return "int64"; case FI_UINT64: return "uint64"; case FI_FLOAT: return "real32"; case FI_DOUBLE: return "real64"; default: return "amoType???"; } } static const char* am_seqIdStr(amRequest_t* req) { static __thread char buf[30]; if (op_uses_on_bundle(req->b.op)) { (void) snprintf(buf, sizeof(buf), "%d:%" PRIu64, req->xo.hdr.comm.node, req->xo.hdr.comm.seq); } else { (void) snprintf(buf, sizeof(buf), "%d:%" PRIu64, req->b.node, req->b.seq); } return buf; } static const char* am_reqStr(c_nodeid_t tgtNode, amRequest_t* req, size_t reqSize) { static __thread char buf[1000]; int len; len = snprintf(buf, sizeof(buf), "seqId %s, %s, sz %zd", am_seqIdStr(req), am_opName(req->b.op), reqSize); switch (req->b.op) { case am_opExecOn: len += snprintf(buf + len, sizeof(buf) - len, ", fid %d(arg %p, sz %zd)%s", req->xo.hdr.comm.fid, &req->xo.hdr.payload, reqSize - offsetof(chpl_comm_on_bundle_t, payload), req->xo.hdr.comm.fast ? ", fast" : ""); break; case am_opExecOnLrg: len += snprintf(buf + len, sizeof(buf) - len, ", fid %d(arg %p, sz %zd)", req->xol.hdr.comm.fid, req->xol.pPayload, req->xol.hdr.comm.argSize); break; case am_opGet: len += snprintf(buf + len, sizeof(buf) - len, ", %d:%p <- %d:%p, sz %zd", (int) tgtNode, req->rma.addr, req->rma.b.node, req->rma.raddr, req->rma.size); break; case am_opPut: len += snprintf(buf + len, sizeof(buf) - len, ", %d:%p -> %d:%p, sz %zd", (int) tgtNode, req->rma.addr, req->rma.b.node, req->rma.raddr, req->rma.size); break; case am_opAMO: if (req->amo.ofiOp == FI_CSWAP) { len += snprintf(buf + len, sizeof(buf) - len, ", obj %p, opnd %s, cmpr %s, res %p" ", ofiOp %s, ofiType %s, sz %d", req->amo.obj, DBG_VAL(&req->amo.opnd, req->amo.ofiType), DBG_VAL(&req->amo.cmpr, req->amo.ofiType), req->amo.result, amo_opName(req->amo.ofiOp), amo_typeName(req->amo.ofiType), req->amo.size); } else if (req->amo.result != NULL) { if (req->amo.ofiOp == FI_ATOMIC_READ) { len += snprintf(buf + len, sizeof(buf) - len, ", obj %p, res %p" ", ofiOp %s, ofiType %s, sz %d", req->amo.obj, req->amo.result, amo_opName(req->amo.ofiOp), amo_typeName(req->amo.ofiType), req->amo.size); } else { len += snprintf(buf + len, sizeof(buf) - len, ", obj %p, opnd %s, res %p" ", ofiOp %s, ofiType %s, sz %d", req->amo.obj, DBG_VAL(&req->amo.opnd, req->amo.ofiType), req->amo.result, amo_opName(req->amo.ofiOp), amo_typeName(req->amo.ofiType), req->amo.size); } } else { len += snprintf(buf + len, sizeof(buf) - len, ", obj %p, opnd %s" ", ofiOp %s, ofiType %s, sz %d", req->amo.obj, DBG_VAL(&req->amo.opnd, req->amo.ofiType), amo_opName(req->amo.ofiOp), amo_typeName(req->amo.ofiType), req->amo.size); } break; case am_opFree: len += snprintf(buf + len, sizeof(buf) - len, ", %p", req->free.p); break; default: break; } amDone_t* pAmDone = op_uses_on_bundle(req->b.op) ? req->xo.hdr.comm.pAmDone : req->b.pAmDone; if (pAmDone == NULL) { (void) snprintf(buf + len, sizeof(buf) - len, ", NB"); } else { (void) snprintf(buf + len, sizeof(buf) - len, ", pAmDone %p", pAmDone); } return buf; } static const char* am_reqStartStr(amRequest_t* req) { static __thread char buf[100]; (void) snprintf(buf, sizeof(buf), "run AM seqId %s body in %s", am_seqIdStr(req), (amTcip == NULL) ? "task" : "AM handler"); return buf; } static const char* am_reqDoneStr(amRequest_t* req) { static __thread char buf[100]; amDone_t* pAmDone = op_uses_on_bundle(req->b.op) ? req->xo.hdr.comm.pAmDone : req->b.pAmDone; if (pAmDone == NULL) { (void) snprintf(buf, sizeof(buf), "fini AM seqId %s, NB", am_seqIdStr(req)); } else { (void) snprintf(buf, sizeof(buf), "fini AM seqId %s, set pAmDone %p", am_seqIdStr(req), pAmDone); } return buf; } static inline void am_debugPrep(amRequest_t* req) { if (DBG_TEST_MASK(DBG_AM | DBG_AM_SEND | DBG_AM_RECV) || (req->b.op == am_opAMO && DBG_TEST_MASK(DBG_AMO))) { static chpl_bool seqInited = false; static atomic_uint_least64_t seqNext; if (!seqInited) { static pthread_mutex_t seqLock = PTHREAD_MUTEX_INITIALIZER; PTHREAD_CHK(pthread_mutex_lock(&seqLock)); if (!seqInited) { seqInited = true; atomic_init_uint_least64_t(&seqNext, 1); } PTHREAD_CHK(pthread_mutex_unlock(&seqLock)); } uint64_t seq = atomic_fetch_add_uint_least64_t(&seqNext, 1); if (op_uses_on_bundle(req->b.op)) { req->xo.hdr.comm.seq = seq; } else { req->b.seq = seq; } } } static void dbg_catfile(const char* fname, const char* match) { FILE* f; char buf[1000]; if ((f = fopen(fname, "r")) == NULL) { INTERNAL_ERROR_V("%s(): fopen(\"%s\") failed", __func__, fname); } (void) fprintf(chpl_comm_ofi_dbg_file, "==============================\nfile: %s\n\n", fname); while (fgets(buf, sizeof(buf), f) != NULL) { if (match == NULL || strstr(buf, match) != NULL) { (void) fputs(buf, chpl_comm_ofi_dbg_file); } } (void) fclose(f); } #endif
32.915754
94
0.589226
[ "object", "vector", "model" ]
b78c14ad255cea3b1a757a1b7cb3e92191858c61
605
h
C
Koulupeliprojekti/src/VM/Compiler/AST/ASTNode.h
Valtis/Peliprojekti-2013
56483e669e040e0180ea244077cbee578c034016
[ "BSL-1.0" ]
null
null
null
Koulupeliprojekti/src/VM/Compiler/AST/ASTNode.h
Valtis/Peliprojekti-2013
56483e669e040e0180ea244077cbee578c034016
[ "BSL-1.0" ]
null
null
null
Koulupeliprojekti/src/VM/Compiler/AST/ASTNode.h
Valtis/Peliprojekti-2013
56483e669e040e0180ea244077cbee578c034016
[ "BSL-1.0" ]
null
null
null
#pragma once #include "VM/Compiler/AST/ASTVisitor.h" #include <vector> #include <memory> #include <string> #include <cstdint> namespace Compiler { class ASTNode { public: virtual ~ASTNode(); std::vector<ASTNode*> GetChildren(); void SetLine(uint32_t line) { m_line = line; } void SetColumn(uint32_t column) { m_column = column; } void AddChild(std::shared_ptr<ASTNode> node); virtual void Accept(ASTVisitor &visitor) = 0; std::string GetPositionInfo(); private: std::vector<std::shared_ptr<ASTNode>> m_children; uint32_t m_line; uint32_t m_column; }; }
24.2
59
0.68595
[ "vector" ]
b796e1ec44443e4bcae6cd4a4630fcfac8f67a97
232
h
C
TinyEngine/src/gltf/Buffer.h
Kimau/KhronosSandbox
e06caed3ab85e620ac2c5860fd31cef6ed6418c3
[ "Apache-2.0" ]
68
2020-04-14T11:03:26.000Z
2020-06-11T16:17:29.000Z
TinyEngine/src/gltf/Buffer.h
Kimau/KhronosSandbox
e06caed3ab85e620ac2c5860fd31cef6ed6418c3
[ "Apache-2.0" ]
5
2020-05-16T05:32:16.000Z
2020-05-21T11:09:52.000Z
TinyEngine/src/gltf/Buffer.h
Kimau/KhronosSandbox
e06caed3ab85e620ac2c5860fd31cef6ed6418c3
[ "Apache-2.0" ]
1
2021-03-19T22:47:00.000Z
2021-03-19T22:47:00.000Z
#ifndef GLTF_BUFFER_H_ #define GLTF_BUFFER_H_ #include <string> #include <vector> struct Buffer { std::string uri = ""; uint32_t byteLength = 0; // Generic helper std::vector<uint8_t> binary; }; #endif /* GLTF_BUFFER_H_ */
13.647059
29
0.702586
[ "vector" ]
b7970b2583bf4e35396e444558f47256d7c8dd5b
9,497
h
C
src/Access/Quota.h
tianyiYoung/ClickHouse
41012b5ba49df807af52fc17ab475a21fadda9b3
[ "Apache-2.0" ]
5
2021-05-14T02:46:44.000Z
2021-11-23T04:58:20.000Z
src/Access/Quota.h
tianyiYoung/ClickHouse
41012b5ba49df807af52fc17ab475a21fadda9b3
[ "Apache-2.0" ]
5
2021-05-21T06:26:01.000Z
2021-08-04T04:57:36.000Z
src/Access/Quota.h
tianyiYoung/ClickHouse
41012b5ba49df807af52fc17ab475a21fadda9b3
[ "Apache-2.0" ]
8
2021-05-12T01:38:18.000Z
2022-02-10T06:08:41.000Z
#pragma once #include <Access/IAccessEntity.h> #include <Access/RolesOrUsersSet.h> #include <ext/range.h> #include <boost/algorithm/string/split.hpp> #include <boost/lexical_cast.hpp> #include <chrono> namespace DB { namespace ErrorCodes { extern const int LOGICAL_ERROR; } /** Quota for resources consumption for specific interval. * Used to limit resource usage by user. * Quota is applied "softly" - could be slightly exceed, because it is checked usually only on each block of processed data. * Accumulated values are not persisted and are lost on server restart. * Quota is local to server, * but for distributed queries, accumulated values for read rows and bytes * are collected from all participating servers and accumulated locally. */ struct Quota : public IAccessEntity { using ResourceAmount = UInt64; enum ResourceType { QUERIES, /// Number of queries. QUERY_SELECTS, /// Number of select queries. QUERY_INSERTS, /// Number of inserts queries. ERRORS, /// Number of queries with exceptions. RESULT_ROWS, /// Number of rows returned as result. RESULT_BYTES, /// Number of bytes returned as result. READ_ROWS, /// Number of rows read from tables. READ_BYTES, /// Number of bytes read from tables. EXECUTION_TIME, /// Total amount of query execution time in nanoseconds. MAX_RESOURCE_TYPE }; struct ResourceTypeInfo { const char * const raw_name = ""; const String name; /// Lowercased with underscores, e.g. "result_rows". const String keyword; /// Uppercased with spaces, e.g. "RESULT ROWS". const bool output_as_float = false; const UInt64 output_denominator = 1; String amountToString(ResourceAmount amount) const; ResourceAmount amountFromString(const String & str) const; String outputWithAmount(ResourceAmount amount) const; static const ResourceTypeInfo & get(ResourceType type); }; /// Amount of resources available to consume for each duration. struct Limits { std::optional<ResourceAmount> max[MAX_RESOURCE_TYPE]; std::chrono::seconds duration = std::chrono::seconds::zero(); /// Intervals can be randomized (to avoid DoS if intervals for many users end at one time). bool randomize_interval = false; friend bool operator ==(const Limits & lhs, const Limits & rhs); friend bool operator !=(const Limits & lhs, const Limits & rhs) { return !(lhs == rhs); } }; std::vector<Limits> all_limits; /// Key to share quota consumption. /// Users with the same key share the same amount of resource. enum class KeyType { NONE, /// All users share the same quota. USER_NAME, /// Connections with the same user name share the same quota. IP_ADDRESS, /// Connections from the same IP share the same quota. FORWARDED_IP_ADDRESS, /// Use X-Forwarded-For HTTP header instead of IP address. CLIENT_KEY, /// Client should explicitly supply a key to use. CLIENT_KEY_OR_USER_NAME, /// Same as CLIENT_KEY, but use USER_NAME if the client doesn't supply a key. CLIENT_KEY_OR_IP_ADDRESS, /// Same as CLIENT_KEY, but use IP_ADDRESS if the client doesn't supply a key. MAX }; struct KeyTypeInfo { const char * const raw_name; const String name; /// Lowercased with underscores, e.g. "client_key". const std::vector<KeyType> base_types; /// For combined types keeps base types, e.g. for CLIENT_KEY_OR_USER_NAME it keeps [KeyType::CLIENT_KEY, KeyType::USER_NAME]. static const KeyTypeInfo & get(KeyType type); }; KeyType key_type = KeyType::NONE; /// Which roles or users should use this quota. RolesOrUsersSet to_roles; bool equal(const IAccessEntity & other) const override; std::shared_ptr<IAccessEntity> clone() const override { return cloneImpl<Quota>(); } static constexpr const Type TYPE = Type::QUOTA; Type getType() const override { return TYPE; } }; inline String Quota::ResourceTypeInfo::amountToString(ResourceAmount amount) const { if (!(amount % output_denominator)) return std::to_string(amount / output_denominator); else return boost::lexical_cast<std::string>(static_cast<double>(amount) / output_denominator); } inline Quota::ResourceAmount Quota::ResourceTypeInfo::amountFromString(const String & str) const { if (output_denominator == 1) return static_cast<ResourceAmount>(std::strtoul(str.c_str(), nullptr, 10)); else return static_cast<ResourceAmount>(std::strtod(str.c_str(), nullptr) * output_denominator); } inline String Quota::ResourceTypeInfo::outputWithAmount(ResourceAmount amount) const { String res = name; res += " = "; res += amountToString(amount); return res; } inline String toString(Quota::ResourceType type) { return Quota::ResourceTypeInfo::get(type).raw_name; } inline const Quota::ResourceTypeInfo & Quota::ResourceTypeInfo::get(ResourceType type) { static constexpr auto make_info = [](const char * raw_name_, UInt64 output_denominator_) { String init_name = raw_name_; boost::to_lower(init_name); String init_keyword = raw_name_; boost::replace_all(init_keyword, "_", " "); bool init_output_as_float = (output_denominator_ != 1); return ResourceTypeInfo{raw_name_, std::move(init_name), std::move(init_keyword), init_output_as_float, output_denominator_}; }; switch (type) { case Quota::QUERIES: { static const auto info = make_info("QUERIES", 1); return info; } case Quota::QUERY_SELECTS: { static const auto info = make_info("QUERY_SELECTS", 1); return info; } case Quota::QUERY_INSERTS: { static const auto info = make_info("QUERY_INSERTS", 1); return info; } case Quota::ERRORS: { static const auto info = make_info("ERRORS", 1); return info; } case Quota::RESULT_ROWS: { static const auto info = make_info("RESULT_ROWS", 1); return info; } case Quota::RESULT_BYTES: { static const auto info = make_info("RESULT_BYTES", 1); return info; } case Quota::READ_ROWS: { static const auto info = make_info("READ_ROWS", 1); return info; } case Quota::READ_BYTES: { static const auto info = make_info("READ_BYTES", 1); return info; } case Quota::EXECUTION_TIME: { static const auto info = make_info("EXECUTION_TIME", 1000000000 /* execution_time is stored in nanoseconds */); return info; } case Quota::MAX_RESOURCE_TYPE: break; } throw Exception("Unexpected resource type: " + std::to_string(static_cast<int>(type)), ErrorCodes::LOGICAL_ERROR); } inline String toString(Quota::KeyType type) { return Quota::KeyTypeInfo::get(type).raw_name; } inline const Quota::KeyTypeInfo & Quota::KeyTypeInfo::get(KeyType type) { static constexpr auto make_info = [](const char * raw_name_) { String init_name = raw_name_; boost::to_lower(init_name); std::vector<KeyType> init_base_types; String replaced = boost::algorithm::replace_all_copy(init_name, "_or_", "|"); Strings tokens; boost::algorithm::split(tokens, replaced, boost::is_any_of("|")); if (tokens.size() > 1) { for (const auto & token : tokens) { for (auto kt : ext::range(KeyType::MAX)) { if (KeyTypeInfo::get(kt).name == token) { init_base_types.push_back(kt); break; } } } } return KeyTypeInfo{raw_name_, std::move(init_name), std::move(init_base_types)}; }; switch (type) { case KeyType::NONE: { static const auto info = make_info("NONE"); return info; } case KeyType::USER_NAME: { static const auto info = make_info("USER_NAME"); return info; } case KeyType::IP_ADDRESS: { static const auto info = make_info("IP_ADDRESS"); return info; } case KeyType::FORWARDED_IP_ADDRESS: { static const auto info = make_info("FORWARDED_IP_ADDRESS"); return info; } case KeyType::CLIENT_KEY: { static const auto info = make_info("CLIENT_KEY"); return info; } case KeyType::CLIENT_KEY_OR_USER_NAME: { static const auto info = make_info("CLIENT_KEY_OR_USER_NAME"); return info; } case KeyType::CLIENT_KEY_OR_IP_ADDRESS: { static const auto info = make_info("CLIENT_KEY_OR_IP_ADDRESS"); return info; } case KeyType::MAX: break; } throw Exception("Unexpected quota key type: " + std::to_string(static_cast<int>(type)), ErrorCodes::LOGICAL_ERROR); } using QuotaPtr = std::shared_ptr<const Quota>; }
34.039427
172
0.621354
[ "vector" ]
b79a800b4299356b114707b6cee8cae184ce545d
583
h
C
AR_Drone_Models/Flight_Models/slprj/ert/_sharedutils/multiword_types.h
raphael-roy/Simulink_AR_Drone
079cb184e78ee940721cdf0cadc4c60ce42f008d
[ "BSD-3-Clause" ]
null
null
null
AR_Drone_Models/Flight_Models/slprj/ert/_sharedutils/multiword_types.h
raphael-roy/Simulink_AR_Drone
079cb184e78ee940721cdf0cadc4c60ce42f008d
[ "BSD-3-Clause" ]
null
null
null
AR_Drone_Models/Flight_Models/slprj/ert/_sharedutils/multiword_types.h
raphael-roy/Simulink_AR_Drone
079cb184e78ee940721cdf0cadc4c60ce42f008d
[ "BSD-3-Clause" ]
2
2018-04-20T20:41:27.000Z
2020-01-14T09:13:11.000Z
/* * File: multiword_types.h * * Code generated for Simulink model 'AR_Drone_Flight_Control'. * * Model version : 1.1216 * Simulink Coder version : 8.6 (R2014a) 27-Dec-2013 * C/C++ source code generated on : Tue Nov 17 10:18:08 2015 */ #ifndef __MULTIWORD_TYPES_H__ #define __MULTIWORD_TYPES_H__ #include "rtwtypes.h" /* * Definitions supporting external data access */ typedef int32_T chunk_T; typedef uint32_T uchunk_T; #endif /* __MULTIWORD_TYPES_H__ */ /* * File trailer for generated code. * * [EOF] */
20.821429
66
0.64494
[ "model" ]
b79e47262b31f47ff383e9b5b780faf69ea6d0bd
7,748
h
C
Algebraic_kernel_d/test/Algebraic_kernel_d/include/CGAL/_test_real_root_isolator.h
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
3,227
2015-03-05T00:19:18.000Z
2022-03-31T08:20:35.000Z
Algebraic_kernel_d/test/Algebraic_kernel_d/include/CGAL/_test_real_root_isolator.h
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
5,574
2015-03-05T00:01:56.000Z
2022-03-31T15:08:11.000Z
Algebraic_kernel_d/test/Algebraic_kernel_d/include/CGAL/_test_real_root_isolator.h
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
1,274
2015-03-05T00:01:12.000Z
2022-03-31T14:47:56.000Z
// Copyright (c) 2006-2009 Max-Planck-Institute Saarbruecken (Germany). // All rights reserved. // // This file is part of CGAL (www.cgal.org) // // $URL$ // $Id$ // SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial // // Author(s) : Michael Hemmer <hemmer@mpi-inf.mpg.de> // // ============================================================================ // TODO: The comments are all original EXACUS comments and aren't adapted. So // they may be wrong now. #include <cassert> #include <vector> #include <CGAL/config.h> #include <CGAL/Arithmetic_kernel.h> #include <CGAL/ipower.h> #ifndef CGAL_TEST_REAL_ROOT_ISOLATOR_H #define CGAL_TEST_REAL_ROOT_ISOLATOR_H namespace CGAL { namespace internal { template <class RealRootIsolator> int check_intervals_real_root_isolator( const typename RealRootIsolator::Polynomial& P) { typedef RealRootIsolator Isolator; typedef typename Isolator::Bound Bound; typedef typename CGAL::Get_arithmetic_kernel< Bound >::Arithmetic_kernel AK; typedef typename AK::Rational Rational; Isolator Isol(P); int n = Isol.number_of_real_roots(); for(int i=0; i<n; i++) { Rational left = Isol.left_bound(i); Rational right = Isol.right_bound(i); if(!Isol.is_exact_root(i)) { assert(left < right); //std::cout << " left = " << left << std::endl; //std::cout << " right = " << right << std::endl; //std::cout << " P = " << P << std::endl; assert(P.sign_at(left) * P.sign_at(right) == CGAL::NEGATIVE); }else{ assert(left == right); assert(P.sign_at(left) == CGAL::ZERO); } } return n; } // Not part of the concept /* template <class RealRootIsolator, class Polynomial, class Bound> int check_intervals_real_root_isolator( const Polynomial& P, const Bound& a, const Bound& b) { typedef RealRootIsolator Isolator; Isolator Isol(P,a,b); int n = Isol.number_of_real_roots(); for(int i=0; i<n; i++) { Bound left = Isol.left_bound(i); Bound right = Isol.right_bound(i); assert( left < right || Isol.is_exact_root(i)); if(!Isol.is_exact_root(i)) { //std::cout << " left = " << left << std::endl; //std::cout << " right = " << right << std::endl; //std::cout << " P = " << P << std::endl; assert(CGAL::evaluate(P,left) * CGAL::evaluate(P,right) < 0); } } return n; }; */ template <class RealRootIsolator> void test_real_root_isolator() { typedef RealRootIsolator Isolator; typedef typename Isolator::Polynomial Polynomial; CGAL_USE_TYPE(typename Isolator::Bound); typedef typename Polynomial::NT NT; // just some Polynomials (not all are used) Polynomial P_00(NT(0)); // zero polynomial Polynomial P_01(NT(1)); // constant polynomial Polynomial P_1(NT(-1),NT(1)); //(x-1) Polynomial P_2(NT(-2),NT(1)); //(x-2) Polynomial P_3(NT(-3),NT(1)); //(x-3) Polynomial P_4(NT(-4),NT(1)); //(x-4) Polynomial P_12=P_1*P_2; //(x-1)(x-2) Polynomial P_123=P_1*P_2*P_3; //(x-1)(x-2)(x-3) Polynomial P_s2(NT(-2),NT(0),NT(1)); //(x^2-2) Polynomial P_s5(-NT(5),NT(0),NT(1)); //(x^2-5) Polynomial P_s10(-NT(10),NT(0),NT(1)); //(x^2-10) Polynomial P_s30(-NT(30),NT(0),NT(1)); //(x^2-30) Polynomial P_s2510= P_s2*P_s5*P_s10; Polynomial P_s530= P_s5*P_s30; // special cases: /* { // default constructor: // as from zero Polynomial Isolator isolator; assert(isolator.number_of_real_roots() == -1); assert(isolator.polynomial() == Polynomial(0)); }{ // from zero polynomial Isolator isolator(P_00); assert(isolator.number_of_real_roots() == -1); assert(isolator.polynomial() == P_00); } */ { // from constant polynomial = 1 Polynomial poly(P_01); Isolator isolator(poly); assert(isolator.number_of_real_roots() == 0); assert(isolator.polynomial() == P_01); }{ // copy constructor Isolator isolator_1(P_123); Isolator isolator_2(isolator_1); assert(isolator_1.number_of_real_roots() == isolator_2.number_of_real_roots()); assert(isolator_1.polynomial() == isolator_2.polynomial()); }{ // assign Isolator isolator_1(P_123); Isolator isolator_2 = isolator_1; assert(isolator_1.number_of_real_roots() == isolator_2.number_of_real_roots()); assert(isolator_1.polynomial() == isolator_2.polynomial()); } { assert( 3 == internal::check_intervals_real_root_isolator<Isolator>(P_123)); }{ assert( 1 == internal::check_intervals_real_root_isolator<Isolator>(P_1)); }{ assert( 3 == internal::check_intervals_real_root_isolator<Isolator>(P_123)); }{ assert(6 == internal::check_intervals_real_root_isolator<Isolator>(P_s2510)); }{ // (x^2-2)*(x^2-3) std::vector<NT> VP(5); VP[0] = NT(6); VP[1] = NT(0); VP[2] = NT(-5); VP[3] = NT(0); VP[4] = NT(1); Polynomial P(VP.begin(), VP.end()); assert(4 == internal::check_intervals_real_root_isolator<Isolator>(P)); } { // (x^2-2)*(x^2+2)*(x-1) std::vector<NT> VP(6); VP[0] = NT(4); VP[1] = NT(-4); VP[2] = NT(0); VP[3] = NT(0); VP[4] = NT(-1); VP[5] = NT(1); Polynomial P(VP.begin(), VP.end()); assert(3 == internal::check_intervals_real_root_isolator<Isolator>(P)); }{ // std::cout << "Wilkinson Polynomial\n"; int number_of_roots = 20; Polynomial P(1); for(int i=1; i<=number_of_roots ; i++) { P*=Polynomial(NT(-i),NT(1)); } Isolator isolator(P); int n = internal::check_intervals_real_root_isolator<Isolator>(P); assert( n == number_of_roots); }{ //std::cout << "Kameny 3\n"; // from http://www-sop.inria.fr/saga/POL/BASE/1.unipol NT c = CGAL::ipower(NT(10),12); Polynomial P(NT(-3),NT(0),c); P = P*P; // (c^2x^2-3)^2 Polynomial Q (NT(0),NT(1)); Q = Q*Q; // x^2 Q = Q*Q; // x^4 Q = Q*Q; // x^8 Q = Q*Polynomial(NT(0),c);//c^2x^9 P = P+Q; assert(3 == internal::check_intervals_real_root_isolator<Isolator>(P)); }{ //std::cout << "Kameny 4\n"; // from http://www-sop.inria.fr/saga/POL/BASE/1.unipol NT z(0); NT a = CGAL::ipower(NT(10),24); // a = 10^{24} Polynomial P(z,NT(4),CGAL::ipower(a,2),z,z,2*a,z,z,NT(1)); // x^8+2*10^{24}*x^5+10^{48}*x^2+4*x P = P * Polynomial(z,z,z,z,z,z,NT(1)); // x^{14}+2*10^{24}*x^{11}+10^{48}*x^8+4*x^7 P = P + Polynomial(NT(4),z,z,z,-4*a); // x^{14}+2*10^{24}*x^{11}+10^{48}*x^8+4*x^7-4*10^{24}*X^4+4 Isolator isol(P); assert( 4 == internal::check_intervals_real_root_isolator<Isolator>(P)); }{ //std::cout << "Polynomial with large and small clustered roots\n"; // from http://www-sop.inria.fr/saga/POL/BASE/1.unipol // there seems to be some error or misunderstanding NT z(0); NT a = CGAL::ipower(NT(10),20); // a = 10^{20} Polynomial P(z,z,z,z,z,z,z,z,NT(1)); //x^8 P = P*Polynomial(z,z,z,z,NT(1)); // x^{12} Polynomial R(NT(-1),a); // ax-1 R = R*R; R = R*R; // (ax-1)^4 P = P-R; // x^{12} - (ax-1)^4 assert( 4 == internal::check_intervals_real_root_isolator<Isolator>(P)); } } } //namespace internal } //namespace CGAL #endif // CGAL_TEST_REAL_ROOT_ISOLATOR_H
31.754098
83
0.564275
[ "vector" ]
b79eacff2683612af4f5a409810f2bf6f62c3c4d
1,582
h
C
ecs/include/huaweicloud/ecs/v2/model/NovaAssociateSecurityGroupRequestBody.h
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
ecs/include/huaweicloud/ecs/v2/model/NovaAssociateSecurityGroupRequestBody.h
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
null
null
null
ecs/include/huaweicloud/ecs/v2/model/NovaAssociateSecurityGroupRequestBody.h
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#ifndef HUAWEICLOUD_SDK_ECS_V2_MODEL_NovaAssociateSecurityGroupRequestBody_H_ #define HUAWEICLOUD_SDK_ECS_V2_MODEL_NovaAssociateSecurityGroupRequestBody_H_ #include <huaweicloud/ecs/v2/EcsExport.h> #include <huaweicloud/core/utils/ModelBase.h> #include <huaweicloud/core/http/HttpResponse.h> #include <huaweicloud/ecs/v2/model/NovaAddSecurityGroupOption.h> namespace HuaweiCloud { namespace Sdk { namespace Ecs { namespace V2 { namespace Model { using namespace HuaweiCloud::Sdk::Core::Utils; using namespace HuaweiCloud::Sdk::Core::Http; /// <summary> /// This is a auto create Body Object /// </summary> class HUAWEICLOUD_ECS_V2_EXPORT NovaAssociateSecurityGroupRequestBody : public ModelBase { public: NovaAssociateSecurityGroupRequestBody(); virtual ~NovaAssociateSecurityGroupRequestBody(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; bool fromJson(const web::json::value& json) override; ///////////////////////////////////////////// /// NovaAssociateSecurityGroupRequestBody members /// <summary> /// /// </summary> NovaAddSecurityGroupOption getAddSecurityGroup() const; bool addSecurityGroupIsSet() const; void unsetaddSecurityGroup(); void setAddSecurityGroup(const NovaAddSecurityGroupOption& value); protected: NovaAddSecurityGroupOption addSecurityGroup_; bool addSecurityGroupIsSet_; }; } } } } } #endif // HUAWEICLOUD_SDK_ECS_V2_MODEL_NovaAssociateSecurityGroupRequestBody_H_
23.969697
79
0.726928
[ "object", "model" ]
b7a090bf9740032875b33411b19970c406422273
8,421
h
C
components/lib/include/dl_lib_matrix3d.h
m5stack/esp-who
102fca12a7349bbac25b09f0919ba3d8dba4e470
[ "MIT-0" ]
13
2018-12-13T10:53:03.000Z
2020-04-20T08:34:09.000Z
components/lib/include/dl_lib_matrix3d.h
m5stack/esp-who
102fca12a7349bbac25b09f0919ba3d8dba4e470
[ "MIT-0" ]
null
null
null
components/lib/include/dl_lib_matrix3d.h
m5stack/esp-who
102fca12a7349bbac25b09f0919ba3d8dba4e470
[ "MIT-0" ]
2
2018-12-19T05:56:52.000Z
2019-02-03T11:06:57.000Z
#pragma once typedef float fptp_t; typedef uint8_t uc_t; typedef enum { DL_C_IMPL = 0, DL_XTENSA_IMPL = 1 } dl_conv_mode; typedef enum { INPUT_UINT8 = 0, INPUT_FLOAT = 1, } dl_op_type; typedef enum { PADDING_VALID = 0, PADDING_SAME = 1, } dl_padding_type; /* * Matrix for 3d * @Warning: the sequence of variables is fixed, cannot be modified, otherwise there will be errors in esp_dsp_dot_float */ typedef struct { /******* fix start *******/ int w; // Width int h; // Height int c; // Channel int n; // Number, to record filter's out_channels. input and output must be 1 int stride; fptp_t *item; /******* fix end *******/ } dl_matrix3d_t; typedef struct { int w; // Width int h; // Height int c; // Channel int n; // Number, to record filter's out_channels. input and output must be 1 int stride; uc_t *item; } dl_matrix3du_t; typedef struct { int stride_x; int stride_y; dl_padding_type padding; dl_conv_mode mode; dl_op_type type; } dl_matrix3d_conv_config_t; /* * @brief Allocate a 3D matrix with float items, the access sequence is NHWC * * @param n Number of matrix3d, for filters it is out channels, for others it is 1 * @param w Width of matrix3d * @param h Height of matrix3d * @param c Channel of matrix3d * @return 3d matrix */ dl_matrix3d_t *dl_matrix3d_alloc(int n, int w, int h, int c); /* * @brief Allocate a 3D matrix with 8-bits items, the access sequence is NHWC * * @param n Number of matrix3d, for filters it is out channels, for others it is 1 * @param w Width of matrix3d * @param h Height of matrix3d * @param c Channel of matrix3d * @return 3d matrix */ dl_matrix3du_t *dl_matrix3du_alloc(int n, int w, int h, int c); /* * @brief Free a matrix3d * * @param m matrix3d with float items */ void dl_matrix3d_free(dl_matrix3d_t *m); /* * @brief Free a matrix3d * * @param m matrix3d with 8-bits items */ void dl_matrix3du_free(dl_matrix3du_t *m); /** * @brief Do a relu (Rectifier Linear Unit) operation, update the input matrix3d * * @param in Floating point input matrix3d * @param clip If value is higher than this, it will be clipped to this value */ void dl_matrix3d_relu (dl_matrix3d_t *m, fptp_t clip); /** * @brief Do a leaky relu (Rectifier Linear Unit) operation, update the input matrix3d * * @param in Floating point input matrix3d * @param clip If value is higher than this, it will be clipped to this value * @param alpha If value is less than zero, it will be updated by multiplying this factor */ void dl_matrix3d_leaky_relu (dl_matrix3d_t *m, fptp_t clip, fptp_t alpha); /** * @brief Do a softmax operation on a matrix3d * * @param in Input matrix3d */ void dl_matrix3d_softmax (dl_matrix3d_t *m); /** * @brief Do a general fully connected layer pass, dimension is (number, width, height, channel) * * @param in Input matrix3d, size is (1, w, 1, 1) * @param filter Weights of the neurons, size is (1, w, h, 1) * @param bias Bias for the fc layer, size is (1, 1, 1, h) * @return The result of fc layer, size is (1, 1, 1, h) */ dl_matrix3d_t *dl_matrix3d_fc (dl_matrix3d_t *in, dl_matrix3d_t *filter, dl_matrix3d_t *bias); /** * @brief Copy a range of float items from an existing matrix to a preallocated matrix * * @param dst The destination slice matrix * @param src The source matrix to slice * @param x X-offset of the origin of the returned matrix within the sliced matrix * @param y Y-offset of the origin of the returned matrix within the sliced matrix * @param w Width of the resulting matrix * @param h Height of the resulting matrix */ void dl_matrix3d_slice_copy (dl_matrix3d_t *dst, dl_matrix3d_t *src, int x, int y, int w, int h); /** * @brief Copy a range of 8-bits items from an existing matrix to a preallocated matrix * * @param dst The destination slice matrix * @param src The source matrix to slice * @param x X-offset of the origin of the returned matrix within the sliced matrix * @param y Y-offset of the origin of the returned matrix within the sliced matrix * @param w Width of the resulting matrix * @param h Height of the resulting matrix */ void dl_matrix3du_slice_copy (dl_matrix3du_t *dst, dl_matrix3du_t *src, int x, int y, int w, int h); /** * @brief Do a general CNN layer pass, dimension is (number, width, height, channel) * * @param in Input matrix3d * @param filter Weights of the neurons * @param bias Bias for the CNN layer * @param stride_x The step length of the convolution window in x(width) direction * @param stride_y The step length of the convolution window in y(height) direction * @param padding One of VALID or SAME * @param mode Do convolution using C implement or xtensa implement, 0 or 1, with respect * If ESP_PLATFORM is not defined, this value is not used. Default is 0 * @return The result of CNN layer */ dl_matrix3d_t *dl_matrix3d_conv (dl_matrix3d_t *in, dl_matrix3d_t *filter, dl_matrix3d_t *bias, int stride_x, int stride_y, int padding, int mode); /** * @brief Do a general CNN layer pass, dimension is (number, width, height, channel) * * @param in Input matrix3d * @param filter Weights of the neurons * @param bias Bias for the CNN layer * @param stride_x The step length of the convolution window in x(width) direction * @param stride_y The step length of the convolution window in y(height) direction * @param padding One of VALID or SAME * @param mode Do convolution using C implement or xtensa implement, 0 or 1, with respect * If ESP_PLATFORM is not defined, this value is not used. Default is 0 * @return The result of CNN layer */ dl_matrix3d_t *dl_matrix3du_conv (dl_matrix3du_t *in, dl_matrix3d_t *filter, dl_matrix3d_t *bias, int stride_x, int stride_y, int padding, int mode); /** * @brief Do a depthwise CNN layer pass, dimension is (number, width, height, channel) * * @param in Input matrix3d * @param filter Weights of the neurons * @param stride_x The step length of the convolution window in x(width) direction * @param stride_y The step length of the convolution window in y(height) direction * @param padding One of VALID or SAME * @param mode Do convolution using C implement or xtensa implement, 0 or 1, with respect * If ESP_PLATFORM is not defined, this value is not used. Default is 0 * @return The result of depthwise CNN layer */ dl_matrix3d_t *dl_matrix3d_depthwise_conv (dl_matrix3d_t *in, dl_matrix3d_t *filter, int stride_x, int stride_y, int padding, int mode); /** * @brief Do a mobilenet block forward, dimension is (number, width, height, channel) * * @param in Input matrix3d * @param filter Weights of the neurons * @param stride_x The step length of the convolution window in x(width) direction * @param stride_y The step length of the convolution window in y(height) direction * @param padding One of VALID or SAME * @param mode Do convolution using C implement or xtensa implement, 0 or 1, with respect * If ESP_PLATFORM is not defined, this value is not used. Default is 0 * @return The result of depthwise CNN layer */ dl_matrix3d_t *dl_matrix3d_mobilenet (void *in, dl_matrix3d_t *dilate, dl_matrix3d_t *depthwise, dl_matrix3d_t *compress, dl_matrix3d_t *bias, dl_matrix3d_t *prelu, dl_matrix3d_conv_config_t *config); /** * @brief Print the matrix3d items * * @param m dl_matrix3d_t to be printed * @param message name of matrix */ void dl_matrix3d_print (dl_matrix3d_t *m, char *message); /** * @brief Print the matrix3du items * * @param m dl_matrix3du_t to be printed * @param message name of matrix */ void dl_matrix3du_print (dl_matrix3du_t *m, char *message);
35.531646
120
0.657642
[ "3d" ]
b7a09b21ab36f026317546c1850e283e951f88a5
12,591
c
C
kernel/linux-5.4/drivers/misc/ocxl/core.c
josehu07/SplitFS
d7442fa67a17de7057664f91defbfdbf10dd7f4a
[ "Apache-2.0" ]
27
2021-10-04T18:56:52.000Z
2022-03-28T08:23:06.000Z
kernel/linux-5.4/drivers/misc/ocxl/core.c
josehu07/SplitFS
d7442fa67a17de7057664f91defbfdbf10dd7f4a
[ "Apache-2.0" ]
1
2022-01-12T04:05:36.000Z
2022-01-16T15:48:42.000Z
kernel/linux-5.4/drivers/misc/ocxl/core.c
josehu07/SplitFS
d7442fa67a17de7057664f91defbfdbf10dd7f4a
[ "Apache-2.0" ]
6
2021-11-02T10:56:19.000Z
2022-03-06T11:58:20.000Z
// SPDX-License-Identifier: GPL-2.0+ // Copyright 2019 IBM Corp. #include <linux/idr.h> #include "ocxl_internal.h" static struct ocxl_fn *ocxl_fn_get(struct ocxl_fn *fn) { return (get_device(&fn->dev) == NULL) ? NULL : fn; } static void ocxl_fn_put(struct ocxl_fn *fn) { put_device(&fn->dev); } static struct ocxl_afu *alloc_afu(struct ocxl_fn *fn) { struct ocxl_afu *afu; afu = kzalloc(sizeof(struct ocxl_afu), GFP_KERNEL); if (!afu) return NULL; kref_init(&afu->kref); mutex_init(&afu->contexts_lock); mutex_init(&afu->afu_control_lock); idr_init(&afu->contexts_idr); afu->fn = fn; ocxl_fn_get(fn); return afu; } static void free_afu(struct kref *kref) { struct ocxl_afu *afu = container_of(kref, struct ocxl_afu, kref); idr_destroy(&afu->contexts_idr); ocxl_fn_put(afu->fn); kfree(afu); } void ocxl_afu_get(struct ocxl_afu *afu) { kref_get(&afu->kref); } EXPORT_SYMBOL_GPL(ocxl_afu_get); void ocxl_afu_put(struct ocxl_afu *afu) { kref_put(&afu->kref, free_afu); } EXPORT_SYMBOL_GPL(ocxl_afu_put); static int assign_afu_actag(struct ocxl_afu *afu) { struct ocxl_fn *fn = afu->fn; int actag_count, actag_offset; struct pci_dev *pci_dev = to_pci_dev(fn->dev.parent); /* * if there were not enough actags for the function, each afu * reduces its count as well */ actag_count = afu->config.actag_supported * fn->actag_enabled / fn->actag_supported; actag_offset = ocxl_actag_afu_alloc(fn, actag_count); if (actag_offset < 0) { dev_err(&pci_dev->dev, "Can't allocate %d actags for AFU: %d\n", actag_count, actag_offset); return actag_offset; } afu->actag_base = fn->actag_base + actag_offset; afu->actag_enabled = actag_count; ocxl_config_set_afu_actag(pci_dev, afu->config.dvsec_afu_control_pos, afu->actag_base, afu->actag_enabled); dev_dbg(&pci_dev->dev, "actag base=%d enabled=%d\n", afu->actag_base, afu->actag_enabled); return 0; } static void reclaim_afu_actag(struct ocxl_afu *afu) { struct ocxl_fn *fn = afu->fn; int start_offset, size; start_offset = afu->actag_base - fn->actag_base; size = afu->actag_enabled; ocxl_actag_afu_free(afu->fn, start_offset, size); } static int assign_afu_pasid(struct ocxl_afu *afu) { struct ocxl_fn *fn = afu->fn; int pasid_count, pasid_offset; struct pci_dev *pci_dev = to_pci_dev(fn->dev.parent); /* * We only support the case where the function configuration * requested enough PASIDs to cover all AFUs. */ pasid_count = 1 << afu->config.pasid_supported_log; pasid_offset = ocxl_pasid_afu_alloc(fn, pasid_count); if (pasid_offset < 0) { dev_err(&pci_dev->dev, "Can't allocate %d PASIDs for AFU: %d\n", pasid_count, pasid_offset); return pasid_offset; } afu->pasid_base = fn->pasid_base + pasid_offset; afu->pasid_count = 0; afu->pasid_max = pasid_count; ocxl_config_set_afu_pasid(pci_dev, afu->config.dvsec_afu_control_pos, afu->pasid_base, afu->config.pasid_supported_log); dev_dbg(&pci_dev->dev, "PASID base=%d, enabled=%d\n", afu->pasid_base, pasid_count); return 0; } static void reclaim_afu_pasid(struct ocxl_afu *afu) { struct ocxl_fn *fn = afu->fn; int start_offset, size; start_offset = afu->pasid_base - fn->pasid_base; size = 1 << afu->config.pasid_supported_log; ocxl_pasid_afu_free(afu->fn, start_offset, size); } static int reserve_fn_bar(struct ocxl_fn *fn, int bar) { struct pci_dev *dev = to_pci_dev(fn->dev.parent); int rc, idx; if (bar != 0 && bar != 2 && bar != 4) return -EINVAL; idx = bar >> 1; if (fn->bar_used[idx]++ == 0) { rc = pci_request_region(dev, bar, "ocxl"); if (rc) return rc; } return 0; } static void release_fn_bar(struct ocxl_fn *fn, int bar) { struct pci_dev *dev = to_pci_dev(fn->dev.parent); int idx; if (bar != 0 && bar != 2 && bar != 4) return; idx = bar >> 1; if (--fn->bar_used[idx] == 0) pci_release_region(dev, bar); WARN_ON(fn->bar_used[idx] < 0); } static int map_mmio_areas(struct ocxl_afu *afu) { int rc; struct pci_dev *pci_dev = to_pci_dev(afu->fn->dev.parent); rc = reserve_fn_bar(afu->fn, afu->config.global_mmio_bar); if (rc) return rc; rc = reserve_fn_bar(afu->fn, afu->config.pp_mmio_bar); if (rc) { release_fn_bar(afu->fn, afu->config.global_mmio_bar); return rc; } afu->global_mmio_start = pci_resource_start(pci_dev, afu->config.global_mmio_bar) + afu->config.global_mmio_offset; afu->pp_mmio_start = pci_resource_start(pci_dev, afu->config.pp_mmio_bar) + afu->config.pp_mmio_offset; afu->global_mmio_ptr = ioremap(afu->global_mmio_start, afu->config.global_mmio_size); if (!afu->global_mmio_ptr) { release_fn_bar(afu->fn, afu->config.pp_mmio_bar); release_fn_bar(afu->fn, afu->config.global_mmio_bar); dev_err(&pci_dev->dev, "Error mapping global mmio area\n"); return -ENOMEM; } /* * Leave an empty page between the per-process mmio area and * the AFU interrupt mappings */ afu->irq_base_offset = afu->config.pp_mmio_stride + PAGE_SIZE; return 0; } static void unmap_mmio_areas(struct ocxl_afu *afu) { if (afu->global_mmio_ptr) { iounmap(afu->global_mmio_ptr); afu->global_mmio_ptr = NULL; } afu->global_mmio_start = 0; afu->pp_mmio_start = 0; release_fn_bar(afu->fn, afu->config.pp_mmio_bar); release_fn_bar(afu->fn, afu->config.global_mmio_bar); } static int configure_afu(struct ocxl_afu *afu, u8 afu_idx, struct pci_dev *dev) { int rc; rc = ocxl_config_read_afu(dev, &afu->fn->config, &afu->config, afu_idx); if (rc) return rc; rc = assign_afu_actag(afu); if (rc) return rc; rc = assign_afu_pasid(afu); if (rc) goto err_free_actag; rc = map_mmio_areas(afu); if (rc) goto err_free_pasid; return 0; err_free_pasid: reclaim_afu_pasid(afu); err_free_actag: reclaim_afu_actag(afu); return rc; } static void deconfigure_afu(struct ocxl_afu *afu) { unmap_mmio_areas(afu); reclaim_afu_pasid(afu); reclaim_afu_actag(afu); } static int activate_afu(struct pci_dev *dev, struct ocxl_afu *afu) { ocxl_config_set_afu_state(dev, afu->config.dvsec_afu_control_pos, 1); return 0; } static void deactivate_afu(struct ocxl_afu *afu) { struct pci_dev *dev = to_pci_dev(afu->fn->dev.parent); ocxl_config_set_afu_state(dev, afu->config.dvsec_afu_control_pos, 0); } static int init_afu(struct pci_dev *dev, struct ocxl_fn *fn, u8 afu_idx) { int rc; struct ocxl_afu *afu; afu = alloc_afu(fn); if (!afu) return -ENOMEM; rc = configure_afu(afu, afu_idx, dev); if (rc) { ocxl_afu_put(afu); return rc; } rc = activate_afu(dev, afu); if (rc) { deconfigure_afu(afu); ocxl_afu_put(afu); return rc; } list_add_tail(&afu->list, &fn->afu_list); return 0; } static void remove_afu(struct ocxl_afu *afu) { list_del(&afu->list); ocxl_context_detach_all(afu); deactivate_afu(afu); deconfigure_afu(afu); ocxl_afu_put(afu); // matches the implicit get in alloc_afu } static struct ocxl_fn *alloc_function(void) { struct ocxl_fn *fn; fn = kzalloc(sizeof(struct ocxl_fn), GFP_KERNEL); if (!fn) return NULL; INIT_LIST_HEAD(&fn->afu_list); INIT_LIST_HEAD(&fn->pasid_list); INIT_LIST_HEAD(&fn->actag_list); return fn; } static void free_function(struct ocxl_fn *fn) { WARN_ON(!list_empty(&fn->afu_list)); WARN_ON(!list_empty(&fn->pasid_list)); kfree(fn); } static void free_function_dev(struct device *dev) { struct ocxl_fn *fn = container_of(dev, struct ocxl_fn, dev); free_function(fn); } static int set_function_device(struct ocxl_fn *fn, struct pci_dev *dev) { int rc; fn->dev.parent = &dev->dev; fn->dev.release = free_function_dev; rc = dev_set_name(&fn->dev, "ocxlfn.%s", dev_name(&dev->dev)); if (rc) return rc; return 0; } static int assign_function_actag(struct ocxl_fn *fn) { struct pci_dev *dev = to_pci_dev(fn->dev.parent); u16 base, enabled, supported; int rc; rc = ocxl_config_get_actag_info(dev, &base, &enabled, &supported); if (rc) return rc; fn->actag_base = base; fn->actag_enabled = enabled; fn->actag_supported = supported; ocxl_config_set_actag(dev, fn->config.dvsec_function_pos, fn->actag_base, fn->actag_enabled); dev_dbg(&fn->dev, "actag range starting at %d, enabled %d\n", fn->actag_base, fn->actag_enabled); return 0; } static int set_function_pasid(struct ocxl_fn *fn) { struct pci_dev *dev = to_pci_dev(fn->dev.parent); int rc, desired_count, max_count; /* A function may not require any PASID */ if (fn->config.max_pasid_log < 0) return 0; rc = ocxl_config_get_pasid_info(dev, &max_count); if (rc) return rc; desired_count = 1 << fn->config.max_pasid_log; if (desired_count > max_count) { dev_err(&fn->dev, "Function requires more PASIDs than is available (%d vs. %d)\n", desired_count, max_count); return -ENOSPC; } fn->pasid_base = 0; return 0; } static int configure_function(struct ocxl_fn *fn, struct pci_dev *dev) { int rc; rc = pci_enable_device(dev); if (rc) { dev_err(&dev->dev, "pci_enable_device failed: %d\n", rc); return rc; } /* * Once it has been confirmed to work on our hardware, we * should reset the function, to force the adapter to restart * from scratch. * A function reset would also reset all its AFUs. * * Some hints for implementation: * * - there's not status bit to know when the reset is done. We * should try reading the config space to know when it's * done. * - probably something like: * Reset * wait 100ms * issue config read * allow device up to 1 sec to return success on config * read before declaring it broken * * Some shared logic on the card (CFG, TLX) won't be reset, so * there's no guarantee that it will be enough. */ rc = ocxl_config_read_function(dev, &fn->config); if (rc) return rc; rc = set_function_device(fn, dev); if (rc) return rc; rc = assign_function_actag(fn); if (rc) return rc; rc = set_function_pasid(fn); if (rc) return rc; rc = ocxl_link_setup(dev, 0, &fn->link); if (rc) return rc; rc = ocxl_config_set_TL(dev, fn->config.dvsec_tl_pos); if (rc) { ocxl_link_release(dev, fn->link); return rc; } return 0; } static void deconfigure_function(struct ocxl_fn *fn) { struct pci_dev *dev = to_pci_dev(fn->dev.parent); ocxl_link_release(dev, fn->link); pci_disable_device(dev); } static struct ocxl_fn *init_function(struct pci_dev *dev) { struct ocxl_fn *fn; int rc; fn = alloc_function(); if (!fn) return ERR_PTR(-ENOMEM); rc = configure_function(fn, dev); if (rc) { free_function(fn); return ERR_PTR(rc); } rc = device_register(&fn->dev); if (rc) { deconfigure_function(fn); put_device(&fn->dev); return ERR_PTR(rc); } return fn; } // Device detection & initialisation struct ocxl_fn *ocxl_function_open(struct pci_dev *dev) { int rc, afu_count = 0; u8 afu; struct ocxl_fn *fn; if (!radix_enabled()) { dev_err(&dev->dev, "Unsupported memory model (hash)\n"); return ERR_PTR(-ENODEV); } fn = init_function(dev); if (IS_ERR(fn)) { dev_err(&dev->dev, "function init failed: %li\n", PTR_ERR(fn)); return fn; } for (afu = 0; afu <= fn->config.max_afu_index; afu++) { rc = ocxl_config_check_afu_index(dev, &fn->config, afu); if (rc > 0) { rc = init_afu(dev, fn, afu); if (rc) { dev_err(&dev->dev, "Can't initialize AFU index %d\n", afu); continue; } afu_count++; } } dev_info(&dev->dev, "%d AFU(s) configured\n", afu_count); return fn; } EXPORT_SYMBOL_GPL(ocxl_function_open); struct list_head *ocxl_function_afu_list(struct ocxl_fn *fn) { return &fn->afu_list; } EXPORT_SYMBOL_GPL(ocxl_function_afu_list); struct ocxl_afu *ocxl_function_fetch_afu(struct ocxl_fn *fn, u8 afu_idx) { struct ocxl_afu *afu; list_for_each_entry(afu, &fn->afu_list, list) { if (afu->config.idx == afu_idx) return afu; } return NULL; } EXPORT_SYMBOL_GPL(ocxl_function_fetch_afu); const struct ocxl_fn_config *ocxl_function_config(struct ocxl_fn *fn) { return &fn->config; } EXPORT_SYMBOL_GPL(ocxl_function_config); void ocxl_function_close(struct ocxl_fn *fn) { struct ocxl_afu *afu, *tmp; list_for_each_entry_safe(afu, tmp, &fn->afu_list, list) { remove_afu(afu); } deconfigure_function(fn); device_unregister(&fn->dev); } EXPORT_SYMBOL_GPL(ocxl_function_close); // AFU Metadata struct ocxl_afu_config *ocxl_afu_config(struct ocxl_afu *afu) { return &afu->config; } EXPORT_SYMBOL_GPL(ocxl_afu_config); void ocxl_afu_set_private(struct ocxl_afu *afu, void *private) { afu->private = private; } EXPORT_SYMBOL_GPL(ocxl_afu_set_private); void *ocxl_afu_get_private(struct ocxl_afu *afu) { if (afu) return afu->private; return NULL; } EXPORT_SYMBOL_GPL(ocxl_afu_get_private);
21.897391
79
0.708919
[ "model" ]
b7a13a8d78b4c3bf98bab6f915c42ffbcfdd0010
142
h
C
GriptLib/pch.h
ogamespec/Gript
7e77947c170b59cda4ebc90661324861543ca3cd
[ "CC0-1.0" ]
2
2020-11-18T01:12:28.000Z
2021-04-12T02:19:53.000Z
GriptLib/pch.h
ogamespec/Gript
7e77947c170b59cda4ebc90661324861543ca3cd
[ "CC0-1.0" ]
null
null
null
GriptLib/pch.h
ogamespec/Gript
7e77947c170b59cda4ebc90661324861543ca3cd
[ "CC0-1.0" ]
null
null
null
#pragma once #include <cstdint> #include <cassert> #include <vector> #include <list> #include <string> #include "Json.h" #include "Gript.h"
12.909091
18
0.704225
[ "vector" ]
b7a3b23fe9a157e1ef580de597bf4f0c6b88c4c1
4,687
h
C
include/Chunk/Chunk.h
ivan-guerra/cpplox
b9bcb1ca94d4f2ad25e08042488520cecd4e9765
[ "MIT" ]
null
null
null
include/Chunk/Chunk.h
ivan-guerra/cpplox
b9bcb1ca94d4f2ad25e08042488520cecd4e9765
[ "MIT" ]
null
null
null
include/Chunk/Chunk.h
ivan-guerra/cpplox
b9bcb1ca94d4f2ad25e08042488520cecd4e9765
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include <cstdint> #include "Value.h" namespace lox { /*! * \class Chunk * \brief The Chunk class represents a grouping of bytecode instructions. */ class Chunk { public: /*! * \enum OpCode * \brief The OpCode enum defines the instruction types supported by Lox. */ enum OpCode { kOpConstant, kOpReturn, kOpNil, kOpTrue, kOpFalse, KOpEqual, kOpGreater, kOpLess, kOpNot, kOpNegate, kOpAdd, kOpSubtract, kOpMultiply, kOpDivide, kOpPrint, kOpPop, kOpDefineGlobal, kOpGetGlobal, kOpSetGlobal, kOpGetLocal, kOpSetLocal, kOpJumpIfFalse, kOpJump, kOpLoop, kOpCall, kOpClosure, kOpGetUpvalue, kOpSetUpvalue, kOpCloseUpvalue, kOpClass, kOpSetProperty, kOpGetProperty, kOpMethod, kOpInvoke, kOpInherit, kOpGetSuper, kOpSuperInvoke }; // end OpCode /* The defaults for compiler generated methods are appropriate. */ Chunk() = default; ~Chunk() = default; Chunk(const Chunk&) = default; Chunk& operator=(const Chunk&) = default; Chunk(Chunk&&) = default; Chunk& operator=(Chunk&&) = default; /*! * \brief Return a const reference to this Chunk's bytecode vector. */ const std::vector<uint8_t>& GetCode() const { return code_; } /*! * \brief Return the instruction at the \a ith position in the Chunk. */ uint8_t GetInstruction(int i) const { return code_[i]; } /*! * \brief Set the \a ith instruction in the Chunk to \a instruction. */ void SetInstruction(int i, uint8_t instruction) { code_[i] = instruction; } /*! * \brief Return a read only view of the Chunk's constants. */ const std::vector<val::Value>& GetConstants() const { return constants_; } /*! * \brief Return a read only view of the Chunk's line array. */ const std::vector<int>& GetLines() const { return lines_; } /*! * \brief Write a raw byte to the Chunk. * * \param byte A byte representing an opcode or opcode argument. * \param line The line number in the source text associated with this * bytecode. */ void Write(uint8_t byte, int line); /*! * \brief Add a new Lox constant value to the Chunk. * * \param value A constant Value parsed from the source text. * * \return The index of \a value in the Chunk's underlying constants array. */ int AddConstant(const val::Value& value); /*! * \brief Disassemble all instructions in this Chunk. * * \param name A label that is printed to STDOUT prior to the printing of * the decoded instruction(s) to STDOUT. */ void Disassemble(const std::string& name) const; /*! * \brief Disassemble an instruction at offset \a offset within this Chunk. */ void Disassemble(int offset) const { DisassembleInstruction(offset); } private: /*! * \brief Disassemble() helper function. * * Print the decoding of the instruction at offset \a offset within this * Chunk to STDOUT. * * \param offset Offset of the instruction being disassembled in #code_. * * \return The offset of the next instruction in the Chunk. */ std::size_t DisassembleInstruction(int offset) const; std::size_t DisassembleSimpleInstruction(const std::string& name, int offset) const; std::size_t DisassembleConstantInstruction(const std::string& name, int offset) const; std::size_t DisassembleByteInstruction(const std::string& name, int offset) const; /*! * \brief Print a jump instruction to STDOUT. * * \param name Instruction label. * \param sign Integer indicating the direction of the jump. * \param offset Offset of instruction in the Chunk's bytecode vector. */ std::size_t DisassembleJumpInstruction(const std::string& name, int sign, int offset) const; std::size_t DisassembleInvokeInstruction(const std::string& name, int offset) const; std::vector<uint8_t> code_; /*!< Vector of compiled bytecode instructions. */ std::vector<val::Value> constants_; /*!< Vector of constants parsed from the source text. */ std::vector<int> lines_; /*!< Vector of line numbers. */ }; // end Chunk } // end lox
26.630682
96
0.604011
[ "vector" ]
b7a3b67ee2cd3527b678257f28aed2db84516566
5,188
h
C
logdevice/ops/ldquery/tables/ShardRebuildings.h
Ikhbar-Kebaa/LogDevice
d69d706fb81d665eb94ee844aab94ff4951c9731
[ "BSD-3-Clause" ]
1
2021-05-19T23:01:58.000Z
2021-05-19T23:01:58.000Z
logdevice/ops/ldquery/tables/ShardRebuildings.h
abhishekg785/LogDevice
060da71ef84b61f3371115ed352a7ee7b07ba9e2
[ "BSD-3-Clause" ]
null
null
null
logdevice/ops/ldquery/tables/ShardRebuildings.h
abhishekg785/LogDevice
060da71ef84b61f3371115ed352a7ee7b07ba9e2
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <map> #include <vector> #include "../Context.h" #include "AdminCommandTable.h" namespace facebook { namespace logdevice { namespace ldquery { namespace tables { class ShardRebuildings : public AdminCommandTable { public: explicit ShardRebuildings(std::shared_ptr<Context> ctx) : AdminCommandTable(ctx) {} static std::string getName() { return "shard_rebuildings"; } std::string getDescription() override { return "Show debugging information about the ShardRebuilding state " "machines (see " "\"logdevice/server/rebuilding/ShardRebuildingV1.h\"). This state " "machine is responsible for running all LogRebuilding state " "machines (see \"logs_rebuilding\" table) for all logs in a donor " "shard."; } TableColumns getFetchableColumns() const override { return { {"shard_id", DataType::BIGINT, "Donor shard."}, {"rebuilding_set", DataType::TEXT, "Rebuilding set considered. See \"rebuilding_set\" column of " "the \"log_rebuilding\" table."}, {"version", DataType::LSN, "Rebuilding version. This version comes from the event log RSM that " "coordinates rebuilding. See the \"event_log\" table."}, {"global_window_end", DataType::TIME, "End of the global window (if enabled with " "--rebuilding-global-window). This is a time window used to " "synchronize all ShardRebuilding state machines across all donor " "shards."}, {"local_window_end", DataType::TIME, "ShardRebuilding schedules reads for all logs within a time window " "called the local window. This shows the end of the current window."}, {"num_logs_waiting_for_plan", DataType::BIGINT, "Number of logs that are waiting for a plan. See " "\"logdevice/include/RebuildingPlanner.h\"."}, {"num_logs_catching_up", DataType::BIGINT, "Number of LogRebuilding state machines currently active."}, {"num_logs_queued_for_catch_up", DataType::BIGINT, "Number of LogRebuilding state machines that are inside the local " "window and queued for catch up."}, {"num_logs_in_restart_queue", DataType::BIGINT, "Number of LogRebuilding state machines that are ready to be " "restarted as soon as a slot is available. Logs are scheduled for a " "restart if we waited too long for writes done by the state machine " "to be acknowledged as durable."}, {"total_memory_used", DataType::BIGINT, "Total amount of memory used by all LogRebuilding state machines."}, {"stall_timer_active", DataType::INTEGER, "If true, all LogRebuilding state machines are stalled until memory " "usage decreased."}, {"num_restart_timers_active", DataType::BIGINT, "Number of logs that have completed but for which we are still " "waiting for acknowlegments that writes were durable."}, {"num_active_logs", DataType::BIGINT, "Set of logs being rebuilt for this shard. The shard completes " "rebuilding when this number reaches zero."}, {"participating", DataType::INTEGER, "true if this shard is a donor for this rebuilding and hasn't " "finished rebuilding yet."}, {"time_by_state", DataType::TEXT, "Time spent in each state. 'stalled' means either waiting for global " "window or aborted because of a persistent error. V2 only"}, {"task_in_flight", DataType::INTEGER, "True if a storage task for reading records is in queue or in flight " "right now. V2 only."}, {"persistent_error", DataType::INTEGER, "True if we encountered an unrecoverable error when reading. Shard " "shouldn't stay in this state for more than a few seconds: it's " "expected that RebuildingCoordinator will request a rebuilding for " "this shard, and rebuilding will rewind without this node's " "participation. V2 only."}, {"read_buffer_bytes", DataType::BIGINT, "Bytes of records that we've read but haven't started re-replicating " "yet. V2 only."}, {"records_in_flight", DataType::BIGINT, "Number of records that are being re-replicated right now. V2 only."}, {"read_pointer", DataType::TEXT, "How far we have read: partition, log ID, LSN. V2 only."}, }; } std::string getCommandToSend(QueryContext& /*ctx*/) const override { // TODO (#35636262): Use "info rebuilding shards --json" instead. return std::string("info rebuildings --shards --json\n"); } }; }}}} // namespace facebook::logdevice::ldquery::tables
40.850394
80
0.634927
[ "vector" ]
b7a46e8b803cc6c13eb1102de6a582690ab53978
15,177
h
C
third_party/heif_decoder/src/main/cpp/libx265/common/common.h
vy12021/glide_webp
23a89575496dd0196e5f15f3d1893a43013deac2
[ "Apache-2.0" ]
1
2016-02-01T02:47:32.000Z
2016-02-01T02:47:32.000Z
third_party/heif_decoder/src/main/cpp/libx265/common/common.h
vy12021/glide_webp
23a89575496dd0196e5f15f3d1893a43013deac2
[ "Apache-2.0" ]
null
null
null
third_party/heif_decoder/src/main/cpp/libx265/common/common.h
vy12021/glide_webp
23a89575496dd0196e5f15f3d1893a43013deac2
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * Copyright (C) 2013-2017 MulticoreWare, Inc * * Authors: Deepthi Nandakumar <deepthi@multicorewareinc.com> * Min Chen <chenm003@163.com> * * 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; 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., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA. * * This program is also available under a commercial proprietary license. * For more information, contact us at license @ x265.com. *****************************************************************************/ #ifndef X265_COMMON_H #define X265_COMMON_H #include <algorithm> #include <climits> #include <cmath> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <cctype> #include <ctime> #include <stdint.h> #include <memory.h> #include <assert.h> #include "x265.h" #if ENABLE_PPA && ENABLE_VTUNE #error "PPA and VTUNE cannot both be enabled. Disable one of them." #endif #if ENABLE_PPA #include "profile/PPA/ppa.h" #define ProfileScopeEvent(x) PPAScopeEvent(x) #define THREAD_NAME(n,i) #define PROFILE_INIT() PPA_INIT() #define PROFILE_PAUSE() #define PROFILE_RESUME() #elif ENABLE_VTUNE #include "profile/vtune/vtune.h" #define ProfileScopeEvent(x) VTuneScopeEvent _vtuneTask(x) #define THREAD_NAME(n,i) vtuneSetThreadName(n, i) #define PROFILE_INIT() vtuneInit() #define PROFILE_PAUSE() __itt_pause() #define PROFILE_RESUME() __itt_resume() #else #define ProfileScopeEvent(x) #define THREAD_NAME(n,i) #define PROFILE_INIT() #define PROFILE_PAUSE() #define PROFILE_RESUME() #endif #define FENC_STRIDE 64 #define NUM_INTRA_MODE 35 #if defined(__GNUC__) #define ALIGN_VAR_4(T, var) T var __attribute__((aligned(4))) #define ALIGN_VAR_8(T, var) T var __attribute__((aligned(8))) #define ALIGN_VAR_16(T, var) T var __attribute__((aligned(16))) #define ALIGN_VAR_32(T, var) T var __attribute__((aligned(32))) #define ALIGN_VAR_64(T, var) T var __attribute__((aligned(64))) #if defined(__MINGW32__) #define fseeko fseeko64 #define ftello ftello64 #endif #elif defined(_MSC_VER) #define ALIGN_VAR_4(T, var) __declspec(align(4)) T var #define ALIGN_VAR_8(T, var) __declspec(align(8)) T var #define ALIGN_VAR_16(T, var) __declspec(align(16)) T var #define ALIGN_VAR_32(T, var) __declspec(align(32)) T var #define ALIGN_VAR_64(T, var) __declspec(align(64)) T var #define fseeko _fseeki64 #define ftello _ftelli64 #endif // if defined(__GNUC__) #if HAVE_INT_TYPES_H #define __STDC_FORMAT_MACROS #include <inttypes.h> #define X265_LL "%" PRIu64 #else #define X265_LL "%lld" #endif #if _DEBUG && defined(_MSC_VER) #define DEBUG_BREAK() __debugbreak() #elif __APPLE_CC__ #define DEBUG_BREAK() __builtin_trap() #else #define DEBUG_BREAK() abort() #endif /* If compiled with CHECKED_BUILD perform run-time checks and log any that * fail, both to stderr and to a file */ #if CHECKED_BUILD || _DEBUG namespace X265_NS { extern int g_checkFailures; } #define X265_CHECK(expr, ...) if (!(expr)) { \ x265_log(NULL, X265_LOG_ERROR, __VA_ARGS__); \ FILE *fp = fopen("x265_check_failures.txt", "a"); \ if (fp) { fprintf(fp, "%s:%d\n", __FILE__, __LINE__); fprintf(fp, __VA_ARGS__); fclose(fp); } \ g_checkFailures++; DEBUG_BREAK(); \ } #if _MSC_VER #pragma warning(disable: 4127) // some checks have constant conditions #endif #else #define X265_CHECK(expr, ...) #endif #if HIGH_BIT_DEPTH typedef uint16_t pixel; typedef uint32_t sum_t; typedef uint64_t sum2_t; typedef uint64_t pixel4; typedef int64_t ssum2_t; #else typedef uint8_t pixel; typedef uint16_t sum_t; typedef uint32_t sum2_t; typedef uint32_t pixel4; typedef int32_t ssum2_t; // Signed sum #endif // if HIGH_BIT_DEPTH #if X265_DEPTH < 10 typedef uint32_t sse_t; #else typedef uint64_t sse_t; #endif #ifndef NULL #define NULL 0 #endif #define MAX_UINT 0xFFFFFFFFU // max. value of unsigned 32-bit integer #define MAX_INT 2147483647 // max. value of signed 32-bit integer #define MAX_INT64 0x7FFFFFFFFFFFFFFFLL // max. value of signed 64-bit integer #define MAX_DOUBLE 1.7e+308 // max. value of double-type value #define QP_MIN 0 #define QP_MAX_SPEC 51 /* max allowed signaled QP in HEVC */ #define QP_MAX_MAX 69 /* max allowed QP to be output by rate control */ #define MIN_QPSCALE 0.21249999999999999 #define MAX_MAX_QPSCALE 615.46574234477100 template<typename T> inline T x265_min(T a, T b) { return a < b ? a : b; } template<typename T> inline T x265_max(T a, T b) { return a > b ? a : b; } template<typename T> inline T x265_clip3(T minVal, T maxVal, T a) { return x265_min(x265_max(minVal, a), maxVal); } template<typename T> /* clip to pixel range, 0..255 or 0..1023 */ inline pixel x265_clip(T x) { return (pixel)x265_min<T>(T((1 << X265_DEPTH) - 1), x265_max<T>(T(0), x)); } typedef int16_t coeff_t; // transform coefficient #define X265_MIN(a, b) ((a) < (b) ? (a) : (b)) #define X265_MAX(a, b) ((a) > (b) ? (a) : (b)) #define COPY1_IF_LT(x, y) {if ((y) < (x)) (x) = (y);} #define COPY2_IF_LT(x, y, a, b) \ if ((y) < (x)) \ { \ (x) = (y); \ (a) = (b); \ } #define COPY3_IF_LT(x, y, a, b, c, d) \ if ((y) < (x)) \ { \ (x) = (y); \ (a) = (b); \ (c) = (d); \ } #define COPY4_IF_LT(x, y, a, b, c, d, e, f) \ if ((y) < (x)) \ { \ (x) = (y); \ (a) = (b); \ (c) = (d); \ (e) = (f); \ } #define X265_MIN3(a, b, c) X265_MIN((a), X265_MIN((b), (c))) #define X265_MAX3(a, b, c) X265_MAX((a), X265_MAX((b), (c))) #define X265_MIN4(a, b, c, d) X265_MIN((a), X265_MIN3((b), (c), (d))) #define X265_MAX4(a, b, c, d) X265_MAX((a), X265_MAX3((b), (c), (d))) #define QP_BD_OFFSET (6 * (X265_DEPTH - 8)) #define MAX_CHROMA_LAMBDA_OFFSET 36 // arbitrary, but low because SATD scores are 1/4 normal #define X265_LOOKAHEAD_QP (12 + QP_BD_OFFSET) // Use the same size blocks as x264. Using larger blocks seems to give artificially // high cost estimates (intra and inter both suffer) #define X265_LOWRES_CU_SIZE 8 #define X265_LOWRES_CU_BITS 3 #define X265_MALLOC(type, count) (type*)x265_malloc(sizeof(type) * (count)) #define X265_FREE(ptr) x265_free(ptr) #define X265_FREE_ZERO(ptr) x265_free(ptr); (ptr) = NULL #define CHECKED_MALLOC(var, type, count) \ { \ var = (type*)x265_malloc(sizeof(type) * (count)); \ if (!var) \ { \ x265_log(NULL, X265_LOG_ERROR, "malloc of size %d failed\n", sizeof(type) * (count)); \ goto fail; \ } \ } #define CHECKED_MALLOC_ZERO(var, type, count) \ { \ var = (type*)x265_malloc(sizeof(type) * (count)); \ if (var) \ memset((void*)var, 0, sizeof(type) * (count)); \ else \ { \ x265_log(NULL, X265_LOG_ERROR, "malloc of size %d failed\n", sizeof(type) * (count)); \ goto fail; \ } \ } #if defined(_MSC_VER) #define X265_LOG2F(x) (logf((float)(x)) * 1.44269504088896405f) #define X265_LOG2(x) (log((double)(x)) * 1.4426950408889640513713538072172) #else #define X265_LOG2F(x) log2f(x) #define X265_LOG2(x) log2(x) #endif #define NUM_CU_DEPTH 4 // maximum number of CU depths #define NUM_FULL_DEPTH 5 // maximum number of full depths #define MIN_LOG2_CU_SIZE 3 // log2(minCUSize) #define MAX_LOG2_CU_SIZE 6 // log2(maxCUSize) #define MIN_CU_SIZE (1 << MIN_LOG2_CU_SIZE) // minimum allowable size of CU #define MAX_CU_SIZE (1 << MAX_LOG2_CU_SIZE) // maximum allowable size of CU #define LOG2_UNIT_SIZE 2 // log2(unitSize) #define UNIT_SIZE (1 << LOG2_UNIT_SIZE) // unit size of CU partition #define LOG2_RASTER_SIZE (MAX_LOG2_CU_SIZE - LOG2_UNIT_SIZE) #define RASTER_SIZE (1 << LOG2_RASTER_SIZE) #define MAX_NUM_PARTITIONS (RASTER_SIZE * RASTER_SIZE) #define MIN_PU_SIZE 4 #define MIN_TU_SIZE 4 #define MAX_NUM_SPU_W (MAX_CU_SIZE / MIN_PU_SIZE) // maximum number of SPU in horizontal line #define MAX_LOG2_TR_SIZE 5 #define MAX_LOG2_TS_SIZE 2 // TODO: RExt #define MAX_TR_SIZE (1 << MAX_LOG2_TR_SIZE) #define MAX_TS_SIZE (1 << MAX_LOG2_TS_SIZE) #define COEF_REMAIN_BIN_REDUCTION 3 // indicates the level at which the VLC // transitions from Golomb-Rice to TU+EG(k) #define SBH_THRESHOLD 4 // fixed sign bit hiding controlling threshold #define C1FLAG_NUMBER 8 // maximum number of largerThan1 flag coded in one chunk: 16 in HM5 #define C2FLAG_NUMBER 1 // maximum number of largerThan2 flag coded in one chunk: 16 in HM5 #define SAO_ENCODING_RATE 0.75 #define SAO_ENCODING_RATE_CHROMA 0.5 #define MLS_GRP_NUM 64 // Max number of coefficient groups, max(16, 64) #define MLS_CG_SIZE 4 // Coefficient group size of 4x4 #define MLS_CG_BLK_SIZE (MLS_CG_SIZE * MLS_CG_SIZE) #define MLS_CG_LOG2_SIZE 2 #define QUANT_IQUANT_SHIFT 20 // Q(QP%6) * IQ(QP%6) = 2^20 #define QUANT_SHIFT 14 // Q(4) = 2^14 #define SCALE_BITS 15 // Inherited from TMuC, presumably for fractional bit estimates in RDOQ #define MAX_TR_DYNAMIC_RANGE 15 // Maximum transform dynamic range (excluding sign bit) #define SHIFT_INV_1ST 7 // Shift after first inverse transform stage #define SHIFT_INV_2ND 12 // Shift after second inverse transform stage #define AMVP_DECIMATION_FACTOR 4 #define SCAN_SET_SIZE 16 #define LOG2_SCAN_SET_SIZE 4 #define ALL_IDX -1 #define PLANAR_IDX 0 #define VER_IDX 26 // index for intra VERTICAL mode #define HOR_IDX 10 // index for intra HORIZONTAL mode #define DC_IDX 1 // index for intra DC mode #define NUM_CHROMA_MODE 5 // total number of chroma modes #define DM_CHROMA_IDX 36 // chroma mode index for derived from luma intra mode #define MDCS_ANGLE_LIMIT 4 // distance from true angle that horiz or vertical scan is allowed #define MDCS_LOG2_MAX_SIZE 3 // TUs with log2 of size greater than this can only use diagonal scan #define MAX_NUM_REF_PICS 16 // max. number of pictures used for reference #define MAX_NUM_REF 16 // max. number of entries in picture reference list #define MAX_NUM_SHORT_TERM_RPS 64 // max. number of short term reference picture set in SPS #define REF_NOT_VALID -1 #define AMVP_NUM_CANDS 2 // number of AMVP candidates #define MRG_MAX_NUM_CANDS 5 // max number of final merge candidates #define CHROMA_H_SHIFT(x) (x == X265_CSP_I420 || x == X265_CSP_I422) #define CHROMA_V_SHIFT(x) (x == X265_CSP_I420) #define X265_MAX_PRED_MODE_PER_CTU 85 * 2 * 8 #define MAX_NUM_TR_COEFFS MAX_TR_SIZE * MAX_TR_SIZE // Maximum number of transform coefficients, for a 32x32 transform #define MAX_NUM_TR_CATEGORIES 16 // 32, 16, 8, 4 transform categories each for luma and chroma #define PIXEL_MAX ((1 << X265_DEPTH) - 1) #define INTEGRAL_PLANE_NUM 12 // 12 integral planes for 32x32, 32x24, 32x8, 24x32, 16x16, 16x12, 16x4, 12x16, 8x32, 8x8, 4x16 and 4x4. #define NAL_TYPE_OVERHEAD 2 #define START_CODE_OVERHEAD 3 #define FILLER_OVERHEAD (NAL_TYPE_OVERHEAD + START_CODE_OVERHEAD + 1) namespace X265_NS { enum { SAO_NUM_OFFSET = 4 }; enum SaoMergeMode { SAO_MERGE_NONE, SAO_MERGE_LEFT, SAO_MERGE_UP }; struct SaoCtuParam { SaoMergeMode mergeMode; int typeIdx; uint32_t bandPos; // BO band position int offset[SAO_NUM_OFFSET]; void reset() { mergeMode = SAO_MERGE_NONE; typeIdx = -1; bandPos = 0; offset[0] = 0; offset[1] = 0; offset[2] = 0; offset[3] = 0; } }; struct SAOParam { SaoCtuParam* ctuParam[3]; bool bSaoFlag[2]; int numCuInWidth; SAOParam() { for (int i = 0; i < 3; i++) ctuParam[i] = NULL; } ~SAOParam() { delete[] ctuParam[0]; delete[] ctuParam[1]; delete[] ctuParam[2]; } }; enum TextType { TEXT_LUMA = 0, // luma TEXT_CHROMA_U = 1, // chroma U TEXT_CHROMA_V = 2, // chroma V MAX_NUM_COMPONENT = 3 }; // coefficient scanning type used in ACS enum ScanType { SCAN_DIAG = 0, // up-right diagonal scan SCAN_HOR = 1, // horizontal first scan SCAN_VER = 2, // vertical first scan NUM_SCAN_TYPE = 3 }; enum SignificanceMapContextType { CONTEXT_TYPE_4x4 = 0, CONTEXT_TYPE_8x8 = 1, CONTEXT_TYPE_NxN = 2, CONTEXT_NUMBER_OF_TYPES = 3 }; /* located in pixel.cpp */ void extendPicBorder(pixel* recon, intptr_t stride, int width, int height, int marginX, int marginY); /* located in common.cpp */ int64_t x265_mdate(void); #define x265_log(param, ...) general_log(param, "x265", __VA_ARGS__) #define x265_log_file(param, ...) general_log_file(param, "x265", __VA_ARGS__) void general_log(const x265_param* param, const char* caller, int level, const char* fmt, ...); #if _WIN32 void general_log_file(const x265_param* param, const char* caller, int level, const char* fmt, ...); FILE* x265_fopen(const char* fileName, const char* mode); int x265_unlink(const char* fileName); int x265_rename(const char* oldName, const char* newName); #else #define general_log_file(param, caller, level, fmt, ...) general_log(param, caller, level, fmt, __VA_ARGS__) #define x265_fopen(fileName, mode) fopen(fileName, mode) #define x265_unlink(fileName) unlink(fileName) #define x265_rename(oldName, newName) rename(oldName, newName) #endif int x265_exp2fix8(double x); double x265_ssim2dB(double ssim); double x265_qScale2qp(double qScale); double x265_qp2qScale(double qp); uint32_t x265_picturePlaneSize(int csp, int width, int height, int plane); void* x265_malloc(size_t size); void x265_free(void *ptr); char* x265_slurp_file(const char *filename); /* located in primitives.cpp */ void x265_setup_primitives(x265_param* param); void x265_report_simd(x265_param* param); } #include "constants.h" #endif // ifndef X265_COMMON_H
33.95302
143
0.654807
[ "transform" ]
b7b81f904ea6622bca1b1b33f0a1920f25ba3752
957
h
C
src/tiny_core/eventloop.h
swaroop0707/TinyWeb
79d20f2bb858581cc5a0ea229bba3a54e5d1bd3e
[ "MIT" ]
352
2018-02-07T08:24:43.000Z
2022-03-31T12:35:17.000Z
src/tiny_core/eventloop.h
zhouq3405/TinyWeb
79d20f2bb858581cc5a0ea229bba3a54e5d1bd3e
[ "MIT" ]
6
2018-02-08T11:52:12.000Z
2022-01-20T03:37:41.000Z
src/tiny_core/eventloop.h
zhouq3405/TinyWeb
79d20f2bb858581cc5a0ea229bba3a54e5d1bd3e
[ "MIT" ]
75
2018-02-07T08:24:42.000Z
2021-10-03T08:20:24.000Z
/* *Author:GeneralSandman *Code:https://github.com/GeneralSandman/TinyWeb *E-mail:generalsandman@163.com *Web:www.dissigil.cn */ /*---XXX--- * **************************************** * */ #ifndef EVENT_LOOP_H #define EVENT_LOOP_H #include <tiny_core/time.h> #include <tiny_core/timer.h> #include <vector> class EPoller; class Channel; class TimerQueue; class TimerId; class EventLoop { private: bool m_nRunning; EPoller *m_pPoller; std::vector<Channel *> m_nActiveChannels; TimerQueue *m_pTimerQueue; public: EventLoop(); void updateChannel(Channel *); void removeChannel(Channel *); void loop(); void quit() { m_nRunning = false; } TimerId runAt(Time, timerReadCallback); TimerId runAfter(double, timerReadCallback); TimerId runEvery(double, timerReadCallback); void cancelTimerId(TimerId &); ~EventLoop(); }; #endif
19.14
52
0.62069
[ "vector" ]
b7c2239dfa44b955665fd5b95ae62db0da12ee8b
4,222
c
C
src/sig/dconv.c
behollis/brlcad-svn-rev65072-gsoc2015
c2e49d80e0776ea6da4358a345a04f56e0088b90
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
src/sig/dconv.c
behollis/brlcad-svn-rev65072-gsoc2015
c2e49d80e0776ea6da4358a345a04f56e0088b90
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
src/sig/dconv.c
behollis/brlcad-svn-rev65072-gsoc2015
c2e49d80e0776ea6da4358a345a04f56e0088b90
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
/* D C O N V . C * BRL-CAD * * Copyright (c) 2004-2014 United States Government as represented by * the U.S. Army Research Laboratory. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this file; see the file named COPYING for more * information. */ /** @file dconv.c * * Fast FFT based convolution * * This uses the overlap-save method to achieve a linear convolution * (straight FFT's give you a circular convolution). An M-point * kernel is convolved with N-point sequences (in xform space). The * first M-1 points are incorrect, while the remaining points yield a * true linear convolution. Thus the first M-1 points of each xform * are thrown away, while the last M-1 points of each input section * are saved for the next xform. * */ #include "common.h" #include <string.h> #include <stdlib.h> #include <math.h> #include "bio.h" #include "bu/log.h" #include "fft.h" /* * Multiply two "real valued" spectra of length n * and put the result in the first. * The order is: [Re(0), Re(1)...Re(N/2), Im(N/2-1), ..., Im(1)] * so for: 0 < i < n/2, (x[i], x[n-i]) is a complex pair. */ static void mult(double *o, double *b, int n) { int i; double r; /* do DC and Nyquist components */ o[0] *= b[0]; o[n/2] *= b[n/2]; for (i = 1; i < n/2; i++) { r = o[i] * b[i] - o[n-i] * b[n-i]; o[n-i] = o[i] * b[n-i] + o[n-i] * b[i]; o[i] = r; } } int main(int argc, char *argv[]) { #define MAXM 4096 double savebuffer[MAXM]; double xbuf[2 * (MAXM + 1)]; double ibuf[2 * (MAXM + 1)]; /* impulse response */ int i; int M = 128; /* kernel size */ int N, L; FILE *fp; size_t ret; if (argc != 2 || isatty(fileno(stdin)) || isatty(fileno(stdout))) { bu_exit(1, "Usage: dconv filterfile < doubles > doubles\n WARNING: kernel size must be 2^i - 1\n"); } N = 2*M; /* input sub-section length (fft size) */ L = M + 1; /* number of "good" points per section, simplified from L = N - M + 1 */ #ifdef never /* prepare the kernel(!) */ /* this is either the direct complex response, * or the FT(impulse resp) */ for (i = 0; i < N; i++) { if (i <= N/2) ibuf[i] = 1.0; /* Real part */ else ibuf[i] = 0.0; /* Imag part */ } #endif /* never */ if ((fp = fopen(argv[1], "r")) == NULL) { bu_exit(2, "dconv: can't open \"%s\"\n", argv[1]); } if ((M = fread(ibuf, sizeof(*ibuf), 2*MAXM, fp)) == 0) { bu_exit(3, "dconv: problem reading filter file\n"); } fclose(fp); if (M > MAXM) { bu_exit(4, "dconv: only compiled for up to %d sized filter kernels\n", MAXM); } /*XXX HACK HACK HACK HACK XXX*/ /* Assume M = 2^i - 1 */ M += 1; N = 2*M; /* input sub-section length (fft size) */ L = N - M + 1; /* number of "good" points per section */ if (N == 256) rfft256(ibuf); else rfft(ibuf, N); while ((i = fread(&xbuf[M-1], sizeof(*xbuf), L, stdin)) > 0) { if (i < L) { /* pad the end with zero's */ memset((char *)&xbuf[M-1+i], 0, (L-i)*sizeof(*savebuffer)); } /* shift contents of savebuffer left */ #define COPY_SIZE ((M - 1) * sizeof(*savebuffer)) memcpy(xbuf, savebuffer, COPY_SIZE); memcpy(savebuffer, &xbuf[L], COPY_SIZE); /*xform(xbuf, N);*/ if (N == 256) rfft256(xbuf); else rfft(xbuf, N); /* Mult */ mult(xbuf, ibuf, N); /*invxform(xbuf, N);*/ if (N == 256) irfft256(xbuf); else irfft(xbuf, N); ret = fwrite(&xbuf[M-1], sizeof(*xbuf), L, stdout); if (ret != (size_t)L) perror("fwrite"); } return 0; } /* * Local Variables: * mode: C * tab-width: 8 * indent-tabs-mode: t * c-file-style: "stroustrup" * End: * ex: shiftwidth=4 tabstop=8 */
24.835294
106
0.591426
[ "cad" ]
b7c792623e06d8d0ee2e18c77cedc7ec92a380c6
1,699
h
C
opt/singleimpl/SingleImpl.h
parind/redex
a919919298f45e7ff33f03be7f819dc04e533182
[ "MIT" ]
1
2019-07-24T16:08:40.000Z
2019-07-24T16:08:40.000Z
opt/singleimpl/SingleImpl.h
parind/redex
a919919298f45e7ff33f03be7f819dc04e533182
[ "MIT" ]
null
null
null
opt/singleimpl/SingleImpl.h
parind/redex
a919919298f45e7ff33f03be7f819dc04e533182
[ "MIT" ]
1
2019-12-21T06:31:53.000Z
2019-12-21T06:31:53.000Z
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include "Pass.h" struct SingleImplConfig { std::vector<std::string> white_list; std::vector<std::string> package_white_list; std::vector<std::string> black_list; std::vector<std::string> package_black_list; std::vector<std::string> anno_black_list; bool intf_anno; bool meth_anno; bool field_anno; bool rename_on_collision; bool filter_proguard_special_interfaces; }; class SingleImplPass : public Pass { public: SingleImplPass() : Pass("SingleImplPass") {} void bind_config() override { bind("white_list", {}, m_pass_config.white_list); bind("package_white_list", {}, m_pass_config.package_white_list); bind("black_list", {}, m_pass_config.black_list); bind("package_black_list", {}, m_pass_config.package_black_list); bind("anno_black_list", {}, m_pass_config.anno_black_list); bind("type_annotations", true, m_pass_config.intf_anno); bind("method_annotations", true, m_pass_config.meth_anno); bind("field_annotations", true, m_pass_config.field_anno); bind("rename_on_collision", false, m_pass_config.rename_on_collision); bind("filter_proguard_special_interfaces", false, m_pass_config.filter_proguard_special_interfaces); } void run_pass(DexStoresVector&, ConfigFiles&, PassManager&) override; // count of removed interfaces size_t removed_count{0}; // count of invoke-interface changed to invoke-virtual static size_t s_invoke_intf_count; private: SingleImplConfig m_pass_config; };
30.890909
74
0.742201
[ "vector" ]
b7cf8e4bbbee72b9360d17011b639b5ea02b1eeb
3,459
h
C
common/3rd-party/mecab/mecab-ko-v0.9.2/src/src/common.h
lesit/NeuroStudio
f505065d694a8614587e7cc243ede72c141bd80b
[ "W3C" ]
21
2018-11-15T08:23:14.000Z
2022-03-30T15:44:59.000Z
common/3rd-party/mecab/mecab-ko-v0.9.2/src/src/common.h
lesit/NeuroStudio
f505065d694a8614587e7cc243ede72c141bd80b
[ "W3C" ]
null
null
null
common/3rd-party/mecab/mecab-ko-v0.9.2/src/src/common.h
lesit/NeuroStudio
f505065d694a8614587e7cc243ede72c141bd80b
[ "W3C" ]
1
2021-12-08T01:17:27.000Z
2021-12-08T01:17:27.000Z
// MeCab -- Yet Another Part-of-Speech and Morphological Analyzer // // // Copyright(C) 2001-2006 Taku Kudo <taku@chasen.org> // Copyright(C) 2004-2006 Nippon Telegraph and Telephone Corporation #ifndef MECAB_COMMON_H_ #define MECAB_COMMON_H_ #include <algorithm> #include <cmath> #include <cstdlib> #include <cstdio> #include <cstring> #include <string> #include <iostream> #include <sstream> #include <iterator> #ifdef __CYGWIN__ #define _GLIBCXX_EXPORT_TEMPLATE #endif #ifdef HAVE_CONFIG_H #include "config.h" #endif #if defined(_MSC_VER) || defined(__CYGWIN__) #define NOMINMAX #define snprintf _snprintf #endif #define COPYRIGHT "MeCab: Yet Another Part-of-Speech and Morphological Analyzer\n\ \nCopyright(C) 2001-2012 Taku Kudo \nCopyright(C) 2004-2008 Nippon Telegraph and Telephone Corporation\n" #define SYS_DIC_FILE "sys.dic" #define UNK_DEF_FILE "unk.def" #define UNK_DIC_FILE "unk.dic" #define MATRIX_DEF_FILE "matrix.def" #define MATRIX_FILE "matrix.bin" #define CHAR_PROPERTY_DEF_FILE "char.def" #define CHAR_PROPERTY_FILE "char.bin" #define FEATURE_FILE "feature.def" #define REWRITE_FILE "rewrite.def" #define LEFT_ID_FILE "left-id.def" #define RIGHT_ID_FILE "right-id.def" #define POS_ID_FILE "pos-id.def" #define MODEL_DEF_FILE "model.def" #define MODEL_FILE "model.bin" #define DICRC "dicrc" #define BOS_KEY "BOS/EOS" #define DEFAULT_MAX_GROUPING_SIZE 24 #define CHAR_PROPERTY_DEF_DEFAULT "DEFAULT 1 0 0\nSPACE 0 1 0\n0x0020 SPACE\n" #define UNK_DEF_DEFAULT "DEFAULT,0,0,0,*\nSPACE,0,0,0,*\n" #define MATRIX_DEF_DEFAULT "1 1\n0 0 0\n" #ifdef MECAB_USE_UTF8_ONLY #define MECAB_DEFAULT_CHARSET "UTF-8" #endif #ifndef MECAB_DEFAULT_CHARSET #if defined(_WIN32) && !defined(__CYGWIN__) #define MECAB_DEFAULT_CHARSET "SHIFT-JIS" #else #define MECAB_DEFAULT_CHARSET "EUC-JP" #endif #endif #define NBEST_MAX 512 #define NODE_FREELIST_SIZE 512 #define PATH_FREELIST_SIZE 2048 #define MIN_INPUT_BUFFER_SIZE 8192 #define MAX_INPUT_BUFFER_SIZE (8192*640) #define BUF_SIZE 8192 #ifndef EXIT_FAILURE #define EXIT_FAILURE 1 #endif #ifndef EXIT_SUCCESS #define EXIT_SUCCESS 0 #endif #ifdef _WIN32 #ifdef __GNUC__ #define WPATH_FORCE(path) (MeCab::Utf8ToWide(path).c_str()) #define WPATH(path) (path) #else #define WPATH_FORCE(path) (MeCab::Utf8ToWide(path).c_str()) #define WPATH(path) WPATH_FORCE(path) #endif #else #define WPATH_FORCE(path) (path) #define WPATH(path) (path) #endif namespace MeCab { class die { public: die() {} ~die() { std::cerr << std::endl; exit(-1); } int operator&(std::ostream&) { return 0; } }; struct whatlog { std::ostringstream stream_; std::string str_; const char *str() { str_ = stream_.str(); return str_.c_str(); } }; class wlog { public: wlog(whatlog *what) : what_(what) { what_->stream_.clear(); } bool operator&(std::ostream &) { return false; } private: whatlog *what_; }; } // MeCab #define WHAT what_.stream_ #define CHECK_FALSE(condition) \ if (condition) {} else return \ wlog(&what_) & what_.stream_ << \ __FILE__ << "(" << __LINE__ << ") [" << #condition << "] " #define CHECK_DIE(condition) \ (condition) ? 0 : die() & std::cerr << __FILE__ << \ "(" << __LINE__ << ") [" << #condition << "] " #endif // MECAB_COMMON_H_
24.188811
105
0.684591
[ "model" ]
b7d64bfa67b7fbe0893395c7a996884146d56fbb
5,213
h
C
middleware/common/include/common/transaction/context.h
tompis/casual
d838716c7052a906af8a19e945a496acdc7899a2
[ "MIT" ]
null
null
null
middleware/common/include/common/transaction/context.h
tompis/casual
d838716c7052a906af8a19e945a496acdc7899a2
[ "MIT" ]
null
null
null
middleware/common/include/common/transaction/context.h
tompis/casual
d838716c7052a906af8a19e945a496acdc7899a2
[ "MIT" ]
null
null
null
//! //! context.h //! //! Created on: Jul 14, 2013 //! Author: Lazan //! #ifndef CASUAL_COMMON_TRANSACTION_CONTEXT_H_ #define CASUAL_COMMON_TRANSACTION_CONTEXT_H_ #include <tx.h> #include "common/transaction/id.h" #include "common/transaction/resource.h" #include "common/transaction/transaction.h" #include "common/message/transaction.h" #include "common/message/service.h" #include <stack> namespace casual { namespace common { namespace transaction { class Context { public: static Context& instance(); //! //! Correspond to the tx API //! //! @{ void open(); void close(); int begin(); int commit(); int rollback(); int setCommitReturn( COMMIT_RETURN value); COMMIT_RETURN get_commit_return(); int setTransactionControl(TRANSACTION_CONTROL control); void setTransactionTimeout( TRANSACTION_TIMEOUT timeout); bool info( TXINFO* info); //! @} //! //! Correspond to casual extension of the tx API //! //! @{ void suspend( XID* xid); void resume( const XID* xid); //! @} //! //! Correspond to the ax API //! //! @{ int resourceRegistration( int rmid, XID* xid, long flags); int resourceUnregistration( int rmid, long flags); //! @} //! //! @ingroup service-start //! //! Join transaction. could be a null xid. //! void join( const transaction::ID& trid); //! //! @ingroup service-start //! //! Start a new transaction //! void start( const platform::time_point& start); //! //! trid server is invoked with //! //! @{ transaction::ID caller; //! @} void update( message::service::call::Reply& state); //! //! commits or rollback transaction created from this server //! void finalize( message::service::call::Reply& message, int return_state); //! //! @return current transaction. 'null xid' if there are none... //! Transaction& current(); //! //! @return true if @p descriptor is associated with an active transaction //! bool associated( platform::descriptor_type descriptor); void set( const std::vector< Resource>& resources); //! //! @return true if there are pending transactions that is owned by this //! process //! bool pending() const; private: using control_type = TRANSACTION_CONTROL; enum class Control : control_type { unchained = TX_UNCHAINED, chained = TX_CHAINED, stacked = TX_STACKED }; Control m_control = Control::unchained; using commit_return_type = COMMIT_RETURN; // TODO: change name enum class Commit_Return : commit_return_type { completed = TX_COMMIT_COMPLETED, logged = TX_COMMIT_DECISION_LOGGED }; Commit_Return m_commit_return = Commit_Return::completed; struct resources_type { std::vector< Resource> all; using range_type = typename common::range::traits< std::vector< Resource>>::type; range_type fixed; range_type dynamic; } m_resources; std::vector< int> resources() const; std::vector< Transaction> m_transactions; transaction::ID m_caller; TRANSACTION_TIMEOUT m_timeout = 0; //! //! Attributes that is initialized from "manager" //! struct Manager { static const Manager& instance(); platform::queue_id_type queue() const; std::vector< message::transaction::resource::Manager> resources; private: Manager(); }; const Manager& manager(); void involved( const transaction::ID& xid, std::vector< int> resources); void apply( const message::transaction::client::connect::Reply& configuration); Context(); int commit( const Transaction& transaction); int rollback( const Transaction& transaction); void resources_start( const Transaction& transaction, long flags); void resources_end( const Transaction& transaction, long flags); int resource_commit( platform::resource::id_type rm, const Transaction& transaction, long flags); int pop_transaction(); }; } // transaction } // common } // casual #endif /* CONTEXT_H_ */
24.474178
109
0.515826
[ "vector" ]
a10589c77f3dff5cae11f2337c0a239d6d8713ac
8,489
h
C
components/touch_element/include/touch_element/touch_slider.h
bieganski/esp-idf
bd5e1b08427aae0ddeabd71956b3f5ab98d90c1c
[ "Apache-2.0" ]
1
2021-03-03T04:58:51.000Z
2021-03-03T04:58:51.000Z
components/touch_element/include/touch_element/touch_slider.h
bieganski/esp-idf
bd5e1b08427aae0ddeabd71956b3f5ab98d90c1c
[ "Apache-2.0" ]
null
null
null
components/touch_element/include/touch_element/touch_slider.h
bieganski/esp-idf
bd5e1b08427aae0ddeabd71956b3f5ab98d90c1c
[ "Apache-2.0" ]
2
2020-11-26T03:48:51.000Z
2022-02-10T02:53:50.000Z
// Copyright 2016-2020 Espressif Systems (Shanghai) PTE LTD // // 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 "touch_element/touch_element.h" #ifdef __cplusplus extern "C" { #endif /* --------------------------------- General slider instance default configuration --------------------------------- */ #define TOUCH_SLIDER_GLOBAL_DEFAULT_CONFIG() \ { \ .quantify_lower_threshold = 0.3, \ .threshold_divider = 0.8, \ .filter_reset_time = 50, \ .benchmark_update_time = 500, \ .position_filter_size = 10, \ .position_filter_factor = 2, \ .calculate_channel_count = 3 \ } /* ------------------------------------------------------------------------------------------------------------------ */ /** * @brief Slider initialization configuration passed to touch_slider_install */ typedef struct { float quantify_lower_threshold; //!< Slider signal quantification threshold float threshold_divider; //!< Slider channel threshold divider uint16_t filter_reset_time; //!< Slider position filter reset time (Unit is esp_timer callback tick) uint16_t benchmark_update_time; //!< Slider benchmark update time (Unit is esp_timer callback tick) uint8_t position_filter_size; //!< Moving window filter buffer size uint8_t position_filter_factor; //!< One-order IIR filter factor uint8_t calculate_channel_count; //!< The number of channels which will take part in calculation } touch_slider_global_config_t; /** * @brief Slider configuration (for new instance) passed to touch_slider_create() */ typedef struct { const touch_pad_t *channel_array; //!< Slider channel array const float *sensitivity_array; //!< Slider channel sensitivity array uint8_t channel_num; //!< The number of slider channels uint8_t position_range; //!< The right region of touch slider position range, [0, position_range (less than or equal to 255)] } touch_slider_config_t; /** * @brief Slider event type */ typedef enum { TOUCH_SLIDER_EVT_ON_PRESS, //!< Slider on Press event TOUCH_SLIDER_EVT_ON_RELEASE, //!< Slider on Release event TOUCH_SLIDER_EVT_ON_CALCULATION, //!< Slider on Calculation event TOUCH_SLIDER_EVT_MAX } touch_slider_event_t; typedef uint32_t touch_slider_position_t; //!< Slider position data type /** * @brief Slider message type */ typedef struct { touch_slider_event_t event; //!< Slider event touch_slider_position_t position; //!< Slider position } touch_slider_message_t; typedef touch_elem_handle_t touch_slider_handle_t; //!< Slider instance handle typedef void(*touch_slider_callback_t)(touch_slider_handle_t, touch_slider_message_t, void *); //!< Slider callback type /** * @brief Touch slider initialize * * This function initializes touch slider object and acts on all * touch slider instances. * * @param[in] global_config Touch slider global initialization configuration * * @return * - ESP_OK: Successfully initialized touch slider * - ESP_ERR_INVALID_STATE: Touch element library was not initialized * - ESP_ERR_INVALID_ARG: slider_init is NULL * - ESP_ERR_NO_MEM: Insufficient memory */ esp_err_t touch_slider_install(const touch_slider_global_config_t *global_config); /** * @brief Release resources allocated using touch_slider_install() * * @return * - ESP_OK: Successfully released resources */ void touch_slider_uninstall(void); /** * @brief Create a new touch slider instance * * @param[in] slider_config Slider configuration * @param[out] slider_handle Slider handle * * @note The index of Channel array and sensitivity array must be one-one correspondence * * @return * - ESP_OK: Successfully create touch slider * - ESP_ERR_INVALID_STATE: Touch slider driver was not initialized * - ESP_ERR_INVALID_ARG: Invalid configuration struct or arguments is NULL * - ESP_ERR_NO_MEM: Insufficient memory */ esp_err_t touch_slider_create(const touch_slider_config_t *slider_config, touch_slider_handle_t *slider_handle); /** * @brief Release resources allocated using touch_slider_create * * @param[in] slider_handle Slider handle * @return * - ESP_OK: Successfully released resources * - ESP_ERR_INVALID_STATE: Touch slider driver was not initialized * - ESP_ERR_INVALID_ARG: slider_handle is null * - ESP_ERR_NOT_FOUND: Input handle is not a slider handle */ esp_err_t touch_slider_delete(touch_slider_handle_t slider_handle); /** * @brief Touch slider subscribes event * * This function uses event mask to subscribe to touch slider events, once one of * the subscribed events occurs, the event message could be retrieved by calling * touch_element_message_receive() or input callback routine. * * @param[in] slider_handle Slider handle * @param[in] event_mask Slider subscription event mask * @param[in] arg User input argument * * @note Touch slider only support three kind of event masks, they are * TOUCH_ELEM_EVENT_ON_PRESS, TOUCH_ELEM_EVENT_ON_RELEASE. You can use those event masks in any * combination to achieve the desired effect. * * @return * - ESP_OK: Successfully subscribed touch slider event * - ESP_ERR_INVALID_STATE: Touch slider driver was not initialized * - ESP_ERR_INVALID_ARG: slider_handle is null or event is not supported */ esp_err_t touch_slider_subscribe_event(touch_slider_handle_t slider_handle, uint32_t event_mask, void *arg); /** * @brief Touch slider set dispatch method * * This function sets a dispatch method that the driver core will use * this method as the event notification method. * * @param[in] slider_handle Slider handle * @param[in] dispatch_method Dispatch method (By callback/event) * * @return * - ESP_OK: Successfully set dispatch method * - ESP_ERR_INVALID_STATE: Touch slider driver was not initialized * - ESP_ERR_INVALID_ARG: slider_handle is null or dispatch_method is invalid */ esp_err_t touch_slider_set_dispatch_method(touch_slider_handle_t slider_handle, touch_elem_dispatch_t dispatch_method); /** * @brief Touch slider set callback * * This function sets a callback routine into touch element driver core, * when the subscribed events occur, the callback routine will be called. * * @param[in] slider_handle Slider handle * @param[in] slider_callback User input callback * * @warning Since this input callback routine runs on driver core (esp-timer callback routine), * it should not do something that attempts to Block, such as calling vTaskDelay(). * * @return * - ESP_OK: Successfully set callback * - ESP_ERR_INVALID_STATE: Touch slider driver was not initialized * - ESP_ERR_INVALID_ARG: slider_handle or slider_callback is null */ esp_err_t touch_slider_set_callback(touch_slider_handle_t slider_handle, touch_slider_callback_t slider_callback); /** * @brief Touch slider get message * * This function decodes the element message from touch_element_message_receive() and return * a slider message pointer. * * @param[in] element_message element message * * @return Touch slider message pointer */ const touch_slider_message_t* touch_slider_get_message(const touch_elem_message_t* element_message); #ifdef __cplusplus } #endif
41.208738
142
0.674638
[ "object" ]
a10d0a543f82b36268485676592bc6fb8b0d67e7
1,058
h
C
third_party/eRPC/src/util/mempool.h
agnesnatasya/Be-Tree
516c97c1a4ee68346e301277cfc318bb07a0c1b7
[ "BSD-2-Clause" ]
579
2019-02-24T20:58:06.000Z
2022-03-31T08:56:48.000Z
third_party/eRPC/src/util/mempool.h
agnesnatasya/Be-Tree
516c97c1a4ee68346e301277cfc318bb07a0c1b7
[ "BSD-2-Clause" ]
64
2019-02-25T02:48:31.000Z
2022-03-30T03:38:40.000Z
third_party/eRPC/src/util/mempool.h
agnesnatasya/Be-Tree
516c97c1a4ee68346e301277cfc318bb07a0c1b7
[ "BSD-2-Clause" ]
86
2019-02-28T01:40:50.000Z
2022-02-23T08:02:26.000Z
#pragma once #include "common.h" #include "util/huge_alloc.h" namespace erpc { /// A hugepage-backed pool for objects of type T. Objects are not registered /// with the NIC. template <class T> class MemPool { size_t num_to_alloc_ = MB(2) / sizeof(T); // Start with 2 MB HugeAlloc *huge_alloc_; std::vector<T *> pool_; void extend_pool() { size_t alloc_sz = sizeof(T) * num_to_alloc_; // alloc_raw()'s result is leaked Buffer b = huge_alloc_->alloc_raw(alloc_sz, DoRegister::kFalse); rt_assert(b.buf_ != nullptr, "Hugepage allocation failed"); for (size_t i = 0; i < num_to_alloc_; i++) { pool_.push_back(reinterpret_cast<T *>(&b.buf_[sizeof(T) * i])); } num_to_alloc_ *= 2; } public: T *alloc() { if (pool_.empty()) extend_pool(); T *ret = pool_.back(); pool_.pop_back(); return ret; } void free(T *t) { pool_.push_back(t); } MemPool(HugeAlloc *huge_alloc) : huge_alloc_(huge_alloc) {} /// Cleanup is done when owner deletes huge_alloc ~MemPool() {} }; } // namespace erpc
23.511111
76
0.646503
[ "vector" ]
a1159a3c69cfec90be8ebe9a63c1d8fd7dd2f666
142
h
C
tbshg_core/lib/Eigen/src/Geometry/InternalHeaderCheck.h
1713175349/tbshg
a3d3cfb0dd9caff4be87943a83a9aed61f3926b7
[ "MIT" ]
null
null
null
tbshg_core/lib/Eigen/src/Geometry/InternalHeaderCheck.h
1713175349/tbshg
a3d3cfb0dd9caff4be87943a83a9aed61f3926b7
[ "MIT" ]
null
null
null
tbshg_core/lib/Eigen/src/Geometry/InternalHeaderCheck.h
1713175349/tbshg
a3d3cfb0dd9caff4be87943a83a9aed61f3926b7
[ "MIT" ]
null
null
null
#ifndef EIGEN_GEOMETRY_MODULE_H #error "Please include Eigen/Geometry instead of including headers inside the src directory directly." #endif
35.5
102
0.838028
[ "geometry" ]
a117542109b615b46c31e999e84fbbe16c69d2fa
32,525
c
C
src/libponyc/pass/sugar.c
rtpax/ponyc
5af6626fcc894ef201bebfac712c454e6c8b14c9
[ "BSD-2-Clause" ]
null
null
null
src/libponyc/pass/sugar.c
rtpax/ponyc
5af6626fcc894ef201bebfac712c454e6c8b14c9
[ "BSD-2-Clause" ]
null
null
null
src/libponyc/pass/sugar.c
rtpax/ponyc
5af6626fcc894ef201bebfac712c454e6c8b14c9
[ "BSD-2-Clause" ]
null
null
null
#include "sugar.h" #include "../ast/astbuild.h" #include "../ast/id.h" #include "../ast/printbuf.h" #include "../pass/syntax.h" #include "../pkg/ifdef.h" #include "../pkg/package.h" #include "../type/alias.h" #include "../type/assemble.h" #include "../type/sanitise.h" #include "../type/subtype.h" #include "../ast/stringtab.h" #include "../ast/token.h" #include "../../libponyrt/mem/pool.h" #include "ponyassert.h" #include <stdio.h> #include <string.h> static ast_t* make_runtime_override_defaults(ast_t* ast) { pony_assert(ast != NULL); // set it as a bare function token_id cap = TK_AT; BUILD(runtime_override_defaults, ast, NODE(TK_FUN, AST_SCOPE NODE(cap) ID("runtime_override_defaults") // name NONE // typeparams NODE(TK_PARAMS, NODE(TK_PARAM, ID("rto") NODE(TK_NOMINAL, ID("$0") ID("RuntimeOptions") NONE NONE NONE) NONE)) // params NONE // return type NONE // error NODE(TK_SEQ, NODE(TK_TRUE)) NONE )); return runtime_override_defaults; } static ast_t* make_create(ast_t* ast) { pony_assert(ast != NULL); // Default constructors on classes can be iso, on actors they must be tag token_id cap = TK_NONE; switch(ast_id(ast)) { case TK_STRUCT: case TK_CLASS: cap = TK_ISO; break; default: {} } BUILD(create, ast, NODE(TK_NEW, AST_SCOPE NODE(cap) ID("create") // name NONE // typeparams NONE // params NONE // return type NONE // error NODE(TK_SEQ, NODE(TK_TRUE)) NONE )); return create; } bool has_member(ast_t* members, const char* name) { name = stringtab(name); ast_t* member = ast_child(members); while(member != NULL) { ast_t* id; switch(ast_id(member)) { case TK_FVAR: case TK_FLET: case TK_EMBED: id = ast_child(member); break; default: id = ast_childidx(member, 1); break; } if(ast_name(id) == name) return true; member = ast_sibling(member); } return false; } static void add_default_runtime_override_defaults_method(ast_t* ast) { pony_assert(ast != NULL); ast_t* members = ast_childidx(ast, 4); // If have no @runtime_override_defaults method, add one. if(has_member(members, "runtime_override_defaults")) return; ast_append(members, make_runtime_override_defaults(ast)); } static void add_default_constructor(ast_t* ast) { pony_assert(ast != NULL); ast_t* members = ast_childidx(ast, 4); // If we have no constructors and no "create" member, add a "create" // constructor. if(has_member(members, "create")) return; ast_t* member = ast_child(members); while(member != NULL) { switch(ast_id(member)) { case TK_NEW: return; default: {} } member = ast_sibling(member); } ast_append(members, make_create(ast)); } static ast_result_t sugar_module(pass_opt_t* opt, ast_t* ast) { ast_t* docstring = ast_child(ast); ast_t* package = ast_parent(ast); pony_assert(ast_id(package) == TK_PACKAGE); if(strcmp(package_name(package), "$0") != 0) { // Every module not in builtin has an implicit use builtin command. // Since builtin is always the first package processed it is $0. BUILD(builtin, ast, NODE(TK_USE, NONE STRING(stringtab("builtin")) NONE)); ast_add(ast, builtin); } if((docstring == NULL) || (ast_id(docstring) != TK_STRING)) return AST_OK; ast_t* package_docstring = ast_childlast(package); if(ast_id(package_docstring) == TK_STRING) { ast_error(opt->check.errors, docstring, "the package already has a docstring"); ast_error_continue(opt->check.errors, package_docstring, "the existing docstring is here"); return AST_ERROR; } ast_append(package, docstring); ast_remove(docstring); return AST_OK; } static void sugar_docstring(ast_t* ast) { pony_assert(ast != NULL); AST_GET_CHILDREN(ast, cap, id, type_params, params, return_type, error, body, docstring); if(ast_id(docstring) == TK_NONE) { ast_t* first = ast_child(body); // First expression in body is a docstring if it is a string literal and // there are any other expressions in the body sequence if((first != NULL) && (ast_id(first) == TK_STRING) && (ast_sibling(first) != NULL)) { ast_pop(body); ast_replace(&docstring, first); } } } static ast_result_t sugar_entity(pass_opt_t* opt, ast_t* ast, bool add_create, token_id def_def_cap) { (void)opt; AST_GET_CHILDREN(ast, id, typeparams, defcap, traits, members); if(ast_name(id) == stringtab("Main")) add_default_runtime_override_defaults_method(ast); if(add_create) add_default_constructor(ast); if(ast_id(defcap) == TK_NONE) ast_setid(defcap, def_def_cap); // Build a reverse sequence of all field initialisers. BUILD(init_seq, members, NODE(TK_SEQ)); ast_t* member = ast_child(members); while(member != NULL) { switch(ast_id(member)) { case TK_FLET: case TK_FVAR: case TK_EMBED: { AST_GET_CHILDREN(member, f_id, f_type, f_init); if(ast_id(f_init) != TK_NONE) { // Replace the initialiser with TK_NONE. ast_swap(f_init, ast_from(f_init, TK_NONE)); // id = init BUILD(init, member, NODE(TK_ASSIGN, NODE(TK_REFERENCE, TREE(f_id)) TREE(f_init))); ast_add(init_seq, init); } break; } default: {} } member = ast_sibling(member); } // Add field initialisers to all constructors. if(ast_child(init_seq) != NULL) { member = ast_child(members); while(member != NULL) { switch(ast_id(member)) { case TK_NEW: { AST_GET_CHILDREN(member, n_cap, n_id, n_typeparam, n_params, n_result, n_partial, n_body); pony_assert(ast_id(n_body) == TK_SEQ); sugar_docstring(member); ast_t* init = ast_child(init_seq); while(init != NULL) { ast_add(n_body, init); init = ast_sibling(init); } break; } default: {} } member = ast_sibling(member); } } ast_free_unattached(init_seq); return AST_OK; } static ast_result_t sugar_typeparam(ast_t* ast) { AST_GET_CHILDREN(ast, id, constraint); if(ast_id(constraint) == TK_NONE) { REPLACE(&constraint, NODE(TK_NOMINAL, NONE TREE(id) NONE NONE NONE)); } return AST_OK; } static ast_result_t check_params(pass_opt_t* opt, ast_t* params) { pony_assert(params != NULL); ast_result_t result = AST_OK; // Check each parameter. for(ast_t* p = ast_child(params); p != NULL; p = ast_sibling(p)) { if(ast_id(p) == TK_ELLIPSIS) continue; AST_GET_CHILDREN(p, id, type, def_arg); if(ast_id(id) != TK_ID) { ast_error(opt->check.errors, p, "expected parameter name"); result = AST_ERROR; } else if(!is_name_internal_test(ast_name(id)) && !check_id_param(opt, id)) { result = AST_ERROR; } if(ast_id(type) == TK_NONE) { ast_error(opt->check.errors, type, "expected parameter type"); result = AST_ERROR; } } return result; } static ast_result_t check_method(pass_opt_t* opt, ast_t* method) { pony_assert(method != NULL); ast_result_t result = AST_OK; ast_t* params = ast_childidx(method, 3); result = check_params(opt, params); return result; } static ast_result_t sugar_new(pass_opt_t* opt, ast_t* ast) { AST_GET_CHILDREN(ast, cap, id, typeparams, params, result); // Return type default to ref^ for classes, val^ for primitives, and // tag^ for actors. if(ast_id(result) == TK_NONE) { token_id tcap = ast_id(cap); if(tcap == TK_NONE) { switch(ast_id(opt->check.frame->type)) { case TK_PRIMITIVE: tcap = TK_VAL; break; case TK_ACTOR: tcap = TK_TAG; break; default: tcap = TK_REF; break; } ast_setid(cap, tcap); } ast_replace(&result, type_for_this(opt, ast, tcap, TK_EPHEMERAL)); } sugar_docstring(ast); return check_method(opt, ast); } static ast_result_t sugar_be(pass_opt_t* opt, ast_t* ast) { (void)opt; AST_GET_CHILDREN(ast, cap, id, typeparams, params, result, can_error, body); ast_setid(cap, TK_TAG); if(ast_id(result) == TK_NONE) { // Return type is None. ast_t* type = type_sugar(ast, NULL, "None"); ast_replace(&result, type); } sugar_docstring(ast); return check_method(opt, ast); } void fun_defaults(ast_t* ast) { pony_assert(ast != NULL); AST_GET_CHILDREN(ast, cap, id, typeparams, params, result, can_error, body, docstring); // If the receiver cap is not specified, set it to box. if(ast_id(cap) == TK_NONE) ast_setid(cap, TK_BOX); // If the return value is not specified, set it to None. if(ast_id(result) == TK_NONE) { ast_t* type = type_sugar(ast, NULL, "None"); ast_replace(&result, type); } // If the return type is None, add a None at the end of the body, unless it // already ends with an error or return statement if(is_none(result) && (ast_id(body) != TK_NONE)) { ast_t* last_cmd = ast_childlast(body); if(ast_id(last_cmd) != TK_ERROR && ast_id(last_cmd) != TK_RETURN) { BUILD(ref, body, NODE(TK_REFERENCE, ID("None"))); ast_append(body, ref); } } } static ast_result_t sugar_fun(pass_opt_t* opt, ast_t* ast) { fun_defaults(ast); sugar_docstring(ast); return check_method(opt, ast); } // If the given tree is a TK_NONE expand it to a source None static void expand_none(ast_t* ast, bool is_scope) { if(ast_id(ast) != TK_NONE) return; if(is_scope) ast_scope(ast); ast_setid(ast, TK_SEQ); BUILD(ref, ast, NODE(TK_REFERENCE, ID("None"))); ast_add(ast, ref); } static ast_result_t sugar_return(pass_opt_t* opt, ast_t* ast) { ast_t* return_value = ast_child(ast); if((ast_id(ast) == TK_RETURN) && (ast_id(opt->check.frame->method) == TK_NEW)) { pony_assert(ast_id(return_value) == TK_NONE); ast_setid(return_value, TK_THIS); } else { expand_none(return_value, false); } return AST_OK; } static ast_result_t sugar_else(ast_t* ast, size_t index) { ast_t* else_clause = ast_childidx(ast, index); expand_none(else_clause, true); return AST_OK; } static ast_result_t sugar_try(ast_t* ast) { AST_GET_CHILDREN(ast, ignore, else_clause, then_clause); if(ast_id(else_clause) == TK_NONE && ast_id(then_clause) != TK_NONE) // Then without else means we don't require a throwable in the try block ast_setid(ast, TK_TRY_NO_CHECK); expand_none(else_clause, true); expand_none(then_clause, true); return AST_OK; } static ast_result_t sugar_for(pass_opt_t* opt, ast_t** astp) { AST_EXTRACT_CHILDREN(*astp, for_idseq, for_iter, for_body, for_else); ast_t* annotation = ast_consumeannotation(*astp); expand_none(for_else, true); const char* iter_name = package_hygienic_id(&opt->check); BUILD(try_next, for_iter, NODE(TK_TRY_NO_CHECK, NODE(TK_SEQ, AST_SCOPE NODE(TK_CALL, NODE(TK_DOT, NODE(TK_REFERENCE, ID(iter_name)) ID("next")) NONE NONE NODE(TK_QUESTION))) NODE(TK_SEQ, AST_SCOPE NODE(TK_BREAK, NONE)) NONE)); sugar_try(try_next); REPLACE(astp, NODE(TK_SEQ, NODE(TK_ASSIGN, NODE(TK_LET, NICE_ID(iter_name, "for loop iterator") NONE) TREE(for_iter)) NODE(TK_WHILE, AST_SCOPE ANNOTATE(annotation) NODE(TK_SEQ, NODE_ERROR_AT(TK_CALL, for_iter, NODE(TK_DOT, NODE(TK_REFERENCE, ID(iter_name)) ID("has_next")) NONE NONE NONE)) NODE(TK_SEQ, AST_SCOPE NODE_ERROR_AT(TK_ASSIGN, for_idseq, TREE(for_idseq) TREE(try_next)) TREE(for_body)) TREE(for_else)))); return AST_OK; } static void build_with_dispose(ast_t* dispose_clause, ast_t* idseq) { pony_assert(dispose_clause != NULL); pony_assert(idseq != NULL); if(ast_id(idseq) == TK_LET) { // Just a single variable ast_t* id = ast_child(idseq); pony_assert(id != NULL); // Don't call dispose() on don't cares if(is_name_dontcare(ast_name(id))) return; BUILD(dispose, idseq, NODE(TK_CALL, NODE(TK_DOT, NODE(TK_REFERENCE, TREE(id)) ID("dispose")) NONE NONE NONE)); ast_add(dispose_clause, dispose); return; } // We have a list of variables pony_assert(ast_id(idseq) == TK_TUPLE); for(ast_t* p = ast_child(idseq); p != NULL; p = ast_sibling(p)) { pony_assert(ast_id(p) == TK_SEQ); ast_t* let = ast_child(p); build_with_dispose(dispose_clause, let); } } static ast_result_t sugar_with(pass_opt_t* opt, ast_t** astp) { AST_EXTRACT_CHILDREN(*astp, withexpr, body); ast_t* main_annotation = ast_consumeannotation(*astp); // First build a skeleton disposing block without the "with" variables BUILD(replace, *astp, NODE(TK_SEQ, NODE(TK_DISPOSING_BLOCK, ANNOTATE(main_annotation) NODE(TK_SEQ, AST_SCOPE TREE(body)) NODE(TK_SEQ, AST_SCOPE)))); ast_t* dblock = ast_child(replace); AST_GET_CHILDREN(dblock, dbody, dexit); // Add the "with" variables from each with element for(ast_t* p = ast_child(withexpr); p != NULL; p = ast_sibling(p)) { pony_assert(ast_id(p) == TK_SEQ); AST_GET_CHILDREN(p, idseq, init); const char* init_name = package_hygienic_id(&opt->check); BUILD(assign, idseq, NODE(TK_ASSIGN, NODE(TK_LET, ID(init_name) NONE) TREE(init))); BUILD(local, idseq, NODE(TK_ASSIGN, TREE(idseq) NODE(TK_REFERENCE, ID(init_name)))); ast_add(replace, assign); ast_add(dbody, local); build_with_dispose(dexit, idseq); ast_add(dexit, local); } ast_replace(astp, replace); return AST_OK; } // Find all captures in the given pattern. static bool sugar_match_capture(pass_opt_t* opt, ast_t* pattern) { switch(ast_id(pattern)) { case TK_VAR: ast_error(opt->check.errors, pattern, "match captures may not be declared with `var`, use `let`"); return false; case TK_LET: { AST_GET_CHILDREN(pattern, id, capture_type); if(ast_id(capture_type) == TK_NONE) { ast_error(opt->check.errors, pattern, "capture types cannot be inferred, please specify type of %s", ast_name(id)); return false; } // Disallow capturing tuples. if(ast_id(capture_type) == TK_TUPLETYPE) { ast_error(opt->check.errors, capture_type, "can't capture a tuple, change this into a tuple of capture " "expressions"); return false; } // Change this to a capture. ast_setid(pattern, TK_MATCH_CAPTURE); return true; } case TK_TUPLE: { // Check all tuple elements. bool r = true; for(ast_t* p = ast_child(pattern); p != NULL; p = ast_sibling(p)) { if(!sugar_match_capture(opt, p)) r = false; } return r; } case TK_SEQ: // Captures in a sequence must be the only element. if(ast_childcount(pattern) != 1) return true; return sugar_match_capture(opt, ast_child(pattern)); default: // Anything else isn't a capture. return true; } } static ast_result_t sugar_case(pass_opt_t* opt, ast_t* ast) { ast_result_t r = AST_OK; AST_GET_CHILDREN(ast, pattern, guard, body); if(!sugar_match_capture(opt, pattern)) r = AST_ERROR; if(ast_id(body) != TK_NONE) return r; // We have no body, take a copy of the next case with a body ast_t* next = ast; ast_t* next_body = body; while(ast_id(next_body) == TK_NONE) { next = ast_sibling(next); pony_assert(next != NULL); pony_assert(ast_id(next) == TK_CASE); next_body = ast_childidx(next, 2); } ast_replace(&body, next_body); return r; } static ast_result_t sugar_update(ast_t** astp) { ast_t* ast = *astp; pony_assert(ast_id(ast) == TK_ASSIGN); AST_GET_CHILDREN(ast, call, value); if(ast_id(call) != TK_CALL) return AST_OK; // We are of the form: x(y) = z // Replace us with: x.update(y where value = z) AST_EXTRACT_CHILDREN(call, expr, positional, named, question); // If there are no named arguments yet, named will be a TK_NONE. ast_setid(named, TK_NAMEDARGS); // Build a new namedarg. BUILD(namedarg, ast, NODE(TK_UPDATEARG, ID("value") NODE(TK_SEQ, TREE(value)))); // Append the named arg to our existing list. ast_append(named, namedarg); // Replace with the update call. REPLACE(astp, NODE(TK_CALL, NODE(TK_DOT, TREE(expr) ID("update")) TREE(positional) TREE(named) TREE(question))); return AST_OK; } static ast_result_t sugar_as(pass_opt_t* opt, ast_t** astp) { (void)opt; ast_t* ast = *astp; pony_assert(ast_id(ast) == TK_AS); AST_GET_CHILDREN(ast, expr, type); if(ast_id(type) == TK_TUPLETYPE) { BUILD(new_type, type, NODE(TK_TUPLETYPE)); for(ast_t* p = ast_child(type); p != NULL; p = ast_sibling(p)) { if(ast_id(p) == TK_NOMINAL && is_name_dontcare(ast_name(ast_childidx(p, 1)))) { BUILD(dontcare, new_type, NODE(TK_DONTCARETYPE)); ast_append(new_type, dontcare); } else ast_append(new_type, p); } REPLACE(astp, NODE(TK_AS, TREE(expr) TREE(new_type))); } return AST_OK; } static ast_result_t sugar_binop(ast_t** astp, const char* fn_name, const char* fn_name_partial) { AST_GET_CHILDREN(*astp, left, right, question); ast_t* positional = ast_from(right, TK_POSITIONALARGS); if(ast_id(right) == TK_TUPLE) { ast_t* value = ast_child(right); while(value != NULL) { BUILD(arg, right, NODE(TK_SEQ, TREE(value))); ast_append(positional, arg); value = ast_sibling(value); } } else { BUILD(arg, right, NODE(TK_SEQ, TREE(right))); ast_add(positional, arg); } const char* name = fn_name; if(fn_name_partial != NULL && ast_id(question) == TK_QUESTION) name = fn_name_partial; REPLACE(astp, NODE(TK_CALL, NODE(TK_DOT, TREE(left) ID(name)) TREE(positional) NONE TREE(question))); return AST_OK; } static ast_result_t sugar_unop(ast_t** astp, const char* fn_name) { AST_GET_CHILDREN(*astp, expr); REPLACE(astp, NODE(TK_CALL, NODE(TK_DOT, TREE(expr) ID(fn_name)) NONE NONE NONE)); return AST_OK; } static ast_result_t sugar_ffi(pass_opt_t* opt, ast_t* ast) { AST_GET_CHILDREN(ast, id, typeargs, args, named_args); const char* name = ast_name(id); size_t len = ast_name_len(id); // Check for \0 in ffi name (it may be a string literal) if(memchr(name, '\0', len) != NULL) { ast_error(opt->check.errors, ast, "FFI function names cannot include null characters"); return AST_ERROR; } // Prefix '@' to the name char* new_name = (char*)ponyint_pool_alloc_size(len + 2); new_name[0] = '@'; memcpy(new_name + 1, name, len); new_name[len + 1] = '\0'; ast_t* new_id = ast_from_string(id, stringtab_consume(new_name, len + 2)); ast_replace(&id, new_id); return AST_OK; } static ast_result_t sugar_ifdef(pass_opt_t* opt, ast_t* ast) { pony_assert(opt != NULL); pony_assert(ast != NULL); AST_GET_CHILDREN(ast, cond, then_block, else_block, else_cond); // Combine parent ifdef condition with ours. ast_t* parent_ifdef_cond = opt->check.frame->ifdef_cond; if(parent_ifdef_cond != NULL) { // We have a parent ifdef, combine its condition with ours. pony_assert(ast_id(ast_parent(parent_ifdef_cond)) == TK_IFDEF); REPLACE(&else_cond, NODE(TK_AND, TREE(parent_ifdef_cond) NODE(TK_NOT, TREE(cond)) NODE(TK_NONE))); REPLACE(&cond, NODE(TK_AND, TREE(parent_ifdef_cond) TREE(cond) NODE(TK_NONE))); } else { // Make else condition for our children to use. REPLACE(&else_cond, NODE(TK_NOT, TREE(cond))); } // Normalise condition so and, or and not nodes aren't sugared to function // calls. if(!ifdef_cond_normalise(&cond, opt)) { ast_error(opt->check.errors, ast, "ifdef condition will never be true"); return AST_ERROR; } if(!ifdef_cond_normalise(&else_cond, opt)) { ast_error(opt->check.errors, ast, "ifdef condition is always true"); return AST_ERROR; } return sugar_else(ast, 2); } static ast_result_t sugar_use(pass_opt_t* opt, ast_t* ast) { pony_assert(ast != NULL); // Normalise condition so and, or and not nodes aren't sugared to function // calls. ast_t* guard = ast_childidx(ast, 2); if(!ifdef_cond_normalise(&guard, opt)) { ast_error(opt->check.errors, ast, "use guard condition will never be true"); return AST_ERROR; } return AST_OK; } static ast_result_t sugar_semi(pass_opt_t* options, ast_t** astp) { ast_t* ast = *astp; pony_assert(ast_id(ast) == TK_SEMI); // Semis are pointless, discard them pony_assert(ast_child(ast) == NULL); *astp = ast_sibling(ast); ast_remove(ast); // Since we've effectively replaced ast with its successor we need to process // that too return pass_sugar(astp, options); } static ast_result_t sugar_lambdatype(pass_opt_t* opt, ast_t** astp) { pony_assert(astp != NULL); ast_t* ast = *astp; pony_assert(ast != NULL); AST_EXTRACT_CHILDREN(ast, apply_cap, apply_name, apply_t_params, params, ret_type, error, interface_cap, ephemeral); bool bare = ast_id(ast) == TK_BARELAMBDATYPE; if(bare) { ast_setid(apply_cap, TK_AT); ast_setid(interface_cap, TK_VAL); } const char* i_name = package_hygienic_id(&opt->check); ast_t* interface_t_params; ast_t* t_args; collect_type_params(ast, NULL, &t_args); // We will replace {..} with $0 REPLACE(astp, NODE(TK_NOMINAL, NONE // Package ID(i_name) TREE(t_args) TREE(interface_cap) TREE(ephemeral))); ast = *astp; // Fetch the interface type parameters after we replace the ast, so that if // we are an interface type parameter, we get ourselves as the constraint. collect_type_params(ast, &interface_t_params, NULL); printbuf_t* buf = printbuf_new(); // Include the receiver capability or the bareness if appropriate. if(ast_id(apply_cap) == TK_AT) printbuf(buf, "@{("); else if(ast_id(apply_cap) != TK_NONE) printbuf(buf, "{%s(", ast_print_type(apply_cap)); else printbuf(buf, "{("); // Convert parameter type list to a normal parameter list. int p_no = 1; for(ast_t* p = ast_child(params); p != NULL; p = ast_sibling(p)) { if(p_no > 1) printbuf(buf, ", "); printbuf(buf, "%s", ast_print_type(p)); char name[12]; snprintf(name, sizeof(name), "p%d", p_no); REPLACE(&p, NODE(TK_PARAM, ID(name) TREE(p) NONE)); p_no++; } printbuf(buf, ")"); if(ast_id(ret_type) != TK_NONE) printbuf(buf, ": %s", ast_print_type(ret_type)); if(ast_id(error) != TK_NONE) printbuf(buf, " ?"); printbuf(buf, "}"); const char* fn_name = "apply"; if(ast_id(apply_name) == TK_ID) fn_name = ast_name(apply_name); // Attach the nice name to the original lambda. ast_setdata(ast_childidx(ast, 1), (void*)stringtab(buf->m)); // Create a new anonymous type. BUILD(def, ast, NODE(TK_INTERFACE, AST_SCOPE NICE_ID(i_name, buf->m) TREE(interface_t_params) NONE // Cap NONE // Provides NODE(TK_MEMBERS, NODE(TK_FUN, AST_SCOPE TREE(apply_cap) ID(fn_name) TREE(apply_t_params) TREE(params) TREE(ret_type) TREE(error) NONE // Body NONE))// Doc string NONE // @ NONE)); // Doc string printbuf_free(buf); if(bare) { BUILD(bare_annotation, def, NODE(TK_ANNOTATION, ID("ponyint_bare"))); // Record the syntax pass as done to avoid the error about internal // annotations. ast_pass_record(bare_annotation, PASS_SYNTAX); ast_setannotation(def, bare_annotation); } // Add new type to current module and bring it up to date with passes. ast_t* module = ast_nearest(ast, TK_MODULE); ast_append(module, def); if(!ast_passes_type(&def, opt, opt->program_pass)) return AST_FATAL; // Sugar the call. if(!ast_passes_subtree(astp, opt, PASS_SUGAR)) return AST_FATAL; return AST_OK; } static ast_result_t sugar_barelambda(pass_opt_t* opt, ast_t* ast) { (void)opt; pony_assert(ast != NULL); AST_GET_CHILDREN(ast, receiver_cap, name, t_params, params, captures, ret_type, raises, body, reference_cap); ast_setid(receiver_cap, TK_AT); ast_setid(reference_cap, TK_VAL); return AST_OK; } ast_t* expand_location(ast_t* location) { pony_assert(location != NULL); const char* file_name = ast_source(location)->file; if(file_name == NULL) file_name = ""; // Find name of containing method. const char* method_name = ""; for(ast_t* method = location; method != NULL; method = ast_parent(method)) { token_id variety = ast_id(method); if(variety == TK_FUN || variety == TK_BE || variety == TK_NEW) { method_name = ast_name(ast_childidx(method, 1)); break; } } // Find name of containing type. const char* type_name = ""; for(ast_t* typ = location; typ != NULL; typ = ast_parent(typ)) { token_id variety = ast_id(typ); if(variety == TK_INTERFACE || variety == TK_TRAIT || variety == TK_PRIMITIVE || variety == TK_STRUCT || variety == TK_CLASS || variety == TK_ACTOR) { type_name = ast_name(ast_child(typ)); break; } } // Create an object literal. BUILD(ast, location, NODE(TK_OBJECT, DATA("__loc") NONE // Capability NONE // Provides NODE(TK_MEMBERS, NODE(TK_FUN, AST_SCOPE NODE(TK_TAG) ID("file") NONE NONE NODE(TK_NOMINAL, NONE ID("String") NONE NONE NONE) NONE NODE(TK_SEQ, STRING(file_name)) NONE) NODE(TK_FUN, AST_SCOPE NODE(TK_TAG) ID("type_name") NONE NONE NODE(TK_NOMINAL, NONE ID("String") NONE NONE NONE) NONE NODE(TK_SEQ, STRING(type_name)) NONE) NODE(TK_FUN, AST_SCOPE NODE(TK_TAG) ID("method_name") NONE NONE NODE(TK_NOMINAL, NONE ID("String") NONE NONE NONE) NONE NODE(TK_SEQ, STRING(method_name)) NONE) NODE(TK_FUN, AST_SCOPE NODE(TK_TAG) ID("line") NONE NONE NODE(TK_NOMINAL, NONE ID("USize") NONE NONE NONE) NONE NODE(TK_SEQ, INT(ast_line(location))) NONE) NODE(TK_FUN, AST_SCOPE NODE(TK_TAG) ID("pos") NONE NONE NODE(TK_NOMINAL, NONE ID("USize") NONE NONE NONE) NONE NODE(TK_SEQ, INT(ast_pos(location))) NONE)))); return ast; } static ast_result_t sugar_location(pass_opt_t* opt, ast_t** astp) { pony_assert(astp != NULL); ast_t* ast = *astp; pony_assert(ast != NULL); if(ast_id(ast_parent(ast_parent(ast))) == TK_PARAM) // Location is a default argument, do not expand yet. return AST_OK; ast_t* location = expand_location(ast); ast_replace(astp, location); // Sugar the expanded object. if(!ast_passes_subtree(astp, opt, PASS_SUGAR)) return AST_FATAL; return AST_OK; } ast_result_t pass_sugar(ast_t** astp, pass_opt_t* options) { ast_t* ast = *astp; pony_assert(ast != NULL); switch(ast_id(ast)) { case TK_MODULE: return sugar_module(options, ast); case TK_PRIMITIVE: return sugar_entity(options, ast, true, TK_VAL); case TK_STRUCT: return sugar_entity(options, ast, true, TK_REF); case TK_CLASS: return sugar_entity(options, ast, true, TK_REF); case TK_ACTOR: return sugar_entity(options, ast, true, TK_TAG); case TK_TRAIT: case TK_INTERFACE: return sugar_entity(options, ast, false, TK_REF); case TK_TYPEPARAM: return sugar_typeparam(ast); case TK_NEW: return sugar_new(options, ast); case TK_BE: return sugar_be(options, ast); case TK_FUN: return sugar_fun(options, ast); case TK_RETURN: return sugar_return(options, ast); case TK_IF: case TK_WHILE: case TK_REPEAT: return sugar_else(ast, 2); case TK_IFTYPE_SET: return sugar_else(ast, 1); case TK_TRY: return sugar_try(ast); case TK_FOR: return sugar_for(options, astp); case TK_WITH: return sugar_with(options, astp); case TK_CASE: return sugar_case(options, ast); case TK_ASSIGN: return sugar_update(astp); case TK_AS: return sugar_as(options, astp); case TK_PLUS: return sugar_binop(astp, "add", "add_partial"); case TK_MINUS: return sugar_binop(astp, "sub", "sub_partial"); case TK_MULTIPLY: return sugar_binop(astp, "mul", "mul_partial"); case TK_DIVIDE: return sugar_binop(astp, "div", "div_partial"); case TK_REM: return sugar_binop(astp, "rem", "rem_partial"); case TK_MOD: return sugar_binop(astp, "mod", "mod_partial"); case TK_PLUS_TILDE: return sugar_binop(astp, "add_unsafe", NULL); case TK_MINUS_TILDE: return sugar_binop(astp, "sub_unsafe", NULL); case TK_MULTIPLY_TILDE: return sugar_binop(astp, "mul_unsafe", NULL); case TK_DIVIDE_TILDE: return sugar_binop(astp, "div_unsafe", NULL); case TK_REM_TILDE: return sugar_binop(astp, "rem_unsafe", NULL); case TK_MOD_TILDE: return sugar_binop(astp, "mod_unsafe", NULL); case TK_LSHIFT: return sugar_binop(astp, "shl", NULL); case TK_RSHIFT: return sugar_binop(astp, "shr", NULL); case TK_LSHIFT_TILDE: return sugar_binop(astp, "shl_unsafe", NULL); case TK_RSHIFT_TILDE: return sugar_binop(astp, "shr_unsafe", NULL); case TK_AND: return sugar_binop(astp, "op_and", NULL); case TK_OR: return sugar_binop(astp, "op_or", NULL); case TK_XOR: return sugar_binop(astp, "op_xor", NULL); case TK_EQ: return sugar_binop(astp, "eq", NULL); case TK_NE: return sugar_binop(astp, "ne", NULL); case TK_LT: return sugar_binop(astp, "lt", NULL); case TK_LE: return sugar_binop(astp, "le", NULL); case TK_GE: return sugar_binop(astp, "ge", NULL); case TK_GT: return sugar_binop(astp, "gt", NULL); case TK_EQ_TILDE: return sugar_binop(astp, "eq_unsafe", NULL); case TK_NE_TILDE: return sugar_binop(astp, "ne_unsafe", NULL); case TK_LT_TILDE: return sugar_binop(astp, "lt_unsafe", NULL); case TK_LE_TILDE: return sugar_binop(astp, "le_unsafe", NULL); case TK_GE_TILDE: return sugar_binop(astp, "ge_unsafe", NULL); case TK_GT_TILDE: return sugar_binop(astp, "gt_unsafe", NULL); case TK_UNARY_MINUS: return sugar_unop(astp, "neg"); case TK_UNARY_MINUS_TILDE: return sugar_unop(astp, "neg_unsafe"); case TK_NOT: return sugar_unop(astp, "op_not"); case TK_FFIDECL: case TK_FFICALL: return sugar_ffi(options, ast); case TK_IFDEF: return sugar_ifdef(options, ast); case TK_USE: return sugar_use(options, ast); case TK_SEMI: return sugar_semi(options, astp); case TK_LAMBDATYPE: case TK_BARELAMBDATYPE: return sugar_lambdatype(options, astp); case TK_BARELAMBDA: return sugar_barelambda(options, ast); case TK_LOCATION: return sugar_location(options, astp); default: return AST_OK; } }
25.077101
135
0.62844
[ "object" ]
a119d5e6123b7b5bfcc2a165f2e30d8c4c6e8807
1,276
h
C
src/module/access/KRewriteMark.h
jcleng/nix-kangle-3.5.13.2
cc7bbaa429ada9a7eb7a023a152b6e2fc5defe3f
[ "MIT" ]
null
null
null
src/module/access/KRewriteMark.h
jcleng/nix-kangle-3.5.13.2
cc7bbaa429ada9a7eb7a023a152b6e2fc5defe3f
[ "MIT" ]
null
null
null
src/module/access/KRewriteMark.h
jcleng/nix-kangle-3.5.13.2
cc7bbaa429ada9a7eb7a023a152b6e2fc5defe3f
[ "MIT" ]
null
null
null
/* * KRewriteMark.h * * Created on: 2010-4-27 * Author: keengo * Copyright (c) 2010, NanChang BangTeng Inc * All Rights Reserved. * * You may use the Software for free for non-commercial use * under the License Restrictions. * * You may modify the source code(if being provieded) or interface * of the Software under the License Restrictions. * * You may use the Software for commercial use after purchasing the * commercial license.Moreover, according to the license you purchased * you may get specified term, manner and content of technical * support from NanChang BangTeng Inc * * See COPYING file for detail. */ #ifndef KREWRITEMARK_H_ #define KREWRITEMARK_H_ #include "KMark.h" #include "KReg.h" #include "KRewriteMarkEx.h" class KRewriteMark: public KMark { public: KRewriteMark(); virtual ~KRewriteMark(); bool mark(KHttpRequest *rq, KHttpObject *obj, const int chainJumpType, int &jumpType); KMark *newInstance(); const char *getName(); std::string getHtml(KModel *model); std::string getDisplay(); void editHtml(std::map<std::string, std::string> &attribute) throw (KHtmlSupportException); void buildXML(std::stringstream &s); private: KRewriteRule rule; std::string prefix; int code; }; #endif /* KREWRITEMARK_H_ */
25.019608
71
0.731975
[ "model" ]
a11c30bf04f055e8f2d3db8ea73caaca7a8f7c9a
14,136
c
C
mame/src/mame/drivers/m57.c
clobber/MAME-OS-X
ca11d0e946636bda042b6db55c82113e5722fc08
[ "MIT" ]
15
2015-03-03T23:15:57.000Z
2021-11-12T07:09:24.000Z
mame/src/mame/drivers/m57.c
clobber/MAME-OS-X
ca11d0e946636bda042b6db55c82113e5722fc08
[ "MIT" ]
null
null
null
mame/src/mame/drivers/m57.c
clobber/MAME-OS-X
ca11d0e946636bda042b6db55c82113e5722fc08
[ "MIT" ]
8
2015-07-07T16:40:44.000Z
2020-08-18T06:57:29.000Z
/**************************************************************************** Irem M57 hardware ***************************************************************************** Tropical Angel driver by Phil Stroffolino IREM M57 board stack with a M52-SOUND-E sound PCB. M57-A-A: TA-A-xx roms and proms NEC D780C (Z80) CPU NANAO KNA6032601 custom chip NANAO KNA6032701 custom chip 8-way dipswitch (x2) M58725P RAM (x3) CN1 - Ribbon cable connector CN2 - Ribbon cable connector Ribbon cable connector to sound PCB M57-B-A: TA-B-xx roms and proms 18.432 MHz OSC CN1 - Ribbon cable connector CN2 - Ribbon cable connector M52: HD6803 CPU AY-3-9810 (x2) sound chips MSM5205 OKI sound chip (and an unpopulated socket for a second MSM5202) 3.579545 MHz OSC 2764 Program rom labeled "TA S-1A-" Ribbon cable connector to M57-A-A PCB New Tropical Angel: Roms were found on an official IREM board with genuine IREM Tropical Angel license seal and genuine IREM serial number sticker. The "new" roms have hand written labels, while those that match the current Tropical Angel set look to be factory labeled chips. ***************************************************************************** Locations based on m58.c driver ****************************************************************************/ #include "emu.h" #include "cpu/z80/z80.h" #include "audio/irem.h" #include "includes/iremipt.h" #include "includes/m57.h" #define MASTER_CLOCK XTAL_18_432MHz /************************************* * * Memory maps * *************************************/ static ADDRESS_MAP_START( main_map, AS_PROGRAM, 8 ) AM_RANGE(0x0000, 0x7fff) AM_ROM AM_RANGE(0x8000, 0x87ff) AM_RAM_WRITE(m57_videoram_w) AM_BASE_MEMBER(m57_state, m_videoram) AM_RANGE(0x9000, 0x91ff) AM_RAM AM_BASE_MEMBER(m57_state, m_scrollram) AM_RANGE(0xc820, 0xc8ff) AM_WRITEONLY AM_BASE_SIZE_MEMBER(m57_state, m_spriteram, m_spriteram_size) AM_RANGE(0xd000, 0xd000) AM_WRITE(irem_sound_cmd_w) AM_RANGE(0xd001, 0xd001) AM_WRITE(m57_flipscreen_w) /* + coin counters */ AM_RANGE(0xd000, 0xd000) AM_READ_PORT("IN0") AM_RANGE(0xd001, 0xd001) AM_READ_PORT("IN1") AM_RANGE(0xd002, 0xd002) AM_READ_PORT("IN2") AM_RANGE(0xd003, 0xd003) AM_READ_PORT("DSW1") AM_RANGE(0xd004, 0xd004) AM_READ_PORT("DSW2") AM_RANGE(0xe000, 0xe7ff) AM_RAM ADDRESS_MAP_END /************************************* * * Generic port definitions * *************************************/ /* Same as m52, m58 and m62 (IREM Z80 hardware) */ static INPUT_PORTS_START( m57 ) PORT_START("IN0") /* Start 1 & 2 also restarts and freezes the game with stop mode on and are used in test mode to enter and esc the various tests */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 ) /* coin input must be active for 19 frames to be consistently recognized */ PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_IMPULSE(19) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_START("IN2") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_COCKTAIL PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_COCKTAIL /* DSW1 is so different from game to game that it isn't included here */ PORT_START("DSW2") PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) ) PORT_DIPLOCATION("SW2:1") PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x00, DEF_STR( Cabinet ) ) PORT_DIPLOCATION("SW2:2") PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x02, DEF_STR( Cocktail ) ) PORT_DIPNAME( 0x04, 0x04, "Coin Mode" ) PORT_DIPLOCATION("SW2:3") PORT_DIPSETTING( 0x04, "Mode 1" ) PORT_DIPSETTING( 0x00, "Mode 2" ) PORT_DIPUNKNOWN_DIPLOC( 0x08, IP_ACTIVE_LOW, "SW2:4" ) PORT_DIPUNKNOWN_DIPLOC( 0x10, IP_ACTIVE_LOW, "SW2:5" ) PORT_DIPUNKNOWN_DIPLOC( 0x20, IP_ACTIVE_LOW, "SW2:6" ) PORT_DIPNAME( 0x40, 0x40, "Invulnerability (Cheat)") PORT_DIPLOCATION("SW2:7") PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_SERVICE_DIPLOC( 0x80, IP_ACTIVE_LOW, "SW2:8" ) INPUT_PORTS_END /************************************* * * Games port definitions * *************************************/ static INPUT_PORTS_START( troangel ) PORT_INCLUDE(m57) PORT_MODIFY("IN1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_2WAY PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_2WAY PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN */ PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP */ PORT_MODIFY("IN2") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_2WAY PORT_COCKTAIL PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_2WAY PORT_COCKTAIL PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_DOWN PORT_COCKTAIL */ PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED ) /* IPT_JOYSTICK_UP PORT_COCKTAIL */ PORT_MODIFY("DSW2") /* TODO: the following enables an analog accelerator input read from 0xd003 */ /* however that is the DSW1 input so it must be multiplexed some way */ PORT_DIPNAME( 0x08, 0x08, "Analog Accelarator" ) PORT_DIPLOCATION("SW2:4") PORT_DIPSETTING( 0x08, DEF_STR( No ) ) PORT_DIPSETTING( 0x00, DEF_STR( Yes ) ) /* In stop mode, press 2 to stop and 1 to restart */ PORT_DIPNAME( 0x10, 0x10, "Stop Mode (Cheat)") PORT_DIPLOCATION("SW2:5") PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPUNUSED_DIPLOC( 0x20, IP_ACTIVE_LOW, "SW2:6" ) PORT_START("DSW1") PORT_DIPNAME( 0x03, 0x03, "Time" ) PORT_DIPLOCATION("SW1:1,2") /* table at 0x6110 - 4 * 8 bytes (B1 B2 bonus A1 A2 bonus M1 M2) */ PORT_DIPSETTING( 0x03, "B:180/A:160/M:140/BG:120" ) PORT_DIPSETTING( 0x02, "B:160/A:140/M:120/BG:100" ) PORT_DIPSETTING( 0x01, "B:140/A:120/M:100/BG:80" ) PORT_DIPSETTING( 0x00, "B:120/A:100/M:100/BG:80" ) PORT_DIPNAME( 0x04, 0x04, "Crash Loss Time" ) PORT_DIPLOCATION("SW1:3") PORT_DIPSETTING( 0x04, "5" ) PORT_DIPSETTING( 0x00, "10" ) PORT_DIPNAME( 0x08, 0x08, "Background Sound" ) PORT_DIPLOCATION("SW1:4") PORT_DIPSETTING( 0x08, "Boat Motor" ) PORT_DIPSETTING( 0x00, "Music" ) IREM_Z80_COINAGE_TYPE_2_LOC(SW1) INPUT_PORTS_END /************************************* * * Graphics layouts * *************************************/ static const gfx_layout spritelayout = { 16,32, 64, 3, { RGN_FRAC(0,3), RGN_FRAC(1,3), RGN_FRAC(2,3) }, { STEP8(0,1), STEP8(16*8,1) }, { STEP16(0,8), STEP16(256*64,8) }, 32*8 }; static GFXDECODE_START( m57 ) GFXDECODE_ENTRY( "gfx1", 0x0000, gfx_8x8x3_planar, 0, 32 ) GFXDECODE_ENTRY( "gfx2", 0x0000, spritelayout, 32*8, 32 ) GFXDECODE_ENTRY( "gfx2", 0x1000, spritelayout, 32*8, 32 ) GFXDECODE_ENTRY( "gfx2", 0x2000, spritelayout, 32*8, 32 ) GFXDECODE_ENTRY( "gfx2", 0x3000, spritelayout, 32*8, 32 ) GFXDECODE_END /************************************* * * Machine drivers * *************************************/ static MACHINE_CONFIG_START( m57, m57_state ) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", Z80, XTAL_18_432MHz/6) /* verified on pcb */ MCFG_CPU_PROGRAM_MAP(main_map) MCFG_CPU_VBLANK_INT("screen", irq0_line_hold) /* video hardware */ MCFG_SCREEN_ADD("screen", RASTER) MCFG_SCREEN_REFRESH_RATE(57) MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(1790) /* accurate frequency, measured on a Moon Patrol board, is 56.75Hz. */) /* the Lode Runner manual (similar but different hardware) */ /* talks about 55Hz and 1790ms vblank duration. */ MCFG_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16) MCFG_SCREEN_SIZE(32*8, 32*8) MCFG_SCREEN_VISIBLE_AREA(1*8, 31*8-1, 1*8, 31*8-1) MCFG_SCREEN_UPDATE(m57) MCFG_GFXDECODE(m57) MCFG_PALETTE_LENGTH(32*8+32*8) MCFG_PALETTE_INIT(m57) MCFG_VIDEO_START(m57) /* sound hardware */ MCFG_FRAGMENT_ADD(m52_sound_c_audio) MACHINE_CONFIG_END /************************************* * * ROM definitions * *************************************/ ROM_START( troangel ) ROM_REGION( 0x10000, "maincpu", 0 ) /* main CPU */ ROM_LOAD( "ta-a-3k", 0x0000, 0x2000, CRC(f21f8196) SHA1(7cbf74b77a559ee70312b799e707394d9b849f5b) ) ROM_LOAD( "ta-a-3m", 0x2000, 0x2000, CRC(58801e55) SHA1(91bdda778f2c4486001bc4ad26d6f21ba275ae08) ) ROM_LOAD( "ta-a-3n", 0x4000, 0x2000, CRC(de3dea44) SHA1(1290755ffc04dc3b3667e063118669a0eab6fb79) ) ROM_LOAD( "ta-a-3q", 0x6000, 0x2000, CRC(fff0fc2a) SHA1(82f3f5a8817e956192323eb555daa85b7766676d) ) ROM_REGION( 0x8000 , "iremsound", 0 ) /* sound CPU */ ROM_LOAD( "ta-s-1a", 0x6000, 0x2000, CRC(15a83210) SHA1(8ada510db689ffa372b2f4dc4bd1b1c69a0c5307) ) ROM_REGION( 0x06000, "gfx1", 0 ) ROM_LOAD( "ta-a-3e", 0x00000, 0x2000, CRC(e49f7ad8) SHA1(915de1084fd3c5fc81dd8c80107c28cc57b33226) ) ROM_LOAD( "ta-a-3d", 0x02000, 0x2000, CRC(06eef241) SHA1(4f327a54169046d8d84b5f5cf5d9f45e1df4dae6) ) ROM_LOAD( "ta-a-3c", 0x04000, 0x2000, CRC(7ff5482f) SHA1(fe8c181fed113007d69d11e8aa467e86a6357ffb) ) /* characters */ ROM_REGION( 0x0c000, "gfx2", 0 ) ROM_LOAD( "ta-b-5j", 0x00000, 0x2000, CRC(86895c0c) SHA1(b42b041e3e20dadd8411805d492133d371426ebf) ) /* sprites */ ROM_LOAD( "ta-b-5h", 0x02000, 0x2000, CRC(f8cff29d) SHA1(dabf3bbf50f73a381056131c2239c84dd966b63e) ) ROM_LOAD( "ta-b-5e", 0x04000, 0x2000, CRC(8b21ee9a) SHA1(1272722211d22d5b153e9415cc189a5aa9028543) ) ROM_LOAD( "ta-b-5d", 0x06000, 0x2000, CRC(cd473d47) SHA1(854cb532bd62851a206da2affd66a1257b7085b6) ) ROM_LOAD( "ta-b-5c", 0x08000, 0x2000, CRC(c19134c9) SHA1(028660e66fd033473c468b694e870c633ca05ec6) ) ROM_LOAD( "ta-b-5a", 0x0a000, 0x2000, CRC(0012792a) SHA1(b4380f5fbe5e9ce9b44f87ce48a8b402bab58b52) ) ROM_REGION( 0x0320, "proms", 0 ) ROM_LOAD( "ta-a-5a", 0x0000, 0x0100, CRC(01de1167) SHA1(b9070f8c70eb362fc4d6a0a92235ce0a5b2ab858) ) /* chars palette low 4 bits */ ROM_LOAD( "ta-a-5b", 0x0100, 0x0100, CRC(efd11d4b) SHA1(7c7c356063ab35e4ffb8d65cd20c27c2a4b36537) ) /* chars palette high 4 bits */ ROM_LOAD( "ta-b-1b", 0x0200, 0x0020, CRC(f94911ea) SHA1(ad61a323476a97156a255a72048a28477b421284) ) /* sprites palette */ ROM_LOAD( "ta-b-3d", 0x0220, 0x0100, CRC(ed3e2aa4) SHA1(cfdfc151803080d1ecdd04af1bfea3dbdce8dca0) ) /* sprites lookup table */ ROM_END ROM_START( newtangl ) /* Offical "upgrade" or hack? */ ROM_REGION( 0x10000, "maincpu", 0 ) /* main CPU */ ROM_LOAD( "3k", 0x0000, 0x2000, CRC(3c6299a8) SHA1(a21a8452b75ce6174076878128d4f20b39b6d69d) ) ROM_LOAD( "3m", 0x2000, 0x2000, CRC(8d09056c) SHA1(4d2585103cc6e6c04015501d3c9e1578a8f9c0f5) ) ROM_LOAD( "3n", 0x4000, 0x2000, CRC(17b5a775) SHA1(d85c3371080bea82f19ac96fa0f1b332e1c86e27) ) ROM_LOAD( "3q", 0x6000, 0x2000, CRC(2e5fa773) SHA1(9a34fa43bde021fc7b00d8c3762c248e7b96dbf1) ) ROM_REGION( 0x8000 , "iremsound", 0 ) /* sound CPU */ ROM_LOAD( "ta-s-1a-", 0x6000, 0x2000, CRC(ea8a05cb) SHA1(5683e4dca93066ee788287ab73a766fa303ebe84) ) ROM_REGION( 0x06000, "gfx1", 0 ) ROM_LOAD( "ta-a-3e", 0x00000, 0x2000, CRC(e49f7ad8) SHA1(915de1084fd3c5fc81dd8c80107c28cc57b33226) ) ROM_LOAD( "ta-a-3d", 0x02000, 0x2000, CRC(06eef241) SHA1(4f327a54169046d8d84b5f5cf5d9f45e1df4dae6) ) ROM_LOAD( "ta-a-3c", 0x04000, 0x2000, CRC(7ff5482f) SHA1(fe8c181fed113007d69d11e8aa467e86a6357ffb) ) /* characters */ ROM_REGION( 0x0c000, "gfx2", 0 ) ROM_LOAD( "5j", 0x00000, 0x2000, CRC(89409130) SHA1(3f37f820b1b86166cde7c039d657ebd036d490dd) ) /* sprites */ ROM_LOAD( "ta-b-5h", 0x02000, 0x2000, CRC(f8cff29d) SHA1(dabf3bbf50f73a381056131c2239c84dd966b63e) ) ROM_LOAD( "5e", 0x04000, 0x2000, CRC(5460a467) SHA1(505c1d9e69c39a74369da17f354b90486ee6afcd) ) ROM_LOAD( "ta-b-5d", 0x06000, 0x2000, CRC(cd473d47) SHA1(854cb532bd62851a206da2affd66a1257b7085b6) ) ROM_LOAD( "5c", 0x08000, 0x2000, CRC(4a20637a) SHA1(74099cb7f1727c2de2f066497097f1a9eeec0cea) ) ROM_LOAD( "ta-b-5a", 0x0a000, 0x2000, CRC(0012792a) SHA1(b4380f5fbe5e9ce9b44f87ce48a8b402bab58b52) ) ROM_REGION( 0x0320, "proms", 0 ) ROM_LOAD( "ta-a-5a", 0x0000, 0x0100, CRC(01de1167) SHA1(b9070f8c70eb362fc4d6a0a92235ce0a5b2ab858) ) /* chars palette low 4 bits */ ROM_LOAD( "ta-a-5b", 0x0100, 0x0100, CRC(efd11d4b) SHA1(7c7c356063ab35e4ffb8d65cd20c27c2a4b36537) ) /* chars palette high 4 bits */ ROM_LOAD( "ta-b-1b", 0x0200, 0x0020, CRC(f94911ea) SHA1(ad61a323476a97156a255a72048a28477b421284) ) /* sprites palette */ ROM_LOAD( "ta-b-3d", 0x0220, 0x0100, CRC(ed3e2aa4) SHA1(cfdfc151803080d1ecdd04af1bfea3dbdce8dca0) ) /* sprites lookup table */ ROM_END /************************************* * * Game drivers * *************************************/ GAME( 1983, troangel, 0, m57, troangel, 0, ROT0, "Irem", "Tropical Angel", GAME_SUPPORTS_SAVE ) GAME( 1983, newtangl, troangel, m57, troangel, 0, ROT0, "Irem", "New Tropical Angel", GAME_SUPPORTS_SAVE )
42.578313
133
0.67558
[ "3d" ]
a11f7371c6ce315a2e8b74563a6f3a7a7f06df64
10,565
h
C
app/src/main/cpp/isEngine/system/android/AdmobManager.h
Is-Daouda/is-Engine
7c289ebaf1b18623350851eb86391ce5a121201c
[ "Zlib" ]
166
2018-12-29T16:17:27.000Z
2022-03-31T07:23:23.000Z
app/src/main/cpp/isEngine/system/android/AdmobManager.h
Is-Daouda/is-Engine-Demo
8a42a2f333374d2ee413a2685fa5d83d548577d4
[ "Zlib" ]
2
2021-04-22T02:42:28.000Z
2021-08-23T21:24:00.000Z
app/src/main/cpp/isEngine/system/android/AdmobManager.h
Is-Daouda/is-Engine-Demo
8a42a2f333374d2ee413a2685fa5d83d548577d4
[ "Zlib" ]
21
2018-12-30T15:57:46.000Z
2022-03-20T16:18:10.000Z
/* is::Engine (Infinity Solution Engine) Copyright (C) 2018-2021 Is Daouda <isdaouda.n@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef ADMOBMANAGER_H_INCLUDED #define ADMOBMANAGER_H_INCLUDED #include "../function/GameFunction.h" #include "../../../app_src/config/GameConfig.h" #if defined(__ANDROID__) #if defined(IS_ENGINE_USE_ADMOB) #include "firebase/admob.h" #include "firebase/admob/types.h" #include "firebase/app.h" #include "firebase/future.h" #include "firebase/admob/banner_view.h" #include "firebase/admob/rewarded_video.h" #include <android/native_activity.h> using namespace is::GameConfig::AdmobConfig; static bool ProcessEvents(int msec) { sf::Time _msec = sf::milliseconds(msec); sf::sleep(_msec); return true; } /// Check ad object state static bool checkAdState(firebase::FutureBase future) { return (future.status() == firebase::kFutureStatusComplete && future.error() == firebase::admob::kAdMobErrorNone); } static void WaitForFutureCompletion(firebase::FutureBase future) { while (!ProcessEvents(1000)) { if (future.status() != firebase::kFutureStatusPending) break; } if (future.error() != firebase::admob::kAdMobErrorNone) { is::showLog("ERROR: Action failed with error code " + is::numToStr(future.error()) + " and message : " + future.error_message()); } } //////////////////////////////////////////////////////////// /// \brief Class to manage ad components /// //////////////////////////////////////////////////////////// class AdmobManager { public: firebase::App *m_admobApp = nullptr; firebase::admob::AdRequest m_request; firebase::admob::BannerView *m_banner = nullptr; ANativeActivity* m_activity; sf::RenderWindow &m_window; bool m_changeBannerPos; bool m_showBanner; bool m_showRewardVideo; bool m_relaunchAd; ~AdmobManager() { delete m_admobApp; delete m_banner; firebase::admob::rewarded_video::Destroy(); firebase::admob::Terminate(); } AdmobManager(sf::RenderWindow &window, ANativeActivity* activity, JNIEnv* env) : m_activity(activity), m_window(window), m_changeBannerPos(false), m_showBanner(false), m_showRewardVideo(false), m_relaunchAd(false) { m_admobApp = ::firebase::App::Create(firebase::AppOptions(), env, m_activity); firebase::admob::Initialize(*m_admobApp, kAdMobAppID); // If the app is aware of the user's gender, it can be added to the targeting // information. Otherwise, "unknown" should be used. m_request.gender = firebase::admob::kGenderUnknown; // This value allows publishers to specify whether they would like the request // to be treated as child-directed for purposes of the Children’s Online // Privacy Protection Act (COPPA). // See http://business.ftc.gov/privacy-and-security/childrens-privacy. m_request.tagged_for_child_directed_treatment = firebase::admob::kChildDirectedTreatmentStateTagged; // The user's birthday, if known. Note that months are indexed from one. m_request.birthday_day = kBirthdayDay; m_request.birthday_month = kBirthdayMonth; m_request.birthday_year = kBirthdayYear; // Sample test device IDs to use in making the request. static const char* kTestDeviceIDs[] = {"2077ef9a63d2b398840261c8221a0c9b", "098fe087d987c9a878965454a65654d7"}; // Additional keywords to be used in targeting. m_request.keyword_count = sizeof(kKeywords) / sizeof(kKeywords[0]); m_request.keywords = kKeywords; // "Extra" key value pairs can be added to the request as well. Typically // these are used when testing new features. static const firebase::admob::KeyValuePair kRequestExtras[] = {{"the_name_of_an_extra", "the_value_for_that_extra"}}; m_request.extras_count = sizeof(kRequestExtras) / sizeof(kRequestExtras[0]); m_request.extras = kRequestExtras; // This example uses ad units that are specially configured to return test ads // for every request. When using your own ad unit IDs, however, it's important // to register the device IDs associated with any devices that will be used to // test the app. This ensures that regardless of the ad unit ID, those // devices will always m_receive test ads in compliance with AdMob policy. // // Device IDs can be obtained by checking the logcat or the Xcode log while // debugging. They appear as a long string of hex characters. m_request.test_device_id_count = sizeof(kTestDeviceIDs) / sizeof(kTestDeviceIDs[0]); m_request.test_device_ids = kTestDeviceIDs; // Create an ad size for the BannerView. firebase::admob::AdSize banner_ad_size; banner_ad_size.ad_size_type = firebase::admob::kAdSizeStandard; banner_ad_size.width = kBannerWidth; banner_ad_size.height = kBannerHeight; m_banner = new firebase::admob::BannerView(); m_banner->Initialize(m_activity, kBannerAdUnit, banner_ad_size); firebase::admob::rewarded_video::Initialize(); } /// Make a request to have ads that will be displayed in the ad banner void loadBannerAd() { if (checkAdState(m_banner->InitializeLastResult())) { m_banner->LoadAd(m_request); } }; /// Display the ad banner (run only when the request is successful) void showBannerAd() { if (checkAdState(m_banner->LoadAdLastResult())) { if (!checkAdState(m_banner->ShowLastResult()) || checkAdState(m_banner->HideLastResult())) { if (!m_showBanner) { if (!m_changeBannerPos) { m_changeBannerPos = true; } m_banner->Show(); WaitForFutureCompletion(m_banner->ShowLastResult()); m_showBanner = true; } } m_relaunchAd = false; } else m_relaunchAd = true; }; /// Hide ad banner void hideBannerAd() { if (checkAdState(m_banner->LoadAdLastResult())) { m_showBanner = false; m_banner->Hide(); } }; /// Make a request to have ads that will be displayed in the reward video void loadRewardVideo() { if (checkAdState(firebase::admob::rewarded_video::InitializeLastResult())) { firebase::admob::rewarded_video::LoadAd(kRewardedVideoAdUnit, m_request); } }; //////////////////////////////////////////////////////////// /// \brief Display the reward video ads (run only when the request is successful) /// /// \return 1 if the reward video has been read correctly 0 if not //////////////////////////////////////////////////////////// virtual int showRewardVideo() { int result(0); if (checkAdState(firebase::admob::rewarded_video::LoadAdLastResult())) { sf::Clock clock; bool stopGameTread(true); firebase::admob::rewarded_video::Show(m_activity); if (checkAdState(firebase::admob::rewarded_video::ShowLastResult())) { while (stopGameTread) { float dTime = clock.restart().asSeconds(); if (dTime > is::MAX_CLOCK_TIME) dTime = is::MAX_CLOCK_TIME; if (firebase::admob::rewarded_video::presentation_state() == firebase::admob::rewarded_video::kPresentationStateHidden) stopGameTread = false; sf::Event ev; while (m_window.pollEvent(ev)) { if (ev.type == sf::Event::Closed) is::closeApplication(); } m_window.clear(sf::Color::Black); m_window.display(); } // End of the video result = 1; checkAdRewardObjReinitialize(); } } else loadRewardVideo(); return result; } //////////////////////////////////////////////////////////// /// This function allows to avoid the loss of the window handle /// when the ad components are used because they use a different /// rendering loop from that of the engine /// /// \param whiteColor true displays white and false display black background color //////////////////////////////////////////////////////////// auto updateSFMLApp(bool whiteColor) { sf::Event m_event; while (m_window.pollEvent(m_event)); m_window.clear((whiteColor) ? sf::Color::White : sf::Color::Black); m_window.display(); }; /// Check if ad components are initialized void checkAdObjInit() { while (!checkAdState(m_banner->InitializeLastResult()) && !checkAdState(firebase::admob::rewarded_video::InitializeLastResult()) ) { updateSFMLApp(true); } } /// Reinitialize ad components void checkAdRewardObjReinitialize() { firebase::admob::rewarded_video::Destroy(); firebase::admob::rewarded_video::Initialize(); while (!checkAdState(firebase::admob::rewarded_video::InitializeLastResult())) updateSFMLApp(true); loadRewardVideo(); } }; #endif // defined #endif // defined #endif // ADMOBMANAGER_H_INCLUDED
36.940559
125
0.61098
[ "object" ]
a122404011ad28ab69490ebc294e2c9aa4bcc149
6,800
h
C
kernel/include/kernel/paging.h
F4doraOfDoom/juos
cdec685701c406defc9204dcadf154df9eefc879
[ "MIT" ]
3
2020-12-22T01:24:56.000Z
2021-01-06T11:44:50.000Z
kernel/include/kernel/paging.h
F4doraOfDoom/juos
cdec685701c406defc9204dcadf154df9eefc879
[ "MIT" ]
null
null
null
kernel/include/kernel/paging.h
F4doraOfDoom/juos
cdec685701c406defc9204dcadf154df9eefc879
[ "MIT" ]
null
null
null
/** * @file paging.h * @author Jonathan Uklisty (F4doraOfDoom) (yoniu7@gmail.com) * @brief Header file containing declerations and definitions * of the paging interface * @version 0.1 * @date 12-11-2019 * * @copyright Copyright Jonathan Uklisty (c) 2019 (MIT License) * */ #ifndef KERNEL_PAGING_H_ #define KERNEL_PAGING_H_ #include <stdint.h> #include <string.h> #include <kernel/klog.h> #include <kernel/hardware.h> #include "interrupts.h" #include "kconstants.h" #include "kheap.h" #include "kuseful.h" #include "kdef.h" #include <kernel/data_structures/vector.hpp> using kernel::data_structures::Vector; #define PAGING_LOG_CREATION 1 #define PAGING_LOG_MAPPING 1 #define PAGE_SIZE_FACTOR 11 // Order of magnitude dictating the page size (2 << PAGE_SIZE_FACTOR) //#define PAGE_SIZE (2 << PAGE_SIZE_FACTOR) // The size of a page and frame #define FRAME_SIZE PAGE_SIZE // frame and page must be of the same size #define PAGE_TABLE_SIZE 1024 #define PAGE_DIRECTORY_SIZE 1024 #define CHUNK_SIZE_ALIGN 8 //Errors #define PAGE_NOT_FOUND -1 #define FRAME_NOT_FOUND -1 #define PAGE_CREATION_FAILED -2 #define BIT_FIELD_TYPE uint32_t #define BIT_FIELD_SIZE sizeof(BIT_FIELD_TYPE) #define INDEX_FROM_BIT(a) a / (8*4) #define OFFSET_FROM_BIT(a) a % (8*4) #define SET_DIRECTORY(directory) asm volatile("mov %0, %%cr3" :: "r"(directory->table_addresses)) NAMESPACE_BEGIN(kernel) NAMESPACE_BEGIN(paging) /** * @brief This struct is passed into paging::Initialize * in order to specify which regions to map for the heap * * begin - beginning address of heap * end - end address of heap */ struct _HeapMappingSettings { uint32_t begin; uint32_t end; }; /** * @brief Structure representing a Page * * is_present - whether or not the page exists * rw - if bit clear - read only; else, read-Write * is_user - whether or not the Page is non kernel owned * was_accessed - set if the page was accessed since the last refresh * was_written - set if the page as written to sicne last refresh * reserved - bits reserved for the CPU * flags - 3 bits available for kernel use * frame_addr - the frame address */ struct Page { BIT_FIELD_TYPE is_present : 1; BIT_FIELD_TYPE rw : 1; BIT_FIELD_TYPE is_user : 1; BIT_FIELD_TYPE was_accessed : 1; BIT_FIELD_TYPE was_written : 1; BIT_FIELD_TYPE reserved : 4; BIT_FIELD_TYPE flags : 3; BIT_FIELD_TYPE frame_addr : 20; }; struct PageTable { // void set_page_idx( // uint32_t idx, // bool is_present, // bool rw, // bool is_user, // bool was_accessed, // bool was_written, // uint32_t frame_addr // ); Page enteries[PAGE_TABLE_SIZE]; }; struct PageDirectory { PageTable* tables[PAGE_TABLE_SIZE] = { 0 }; uint32_t table_addresses[PAGE_TABLE_SIZE] = { 0 }; // defined in paging.cpp ~PageDirectory(); }; struct Frame { bool is_taken = false; }; /** * @brief Struct representing a table of frames * * frames - pointer to an array of frames * length - length of the array */ struct FrameTable { struct FrameTableResult { uint32_t idx = 0; bool error = false; }; typedef FrameTableResult frame_table_result_t; FrameTable(uint32_t length); /** * @brief Dont use this constructor * */ FrameTable() {}; frame_table_result_t FindFirst(); void SetAtIndex(uint32_t idx); void FreeAtIndex(uint32_t idx); void SetAtAddress(uint32_t addr); Frame* frames = nullptr; uint32_t length = 0; }; typedef Page page_t; typedef PageTable page_table_t; typedef PageDirectory page_directory_t; typedef Frame frame_t; typedef FrameTable frame_table_t; using MemoryAlloctor = void* (*)(uint32_t, void*); /** * @brief Initialize paging in the kernel * * _heap_mapping - if not null, map the heap according * to _heap_mapping. If null, do not map the heap. */ void Initialize(_HeapMappingSettings* _heap_mapping); /** * @brief Map the region between _start_ and _end_ in the paging directory _dir_ * using the memory allocator _allocator_ * * @param start * @param end * @param allocator * @param dir * @return uint32_t */ uint32_t map_region(uint32_t start, uint32_t end, MemoryAlloctor allocator, page_directory_t* dir = nullptr); /** * @brief Set the current_directory object * * @param directory */ void SetDirectory(PageDirectory* directory); // creates a new page directory with mappings _mappings_ // meant to be used only once the memory manager is initialized PageDirectory* create_directory(Vector<_HeapMappingSettings>& mappings); /** * @brief Get the Kernel Directory object * * @return PageDirectory* */ PageDirectory* GetKernelDirectory(); /** * @brief Function to handle page faults * */ void page_fault_handler(void*); auto StandartAllocator = [](uint32_t size, void* args) { return (void*)kernel::heap::Allocate_WPointer(size, (uint32_t*)args); }; NAMESPACE_END(paging) NAMESPACE_END(kernel) // the current paging directory extern kernel::paging::PageDirectory* paging_current_directory; // the kernel's paging directory extern kernel::paging::PageDirectory* paging_kernel_directory; // implemented by arch __NO_MANGELING void _load_page_directory(uint32_t*); __NO_MANGELING void _enable_paging(); //__NO_MANGELING void _disable_paging(); #endif //KERNEL_PAGING_H_
29.437229
118
0.568676
[ "object", "vector" ]
a12653c0a20d9748ec6410c74f749313f7f04a41
3,498
h
C
Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.h
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2020-10-09T18:12:53.000Z
2020-10-09T18:12:53.000Z
Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.h
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2017-08-18T19:28:52.000Z
2017-08-18T19:28:52.000Z
Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.h
floryst/ITK
321e673bcbac15aae2fcad863fd0977b7fbdb3e9
[ "Apache-2.0" ]
1
2017-08-18T19:07:39.000Z
2017-08-18T19:07:39.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 itkImageVectorOptimizerParametersHelper_h #define itkImageVectorOptimizerParametersHelper_h #include "itkOptimizerParametersHelper.h" #include "itkImage.h" namespace itk { /** \class ImageVectorOptimizerParametersHelper * \brief Class to hold and manage parameters of type * Image<Vector<...>,...>, used in Transforms, etc. * * \sa OptimizerParametersHelper * \ingroup ITKCommon */ /* Can we template of Image type instead, but require that Image be of type * Image< Vector< TValue, NVectorDimension >, VImageDimension > ? */ template< typename TValue, unsigned int NVectorDimension, unsigned int VImageDimension > class ITK_TEMPLATE_EXPORT ImageVectorOptimizerParametersHelper : public OptimizerParametersHelper< TValue > { public: /** The element type stored at each location in the Array. */ using ValueType = TValue; using Self = ImageVectorOptimizerParametersHelper; using Superclass = OptimizerParametersHelper< TValue >; /** Image type that this class expects. */ using ParameterImageType = Image< Vector<TValue, NVectorDimension>, VImageDimension >; using ParameterImagePointer = typename ParameterImageType::Pointer; /** Type of the common data object used in OptimizerParameters */ using CommonContainerType = typename Superclass::CommonContainerType; /** Default constructor. */ ImageVectorOptimizerParametersHelper(); /** Set a new data pointer for *both* the Array and parameter image, * pointing both to a different memory block. * The size of the new memroy block must be the same as current size of * Array and the parameter image's buffer, in elements of TValue. * Memory must be managed by caller afterwards. */ void MoveDataPointer(CommonContainerType* container, TValue * pointer ) override; /** Set an image that holds the parameter data. \c container is a pointer * of type itkArray to the object to which this helper is assigned. *\c container will be pointed to the image data buffer, and set not to * manage memory, so the image still manages its memory. * A dynamic cast is performed on \c object to make sure its of proper type. * Generally this will be called from * OptimizerParameters::SetParameterObject. */ void SetParametersObject(CommonContainerType * container, LightObject * ) override; ~ImageVectorOptimizerParametersHelper() override = default; private: /** The parameter image used by the class */ ParameterImagePointer m_ParameterImage; }; }//namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkImageVectorOptimizerParametersHelper.hxx" #endif #endif
37.612903
78
0.699543
[ "object", "vector" ]
a12c4d69e39f853439198cdbf17338ec9dc141c3
9,631
c
C
fidimag/micro/lib/exch.c
computationalmodelling/fidimag
07a275c897a44ad1e0d7e8ef563f10345fdc2a6e
[ "BSD-2-Clause" ]
53
2016-02-27T09:40:21.000Z
2022-01-19T21:37:44.000Z
fidimag/micro/lib/exch.c
computationalmodelling/fidimag
07a275c897a44ad1e0d7e8ef563f10345fdc2a6e
[ "BSD-2-Clause" ]
132
2016-02-26T13:18:58.000Z
2021-12-01T21:52:42.000Z
fidimag/micro/lib/exch.c
computationalmodelling/fidimag
07a275c897a44ad1e0d7e8ef563f10345fdc2a6e
[ "BSD-2-Clause" ]
32
2016-02-26T13:21:40.000Z
2022-03-08T08:54:51.000Z
#include "micro_clib.h" void compute_exch_field_micro(double *restrict m, double *restrict field, double *restrict energy, double *restrict Ms_inv, double A, double dx, double dy, double dz, int n, int *restrict ngbs) { /* Compute the micromagnetic exchange field and energy using the * matrix of neighbouring spins and a second order approximation * for the derivative * * Ms_inv :: Array with the (1 / Ms) values for every mesh node. * The values are zero for points with Ms = 0 (no material) * * A :: Exchange constant * * dx, dy, dz :: Mesh spacings in the corresponding directions * * n :: Number of mesh nodes * * ngbs :: The array of neighbouring spins, which has (6 * n) * entries. Specifically, it contains the indexes of * the neighbours of every mesh node, in the following order: * -x, +x, -y, +y, -z, +z * * Thus, the array is like: * | 0-x, 0+x, 0-y, 0+y, 0-z, 0+z, 1-x, 1+x, 1-y, ... | * i=0 i=1 ... * * where 0-y is the index of the neighbour of the 0th spin, * in the -y direction, for example. The index value for a * neighbour where Ms = 0, is evaluated as -1. The array * automatically gives periodic boundaries. * * A basic example is a 3 x 3 two dimensional mesh with PBCs * in the X and Y direction: * * +-----------+ * | 6 | 7 | 8 | * +-----------+ * | 3 | 4 | 5 | * +-----------+ * | 0 | 1 | 2 | * +-----------+ * * so, the first 6 entries (neighbours of the 0th mesh node) * of the array would be: [ 2 1 6 3 -1 -1 ... ] * (-1 since there is no material in +-z, and a '2' first, * since it is the left neighbour which is the PBC in x, etc..) * * For the exchange computation, the field is defined as: * H_ex = (2 * A / (mu0 * Ms)) * nabla^2 (mx, my, mz) * * Therefore, for the i-th mesh node (spin), we approximate the * derivatives as: * nabla^2 mx = (1 / dx^2) * ( m[i-x] - 2 * m[i] + m[i+x] ) + * (1 / dy^2) * ( m[i-y] - 2 * m[i] + m[i+y] ) + * (1 / dz^2) * ( m[i-z] - 2 * m[i] + m[i+z] ) * * Where i-x is the neighbour in the -x direction. This is similar * for my and mz. * We can notice that the sum is the same if we do: * ( m[i-x] - m[i] ) + ( m[i+x] - m[i] ) * so we can iterate through the neighbours and perform the sum with the * corresponding coefficient 1 /dx, 1/dy or 1/dz * * The *m array contains the spins as: * [mx0, my0, mz0, mx1, my1, mz1, mx2, ...] * so if we want the starting position of the magnetisation for the * i-th spin, we only have to do (3 * i) for mx, (3 * i + 1) for my * and (3 * i + 2) for mz * * * IMPORTANT: The ex field usually has the structure: * 2 * A / (mu0 Ms ) * (Second derivative of M) * When discretising the derivative, it carries a "2" in the * denominator which we "cancel" with the "2" in the prefactor, * hence we do not put it explicitly in the calculations * * So, when computing the energy: (-1/2) * mu * Ms * H_ex * we only put the 0.5 factor and don't worry about the "2"s in the * field * */ /* Define the coefficients */ double ax = 2 * A / (dx * dx); double ay = 2 * A / (dy * dy); double az = 2 * A / (dz * dz); /* Here we iterate through every mesh node */ #pragma omp parallel for for (int i = 0; i < n; i++) { double fx = 0, fy = 0, fz = 0; int idnm = 0; // Index for the magnetisation matrix int idn = 6 * i; // index for the neighbours /* Set a zero field for sites without magnetic material */ if (Ms_inv[i] == 0.0){ field[3 * i] = 0; field[3 * i + 1] = 0; field[3 * i + 2] = 0; continue; } /* Here we iterate through the neighbours */ for (int j = 0; j < 6; j++) { /* Remember that index=-1 is for sites without material */ if (ngbs[idn + j] >= 0) { /* Magnetisation of the neighbouring spin since ngbs gives * the neighbour's index */ idnm = 3 * ngbs[idn + j]; /* Check that the magnetisation of the neighbouring spin * is larger than zero */ if (Ms_inv[ngbs[idn + j]] > 0){ /* Neighbours in the -x and +x directions * giving: ( m[i-x] - m[i] ) + ( m[i+x] - m[i] ) * when ngbs[idn + j] > 0 for j = 0 and j=1 * If, for example, there is no * neighbour at -x (j=0) in the 0th node (no PBCs), * the second derivative would only be avaluated as: * (1 / dx * dx) * ( m[i+x] - m[i] ) * which, according to * [M.J. Donahue and D.G. Porter; Physica B, 343, 177-183 (2004)] * when performing the integration of the energy, we still * have error of the order O(dx^2) * This same applies for the other directions */ if (j == 0 || j == 1) { fx += ax * (m[idnm] - m[3 * i]); fy += ax * (m[idnm + 1] - m[3 * i + 1]); fz += ax * (m[idnm + 2] - m[3 * i + 2]); } /* Neighbours in the -y and +y directions */ else if (j == 2 || j == 3) { fx += ay * (m[idnm] - m[3 * i]); fy += ay * (m[idnm + 1] - m[3 * i + 1]); fz += ay * (m[idnm + 2] - m[3 * i + 2]); } /* Neighbours in the -z and +z directions */ else if (j == 4 || j == 5) { fx += az * (m[idnm] - m[3 * i]); fy += az * (m[idnm + 1] - m[3 * i + 1]); fz += az * (m[idnm + 2] - m[3 * i + 2]); } else { continue; } } } } /* Energy as: (-mu0 * Ms / 2) * [ H_ex * m ] */ energy[i] = -0.5 * (fx * m[3 * i] + fy * m[3 * i + 1] + fz * m[3 * i + 2]); /* Update the field H_ex which has the same structure than *m */ field[3 * i] = fx * Ms_inv[i] * MU0_INV; field[3 * i + 1] = fy * Ms_inv[i] * MU0_INV; field[3 * i + 2] = fz * Ms_inv[i] * MU0_INV; } } inline int get_index(int nx, int ny, int i, int j, int k){ return k * nx*ny + j * nx + i; } void compute_exch_field_rkky_micro(double *m, double *field, double *energy, double *Ms_inv, double sigma, int nx, double ny, double nz, int z_bottom, int z_top){ /* Compute the micromagnetic exchange field and energy using the * matrix of neighbouring spins and a second order approximation * for the derivative * * Ms_inv :: Array with the (1 / Ms) values for every mesh node. * The values are zero for points with Ms = 0 (no material) * * sigma :: Exchange constant * * nx, ny, nz :: Mesh dimensions. * The exchange field at the top (bottom) layer can be computed as: * * H_top = (sigma / (mu0 * Ms)) * m_bottom * H_bottom = (sigma / (mu0 * Ms)) * m_top * * The *m array contains the spins as: * [mx0, my0, mz0, mx1, my1, mz1, mx2, ...] * so if we want the starting position of the magnetisation for the * i-th spin, we only have to do (3 * i) for mx, (3 * i + 1) for my * and (3 * i + 2) for mz * * * */ int n = nx*ny*nz; for (int i = 0; i < n; i++){ energy[i] = 0; field[3*i]=0; field[3*i+1]=0; field[3*i+2]=0; } #pragma omp parallel for for (int i = 0; i < nx; i++) { for (int j = 0; j < ny; j++){ double mtx=0, mty=0, mtz=0; double mbx=0, mby=0, mbz=0; int id1 = get_index(nx,ny, i, j, z_bottom); int id2 = get_index(nx,ny, i, j, z_top); mtx = m[3*id2]; mty = m[3*id2+1]; mtz = m[3*id2+2]; mbx = m[3*id1]; mby = m[3*id1+1]; mbz = m[3*id1+2]; if (Ms_inv[id1] != 0.0){ energy[id1] = sigma*(1-mtx*mbx-mty*mby-mtz*mbz); field[3*id1] = sigma * mtx * Ms_inv[id1] * MU0_INV; field[3*id1+1] = sigma * mty * Ms_inv[id1] * MU0_INV; field[3*id1+2] = sigma * mtz * Ms_inv[id1] * MU0_INV; } if (Ms_inv[id2] != 0.0){ energy[id2] = sigma*(1-mtx*mbx-mty*mby-mtz*mbz); field[3*id2] = sigma * mbx * Ms_inv[id2] * MU0_INV; field[3*id2+1] = sigma * mby * Ms_inv[id2] * MU0_INV; field[3*id2+2] = sigma * mbz * Ms_inv[id2] * MU0_INV; } } } }
40.637131
98
0.446267
[ "mesh" ]
a13374472279d5577126decb9fa24d4aa95e1aba
4,523
h
C
apps/sds_support/include/hls/dsp/hls_qam_mod.h
were/Halide-SDSoC
a0fe073d4e5af45997338a8e834af88b0e5c73d5
[ "MIT" ]
3
2019-05-18T11:30:53.000Z
2021-06-29T04:00:33.000Z
caffe/FPGA/Vivado_HLS/include/hls/dsp/hls_qam_mod.h
zhacmsra/Caffeine
458d85dbd3f4507cc727a8901c3127bfc249c96a
[ "MIT" ]
null
null
null
caffe/FPGA/Vivado_HLS/include/hls/dsp/hls_qam_mod.h
zhacmsra/Caffeine
458d85dbd3f4507cc727a8901c3127bfc249c96a
[ "MIT" ]
1
2020-05-15T17:07:54.000Z
2020-05-15T17:07:54.000Z
/***************************************************************************** * * Author: Xilinx, Inc. * * This text contains proprietary, confidential information of * Xilinx, Inc. , is distributed by under license from Xilinx, * Inc., and may be used, copied and/or disclosed only pursuant to * the terms of a valid license agreement with Xilinx, Inc. * * XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" * AS A COURTESY TO YOU, SOLELY FOR USE IN DEVELOPING PROGRAMS AND * SOLUTIONS FOR XILINX DEVICES. BY PROVIDING THIS DESIGN, CODE, * OR INFORMATION AS ONE POSSIBLE IMPLEMENTATION OF THIS FEATURE, * APPLICATION OR STANDARD, XILINX IS MAKING NO REPRESENTATION * THAT THIS IMPLEMENTATION IS FREE FROM ANY CLAIMS OF INFRINGEMENT, * AND YOU ARE RESPONSIBLE FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE * FOR YOUR IMPLEMENTATION. XILINX EXPRESSLY DISCLAIMS ANY * WARRANTY WHATSOEVER WITH RESPECT TO THE ADEQUACY OF THE * IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OR * REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE FROM CLAIMS OF * INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. * * Xilinx products are not intended for use in life support appliances, * devices, or systems. Use in such applications is expressly prohibited. * * (c) Copyright 2014 Xilinx Inc. * All rights reserved. * *****************************************************************************/ #ifndef HLS_QAM_MOD_H #define HLS_QAM_MOD_H #include "ap_int.h" #include <hls_stream.h> #include <complex> #include "hls/dsp/utils/hls_dsp_common_utils.h" namespace hls { #if (defined(OutputWidth) || \ defined(Constellation)) #error One or more of the template parameters used by this function is already defined and will cause a conflict #endif // =================================================================================================================== // QAM MODULATOR: Class definition // o Template parameters: // - Constellation : Selects the QAM modulation scheme to be used (QPSK, QAM16, etc) // - OutputWidth : Number of bits in each scalar component of the complex t_iq output. // The qam_mod block performs symbol to I/Q mapping as used in a QAM encoder. The output is zero extended up to the OutputWidth template parameter template< class Constellation, int OutputWidth> class qam_mod { public: typedef ap_int< OutputWidth > t_outcomponent; typedef std::complex< t_outcomponent > t_iq; qam_mod() { check_params(); };//end of constructor ~qam_mod() { }; //end of destructor //Utilities //static function - owned by class not object since return value doesn't vary by object static int get_symbol_width() { return Constellation::SymbolWidth; } // =================================================================================================================== // QAM MODULATOR: Entry point function // o Arguments: // - symbol : type t_symbol. This is an N-bit symbol to be iq encoded. N is determined by the choice of QAM modulation scheme. // - outputData : type t_iq. This is a complex IQ output signal. void operator()(const typename Constellation::t_symbol &symbol, t_iq &outputData) { Function_qam_mod_operator:; typename Constellation::t_star iq; Constellation::hardEncode(symbol,iq); outputData.real((t_outcomponent)iq.real() << (OutputWidth-Constellation::STAR_WIDTH)); outputData.imag((t_outcomponent)iq.imag() << (OutputWidth-Constellation::STAR_WIDTH)); } // operator() private: static const int MAX_OUTPUT_WIDTH = 16; Constellation asterism; void check_params() { // Verify that template parameters are correct in simulation #ifndef __SYNTHESIS__ if (OutputWidth < Constellation::STAR_WIDTH || OutputWidth > MAX_OUTPUT_WIDTH) { std::cout << "ERROR: " << __FILE__ << ": OutputWidth must be between " << Constellation::STAR_WIDTH << " and " << MAX_OUTPUT_WIDTH << std::endl; exit(1); } #endif } //end of check_params }; // qam_mod } //end namespace hls #endif // HLS_QAM_MOD_H // XSIP watermark, do not delete 67d7842dbbe25473c3c32b93c0da8047785f30d78e8a024de1b57352245f9689
39.675439
154
0.623259
[ "object" ]
a1424bab8bd1c41e9099484af35da0e17ee4b076
28,797
c
C
Optimization/LevmarAndroid/jni/Thirdparty/clapack/TESTING/LIN/clattb.c
faipaz/Algorithms
738991d5e4372ef6ba8e489ea867d92ea406b729
[ "MIT" ]
48
2015-01-28T00:09:49.000Z
2021-12-09T11:38:59.000Z
Optimization/LevmarAndroid/jni/Thirdparty/clapack/TESTING/LIN/clattb.c
faipaz/Algorithms
738991d5e4372ef6ba8e489ea867d92ea406b729
[ "MIT" ]
8
2017-05-30T16:58:39.000Z
2022-02-22T16:51:34.000Z
ExternalCode/lapack/TESTING/LIN/clattb.c
daniel-anavaino/tinkercell
7896a7f809a0373ab3c848d25e3691d10a648437
[ "BSD-3-Clause" ]
12
2015-01-21T12:54:46.000Z
2022-01-20T03:44:26.000Z
/* clattb.f -- translated by f2c (version 20061008). 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" #include "blaswrap.h" /* Table of constant values */ static integer c__5 = 5; static integer c__2 = 2; static integer c__1 = 1; static integer c__4 = 4; static real c_b91 = 2.f; static integer c_n1 = -1; /* Subroutine */ int clattb_(integer *imat, char *uplo, char *trans, char * diag, integer *iseed, integer *n, integer *kd, complex *ab, integer * ldab, complex *b, complex *work, real *rwork, integer *info) { /* System generated locals */ integer ab_dim1, ab_offset, i__1, i__2, i__3, i__4, i__5; real r__1; doublereal d__1, d__2; complex q__1, q__2; /* Builtin functions */ /* Subroutine */ int s_copy(char *, char *, ftnlen, ftnlen); double sqrt(doublereal); void c_div(complex *, complex *, complex *); double pow_dd(doublereal *, doublereal *), c_abs(complex *); /* Local variables */ integer i__, j, kl, ku, iy; real ulp, sfac; integer ioff, mode, lenj; char path[3], dist[1]; real unfl, rexp; char type__[1]; real texp; complex star1, plus1, plus2; real bscal; extern logical lsame_(char *, char *); real tscal, anorm, bnorm, tleft; extern /* Subroutine */ int ccopy_(integer *, complex *, integer *, complex *, integer *), cswap_(integer *, complex *, integer *, complex *, integer *); logical upper; real tnorm; extern /* Subroutine */ int clatb4_(char *, integer *, integer *, integer *, char *, integer *, integer *, real *, integer *, real *, char * ), slabad_(real *, real *); extern integer icamax_(integer *, complex *, integer *); extern /* Complex */ VOID clarnd_(complex *, integer *, integer *); extern doublereal slamch_(char *); extern /* Subroutine */ int csscal_(integer *, real *, complex *, integer *); char packit[1]; real bignum; extern doublereal slarnd_(integer *, integer *); real cndnum; extern /* Subroutine */ int clarnv_(integer *, integer *, integer *, complex *), clatms_(integer *, integer *, char *, integer *, char *, real *, integer *, real *, real *, integer *, integer *, char * , complex *, integer *, complex *, integer *); integer jcount; extern /* Subroutine */ int slarnv_(integer *, integer *, integer *, real *); real smlnum; /* -- LAPACK test routine (version 3.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ /* November 2006 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* CLATTB generates a triangular test matrix in 2-dimensional storage. */ /* IMAT and UPLO uniquely specify the properties of the test matrix, */ /* which is returned in the array A. */ /* Arguments */ /* ========= */ /* IMAT (input) INTEGER */ /* An integer key describing which matrix to generate for this */ /* path. */ /* UPLO (input) CHARACTER*1 */ /* Specifies whether the matrix A will be upper or lower */ /* triangular. */ /* = 'U': Upper triangular */ /* = 'L': Lower triangular */ /* TRANS (input) CHARACTER*1 */ /* Specifies whether the matrix or its transpose will be used. */ /* = 'N': No transpose */ /* = 'T': Transpose */ /* = 'C': Conjugate transpose (= transpose) */ /* DIAG (output) CHARACTER*1 */ /* Specifies whether or not the matrix A is unit triangular. */ /* = 'N': Non-unit triangular */ /* = 'U': Unit triangular */ /* ISEED (input/output) INTEGER array, dimension (4) */ /* The seed vector for the random number generator (used in */ /* CLATMS). Modified on exit. */ /* N (input) INTEGER */ /* The order of the matrix to be generated. */ /* KD (input) INTEGER */ /* The number of superdiagonals or subdiagonals of the banded */ /* triangular matrix A. KD >= 0. */ /* AB (output) COMPLEX array, dimension (LDAB,N) */ /* The upper or lower triangular banded matrix A, stored in the */ /* first KD+1 rows of AB. Let j be a column of A, 1<=j<=n. */ /* If UPLO = 'U', AB(kd+1+i-j,j) = A(i,j) for max(1,j-kd)<=i<=j. */ /* If UPLO = 'L', AB(1+i-j,j) = A(i,j) for j<=i<=min(n,j+kd). */ /* LDAB (input) INTEGER */ /* The leading dimension of the array AB. LDAB >= KD+1. */ /* B (workspace) COMPLEX array, dimension (N) */ /* WORK (workspace) COMPLEX array, dimension (2*N) */ /* RWORK (workspace) REAL array, dimension (N) */ /* INFO (output) INTEGER */ /* = 0: successful exit */ /* < 0: if INFO = -i, the i-th argument had an illegal value */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Parameter adjustments */ --iseed; ab_dim1 = *ldab; ab_offset = 1 + ab_dim1; ab -= ab_offset; --b; --work; --rwork; /* Function Body */ s_copy(path, "Complex precision", (ftnlen)1, (ftnlen)17); s_copy(path + 1, "TB", (ftnlen)2, (ftnlen)2); unfl = slamch_("Safe minimum"); ulp = slamch_("Epsilon") * slamch_("Base"); smlnum = unfl; bignum = (1.f - ulp) / smlnum; slabad_(&smlnum, &bignum); if (*imat >= 6 && *imat <= 9 || *imat == 17) { *(unsigned char *)diag = 'U'; } else { *(unsigned char *)diag = 'N'; } *info = 0; /* Quick return if N.LE.0. */ if (*n <= 0) { return 0; } /* Call CLATB4 to set parameters for CLATMS. */ upper = lsame_(uplo, "U"); if (upper) { clatb4_(path, imat, n, n, type__, &kl, &ku, &anorm, &mode, &cndnum, dist); ku = *kd; /* Computing MAX */ i__1 = 0, i__2 = *kd - *n + 1; ioff = max(i__1,i__2) + 1; kl = 0; *(unsigned char *)packit = 'Q'; } else { i__1 = -(*imat); clatb4_(path, &i__1, n, n, type__, &kl, &ku, &anorm, &mode, &cndnum, dist); kl = *kd; ioff = 1; ku = 0; *(unsigned char *)packit = 'B'; } /* IMAT <= 5: Non-unit triangular matrix */ if (*imat <= 5) { clatms_(n, n, dist, &iseed[1], type__, &rwork[1], &mode, &cndnum, & anorm, &kl, &ku, packit, &ab[ioff + ab_dim1], ldab, &work[1], info); /* IMAT > 5: Unit triangular matrix */ /* The diagonal is deliberately set to something other than 1. */ /* IMAT = 6: Matrix is the identity */ } else if (*imat == 6) { if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__2 = 1, i__3 = *kd + 2 - j; i__4 = *kd; for (i__ = max(i__2,i__3); i__ <= i__4; ++i__) { i__2 = i__ + j * ab_dim1; ab[i__2].r = 0.f, ab[i__2].i = 0.f; /* L10: */ } i__4 = *kd + 1 + j * ab_dim1; ab[i__4].r = (real) j, ab[i__4].i = 0.f; /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__4 = j * ab_dim1 + 1; ab[i__4].r = (real) j, ab[i__4].i = 0.f; /* Computing MIN */ i__2 = *kd + 1, i__3 = *n - j + 1; i__4 = min(i__2,i__3); for (i__ = 2; i__ <= i__4; ++i__) { i__2 = i__ + j * ab_dim1; ab[i__2].r = 0.f, ab[i__2].i = 0.f; /* L30: */ } /* L40: */ } } /* IMAT > 6: Non-trivial unit triangular matrix */ /* A unit triangular matrix T with condition CNDNUM is formed. */ /* In this version, T only has bandwidth 2, the rest of it is zero. */ } else if (*imat <= 9) { tnorm = sqrt(cndnum); /* Initialize AB to zero. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MAX */ i__4 = 1, i__2 = *kd + 2 - j; i__3 = *kd; for (i__ = max(i__4,i__2); i__ <= i__3; ++i__) { i__4 = i__ + j * ab_dim1; ab[i__4].r = 0.f, ab[i__4].i = 0.f; /* L50: */ } i__3 = *kd + 1 + j * ab_dim1; r__1 = (real) j; ab[i__3].r = r__1, ab[i__3].i = 0.f; /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__4 = *kd + 1, i__2 = *n - j + 1; i__3 = min(i__4,i__2); for (i__ = 2; i__ <= i__3; ++i__) { i__4 = i__ + j * ab_dim1; ab[i__4].r = 0.f, ab[i__4].i = 0.f; /* L70: */ } i__3 = j * ab_dim1 + 1; r__1 = (real) j; ab[i__3].r = r__1, ab[i__3].i = 0.f; /* L80: */ } } /* Special case: T is tridiagonal. Set every other offdiagonal */ /* so that the matrix has norm TNORM+1. */ if (*kd == 1) { if (upper) { i__1 = (ab_dim1 << 1) + 1; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = tnorm * q__2.r, q__1.i = tnorm * q__2.i; ab[i__1].r = q__1.r, ab[i__1].i = q__1.i; lenj = (*n - 3) / 2; clarnv_(&c__2, &iseed[1], &lenj, &work[1]); i__1 = lenj; for (j = 1; j <= i__1; ++j) { i__3 = (j + 1 << 1) * ab_dim1 + 1; i__4 = j; q__1.r = tnorm * work[i__4].r, q__1.i = tnorm * work[i__4] .i; ab[i__3].r = q__1.r, ab[i__3].i = q__1.i; /* L90: */ } } else { i__1 = ab_dim1 + 2; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = tnorm * q__2.r, q__1.i = tnorm * q__2.i; ab[i__1].r = q__1.r, ab[i__1].i = q__1.i; lenj = (*n - 3) / 2; clarnv_(&c__2, &iseed[1], &lenj, &work[1]); i__1 = lenj; for (j = 1; j <= i__1; ++j) { i__3 = ((j << 1) + 1) * ab_dim1 + 2; i__4 = j; q__1.r = tnorm * work[i__4].r, q__1.i = tnorm * work[i__4] .i; ab[i__3].r = q__1.r, ab[i__3].i = q__1.i; /* L100: */ } } } else if (*kd > 1) { /* Form a unit triangular matrix T with condition CNDNUM. T is */ /* given by */ /* | 1 + * | */ /* | 1 + | */ /* T = | 1 + * | */ /* | 1 + | */ /* | 1 + * | */ /* | 1 + | */ /* | . . . | */ /* Each element marked with a '*' is formed by taking the product */ /* of the adjacent elements marked with '+'. The '*'s can be */ /* chosen freely, and the '+'s are chosen so that the inverse of */ /* T will have elements of the same magnitude as T. */ /* The two offdiagonals of T are stored in WORK. */ clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = tnorm * q__2.r, q__1.i = tnorm * q__2.i; star1.r = q__1.r, star1.i = q__1.i; sfac = sqrt(tnorm); clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = sfac * q__2.r, q__1.i = sfac * q__2.i; plus1.r = q__1.r, plus1.i = q__1.i; i__1 = *n; for (j = 1; j <= i__1; j += 2) { c_div(&q__1, &star1, &plus1); plus2.r = q__1.r, plus2.i = q__1.i; i__3 = j; work[i__3].r = plus1.r, work[i__3].i = plus1.i; i__3 = *n + j; work[i__3].r = star1.r, work[i__3].i = star1.i; if (j + 1 <= *n) { i__3 = j + 1; work[i__3].r = plus2.r, work[i__3].i = plus2.i; i__3 = *n + j + 1; work[i__3].r = 0.f, work[i__3].i = 0.f; c_div(&q__1, &star1, &plus2); plus1.r = q__1.r, plus1.i = q__1.i; /* Generate a new *-value with norm between sqrt(TNORM) */ /* and TNORM. */ rexp = slarnd_(&c__2, &iseed[1]); if (rexp < 0.f) { d__1 = (doublereal) sfac; d__2 = (doublereal) (1.f - rexp); r__1 = -pow_dd(&d__1, &d__2); clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = r__1 * q__2.r, q__1.i = r__1 * q__2.i; star1.r = q__1.r, star1.i = q__1.i; } else { d__1 = (doublereal) sfac; d__2 = (doublereal) (rexp + 1.f); r__1 = pow_dd(&d__1, &d__2); clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = r__1 * q__2.r, q__1.i = r__1 * q__2.i; star1.r = q__1.r, star1.i = q__1.i; } } /* L110: */ } /* Copy the tridiagonal T to AB. */ if (upper) { i__1 = *n - 1; ccopy_(&i__1, &work[1], &c__1, &ab[*kd + (ab_dim1 << 1)], ldab); i__1 = *n - 2; ccopy_(&i__1, &work[*n + 1], &c__1, &ab[*kd - 1 + ab_dim1 * 3] , ldab); } else { i__1 = *n - 1; ccopy_(&i__1, &work[1], &c__1, &ab[ab_dim1 + 2], ldab); i__1 = *n - 2; ccopy_(&i__1, &work[*n + 1], &c__1, &ab[ab_dim1 + 3], ldab); } } /* IMAT > 9: Pathological test cases. These triangular matrices */ /* are badly scaled or badly conditioned, so when used in solving a */ /* triangular system they may cause overflow in the solution vector. */ } else if (*imat == 10) { /* Type 10: Generate a triangular matrix with elements between */ /* -1 and 1. Give the diagonal norm 2 to make it well-conditioned. */ /* Make the right hand side large so that it requires scaling. */ if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = j - 1; lenj = min(i__3,*kd); clarnv_(&c__4, &iseed[1], &lenj, &ab[*kd + 1 - lenj + j * ab_dim1]); i__3 = *kd + 1 + j * ab_dim1; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = q__2.r * 2.f, q__1.i = q__2.i * 2.f; ab[i__3].r = q__1.r, ab[i__3].i = q__1.i; /* L120: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n - j; lenj = min(i__3,*kd); if (lenj > 0) { clarnv_(&c__4, &iseed[1], &lenj, &ab[j * ab_dim1 + 2]); } i__3 = j * ab_dim1 + 1; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = q__2.r * 2.f, q__1.i = q__2.i * 2.f; ab[i__3].r = q__1.r, ab[i__3].i = q__1.i; /* L130: */ } } /* Set the right hand side so that the largest value is BIGNUM. */ clarnv_(&c__2, &iseed[1], n, &b[1]); iy = icamax_(n, &b[1], &c__1); bnorm = c_abs(&b[iy]); bscal = bignum / dmax(1.f,bnorm); csscal_(n, &bscal, &b[1], &c__1); } else if (*imat == 11) { /* Type 11: Make the first diagonal element in the solve small to */ /* cause immediate overflow when dividing by T(j,j). */ /* In type 11, the offdiagonal elements are small (CNORM(j) < 1). */ clarnv_(&c__2, &iseed[1], n, &b[1]); tscal = 1.f / (real) (*kd + 1); if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = j - 1; lenj = min(i__3,*kd); if (lenj > 0) { clarnv_(&c__4, &iseed[1], &lenj, &ab[*kd + 2 - lenj + j * ab_dim1]); csscal_(&lenj, &tscal, &ab[*kd + 2 - lenj + j * ab_dim1], &c__1); } i__3 = *kd + 1 + j * ab_dim1; clarnd_(&q__1, &c__5, &iseed[1]); ab[i__3].r = q__1.r, ab[i__3].i = q__1.i; /* L140: */ } i__1 = *kd + 1 + *n * ab_dim1; i__3 = *kd + 1 + *n * ab_dim1; q__1.r = smlnum * ab[i__3].r, q__1.i = smlnum * ab[i__3].i; ab[i__1].r = q__1.r, ab[i__1].i = q__1.i; } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n - j; lenj = min(i__3,*kd); if (lenj > 0) { clarnv_(&c__4, &iseed[1], &lenj, &ab[j * ab_dim1 + 2]); csscal_(&lenj, &tscal, &ab[j * ab_dim1 + 2], &c__1); } i__3 = j * ab_dim1 + 1; clarnd_(&q__1, &c__5, &iseed[1]); ab[i__3].r = q__1.r, ab[i__3].i = q__1.i; /* L150: */ } i__1 = ab_dim1 + 1; i__3 = ab_dim1 + 1; q__1.r = smlnum * ab[i__3].r, q__1.i = smlnum * ab[i__3].i; ab[i__1].r = q__1.r, ab[i__1].i = q__1.i; } } else if (*imat == 12) { /* Type 12: Make the first diagonal element in the solve small to */ /* cause immediate overflow when dividing by T(j,j). */ /* In type 12, the offdiagonal elements are O(1) (CNORM(j) > 1). */ clarnv_(&c__2, &iseed[1], n, &b[1]); if (upper) { i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = j - 1; lenj = min(i__3,*kd); if (lenj > 0) { clarnv_(&c__4, &iseed[1], &lenj, &ab[*kd + 2 - lenj + j * ab_dim1]); } i__3 = *kd + 1 + j * ab_dim1; clarnd_(&q__1, &c__5, &iseed[1]); ab[i__3].r = q__1.r, ab[i__3].i = q__1.i; /* L160: */ } i__1 = *kd + 1 + *n * ab_dim1; i__3 = *kd + 1 + *n * ab_dim1; q__1.r = smlnum * ab[i__3].r, q__1.i = smlnum * ab[i__3].i; ab[i__1].r = q__1.r, ab[i__1].i = q__1.i; } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { /* Computing MIN */ i__3 = *n - j; lenj = min(i__3,*kd); if (lenj > 0) { clarnv_(&c__4, &iseed[1], &lenj, &ab[j * ab_dim1 + 2]); } i__3 = j * ab_dim1 + 1; clarnd_(&q__1, &c__5, &iseed[1]); ab[i__3].r = q__1.r, ab[i__3].i = q__1.i; /* L170: */ } i__1 = ab_dim1 + 1; i__3 = ab_dim1 + 1; q__1.r = smlnum * ab[i__3].r, q__1.i = smlnum * ab[i__3].i; ab[i__1].r = q__1.r, ab[i__1].i = q__1.i; } } else if (*imat == 13) { /* Type 13: T is diagonal with small numbers on the diagonal to */ /* make the growth factor underflow, but a small right hand side */ /* chosen so that the solution does not overflow. */ if (upper) { jcount = 1; for (j = *n; j >= 1; --j) { /* Computing MAX */ i__1 = 1, i__3 = *kd + 1 - (j - 1); i__4 = *kd; for (i__ = max(i__1,i__3); i__ <= i__4; ++i__) { i__1 = i__ + j * ab_dim1; ab[i__1].r = 0.f, ab[i__1].i = 0.f; /* L180: */ } if (jcount <= 2) { i__4 = *kd + 1 + j * ab_dim1; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = smlnum * q__2.r, q__1.i = smlnum * q__2.i; ab[i__4].r = q__1.r, ab[i__4].i = q__1.i; } else { i__4 = *kd + 1 + j * ab_dim1; clarnd_(&q__1, &c__5, &iseed[1]); ab[i__4].r = q__1.r, ab[i__4].i = q__1.i; } ++jcount; if (jcount > 4) { jcount = 1; } /* L190: */ } } else { jcount = 1; i__4 = *n; for (j = 1; j <= i__4; ++j) { /* Computing MIN */ i__3 = *n - j + 1, i__2 = *kd + 1; i__1 = min(i__3,i__2); for (i__ = 2; i__ <= i__1; ++i__) { i__3 = i__ + j * ab_dim1; ab[i__3].r = 0.f, ab[i__3].i = 0.f; /* L200: */ } if (jcount <= 2) { i__1 = j * ab_dim1 + 1; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = smlnum * q__2.r, q__1.i = smlnum * q__2.i; ab[i__1].r = q__1.r, ab[i__1].i = q__1.i; } else { i__1 = j * ab_dim1 + 1; clarnd_(&q__1, &c__5, &iseed[1]); ab[i__1].r = q__1.r, ab[i__1].i = q__1.i; } ++jcount; if (jcount > 4) { jcount = 1; } /* L210: */ } } /* Set the right hand side alternately zero and small. */ if (upper) { b[1].r = 0.f, b[1].i = 0.f; for (i__ = *n; i__ >= 2; i__ += -2) { i__4 = i__; b[i__4].r = 0.f, b[i__4].i = 0.f; i__4 = i__ - 1; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = smlnum * q__2.r, q__1.i = smlnum * q__2.i; b[i__4].r = q__1.r, b[i__4].i = q__1.i; /* L220: */ } } else { i__4 = *n; b[i__4].r = 0.f, b[i__4].i = 0.f; i__4 = *n - 1; for (i__ = 1; i__ <= i__4; i__ += 2) { i__1 = i__; b[i__1].r = 0.f, b[i__1].i = 0.f; i__1 = i__ + 1; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = smlnum * q__2.r, q__1.i = smlnum * q__2.i; b[i__1].r = q__1.r, b[i__1].i = q__1.i; /* L230: */ } } } else if (*imat == 14) { /* Type 14: Make the diagonal elements small to cause gradual */ /* overflow when dividing by T(j,j). To control the amount of */ /* scaling needed, the matrix is bidiagonal. */ texp = 1.f / (real) (*kd + 1); d__1 = (doublereal) smlnum; d__2 = (doublereal) texp; tscal = pow_dd(&d__1, &d__2); clarnv_(&c__4, &iseed[1], n, &b[1]); if (upper) { i__4 = *n; for (j = 1; j <= i__4; ++j) { /* Computing MAX */ i__1 = 1, i__3 = *kd + 2 - j; i__2 = *kd; for (i__ = max(i__1,i__3); i__ <= i__2; ++i__) { i__1 = i__ + j * ab_dim1; ab[i__1].r = 0.f, ab[i__1].i = 0.f; /* L240: */ } if (j > 1 && *kd > 0) { i__2 = *kd + j * ab_dim1; ab[i__2].r = -1.f, ab[i__2].i = -1.f; } i__2 = *kd + 1 + j * ab_dim1; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = tscal * q__2.r, q__1.i = tscal * q__2.i; ab[i__2].r = q__1.r, ab[i__2].i = q__1.i; /* L250: */ } i__4 = *n; b[i__4].r = 1.f, b[i__4].i = 1.f; } else { i__4 = *n; for (j = 1; j <= i__4; ++j) { /* Computing MIN */ i__1 = *n - j + 1, i__3 = *kd + 1; i__2 = min(i__1,i__3); for (i__ = 3; i__ <= i__2; ++i__) { i__1 = i__ + j * ab_dim1; ab[i__1].r = 0.f, ab[i__1].i = 0.f; /* L260: */ } if (j < *n && *kd > 0) { i__2 = j * ab_dim1 + 2; ab[i__2].r = -1.f, ab[i__2].i = -1.f; } i__2 = j * ab_dim1 + 1; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = tscal * q__2.r, q__1.i = tscal * q__2.i; ab[i__2].r = q__1.r, ab[i__2].i = q__1.i; /* L270: */ } b[1].r = 1.f, b[1].i = 1.f; } } else if (*imat == 15) { /* Type 15: One zero diagonal element. */ iy = *n / 2 + 1; if (upper) { i__4 = *n; for (j = 1; j <= i__4; ++j) { /* Computing MIN */ i__2 = j, i__1 = *kd + 1; lenj = min(i__2,i__1); clarnv_(&c__4, &iseed[1], &lenj, &ab[*kd + 2 - lenj + j * ab_dim1]); if (j != iy) { i__2 = *kd + 1 + j * ab_dim1; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = q__2.r * 2.f, q__1.i = q__2.i * 2.f; ab[i__2].r = q__1.r, ab[i__2].i = q__1.i; } else { i__2 = *kd + 1 + j * ab_dim1; ab[i__2].r = 0.f, ab[i__2].i = 0.f; } /* L280: */ } } else { i__4 = *n; for (j = 1; j <= i__4; ++j) { /* Computing MIN */ i__2 = *n - j + 1, i__1 = *kd + 1; lenj = min(i__2,i__1); clarnv_(&c__4, &iseed[1], &lenj, &ab[j * ab_dim1 + 1]); if (j != iy) { i__2 = j * ab_dim1 + 1; clarnd_(&q__2, &c__5, &iseed[1]); q__1.r = q__2.r * 2.f, q__1.i = q__2.i * 2.f; ab[i__2].r = q__1.r, ab[i__2].i = q__1.i; } else { i__2 = j * ab_dim1 + 1; ab[i__2].r = 0.f, ab[i__2].i = 0.f; } /* L290: */ } } clarnv_(&c__2, &iseed[1], n, &b[1]); csscal_(n, &c_b91, &b[1], &c__1); } else if (*imat == 16) { /* Type 16: Make the offdiagonal elements large to cause overflow */ /* when adding a column of T. In the non-transposed case, the */ /* matrix is constructed to cause overflow when adding a column in */ /* every other step. */ tscal = unfl / ulp; tscal = (1.f - ulp) / tscal; i__4 = *n; for (j = 1; j <= i__4; ++j) { i__2 = *kd + 1; for (i__ = 1; i__ <= i__2; ++i__) { i__1 = i__ + j * ab_dim1; ab[i__1].r = 0.f, ab[i__1].i = 0.f; /* L300: */ } /* L310: */ } texp = 1.f; if (*kd > 0) { if (upper) { i__4 = -(*kd); for (j = *n; i__4 < 0 ? j >= 1 : j <= 1; j += i__4) { /* Computing MAX */ i__1 = 1, i__3 = j - *kd + 1; i__2 = max(i__1,i__3); for (i__ = j; i__ >= i__2; i__ += -2) { i__1 = j - i__ + 1 + i__ * ab_dim1; r__1 = -tscal / (real) (*kd + 2); ab[i__1].r = r__1, ab[i__1].i = 0.f; i__1 = *kd + 1 + i__ * ab_dim1; ab[i__1].r = 1.f, ab[i__1].i = 0.f; i__1 = i__; r__1 = texp * (1.f - ulp); b[i__1].r = r__1, b[i__1].i = 0.f; /* Computing MAX */ i__1 = 1, i__3 = j - *kd + 1; if (i__ > max(i__1,i__3)) { i__1 = j - i__ + 2 + (i__ - 1) * ab_dim1; r__1 = -(tscal / (real) (*kd + 2)) / (real) (*kd + 3); ab[i__1].r = r__1, ab[i__1].i = 0.f; i__1 = *kd + 1 + (i__ - 1) * ab_dim1; ab[i__1].r = 1.f, ab[i__1].i = 0.f; i__1 = i__ - 1; r__1 = texp * (real) ((*kd + 1) * (*kd + 1) + *kd) ; b[i__1].r = r__1, b[i__1].i = 0.f; } texp *= 2.f; /* L320: */ } /* Computing MAX */ i__1 = 1, i__3 = j - *kd + 1; i__2 = max(i__1,i__3); r__1 = (real) (*kd + 2) / (real) (*kd + 3) * tscal; b[i__2].r = r__1, b[i__2].i = 0.f; /* L330: */ } } else { i__4 = *n; i__2 = *kd; for (j = 1; i__2 < 0 ? j >= i__4 : j <= i__4; j += i__2) { texp = 1.f; /* Computing MIN */ i__1 = *kd + 1, i__3 = *n - j + 1; lenj = min(i__1,i__3); /* Computing MIN */ i__3 = *n, i__5 = j + *kd - 1; i__1 = min(i__3,i__5); for (i__ = j; i__ <= i__1; i__ += 2) { i__3 = lenj - (i__ - j) + j * ab_dim1; r__1 = -tscal / (real) (*kd + 2); ab[i__3].r = r__1, ab[i__3].i = 0.f; i__3 = j * ab_dim1 + 1; ab[i__3].r = 1.f, ab[i__3].i = 0.f; i__3 = j; r__1 = texp * (1.f - ulp); b[i__3].r = r__1, b[i__3].i = 0.f; /* Computing MIN */ i__3 = *n, i__5 = j + *kd - 1; if (i__ < min(i__3,i__5)) { i__3 = lenj - (i__ - j + 1) + (i__ + 1) * ab_dim1; r__1 = -(tscal / (real) (*kd + 2)) / (real) (*kd + 3); ab[i__3].r = r__1, ab[i__3].i = 0.f; i__3 = (i__ + 1) * ab_dim1 + 1; ab[i__3].r = 1.f, ab[i__3].i = 0.f; i__3 = i__ + 1; r__1 = texp * (real) ((*kd + 1) * (*kd + 1) + *kd) ; b[i__3].r = r__1, b[i__3].i = 0.f; } texp *= 2.f; /* L340: */ } /* Computing MIN */ i__3 = *n, i__5 = j + *kd - 1; i__1 = min(i__3,i__5); r__1 = (real) (*kd + 2) / (real) (*kd + 3) * tscal; b[i__1].r = r__1, b[i__1].i = 0.f; /* L350: */ } } } } else if (*imat == 17) { /* Type 17: Generate a unit triangular matrix with elements */ /* between -1 and 1, and make the right hand side large so that it */ /* requires scaling. */ if (upper) { i__2 = *n; for (j = 1; j <= i__2; ++j) { /* Computing MIN */ i__4 = j - 1; lenj = min(i__4,*kd); clarnv_(&c__4, &iseed[1], &lenj, &ab[*kd + 1 - lenj + j * ab_dim1]); i__4 = *kd + 1 + j * ab_dim1; r__1 = (real) j; ab[i__4].r = r__1, ab[i__4].i = 0.f; /* L360: */ } } else { i__2 = *n; for (j = 1; j <= i__2; ++j) { /* Computing MIN */ i__4 = *n - j; lenj = min(i__4,*kd); if (lenj > 0) { clarnv_(&c__4, &iseed[1], &lenj, &ab[j * ab_dim1 + 2]); } i__4 = j * ab_dim1 + 1; r__1 = (real) j; ab[i__4].r = r__1, ab[i__4].i = 0.f; /* L370: */ } } /* Set the right hand side so that the largest value is BIGNUM. */ clarnv_(&c__2, &iseed[1], n, &b[1]); iy = icamax_(n, &b[1], &c__1); bnorm = c_abs(&b[iy]); bscal = bignum / dmax(1.f,bnorm); csscal_(n, &bscal, &b[1], &c__1); } else if (*imat == 18) { /* Type 18: Generate a triangular matrix with elements between */ /* BIGNUM/(KD+1) and BIGNUM so that at least one of the column */ /* norms will exceed BIGNUM. */ /* 1/3/91: CLATBS no longer can handle this case */ tleft = bignum / (real) (*kd + 1); tscal = bignum * ((real) (*kd + 1) / (real) (*kd + 2)); if (upper) { i__2 = *n; for (j = 1; j <= i__2; ++j) { /* Computing MIN */ i__4 = j, i__1 = *kd + 1; lenj = min(i__4,i__1); clarnv_(&c__5, &iseed[1], &lenj, &ab[*kd + 2 - lenj + j * ab_dim1]); slarnv_(&c__1, &iseed[1], &lenj, &rwork[*kd + 2 - lenj]); i__4 = *kd + 1; for (i__ = *kd + 2 - lenj; i__ <= i__4; ++i__) { i__1 = i__ + j * ab_dim1; i__3 = i__ + j * ab_dim1; r__1 = tleft + rwork[i__] * tscal; q__1.r = r__1 * ab[i__3].r, q__1.i = r__1 * ab[i__3].i; ab[i__1].r = q__1.r, ab[i__1].i = q__1.i; /* L380: */ } /* L390: */ } } else { i__2 = *n; for (j = 1; j <= i__2; ++j) { /* Computing MIN */ i__4 = *n - j + 1, i__1 = *kd + 1; lenj = min(i__4,i__1); clarnv_(&c__5, &iseed[1], &lenj, &ab[j * ab_dim1 + 1]); slarnv_(&c__1, &iseed[1], &lenj, &rwork[1]); i__4 = lenj; for (i__ = 1; i__ <= i__4; ++i__) { i__1 = i__ + j * ab_dim1; i__3 = i__ + j * ab_dim1; r__1 = tleft + rwork[i__] * tscal; q__1.r = r__1 * ab[i__3].r, q__1.i = r__1 * ab[i__3].i; ab[i__1].r = q__1.r, ab[i__1].i = q__1.i; /* L400: */ } /* L410: */ } } clarnv_(&c__2, &iseed[1], n, &b[1]); csscal_(n, &c_b91, &b[1], &c__1); } /* Flip the matrix if the transpose will be used. */ if (! lsame_(trans, "N")) { if (upper) { i__2 = *n / 2; for (j = 1; j <= i__2; ++j) { /* Computing MIN */ i__4 = *n - (j << 1) + 1, i__1 = *kd + 1; lenj = min(i__4,i__1); i__4 = *ldab - 1; cswap_(&lenj, &ab[*kd + 1 + j * ab_dim1], &i__4, &ab[*kd + 2 - lenj + (*n - j + 1) * ab_dim1], &c_n1); /* L420: */ } } else { i__2 = *n / 2; for (j = 1; j <= i__2; ++j) { /* Computing MIN */ i__4 = *n - (j << 1) + 1, i__1 = *kd + 1; lenj = min(i__4,i__1); i__4 = -(*ldab) + 1; cswap_(&lenj, &ab[j * ab_dim1 + 1], &c__1, &ab[lenj + (*n - j + 2 - lenj) * ab_dim1], &i__4); /* L430: */ } } } return 0; /* End of CLATTB */ } /* clattb_ */
28.825826
78
0.490433
[ "object", "vector" ]
a144929670e4de83e883d3f2a1c169cb08385219
4,348
h
C
projects/CFCSS/CFCSS.h
mfkiwl/coast-compilerAssistedSoftwareFaultTolerance
397a26ecdb01e7c329884d12c9f6bb2a05c3abc9
[ "MIT" ]
12
2019-08-19T17:05:17.000Z
2022-03-21T23:07:41.000Z
projects/CFCSS/CFCSS.h
mfkiwl/coast-compilerAssistedSoftwareFaultTolerance
397a26ecdb01e7c329884d12c9f6bb2a05c3abc9
[ "MIT" ]
3
2020-02-13T12:46:07.000Z
2022-03-23T22:48:29.000Z
projects/CFCSS/CFCSS.h
mfkiwl/coast-compilerAssistedSoftwareFaultTolerance
397a26ecdb01e7c329884d12c9f6bb2a05c3abc9
[ "MIT" ]
7
2019-04-23T13:52:28.000Z
2021-09-23T03:49:16.000Z
/* * CFCSS.h * * Created on: May 17, 2017 * Author: B James * * requires that -ErrorBlocks be run before this pass */ #ifndef PROJECTS_CFCSS_CFCSS_H_ #define PROJECTS_CFCSS_CFCSS_H_ #define DEBUG_TYPE "CFCSS" #include "llvm/Pass.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/SmallVector.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/BasicBlock.h" #include <llvm/PassAnalysisSupport.h> #include <list> #include <vector> using namespace llvm; STATISTIC(BBCount, "The number of Basic Blocks in the program"); STATISTIC(passTime, "How long it took to run this pass"); STATISTIC(fixBranchCount, "How many buffer blocks were inserted"); STATISTIC(splitBlockCount, "How many times a block was split"); #define MAX_16_BIT_INT_SIZE 65536 #define REGISTER_SIZE 16 //change this ^ if you have something bigger than a 16-bit processor class CFCSS : public ModulePass { public: static char ID; struct BBNode { BasicBlock* node; int num; SmallVector<BasicBlockEdge*, 5> edges; SmallVector<int, 5> edgeNums; SmallVector<CallInst*, 5> callList; unsigned short sig; //signature unsigned short sigDiff; //difference between signature and the one before it unsigned short sigAdj; //run-time adjusting signature constant bool isBranchFanIn; //true for nodes with multiple predecessors bool isBuffer = false; BBNode(BasicBlock* no, int nu); void addEdge(BasicBlockEdge* e, int n); void removeEdge(int n); std::string printNode(); }; //blacklist of blocks/functions we should skip if discovered std::list<StringRef> skipList = {StringRef("EDDI_FAULT_DETECTED"), StringRef("errorHandler"), StringRef("CF_FAULT_DETECTED"), StringRef("CFerrorHandler")}; std::list<StringRef> skipFList = {StringRef("EDDI_FAULT_DETECTED"), StringRef("CF_FAULT_DETECTED")}; std::vector< std::pair<BasicBlock*, int>* > workList; std::vector<BBNode*> graph; std::set<Function*> calledFunctionList; std::set<Function*> multipleFunctionCalls; std::vector<Instruction*> retInstList; std::set<unsigned short> signatures; std::vector<int> visited; std::map< Instruction*, unsigned short > retAdjMap; std::vector<CallInst*> callInstList; std::map<StringRef, int> callCount; std::vector<Instruction*> splitList; std::map<Function*, BasicBlock*> errBlockMap; CFCSS() : ModulePass(ID) {BBCount = 0; passTime = 0; fixBranchCount = 0; splitBlockCount = 0;} void getAnalysisUsage(AnalysisUsage& AU) const override ; void insertErrorFunction(Module &M, StringRef name); void createErrorBlocks(Function &F); bool skipFnCl(Function* F); bool shouldSkipF(StringRef name); void populateGraph(Module &M); void generateSignatures(); void BubbleSort(); void sortGraph(); int getIndex(BasicBlock* bb); void checkBuffSig(BBNode* parent, BBNode* buff, BBNode* child); void updateEdgeNums(BBNode* pred, BBNode* buff, BBNode* succ); void updatePhiNodes(BBNode* pred, BBNode* buff, BBNode* succ); void updateBranchInst(BBNode* pred, BBNode* buff, BBNode* succ); unsigned short getSingleSig(); BBNode* insertBufferBlock(CFCSS::BBNode* pred, CFCSS::BBNode* succ); bool verifySignatures(); bool shouldSkipBB(StringRef name); unsigned short calcSigDiff(CFCSS::BBNode* pn, CFCSS::BBNode* sn); void sigDiffGen(); void printGraph(); GlobalVariable* setUpGlobal(Module &M, StringRef vName, IntegerType* IT1); void insertStoreInsts(BBNode* b1, IntegerType* IT1, GlobalVariable* RTS, GlobalVariable* RTSA, Instruction* insertSpot); void insertCompInsts(BBNode* b1, IntegerType* IT1, GlobalVariable* RTS, GlobalVariable* RTSA, Instruction* insertSpot, bool fromCallInst); Instruction* getInstructionBeforeOrAfter(Instruction* insertAfter, int steps); Instruction* isInBB(BasicBlock* BB); std::list<BBNode*> getRetBBs(Function* F); void updateCallInsts(CallInst* callI, BBNode* bn, IntegerType* IT1, GlobalVariable* RTS, GlobalVariable* RTSA); void verifyCallSignatures(IntegerType* IT1); void updateRetInsts(IntegerType* IT1); void splitBlocks(Instruction* I, BasicBlock* b1); bool runOnModule(Module &M); }; char CFCSS::ID = 0; static RegisterPass< CFCSS > X("CFCSS", "Control Flow checker", false, false); #endif /* PROJECTS_CFCSS_CFCSS_H_ */
34.784
95
0.73827
[ "vector" ]
a1487a0bda178141f6ad95c8a60c16b5a7029062
25,022
h
C
src/cc65/exprdesc.h
C-Chads/cc65
52e43879298c2fb30c7bc6fd95fae3b3f1458793
[ "Zlib" ]
1,673
2015-01-01T23:03:31.000Z
2022-03-30T21:49:03.000Z
src/cc65/exprdesc.h
C-Chads/cc65
52e43879298c2fb30c7bc6fd95fae3b3f1458793
[ "Zlib" ]
1,307
2015-01-06T09:32:26.000Z
2022-03-31T19:57:16.000Z
src/cc65/exprdesc.h
C-Chads/cc65
52e43879298c2fb30c7bc6fd95fae3b3f1458793
[ "Zlib" ]
423
2015-01-01T19:11:31.000Z
2022-03-30T14:36:00.000Z
/*****************************************************************************/ /* */ /* exprdesc.h */ /* */ /* Expression descriptor structure */ /* */ /* */ /* */ /* (C) 2002-2010, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #ifndef EXPRDESC_H #define EXPRDESC_H #include <string.h> /* common */ #include "fp.h" #include "inline.h" #include "inttypes.h" /* cc65 */ #include "asmcode.h" #include "datatype.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Defines for the flags field of the expression descriptor */ enum { /* Location: Where is the value we're talking about? ** ** Remarks: ** - E_LOC_<else> refers to any other than E_LOC_NONE and E_LOC_PRIMARY. ** - E_LOC_EXPR can be regarded as a generalized E_LOC_<else>. ** - E_LOC_NONE can be regarded as E_LOC_PRIMARY + E_ADDRESS_OF unless ** remarked otherwise (see below). ** - An E_LOC_NONE value is not considered to be an "address". ** - ref-load doesn't change the location, while rval-load puts into the ** primary register a "temporary" that is the straight integer rvalue or ** a "delegate" to the real rvalue somewhere else. ** - ref-load doesn't change the rval/lval category of the expression, ** while rval-load converts it to an rvalue if it wasn't. ** - In practice, ref-load is unimplemented, and can be simulated with ** adding E_ADDRESS_OF temporaily through LoadExpr + FinalizeLoad, ** whilst val-load is done with LoadExpr + FinalizeRValLoad. ** ** E_LOC_NONE -- ref-load -> + E_LOADED (int rvalue) ** E_LOC_PRIMARY -- ref-load -> + E_LOADED (unchanged) ** E_LOC_<else> -- ref-load -> + E_LOADED (reference lvalue) ** + E_ADDRESS_OF -- ref-load -> + E_LOADED (address rvalue) ** E_LOC_NONE -- val-load -> E_LOC_PRIMARY (int rvalue) ** E_LOC_PRIMARY -- val-load -> E_LOC_PRIMARY (unchanged) ** E_LOC_<else> -- val-load -> E_LOC_PRIMARY (rvalue/delegate) ** + E_ADDRESS_OF -- val-load -> E_LOC_PRIMARY (address rvalue) ** E_LOC_NONE -- take address -> (error) ** E_LOC_PRIMARY -- take address -> + E_ADDRESS_OF (or error) ** E_LOC_EXPR -- take address -> E_LOC_PRIMARY (address) ** E_LOC_<else> -- take address -> + E_ADDRESS_OF (address) ** + E_ADDRESS_OF -- take address -> (error) ** E_LOC_NONE -- dereference -> E_LOC_ABS (lvalue reference) ** E_LOC_PRIMARY -- dereference -> E_LOC_EXPR (lvalue reference) ** E_LOC_<else> -- dereference -> E_LOC_EXPR (pointed-to-value, must load) ** + E_ADDRESS_OF -- dereference -> (lvalue reference) */ E_MASK_LOC = 0x01FF, E_LOC_NONE = 0x0000, /* Pure rvalue with no storage */ E_LOC_ABS = 0x0001, /* Absolute numeric addressed variable */ E_LOC_GLOBAL = 0x0002, /* Global variable */ E_LOC_STATIC = 0x0004, /* Static variable */ E_LOC_REGISTER = 0x0008, /* Register variable */ E_LOC_STACK = 0x0010, /* Value on the stack */ E_LOC_PRIMARY = 0x0020, /* Temporary in primary register */ E_LOC_EXPR = 0x0040, /* A location that the primary register points to */ E_LOC_LITERAL = 0x0080, /* Literal in the literal pool */ E_LOC_CODE = 0x0100, /* C code label location (&&Label) */ /* Immutable location addresses (immutable bases and offsets) */ E_LOC_CONST = E_LOC_NONE | E_LOC_ABS | E_LOC_GLOBAL | E_LOC_STATIC | E_LOC_REGISTER | E_LOC_LITERAL | E_LOC_CODE, /* Not-so-immutable location addresses (stack offsets may change dynamically) */ E_LOC_QUASICONST = E_LOC_CONST | E_LOC_STACK, /* Expression type modifiers */ E_ADDRESS_OF = 0x0400, /* Expression is the address of the lvalue */ /* lvalue/rvalue in C language's sense */ E_MASK_RTYPE = 0x0800, E_RTYPE_RVAL = 0x0000, E_RTYPE_LVAL = 0x0800, /* Expression status */ E_LOADED = 0x1000, /* Expression is loaded in primary */ E_CC_SET = 0x2000, /* Condition codes are set */ E_HAVE_MARKS = 0x4000, /* Code marks are valid */ /* Optimization hints */ E_MASK_NEED = 0x030000, E_NEED_EAX = 0x000000, /* Expression result needs to be loaded in Primary */ E_NEED_NONE = 0x010000, /* Expression result is unused */ E_NEED_TEST = 0x020000, /* Expression needs a test to set cc */ /* Expression evaluation requirements. ** Usage: (Flags & E_EVAL_<Flag>) == E_EVAL_<Flag> ** ** Remark: ** - Expression result, that is the "final value" of the expression, is no ** more than one of the effects of the whole expression. Effects other ** than it are usually consided "side-effects" in this regard. ** - The compiler front end cannot know things determined by the linker, ** such as the actual address of an object with static storage. What it ** can know is categorized as "compiler-known" here. ** - The concept "immutable" here means that once something is determined ** (not necessarily by the compiler), it will never change. This is not ** the same meaning as the "constant" word in the C standard. ** - The concept "compile-time" ( not to be confued with "compiler-known"), ** or "static" (compared to "run-time" as in "_Static_assert" in C, not ** to be confused with the "static" storage) here means that something ** has no run-time behaviors, enforced by the fact that it generates no ** target code (hence "no-code"). It is closely related to the concepts ** above but not the same. ** - An "unevaluated" expression is special and different from the above: ** while it generates no code, cannot change its "value" (it actually has ** no value), and must be completely handled by the compiler front-end, ** it is unique in that it is not "evaluated" while the others are, and ** the codegen routine of such an expression is usually separated from ** the normally evaluated ones. Therefore it is treated differently from ** the above and uses a separate flag that implies none of the above. ** - The "maybe-unused" flag is to suppress the checking and warning on ** expressions with no effects. It doesn't have any special meanings ** beyond that, and is independent from the E_NEED_<flag>s. All ** "unevaluated" expressions are flagged as "maybe-unused" just to ** avoid unnecessary warnings. ** ** Relationship of some concepts: ** - "no-code" implies "no-side-effects" ** - "immutable" = "compiler-known" OR "no-code" ** - "constant expression" in C = "compiler-known" AND "no-code", with minor differences */ E_MASK_EVAL = 0xFC0000, E_EVAL_NONE = 0x000000, /* No requirements */ E_EVAL_IMMUTABLE_RESULT = 0x040000, /* Expression result must be immutable */ E_EVAL_COMPILER_KNOWN = 0x0C0000, /* Expression result must be known to the compiler */ E_EVAL_NO_SIDE_EFFECTS = 0x100000, /* Evaluation must have no side effects */ E_EVAL_NO_CODE = 0x340000, /* Evaluation must generate no code */ E_EVAL_MAYBE_UNUSED = 0x400000, /* Expression result may be unused */ E_EVAL_UNEVAL = 0xC00000, /* Expression is unevaluated */ /* Expression result must be known to the compiler and generate no code to load */ E_EVAL_C_CONST = E_EVAL_COMPILER_KNOWN | E_EVAL_NO_CODE, /* Flags to keep in subexpressions of most operations other than ternary */ E_MASK_KEEP_SUBEXPR = E_MASK_EVAL, /* Flags to keep for the two result subexpressions of the ternary operation */ E_MASK_KEEP_RESULT = E_MASK_NEED | E_MASK_EVAL, /* Flags to keep when using the ED_Make functions */ E_MASK_KEEP_MAKE = E_HAVE_MARKS | E_MASK_KEEP_RESULT, }; /* Forward */ struct Literal; /* Describe the result of an expression */ typedef struct ExprDesc ExprDesc; struct ExprDesc { const Type* Type; /* C type of the expression */ unsigned Flags; /* Properties of the expression */ uintptr_t Name; /* Name pointer or label number */ struct SymEntry* Sym; /* Symbol table entry if any */ long IVal; /* Integer value if expression constant */ union { Double FVal; /* Floating point value */ struct Literal* LVal; /* Literal value */ } V; /* Start and end of generated code */ CodeMark Start; CodeMark End; }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ ExprDesc* ED_Init (ExprDesc* Expr); /* Initialize an ExprDesc */ #if defined(HAVE_INLINE) INLINE int ED_GetLoc (const ExprDesc* Expr) /* Return the location flags from the expression */ { return (Expr->Flags & E_MASK_LOC); } #else # define ED_GetLoc(Expr) ((Expr)->Flags & E_MASK_LOC) #endif #if defined(HAVE_INLINE) INLINE int ED_IsLocNone (const ExprDesc* Expr) /* Return true if the expression is an absolute value */ { return (Expr->Flags & E_MASK_LOC) == E_LOC_NONE; } #else # define ED_IsLocNone(Expr) (((Expr)->Flags & E_MASK_LOC) == E_LOC_NONE) #endif #if defined(HAVE_INLINE) INLINE int ED_IsLocAbs (const ExprDesc* Expr) /* Return true if the expression is referenced with an absolute address */ { return (Expr->Flags & E_MASK_LOC) == E_LOC_ABS; } #else # define ED_IsLocAbs(Expr) (((Expr)->Flags & E_MASK_LOC) == E_LOC_ABS) #endif #if defined(HAVE_INLINE) INLINE int ED_IsLocRegister (const ExprDesc* Expr) /* Return true if the expression is located in a register */ { return (Expr->Flags & E_MASK_LOC) == E_LOC_REGISTER; } #else # define ED_IsLocRegister(Expr) (((Expr)->Flags & E_MASK_LOC) == E_LOC_REGISTER) #endif #if defined(HAVE_INLINE) INLINE int ED_IsLocStack (const ExprDesc* Expr) /* Return true if the expression is located on the stack */ { return (Expr->Flags & E_MASK_LOC) == E_LOC_STACK; } #else # define ED_IsLocStack(Expr) (((Expr)->Flags & E_MASK_LOC) == E_LOC_STACK) #endif #if defined(HAVE_INLINE) INLINE int ED_IsLocPrimary (const ExprDesc* Expr) /* Return true if the expression is an expression in the register pseudo variable */ { return (Expr->Flags & E_MASK_LOC) == E_LOC_PRIMARY; } #else # define ED_IsLocPrimary(Expr) (((Expr)->Flags & E_MASK_LOC) == E_LOC_PRIMARY) #endif #if defined(HAVE_INLINE) INLINE int ED_IsLocExpr (const ExprDesc* Expr) /* Return true if the expression is an expression in the primary */ { return (Expr->Flags & E_MASK_LOC) == E_LOC_EXPR; } #else # define ED_IsLocExpr(Expr) (((Expr)->Flags & E_MASK_LOC) == E_LOC_EXPR) #endif #if defined(HAVE_INLINE) INLINE int ED_IsLocLiteral (const ExprDesc* Expr) /* Return true if the expression is a string from the literal pool */ { return (Expr->Flags & E_MASK_LOC) == E_LOC_LITERAL; } #else # define ED_IsLocLiteral(Expr) (((Expr)->Flags & E_MASK_LOC) == E_LOC_LITERAL) #endif #if defined(HAVE_INLINE) INLINE int ED_IsLocConst (const ExprDesc* Expr) /* Return true if the expression is a constant location of some sort */ { return ((Expr)->Flags & E_MASK_LOC & ~E_LOC_CONST) == 0; } #else # define ED_IsLocConst(Expr) (((Expr)->Flags & E_MASK_LOC & ~E_LOC_CONST) == 0) #endif #if defined(HAVE_INLINE) INLINE int ED_IsLocQuasiConst (const ExprDesc* Expr) /* Return true if the expression is a constant location of some sort or on the ** stack. */ { return ED_IsLocConst (Expr) || ED_IsLocStack (Expr); } #else int ED_IsLocQuasiConst (const ExprDesc* Expr); /* Return true if the expression denotes a constant address of some sort. This ** can be the address of a global variable (maybe with offset) or similar. */ #endif #if defined(HAVE_INLINE) INLINE void ED_RequireTest (ExprDesc* Expr) /* Mark the expression for a test. */ { Expr->Flags |= E_NEED_TEST; } #else # define ED_RequireTest(Expr) do { (Expr)->Flags |= E_NEED_TEST; } while (0) #endif #if defined(HAVE_INLINE) INLINE void ED_RequireNoTest (ExprDesc* Expr) /* Mark the expression not for a test. */ { Expr->Flags &= ~E_NEED_TEST; } #else # define ED_RequireNoTest(Expr) do { (Expr)->Flags &= ~E_NEED_TEST; } while (0) #endif #if defined(HAVE_INLINE) INLINE int ED_GetNeeds (const ExprDesc* Expr) /* Get flags about what the expression needs. */ { return (Expr->Flags & E_MASK_NEED); } #else # define ED_GetNeeds(Expr) ((Expr)->Flags & E_MASK_NEED) #endif #if defined(HAVE_INLINE) INLINE int ED_NeedsPrimary (const ExprDesc* Expr) /* Check if the expression needs to be in Primary. */ { return (Expr->Flags & E_MASK_NEED) == E_NEED_EAX; } #else # define ED_NeedsPrimary(Expr) (((Expr)->Flags & E_MASK_NEED) == E_NEED_EAX) #endif #if defined(HAVE_INLINE) INLINE int ED_NeedsTest (const ExprDesc* Expr) /* Check if the expression needs a test. */ { return (Expr->Flags & E_NEED_TEST) != 0; } #else # define ED_NeedsTest(Expr) (((Expr)->Flags & E_NEED_TEST) != 0) #endif #if defined(HAVE_INLINE) INLINE int ED_YetToTest (const ExprDesc* Expr) /* Check if the expression needs to be tested but not yet. */ { return ((Expr)->Flags & (E_NEED_TEST | E_CC_SET)) == E_NEED_TEST; } #else # define ED_YetToTest(Expr) (((Expr)->Flags & (E_NEED_TEST | E_CC_SET)) == E_NEED_TEST) #endif #if defined(HAVE_INLINE) INLINE void ED_TestDone (ExprDesc* Expr) /* Mark the expression as tested and condition codes set. */ { Expr->Flags |= E_CC_SET; } #else # define ED_TestDone(Expr) \ do { (Expr)->Flags |= E_CC_SET; } while (0) #endif #if defined(HAVE_INLINE) INLINE int ED_IsTested (const ExprDesc* Expr) /* Check if the expression has set the condition codes. */ { return (Expr->Flags & E_CC_SET) != 0; } #else # define ED_IsTested(Expr) (((Expr)->Flags & E_CC_SET) != 0) #endif #if defined(HAVE_INLINE) INLINE void ED_MarkAsUntested (ExprDesc* Expr) /* Mark the expression as not tested (condition codes not set). */ { Expr->Flags &= ~E_CC_SET; } #else # define ED_MarkAsUntested(Expr) do { (Expr)->Flags &= ~E_CC_SET; } while (0) #endif #if defined(HAVE_INLINE) INLINE int ED_IsLoaded (const ExprDesc* Expr) /* Check if the expression is loaded. ** NOTE: This is currently unused and not working due to code complexity. */ { return (Expr->Flags & E_LOADED) != 0; } #else # define ED_IsLoaded(Expr) (((Expr)->Flags & E_LOADED) != 0) #endif int ED_YetToLoad (const ExprDesc* Expr); /* Check if the expression is yet to be loaded somehow. */ #if defined(HAVE_INLINE) INLINE int ED_NeedsConst (const ExprDesc* Expr) /* Check if the expression need be immutable */ { return (Expr->Flags & E_EVAL_IMMUTABLE_RESULT) == E_EVAL_IMMUTABLE_RESULT; } #else # define ED_NeedsConst(Expr) (((Expr)->Flags & E_EVAL_IMMUTABLE_RESULT) == E_EVAL_IMMUTABLE_RESULT) #endif void ED_MarkForUneval (ExprDesc* Expr); /* Mark the expression as not to be evaluated */ #if defined(HAVE_INLINE) INLINE int ED_IsUneval (const ExprDesc* Expr) /* Check if the expression is not to be evaluated */ { return (Expr->Flags & E_EVAL_UNEVAL) == E_EVAL_UNEVAL; } #else # define ED_IsUneval(Expr) (((Expr)->Flags & E_EVAL_UNEVAL) == E_EVAL_UNEVAL) #endif #if defined(HAVE_INLINE) INLINE int ED_MayHaveNoEffect (const ExprDesc* Expr) /* Check if the expression may be present without effects */ { return (Expr->Flags & E_EVAL_MAYBE_UNUSED) == E_EVAL_MAYBE_UNUSED; } #else # define ED_MayHaveNoEffect(Expr) (((Expr)->Flags & E_EVAL_MAYBE_UNUSED) == E_EVAL_MAYBE_UNUSED) #endif #if defined(HAVE_INLINE) INLINE int ED_IsLocPrimaryOrExpr (const ExprDesc* Expr) /* Return true if the expression is E_LOC_PRIMARY or E_LOC_EXPR */ { return ED_IsLocPrimary (Expr) || ED_IsLocExpr (Expr); } #else int ED_IsLocPrimaryOrExpr (const ExprDesc* Expr); /* Return true if the expression is E_LOC_PRIMARY or E_LOC_EXPR */ #endif #if defined(HAVE_INLINE) INLINE int ED_IsAddrExpr (const ExprDesc* Expr) /* Check if the expression is taken address of instead of its value. */ { return (Expr->Flags & E_ADDRESS_OF) != 0; } #else # define ED_IsAddrExpr(Expr) (((Expr)->Flags & E_ADDRESS_OF) != 0) #endif #if defined(HAVE_INLINE) INLINE int ED_IsIndExpr (const ExprDesc* Expr) /* Check if the expression is a reference to its value */ { return (Expr->Flags & E_ADDRESS_OF) == 0 && !ED_IsLocNone (Expr) && !ED_IsLocPrimary (Expr); } #else int ED_IsIndExpr (const ExprDesc* Expr); /* Check if the expression is a reference to its value */ #endif void ED_SetCodeRange (ExprDesc* Expr, const CodeMark* Start, const CodeMark* End); /* Set the code range for this expression */ int ED_CodeRangeIsEmpty (const ExprDesc* Expr); /* Return true if no code was output for this expression */ const char* ED_GetLabelName (const ExprDesc* Expr, long Offs); /* Return the assembler label name of the given expression. Beware: This ** function may use a static buffer, so the name may get "lost" on the second ** call to the function. */ int ED_GetStackOffs (const ExprDesc* Expr, int Offs); /* Get the stack offset of an address on the stack in Expr taking into account ** an additional offset in Offs. */ ExprDesc* ED_MakeConstAbs (ExprDesc* Expr, long Value, const Type* Type); /* Replace Expr with an absolute const with the given value and type */ ExprDesc* ED_MakeConstAbsInt (ExprDesc* Expr, long Value); /* Replace Expr with an constant integer with the given value */ ExprDesc* ED_MakeConstBool (ExprDesc* Expr, long Value); /* Replace Expr with a constant boolean expression with the given value */ ExprDesc* ED_FinalizeRValLoad (ExprDesc* Expr); /* Finalize the result of LoadExpr to be an rvalue in the primary register */ #if defined(HAVE_INLINE) INLINE int ED_IsLVal (const ExprDesc* Expr) /* Return true if the expression is a reference */ { return ((Expr)->Flags & E_MASK_RTYPE) == E_RTYPE_LVAL; } #else # define ED_IsLVal(Expr) (((Expr)->Flags & E_MASK_RTYPE) == E_RTYPE_LVAL) #endif #if defined(HAVE_INLINE) INLINE int ED_IsRVal (const ExprDesc* Expr) /* Return true if the expression is an rvalue */ { return ((Expr)->Flags & E_MASK_RTYPE) == E_RTYPE_RVAL; } #else # define ED_IsRVal(Expr) (((Expr)->Flags & E_MASK_RTYPE) == E_RTYPE_RVAL) #endif #if defined(HAVE_INLINE) INLINE void ED_MarkExprAsLVal (ExprDesc* Expr) /* Mark the expression as an lvalue. ** HINT: Consider using ED_IndExpr instead of this, unless you know what ** consequence there will be, as there are both a big part in the code ** assuming rvalue = const and a big part assuming rvalue = address. */ { Expr->Flags |= E_RTYPE_LVAL; } #else # define ED_MarkExprAsLVal(Expr) do { (Expr)->Flags |= E_RTYPE_LVAL; } while (0) #endif #if defined(HAVE_INLINE) INLINE void ED_MarkExprAsRVal (ExprDesc* Expr) /* Mark the expression as an rvalue. ** HINT: Consider using ED_AddrExpr instead of this, unless you know what ** consequence there will be, as there are both a big part in the code ** assuming rvalue = const and a big part assuming rvalue = address. */ { Expr->Flags &= ~E_RTYPE_LVAL; } #else # define ED_MarkExprAsRVal(Expr) do { (Expr)->Flags &= ~E_RTYPE_LVAL; } while (0) #endif ExprDesc* ED_AddrExpr (ExprDesc* Expr); /* Take address of Expr */ ExprDesc* ED_IndExpr (ExprDesc* Expr); /* Dereference Expr */ #if defined(HAVE_INLINE) INLINE int ED_IsAbs (const ExprDesc* Expr) /* Return true if the expression denotes a numeric value or address. */ { return (Expr->Flags & (E_MASK_LOC)) == (E_LOC_NONE) || (Expr->Flags & (E_MASK_LOC|E_ADDRESS_OF)) == (E_LOC_ABS|E_ADDRESS_OF); } #else int ED_IsAbs (const ExprDesc* Expr); /* Return true if the expression denotes a numeric value or address. */ #endif #if defined(HAVE_INLINE) INLINE int ED_IsConstAbs (const ExprDesc* Expr) /* Return true if the expression denotes a constant absolute value. This can be ** a numeric constant, cast to any type. */ { return ED_IsRVal (Expr) && ED_IsAbs (Expr); } #else int ED_IsConstAbs (const ExprDesc* Expr); /* Return true if the expression denotes a constant absolute value. This can be ** a numeric constant, cast to any type. */ #endif int ED_IsConstAbsInt (const ExprDesc* Expr); /* Return true if the expression is a constant (numeric) integer. */ int ED_IsConstBool (const ExprDesc* Expr); /* Return true if the expression can be constantly evaluated as a boolean. */ int ED_IsConstTrue (const ExprDesc* Expr); /* Return true if the constant expression can be evaluated as boolean true at ** compile time. */ int ED_IsConstFalse (const ExprDesc* Expr); /* Return true if the constant expression can be evaluated as boolean false at ** compile time. */ int ED_IsConst (const ExprDesc* Expr); /* Return true if the expression denotes a constant of some sort. This can be a ** numeric constant, the address of a global variable (maybe with offset) or ** similar. */ int ED_IsQuasiConst (const ExprDesc* Expr); /* Return true if the expression denotes a quasi-constant of some sort. This ** can be a numeric constant, a constant address or a stack variable address. */ int ED_IsConstAddr (const ExprDesc* Expr); /* Return true if the expression denotes a constant address of some sort. This ** can be the address of a global variable (maybe with offset) or similar. */ int ED_IsQuasiConstAddr (const ExprDesc* Expr); /* Return true if the expression denotes a quasi-constant address of some sort. ** This can be a constant address or a stack variable address. */ int ED_IsNullPtr (const ExprDesc* Expr); /* Return true if the given expression is a NULL pointer constant */ int ED_IsBool (const ExprDesc* Expr); /* Return true if the expression can be treated as a boolean, that is, it can ** be an operand to a compare operation with 0/NULL. */ void PrintExprDesc (FILE* F, ExprDesc* Expr); /* Print an ExprDesc */ const Type* ReplaceType (ExprDesc* Expr, const Type* NewType); /* Replace the type of Expr by a copy of Newtype and return the old type string */ /* End of exprdesc.h */ #endif
37.346269
102
0.631364
[ "object" ]
a149751fa6ba6d81302439bfdb383a94e253c928
15,739
h
C
SRC/material/nD/UWmaterials/PM4Silt.h
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
8
2019-03-05T16:25:10.000Z
2020-04-17T14:12:03.000Z
SRC/material/nD/UWmaterials/PM4Silt.h
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
null
null
null
SRC/material/nD/UWmaterials/PM4Silt.h
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
3
2019-09-21T03:11:11.000Z
2020-01-19T07:29:37.000Z
/* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** Frank McKenna (fmckenna@ce.berkeley.edu) ** ** Gregory L. Fenves (fenves@ce.berkeley.edu) ** ** Filip C. Filippou (filippou@ce.berkeley.edu) ** ** ** ** ****************************************************************** */ // Author: Long Chen, Pedro Arduino // Computational Geomechanics Group // University of Washington // Date: Sep 2018 // Last Modified: May 2019 // Description: This file contains the implementation for the PM4Silt class. // PM4Silt(Version 1): A Silt Plasticity Model For Earthquake Engineering Applications // by R.W.Boulanger and K.Ziotopoulou // Jan 2018 #ifndef PM4Silt_h #define PM4Silt_h #include <stdio.h> #include <stdlib.h> #include <math.h> #include <NDMaterial.h> #include <Matrix.h> #include <Vector.h> #include <Information.h> //#include <MaterialResponse.h> #include <Parameter.h> #include <Channel.h> #include <FEM_ObjectBroker.h> #include <string.h> #include <elementAPI.h> class PM4Silt : public NDMaterial { public: // full constructor PM4Silt(int tag, int classTag, double Su, double Su_rate, double G0, double hpo, double mDen, double Fsu = 1.0, double P_atm = 101.3, double nu = 0.3, double nG = 0.75, double h0 = 0.5, double einit = 0.9, double lambda = 0.06, double phi_cv = 32.0, double nbwet = 0.8, double nbdry = 0.5, double nd = 0.3, double Ado = 0.8, double ru_max = -1, double z_max = -1, double cz = 100.0, double ce = -1, double Cgd = 3.0, double Ckaf = 4.0, double m = 0.01, double CG_consol = 2.0, int integrationScheme = 1, int tangentType = 0, double TolF = 1.0e-7, double TolR = 1.0e-7); // full constructor PM4Silt(int tag, double Su, double Su_rate, double G0, double hpo, double mDen, double Fsu = 1.0, double P_atm = 101.3, double nu = 0.3, double nG = 0.75, double h0 = 0.5, double einit = 0.9, double lambda = 0.06, double phi_cv = 32.0, double nbwet = 0.8, double nbdry = 0.5, double nd = 0.3, double Ado = 0.8, double ru_max = -1, double z_max = -1, double cz = 100.0, double ce = -1, double Cgd = 3.0, double Ckaf = 4.0, double m = 0.01, double CG_consol = 2.0, int integrationScheme = 1, int tangentType = 0, double TolF = 1.0e-7, double TolR = 1.0e-7); // null constructor PM4Silt(); // destructor ~PM4Silt(); // send mass density to element in dynamic analysis double getRho(void) { return massDen; }; double getVoidRatio(void) { return mVoidRatio; }; int getNumIterations(void) { return mIter; }; int setTrialStrain(const Vector &v); int setTrialStrain(const Vector &v, const Vector &r); int initialize(Vector initStress); int initialize(); NDMaterial *getCopy(const char *type); int commitState(void); int revertToLastCommit(void); int revertToStart(void); NDMaterial *getCopy(void); const char *getType(void) const; int getOrder(void) const; // Recorder functions virtual const Vector& getStressToRecord() { return mSigma; }; double getDGamma(); const Vector getState(); const Vector getAlpha(); const Vector getFabric(); const Vector getAlpha_in(); const Vector getTracker(); double getG(); double getKp(); const Vector getAlpha_in_p(); const Matrix &getTangent(); const Matrix &getInitialTangent(); const Vector &getStress(); const Vector &getStrain(); const Vector &getElasticStrain(); Response *setResponse(const char **argv, int argc, OPS_Stream &output); int getResponse(int responseID, Information &matInformation); int sendSelf(int commitTag, Channel &theChannel); int recvSelf(int commitTag, Channel &theChannel, FEM_ObjectBroker &theBroker); void Print(OPS_Stream &s, int flag = 0); int setParameter(const char **argv, int argc, Parameter &param); int updateParameter(int responseID, Information &info); protected: // Material constants double m_Su; double m_Su_rate; double m_G0; double m_hpo; double massDen; // mass density for dynamic analysis double m_Fsu; double m_P_atm; double m_nG; double m_h0; double m_e_init; double m_lambda; double m_nbwet; double m_nbdry; double m_nd; double m_Ado; double m_ru_max; double m_z_max; double m_cz; double m_ce; double m_Mc; double m_Cgd; double m_Ckaf; double m_nu; double m_m; double m_CG_consol; int m_FirstCall; int m_PostShake; // internal variables Vector mEpsilon; // strain tensor Vector mEpsilon_n; // strain tensor (last committed) Vector mEpsilon_r; // negative strain tensor for returning Vector mSigma; // stress tensor Vector mSigma_n; // stress tensor (last committed) Vector mSigma_r; // negative stress tensor for returning Vector mSigma_b; // stress tensor offset from initial stress state outside bounding surface correction Vector mEpsilonE; // elastic strain tensor Vector mEpsilonE_n; // elastic strain tensor (last committed) Vector mEpsilonE_r; // negative elastic strain tensor for returning Vector mAlpha; // back-stress ratio Vector mAlpha_n; // back-stress ratio (last committed) Vector mAlpha_in; // back-stress ratio at loading reversal Vector mAlpha_in_n; // back-stress ratio at loading reversal (last committed) Vector mAlpha_in_p; // previous back-stress ratio at loading reversal Vector mAlpha_in_p_n; // previous back-stress ratio at loading reversal (last committed) Vector mAlpha_in_true; // true initial back stress ratio tensor Vector mAlpha_in_true_n; // true initial back stress ratio tensor (last committed) Vector mAlpha_in_max; // Maximum value of initial back stress ratio Vector mAlpha_in_max_n; // Maximum value of initial back stress ratio (last committed) Vector mAlpha_in_min; // Minimum value of initial back stress ratio Vector mAlpha_in_min_n; // Minimum value of initial back stress ratio (last committed) double mDGamma; // plastic multiplier double mDGamma_n; // plastic multiplier (last committed) Vector mFabric; // fabric tensor Vector mFabric_n; // fabric tensor (last committed) Vector mFabric_in; // fabric tensor at loading reversal Vector mFabric_in_n; // fabric tensor at loading reversal (last committed) Matrix mCe; // elastic tangent Matrix mCep; // continuum elastoplastic tangent Matrix mCep_Consistent; // consistent elastoplastic tangent double me0; // Critical state line intercept at p = 1kPa, Gamma in Manual double mpcs; // confining pressure at critical state double mK; // state dependent Bulk modulus double mG; // state dependent Shear modulus double mVoidRatio; // material void ratio double mKp; // plastic mudulus double mzcum; // current cumulated fabric double mzpeak; // current peak fabric double mpzp; double mzxp; // product of z and p double mMb; double mMb_max; // the maximum Mb at the origin double mC_MB; // constant to calculate Mb for dense of critical states double mMd; double mMcur; // current stress ratio Vector mTracker; // tracker of internal variables; double mTolF; // max drift from yield surface double mTolR; // tolerance for Newton iterations char unsigned mIter; // number of iterations char unsigned mScheme; // 1: Forward Euler Explicit, 2: Modified Euler Explicit char unsigned mTangType;// 0: Elastic Tangent, 1: Contiuum ElastoPlastic Tangent, 2: Consistent ElastoPlastic Tangent double m_Pmin; // Minimum allowable mean effective stress bool m_pzpFlag; // flag for updating pzp static char unsigned me2p; // 1: enforce elastic response static Vector mI1; // 2nd Order Identity Tensor static Matrix mIIco; // 4th-order identity tensor, covariant static Matrix mIIcon; // 4th-order identity tensor, contravariant static Matrix mIImix; // 4th-order identity tensor, mixed variant static Matrix mIIvol; // 4th-order volumetric tensor, IIvol = I1 tensor I1 static Matrix mIIdevCon; // 4th order deviatoric tensor, contravariant static Matrix mIIdevMix; // 4th order deviatoric tensor, mixed variant static Matrix mIIdevCo; // 4th order deviatoric tensor, covariant // initialize these Vector and Matrices: static class initTensors { public: initTensors() { // 2nd order identity tensor mI1.Zero(); mI1(0) = 1.0; mI1(1) = 1.0; // 4th order mixed variant identity tensor mIImix.Zero(); for (int i = 0; i < 3; i++) { mIImix(i, i) = 1.0; } // 4th order covariant identity tensor mIIco = mIImix; mIIco(2, 2) = 2.0; // 4th order contravariant identity tensor mIIcon = mIImix; mIIcon(2, 2) = 0.5; // 4th order volumetric tensor, IIvol = I1 tensor I1 mIIvol.Zero(); for (int i = 0; i < 2; i++) { mIIvol(i, 0) = 1.0; mIIvol(i, 1) = 1.0; } // 4th order contravariant deviatoric tensor mIIdevCon = mIIcon - 0.5*mIIvol; // 4th order covariant deviatoric tensor mIIdevCo = mIIco - 0.5*mIIvol; // 4th order mixed variant deviatoric tensor mIIdevMix = mIImix - 0.5*mIIvol; } } initTensorOps; // constant computation parameters static const double one3; static const double two3; static const double root23; static const double root12; static const double small; static const bool debugFlag; static const double maxStrainInc; static const char unsigned mMaxSubStep; // Max number of substepping //Member Functions specific for PM4Silt model //void initialize(); void integrate(); void elastic_integrator(const Vector& CurStress, const Vector& CurStrain, const Vector& CurElasticStrain, const Vector& NextStrain, Vector& NextElasticStrain, Vector& NextStress, Vector& NextAlpha, double& NextVoidRatio, double& G, double& K, Matrix& aC, Matrix& aCep, Matrix& aCep_Consistent); void explicit_integrator(const Vector& CurStress, const Vector& CurStrain, const Vector& CurElasticStrain, const Vector& CurAlpha, const Vector& CurFabric, const Vector& alpha_in, const Vector& alpha_in_p, const Vector& NextStrain, Vector& NextElasticStrain, Vector& NextStress, Vector& NextAlpha, Vector& NextFabric, double& NextDGamma, double& NextVoidRatio, double& G, double& K, Matrix& aC, Matrix& aCep, Matrix& aCep_Consistent); void ForwardEuler(const Vector& CurStress, const Vector& CurStrain, const Vector& CurElasticStrain, const Vector& CurAlpha, const Vector& CurFabric, const Vector& alpha_in, const Vector& alpha_in_p, const Vector& NextStrain, Vector& NextElasticStrain, Vector& NextStress, Vector& NextAlpha, Vector& NextFabric, double& NextDGamma, double& NextVoidRatio, double& G, double& K, Matrix& aC, Matrix& aCep, Matrix& aCep_Consistent); void ModifiedEuler(const Vector& CurStress, const Vector& CurStrain, const Vector& CurElasticStrain, const Vector& CurAlpha, const Vector& CurFabric, const Vector& alpha_in, const Vector& alpha_in_p, const Vector& NextStrain, Vector& NextElasticStrain, Vector& NextStress, Vector& NextAlpha, Vector& NextFabric, double& NextDGamma, double& NextVoidRatio, double& G, double& K, Matrix& aC, Matrix& aCep, Matrix& aCep_Consistent); void RungeKutta4(const Vector& CurStress, const Vector& CurStrain, const Vector& CurElasticStrain, const Vector& CurAlpha, const Vector& CurFabric, const Vector& alpha_in, const Vector& alpha_in_p, const Vector& NextStrain, Vector& NextElasticStrain, Vector& NextStress, Vector& NextAlpha, Vector& NextFabric, double& NextDGamma, double& NextVoidRatio, double& G, double& K, Matrix& aC, Matrix& aCep, Matrix& aCep_Consistent); void MaxStrainInc(const Vector& CurStress, const Vector& CurStrain, const Vector& CurElasticStrain, const Vector& CurAlpha, const Vector& CurFabric, const Vector& alpha_in, const Vector& alpha_in_p, const Vector& NextStrain, Vector& NextElasticStrain, Vector& NextStress, Vector& NextAlpha, Vector& NextFabric, double& NextDGamma, double& NextVoidRatio, double& G, double& K, Matrix& aC, Matrix& aCep, Matrix& aCep_Consistent); double IntersectionFactor(const Vector& CurStress, const Vector& CurStrain, const Vector& NextStrain, const Vector& CurAlpha, double a0, double a1); double IntersectionFactor_Unloading(const Vector& CurStress, const Vector& CurStrain, const Vector& NextStrain, const Vector& CurAlpha); void Stress_Correction(Vector& NextStress, Vector& NextAlpha, const Vector& alpha_in, const Vector& alpha_in_p, const Vector& CurFabric, double& NextVoidRatio); void Stress_Correction(Vector& NextStress, Vector& NextAlpha, const Vector& dAlpha, const double m, const Vector& R, const Vector& n, const Vector& r); // Material Specific Methods double Macauley(double x); double MacauleyIndex(double x); double GetF(const Vector& nStress, const Vector& nAlpha); double GetKsi(const double& e, const double& p); void GetElasticModuli(const Vector& sigma, double &K, double &G); void GetElasticModuli(const Vector& sigma, double &K, double &G, double &Mcur, const double& zcum); Matrix GetStiffness(const double& K, const double& G); Matrix GetCompliance(const double& K, const double& G); void GetStateDependent(const Vector &stress, const Vector &alpha, const Vector &alpha_in, const Vector& alpha_in_p , const Vector &fabric, const Vector &fabric_in, const double &G, const double &zcum, const double &zpeak , const double &pzp, const double &Mcur, const double &dr, Vector &n, double &D, Vector &R, double &K_p , Vector &alphaD, double &Cka, double &h, Vector &b, double &AlphaAlphaBDotN); Matrix GetElastoPlasticTangent(const Vector& NextStress, const Matrix& aCe, const Vector& R, const Vector& n, const double K_p); Vector GetNormalToYield(const Vector &stress, const Vector &alpha); int Check(const Vector& TrialStress, const Vector& stress, const Vector& CurAlpha, const Vector& NextAlpha); // Symmetric Tensor Operations double GetTrace(const Vector& v); Vector GetDevPart(const Vector& aV); double DoubleDot2_2_Contr(const Vector& v1, const Vector& v2); double DoubleDot2_2_Cov(const Vector& v1, const Vector& v2); double DoubleDot2_2_Mixed(const Vector& v1, const Vector& v2); double GetNorm_Contr(const Vector& v); double GetNorm_Cov(const Vector& v); Matrix Dyadic2_2(const Vector& v1, const Vector& v2); Vector DoubleDot4_2(const Matrix& m1, const Vector& v1); Vector DoubleDot2_4(const Vector& v1, const Matrix& m1); Matrix DoubleDot4_4(const Matrix& m1, const Matrix& m2); Vector ToContraviant(const Vector& v1); Vector ToCovariant(const Vector& v1); }; #endif
48.131498
162
0.689116
[ "vector", "model" ]
a14b4aeff52f7c0d0a01262b3e728bcff7e09cce
6,146
h
C
FFmpegServer/YAGui/include/Engine/UI/WWidgetManager.h
aalekhm/OpenFF
9df23a21727f29a871f7239ccf15e3100ae9780e
[ "MIT" ]
null
null
null
FFmpegServer/YAGui/include/Engine/UI/WWidgetManager.h
aalekhm/OpenFF
9df23a21727f29a871f7239ccf15e3100ae9780e
[ "MIT" ]
null
null
null
FFmpegServer/YAGui/include/Engine/UI/WWidgetManager.h
aalekhm/OpenFF
9df23a21727f29a871f7239ccf15e3100ae9780e
[ "MIT" ]
null
null
null
#pragma once #ifdef USE_YAGUI #include "Engine/UI/widgetdef.h" #include "Common/Defines.h" #include "Engine/Texture.h" #include "UIDefines.h" #include "glm/ext/matrix_float4x4.hpp" #include "glm/ext/matrix_clip_space.hpp" #include <functional> #define TEXTURE_CORE 0 #define TEXTURE_FONT_ROSEMARY_16 1 #define MAX_WIDGETS 80 typedef L_RESULT (__stdcall* YAGUICallback)(H_WND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); typedef std::function<L_RESULT(H_WND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)> UI_FUNC_CALLBACK; struct WWidgetManager { public: ~WWidgetManager(); static WWidgetManager* getInstance(); static UI_FUNC_CALLBACK* m_lpfnWWndProc; H_WND m_pBaseWindow; static void setCallback(UI_FUNC_CALLBACK* wndProc); H_WND GetWindow(int ID_WINDOW); H_WND FindWindowQ(LPCSTR lpClassName, LPCSTR lpWindowName); void init(int32_t iScreenWidth, int32_t iScreenHeight); void update(float deltaTimeMs); H_WND GetWindowQ(UINT ID_WINDOW); BOOL ShowWindowQ(H_WND hWnd, int nCmdShow); H_WND GetParentQ(H_WND hWnd); bool isMousePressed(int32_t iKey); bool isMouseReleased(int32_t iKey); void simulateMousePress(uint32_t iKey); void simulateMouseRelease(uint32_t iKey); void simulateMouseMove(double dXPos, double dYPos); bool isModifierKeyDown(int32_t iModifierKey); void keyPressed(unsigned int iVirtualKeycode, unsigned short ch); void keyReleased(unsigned int iVirtualKeycode, unsigned short ch); void onMouseDown(int mCode, int x, int y); void onMouseUp(int mCode, int x, int y); void onMouseRDown(int mCode, int x, int y); void onMouseRUp(int mCode, int x, int y); void onMouseHover(int mCode, int x, int y); void onMouseMove(int mCode, int x, int y); void onMouseWheel(WPARAM wParam, LPARAM lParam); void setGLStates(); void flush(); static void drawFont(int x, int y, int charW, int charH, int tX, int tY); static int getGlyphU(int c); static int getGlyphV(int c); static void renderWidget(const char* sWidgetName, RectF* WndRect); static void renderSkin(WIDGET* widget, BASESKIN* skinPtr, RectF* wndRect); static void renderChild(WIDGET* widget, CHILD* childPtr, RectF* wndRect); static void renderChild(WIDGET* widget, CHILD* childPtr, RectF* wndRect, float x, float y); static void renderClientArea(WIDGET* widget, int i, RectF* wndRect); static WIDGET* getWidget(const char* sWidgetName); static int getWidgetID(const char* sWidgetName); static float getWidgetWidth(const char* sWidgetName); static float getWidgetHeight(const char* sWidgetName); static void getDestinationRect(RectF& destRect, float parentW, float parentH, RectF* wndRect, RectF* idealRect, H_ALIGN hAlign, V_ALIGN vAlign); bool loadMainWindowDefaults(); static void setClip(int x, int y, int w, int h ); static void GetClipBounds(RectF* reclaimRect); static void SET_CLIP(int x, int y , int width, int height); static void RESET_CLIP(); static RectF m_reclaimRect; static void drawStringFont(const char* cStr, int x, int y, int anchor); static int getCharWidth(int c); static int getStringWidthTillPos(const char* cStr, int iPos); void fillRect(Color* color, Rect* rect); void fillRect(float r, float g, float b, float a, Rect* rect); void drawRect(float r, float g, float b, float a, Rect* rect, int iStrokeWidth = 1); void drawHorizontalLine(float r, float g, float b, float a, int x, int y, int width, int iStrokeWidth); void drawVerticalLine(float r, float g, float b, float a, int x, int y, int height, int iStrokeWidth); static void drawVerticalLine(float x1, float y1, float x2, float y2); static int getNextWhitespacePos(const char* str, int curPos, bool isLeft); static void clearScreen(); static void setCursor(int MOUSE_IDC); static void drawQuadU( Texture* texture, float posX, float posY, float posW, float posH, float texX, float texY, float texW, float texH); static void setColor(float r, float g, float b, float a); static void resetColor(); static H_FONT loadFont(const char* sFontFileName, unsigned int iFontSize, unsigned int iFontDPI); static bool selectFont(H_FONT hFont); static L_RESULT onEvent(H_WND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); static H_WND getWindow(int wndID); static std::string m_clipboardTextData; static WWidgetManager* m_pInstance; static int m_SpriteCount; static int m_FrameCount; static Color m_RenderColour; static VertexV3F_T2F_C4UB* m_VB; static unsigned int CHARACTER_WIDTH; static unsigned int CHARACTER_HEIGHT; static Glyph m_GlyphArray[]; private: WWidgetManager(); bool readMap(const char* filePathAndName); bool initShaders(GLint& iProgramID); GLint compileShaderFromFile(GLenum iShaderType, const char* sShaderFile, GLuint& iShaderID); GLint compileShader(GLenum iShaderType, const char* sShaderSource, GLuint& iShaderID); H_ALIGN getWidgetHAlign(char* sAlign); V_ALIGN getWidgetVAlign(char* sAlign); int getTextAlignInt(char* sAlign); static std::vector<WIDGET*> m_pWidgets; static RectF m_ClipRect; static int m_iCurrentTextureID; static Texture* m_pCurrentTexture; static Texture* m_pTextureCoreUI; static H_FONT m_pCurrentFont; ColorUV m_ColorWhiteUV; int lastMouseX; int lastMouseY; static HCURSOR m_hCurArrow; static HCURSOR m_hCurIBeam; static HCURSOR m_hCurCross; static HCURSOR m_hCurSizeWE; static HCURSOR m_hCurSizeNESW; static HCURSOR m_hCurSizeNWSE; GLuint m_iVAO; GLuint m_iVBO; GLint m_iProgramID; static float m_fOneOverWidth; static float m_fOneOverHeight; static glm::mat4 m_Mat2DOrthogonalTransform; int32_t m_iScreenWidth; int32_t m_iScreenHeight; }; #endif
37.47561
150
0.704686
[ "vector" ]
a1514f85dd75e4accc41cb23fbe0ab724479706d
5,328
h
C
2006/inc/acuiString.h
kevinzhwl/ObjectARXCore
ce09e150aa7d87675ca15c9416497c0487e3d4d4
[ "MIT" ]
12
2015-10-05T07:11:57.000Z
2021-11-20T10:22:38.000Z
2006/inc/acuiString.h
HelloWangQi/ObjectARXCore
ce09e150aa7d87675ca15c9416497c0487e3d4d4
[ "MIT" ]
null
null
null
2006/inc/acuiString.h
HelloWangQi/ObjectARXCore
ce09e150aa7d87675ca15c9416497c0487e3d4d4
[ "MIT" ]
14
2015-12-04T08:42:08.000Z
2022-01-08T02:09:23.000Z
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright 1993-2002 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // ////////////////////////////////////////////////////////////////////////////// #ifndef _acuiString_h #define _acuiString_h #pragma pack (push, 8) #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 ////////////////////////////////////////////////////////////////////////////// // Note: This class is now obsolete and is slated for removal. class CAcUiString : public CString { public: ADUI_PORT CAcUiString (); ADUI_PORT CAcUiString (const CString& stringSrc); ADUI_PORT CAcUiString (char ch, int nRepeat = 1); ADUI_PORT CAcUiString (LPCTSTR psz); ADUI_PORT CAcUiString (LPCTSTR pch, int nLength); ADUI_PORT CAcUiString (UINT nStringResourceID); // Character Query Member Functions public: ADUI_PORT BOOL IsTab (int nIndex) const; ADUI_PORT BOOL IsWhiteSpace (int nIndex) const; ADUI_PORT BOOL IsAlphabetic (int nIndex) const; ADUI_PORT BOOL IsAlphanumeric (int nIndex) const; ADUI_PORT BOOL IsBlank (int nIndex) const; ADUI_PORT BOOL IsPunctuation (int nIndex) const; ADUI_PORT BOOL IsUppercase (int nIndex) const; ADUI_PORT BOOL IsLowercase (int nIndex) const; ADUI_PORT BOOL IsNumeric (int nIndex) const; ADUI_PORT BOOL IsHexNumeric (int nIndex) const; // Misc Functions public: ADUI_PORT void MakeCharUpper (int nIndex); ADUI_PORT void MakeCharLower (int nIndex); ADUI_PORT void GetCurrentWorkingDirectory (); ADUI_PORT void ReplaceCharWithChar (char chFrom, char chTo); // Strip the mnemonic character '&'. ADUI_PORT void StripMnemonic (); // Strip the diesel prefix "$M=" ADUI_PORT void StripDiesel (); // Convert Menu execution string to AutoCAD input throat form ADUI_PORT void ConvertMenuExecString (); // Go the other way for display in dialogs and such ADUI_PORT void ConvertFromMenuExecString (); ADUI_PORT void FixFileName (); ADUI_PORT void WrapLine (CAcUiString& strRest, int nWrapAt); ADUI_PORT void WrapLine (CStringList& strListWrapped, int nWrapAt); // Tab Expansion ADUI_PORT void ExpandTabs (int nTabSize = 8); // Stripping Functions public: ADUI_PORT void StripTrailingBlanks (); ADUI_PORT void StripPrecedingBlanks (); ADUI_PORT void StripTrailingCharacters (char cChar); ADUI_PORT void StripPrecedingCharacters (char cChar); // Name shortening functions for symbol table names. // Useful for Layer and Linetype controls. public: ADUI_PORT void ShortenString ( CDC *pDC, CString OriginalString, UINT width ); ADUI_PORT CString CreateEllipsedString ( CDC *pDC, CString OriginalString, UINT width ); }; // string class that allows for macro expansion // use this class instead of CAcUiString when you need to expand a macro // such as %AUTOCAD% or %PRODUCT% in your string class CAcUiStringExp : public CAcUiString { public: ADUI_PORT CAcUiStringExp (); ADUI_PORT CAcUiStringExp (const CString& stringSrc); ADUI_PORT CAcUiStringExp (char ch, int nRepeat = 1); ADUI_PORT CAcUiStringExp (LPCTSTR psz); ADUI_PORT CAcUiStringExp (LPCTSTR pch, int nLength); ADUI_PORT CAcUiStringExp (UINT nStringResourceID); public: ADUI_PORT virtual BOOL LoadString(UINT nID); // Function to handle replacing product-specific string macros // with the appropriate text ADUI_PORT void ReplaceProductMacroStrings(); }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #pragma pack (pop) #endif //////////////////////////////////////////////////////////////////////////////
39.176471
104
0.602102
[ "object" ]
a15e2aac87d566601886d16d553e23293b9dea6a
8,972
h
C
cpp/util/include/util/tc_consistent_hash_new.h
yangg37/Tars
a4ed7b1706a800175dd02775c12ba3afb89a07ee
[ "Apache-2.0" ]
137
2017-01-20T03:24:33.000Z
2022-02-28T16:09:42.000Z
cpp/util/include/util/tc_consistent_hash_new.h
playbar/TAFS
bb58e48954b5725a65b8054c13ae3713c3eeb7ca
[ "Apache-2.0" ]
null
null
null
cpp/util/include/util/tc_consistent_hash_new.h
playbar/TAFS
bb58e48954b5725a65b8054c13ae3713c3eeb7ca
[ "Apache-2.0" ]
49
2017-01-28T07:43:43.000Z
2021-10-31T03:20:50.000Z
/** * Tencent is pleased to support the open source community by making Tars available. * * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 __TC_CONSISTENT_HASH_NEW_H_ #define __TC_CONSISTENT_HASH_NEW_H_ #include "util/tc_md5.h" #include "util/tc_autoptr.h" #include "util/tc_hash_fun.h" using namespace tars; namespace tars { struct node_T_new { /** *节点hash值 */ long iHashCode; /** *节点下标 */ unsigned int iIndex; }; enum TC_HashAlgorithmType { E_TC_CONHASH_KETAMAHASH = 0, E_TC_CONHASH_DEFAULTHASH = 1 }; /** * @brief hash 算法虚基类 */ class TC_HashAlgorithm : public TC_HandleBase { public: virtual long hash(const string & sKey) = 0; virtual TC_HashAlgorithmType getHashType() = 0; protected: long subTo32Bit(long hash) { return (hash & 0xFFFFFFFFL); } }; typedef TC_AutoPtr<TC_HashAlgorithm> TC_HashAlgorithmPtr; /** * @brief ketama hash 算法 */ class TC_KetamaHashAlg : public TC_HashAlgorithm { public: virtual long hash(const string & sKey) { string sMd5 = TC_MD5::md5bin(sKey); const char *p = (const char *) sMd5.c_str(); long hash = ((long)(p[3] & 0xFF) << 24) | ((long)(p[2] & 0xFF) << 16) | ((long)(p[1] & 0xFF) << 8) | ((long)(p[0] & 0xFF)); return subTo32Bit(hash); } virtual TC_HashAlgorithmType getHashType() { return E_TC_CONHASH_KETAMAHASH; } }; /** * @brief 默认的 hash 算法 */ class TC_DefaultHashAlg : public TC_HashAlgorithm { public: virtual long hash(const string & sKey) { string sMd5 = TC_MD5::md5bin(sKey); const char *p = (const char *) sMd5.c_str(); long hash = (*(int*)(p)) ^ (*(int*)(p+4)) ^ (*(int*)(p+8)) ^ (*(int*)(p+12)); return subTo32Bit(hash); } virtual TC_HashAlgorithmType getHashType() { return E_TC_CONHASH_DEFAULTHASH; } }; /** * @brief hash alg 工厂 */ class TC_HashAlgFactory { public: static TC_HashAlgorithm *getHashAlg() { TC_HashAlgorithm *ptrHashAlg = new TC_DefaultHashAlg(); return ptrHashAlg; } static TC_HashAlgorithm *getHashAlg(TC_HashAlgorithmType hashType) { TC_HashAlgorithm *ptrHashAlg = NULL; switch(hashType) { case E_TC_CONHASH_KETAMAHASH: { ptrHashAlg = new TC_KetamaHashAlg(); break; } case E_TC_CONHASH_DEFAULTHASH: default: { ptrHashAlg = new TC_DefaultHashAlg(); break; } } return ptrHashAlg; } }; /** * @brief 一致性hash算法类 */ class TC_ConsistentHashNew { public: /** * @brief 构造函数 */ TC_ConsistentHashNew() { _ptrHashAlg = TC_HashAlgFactory::getHashAlg(); } /** * @brief 构造函数 */ TC_ConsistentHashNew(TC_HashAlgorithmType hashType) { _ptrHashAlg = TC_HashAlgFactory::getHashAlg(hashType); } /** * @brief 节点比较. * * @param m1 node_T_new类型的对象,比较节点之一 * @param m2 node_T_new类型的对象,比较节点之一 * @return less or not 比较结果,less返回ture,否则返回false */ static bool less_hash(const node_T_new & m1, const node_T_new & m2) { return m1.iHashCode < m2.iHashCode; } /** * @brief 增加节点. * * @param node 节点名称 * @param index 节点的下标值 * @return 节点的hash值 */ int sortNode() { sort(_vHashList.begin(), _vHashList.end(), less_hash); return 0; } /** * @brief 打印节点信息 * */ void printNode() { map<unsigned int, unsigned int> mapNode; size_t size = _vHashList.size(); for (size_t i = 0; i < size; i++) { if (i == 0) { unsigned int value = 0xFFFFFFFF - _vHashList[size - 1].iHashCode + _vHashList[0].iHashCode; mapNode[_vHashList[0].iIndex] = value; } else { unsigned int value = _vHashList[i].iHashCode - _vHashList[i - 1].iHashCode; if (mapNode.find(_vHashList[i].iIndex) != mapNode.end()) { value += mapNode[_vHashList[i].iIndex]; } mapNode[_vHashList[i].iIndex] = value; } cout << "printNode: " << _vHashList[i].iHashCode << "|" << _vHashList[i].iIndex << "|" << mapNode[_vHashList[i].iIndex] << endl; } map<unsigned int, unsigned int>::iterator it = mapNode.begin(); double avg = 100; double sum = 0; while (it != mapNode.end()) { double tmp = it->second; cerr << "result: " << it->first << "|" << it->second << "|" << (tmp * 100 * mapNode.size() / 0xFFFFFFFF - avg) << endl; sum += (tmp * 100 * mapNode.size() / 0xFFFFFFFF - avg) * (tmp * 100 * mapNode.size() / 0xFFFFFFFF - avg); it++; } cerr << "variance: " << sum / mapNode.size() << ", size: " << _vHashList.size() << endl; } /** * @brief 增加节点. * * @param node 节点名称 * @param index 节点的下标值 * @param weight 节点的权重,默认为1 * @return 是否成功 */ int addNode(const string & node, unsigned int index, int weight = 1) { if (_ptrHashAlg.get() == NULL) { return -1; } node_T_new stItem; stItem.iIndex = index; for (int j = 0; j < weight; j++) { string virtualNode = node + "_" + TC_Common::tostr<int>(j); // TODO: 目前写了2 种hash 算法,可以根据需要选择一种, // TODO: 其中KEMATA 为参考memcached client 的hash 算法,default 为原有的hash 算法,测试结论在表格里有 if (_ptrHashAlg->getHashType() == E_TC_CONHASH_KETAMAHASH) { string sMd5 = TC_MD5::md5bin(virtualNode); char *p = (char *) sMd5.c_str(); for (int i = 0; i < 4; i++) { stItem.iHashCode = ((long)(p[i * 4 + 3] & 0xFF) << 24) | ((long)(p[i * 4 + 2] & 0xFF) << 16) | ((long)(p[i * 4 + 1] & 0xFF) << 8) | ((long)(p[i * 4 + 0] & 0xFF)); stItem.iIndex = index; _vHashList.push_back(stItem); } } else { stItem.iHashCode = _ptrHashAlg->hash(virtualNode); _vHashList.push_back(stItem); } } return 0; } /** * @brief 获取某key对应到的节点node的下标. * * @param key key名称 * @param iIndex 对应到的节点下标 * @return 0:获取成功 -1:没有被添加的节点 */ int getIndex(const string & key, unsigned int & iIndex) { if(_ptrHashAlg.get() == NULL || _vHashList.size() == 0) { iIndex = 0; return -1; } long iCode = _ptrHashAlg->hash(TC_MD5::md5bin(key)); return getIndex(iCode, iIndex); } /** * @brief 获取某hashcode对应到的节点node的下标. * * @param hashcode hashcode * @param iIndex 对应到的节点下标 * @return 0:获取成功 -1:没有被添加的节点 */ int getIndex(long hashcode, unsigned int & iIndex) { if(_ptrHashAlg.get() == NULL || _vHashList.size() == 0) { iIndex = 0; return -1; } // 只保留32位 long iCode = (hashcode & 0xFFFFFFFFL); int low = 0; int high = _vHashList.size(); if(iCode <= _vHashList[0].iHashCode || iCode > _vHashList[high-1].iHashCode) { iIndex = _vHashList[0].iIndex; return 0; } while (low < high - 1) { int mid = (low + high) / 2; if (_vHashList[mid].iHashCode > iCode) { high = mid; } else { low = mid; } } iIndex = _vHashList[low+1].iIndex; return 0; } /** * @brief 获取当前hash列表的长度. * * @return 长度值 */ size_t size() { return _vHashList.size(); } /** * @brief 清空当前的hash列表. * */ void clear() { _vHashList.clear(); } protected: vector<node_T_new> _vHashList; TC_HashAlgorithmPtr _ptrHashAlg; }; } #endif
23.364583
140
0.521511
[ "vector" ]
a15ede65467e030a1ba5db07695a0d327fd241f6
2,600
h
C
components/autofill_assistant/browser/website_login_manager.h
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
components/autofill_assistant/browser/website_login_manager.h
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/autofill_assistant/browser/website_login_manager.h
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_WEBSITE_LOGIN_MANAGER_H_ #define COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_WEBSITE_LOGIN_MANAGER_H_ #include <memory> #include <string> #include <vector> #include "base/callback.h" #include "base/macros.h" #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/signatures.h" #include "url/gurl.h" namespace autofill_assistant { // Common interface for implementations that fetch login details for websites. class WebsiteLoginManager { public: // Uniquely represents a particular login. struct Login { Login(const GURL& origin, const std::string& username); Login(const Login& other); ~Login(); // The origin of the login website. GURL origin; std::string username; }; WebsiteLoginManager() = default; virtual ~WebsiteLoginManager() = default; // Asynchronously returns all matching login details for |url| in the // specified callback. virtual void GetLoginsForUrl( const GURL& url, base::OnceCallback<void(std::vector<Login>)> callback) = 0; // Retrieves the password for |login| in the specified |callback|, or |false| // if the password could not be retrieved. virtual void GetPasswordForLogin( const Login& login, base::OnceCallback<void(bool, std::string)> callback) = 0; // Generates new strong password. |form/field_signature| are used to fetch // password requirements. |max_length| is the "max_length" attribute of input // field that limits the length of value. virtual std::string GeneratePassword(autofill::FormSignature form_signature, autofill::FieldSignature field_signature, uint64_t max_length) = 0; // Presaves generated passwod for the form. Password will be saved after // successful form submission. virtual void PresaveGeneratedPassword( const Login& login, const std::string& password, const autofill::FormData& form_data, base::OnceCallback<void()> callback) = 0; // Checks if generated password can be committed. virtual bool ReadyToCommitGeneratedPassword() = 0; // Commits the presaved passwod to the store. virtual void CommitGeneratedPassword() = 0; DISALLOW_COPY_AND_ASSIGN(WebsiteLoginManager); }; } // namespace autofill_assistant #endif // COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_WEBSITE_LOGIN_MANAGER_H_
34.210526
80
0.728462
[ "vector" ]
a15ee901958fbb6704a37757ef61e9d1cddd0510
3,903
h
C
purelib/NXTcpClient.h
xubingyue/libxstudio365
99a11fe8ac1644fcc2d4d5331779c4b13afa158e
[ "MIT" ]
null
null
null
purelib/NXTcpClient.h
xubingyue/libxstudio365
99a11fe8ac1644fcc2d4d5331779c4b13afa158e
[ "MIT" ]
null
null
null
purelib/NXTcpClient.h
xubingyue/libxstudio365
99a11fe8ac1644fcc2d4d5331779c4b13afa158e
[ "MIT" ]
4
2017-09-04T02:11:00.000Z
2022-01-01T06:21:49.000Z
#ifndef _NXTCPCLIENT_H_ #define _NXTCPCLIENT_H_ #include "utils/xxsocket.h" #include "utils/endian_portable.h" #include "utils/singleton.h" #include <cocos2d.h> #include <vector> #include <thread> #include <mutex> #include <ctime> #include <condition_variable> using namespace purelib; using namespace purelib::net; namespace inet { class TcpSendingPacket; // single thread only class TcpClient : public cocos2d::Ref { public: enum ErrorCode { ERR_OK, // NO ERROR ERR_CONNECT_FAILED, // connect failed ERR_CONNECT_TIMEOUT, // connect timeout ERR_SEND_FAILED, // send error, failed ERR_SEND_TIMEOUT, // send timeout ERR_RECV_FAILED, // recv failed ERR_NETWORK_UNREACHABLE, // wifi or 2,3,4G not open ERR_CONNECTION_LOST, // connection lost ERR_PACKET_TOO_LONG, // packet too long ERR_DPL_ILLEGAL_PACKET, // decode packet error. }; // End user packet decode length func typedef bool(*DecodePacketLengthFunc)(const char* data, size_t datalen, int& len); // callbacks typedef std::function<void(ErrorCode)> OnPacketSendCallback; typedef std::function<void(std::vector<char>&&)> OnPacketRecvCallback; public: TcpClient(); ~TcpClient(); bool init(); void close(); void setEndpoint(const char* address, u_short port); void setConnectionEstablishedListener(const std::function<void()>& callback); void setConnectionLostListener(const std::function<void()>& callback); void setDecodeLengthFunc(DecodePacketLengthFunc func); void setOnRecvListener(const OnPacketRecvCallback& callback); void send(std::vector<char>&& data, const OnPacketSendCallback& callback = nullptr); void setTimeoutForConnect(int timeout); void setTimeoutForSend(int timeout); ErrorCode getErrorCode(void) { return error; } private: // collect void scheduleCollectResponse(); void unscheduleCollectResponse(); void dispatchResponseCallbacks(float delta); private: bool connect(void); void service(void); bool doWrite(void); bool doRead(void); void handleError(void); // TODO: add errorcode parameter void moveReceivedPacket(); // move received properly packet to recv queue private: bool bAppExiting; bool threadStarted; std::string address; u_short port; xxsocket impl; bool connected; ErrorCode error; int timeoutForConnect; int timeoutForSend; std::mutex sendQueueMtx; std::mutex recvQueueMtx; std::queue<TcpSendingPacket*> sendQueue; std::queue<std::vector<char>> recvQueue; char buffer[512]; // recv buffer int offset; // recv buffer offset std::vector<char> recvingPacket; int expectedPacketLength; // socket event set fd_set readfds, writefds, excepfds; // std::function<void()> connectionLostListener; std::function<void()> connectionEstablishedListener; OnPacketRecvCallback onRecvPacket; DecodePacketLengthFunc decodePacketLength; bool idle; long reconnClock; }; } #endif #define tcpclient purelib::gc::delayed<inet::TcpClient>::instance(&inet::TcpClient::init)
30.255814
93
0.575199
[ "vector" ]
a15f0e249ac58c0644977f33892ab36456bc37e7
822
h
C
src/Ethereum/ABI/ParamFactory.h
vladyslav-iosdev/wallet-core
6f8f175a380bdf9756f38bfd82fedd9b73b67580
[ "MIT" ]
8
2020-10-19T19:10:57.000Z
2022-01-26T09:40:58.000Z
src/Ethereum/ABI/ParamFactory.h
vladyslav-iosdev/wallet-core
6f8f175a380bdf9756f38bfd82fedd9b73b67580
[ "MIT" ]
3
2019-10-31T06:04:45.000Z
2019-12-06T00:47:41.000Z
src/Ethereum/ABI/ParamFactory.h
vladyslav-iosdev/wallet-core
6f8f175a380bdf9756f38bfd82fedd9b73b67580
[ "MIT" ]
2
2020-11-10T13:40:04.000Z
2022-03-28T07:03:18.000Z
// Copyright © 2017-2020 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #pragma once #include "Array.h" #include "Bytes.h" #include "ParamAddress.h" #include <string> #include <vector> namespace TW::Ethereum::ABI { /// Factory creates concrete ParamBase class from string type. class ParamFactory { public: static std::shared_ptr<ParamBase> make(const std::string& type); static std::string getValue(const std::shared_ptr<ParamBase>& param, const std::string& type); static std::vector<std::string> getArrayValue(const std::shared_ptr<ParamBase>& param, const std::string& type); }; } // namespace TW::Ethereum::ABI
29.357143
116
0.738443
[ "vector" ]
a16009321a65d190c46f37fb1daca9bb5d5183f5
1,179
h
C
src/SwGameState.h
clauderichard/ShizzleWozzle
b491552a13a4bd39674ce264c23d16e3cc87e4c1
[ "MIT" ]
null
null
null
src/SwGameState.h
clauderichard/ShizzleWozzle
b491552a13a4bd39674ce264c23d16e3cc87e4c1
[ "MIT" ]
null
null
null
src/SwGameState.h
clauderichard/ShizzleWozzle
b491552a13a4bd39674ce264c23d16e3cc87e4c1
[ "MIT" ]
null
null
null
#pragma once #include <allegro5\allegro.h> #include <allegro5\allegro_font.h> #include <allegro5\allegro_ttf.h> #include <cgGameState.h> #include "sw_pde_plane.h" #include "sw_camera.h" class SwGameState : public cgGameState { // pde sw_pde_plane _pde; // camera sw_camera _camera; // for graphics ALLEGRO_FONT* font; int radius; int legs_y; int legs_height; int enemy_height; int enemy_width; int enemy_dx; int ground_y; double wheelradius; double wheelseparation_2; double angle_arms; double arm_length; // physics constants double grav; double legs_mass; double head_mass; double stick_length; double jetpackforce; // physics variables double legs_x; double theta; double legs_dx; double dtheta; double enemy_x; bool enemy_dir; // true if right // 3d physics variables double _x; double _y; double _phi; double _theta; double _dx; double _dy; double _dphi; double _dtheta; double cur_score; double high_score; int cur_enemy_score; int high_enemy_score; bool resting; int resting_count; bool game_over(); void reset(); public: SwGameState(cgGame*); ~SwGameState(); void draw_on_screen(); void compute_timestep(); };
16.375
40
0.746395
[ "3d" ]
a166d810d558a6806e26c2aca9480c3f8d37cf43
4,618
h
C
concurrency_control/ideal_mvcc_manager.h
c5h11oh/Sundial
972af0a93797dd05203ddefd9d546b8401da65c6
[ "0BSD" ]
24
2018-09-15T10:35:21.000Z
2021-07-12T06:17:54.000Z
concurrency_control/ideal_mvcc_manager.h
c5h11oh/Sundial
972af0a93797dd05203ddefd9d546b8401da65c6
[ "0BSD" ]
3
2019-10-14T02:57:21.000Z
2022-02-17T19:53:46.000Z
concurrency_control/ideal_mvcc_manager.h
c5h11oh/Sundial
972af0a93797dd05203ddefd9d546b8401da65c6
[ "0BSD" ]
10
2018-12-20T18:34:47.000Z
2020-10-06T13:49:30.000Z
#pragma once #include "cc_manager.h" #include <chrono> #include <thread> #if CC_ALG == IDEAL_MVCC class MVCCManager : public CCManager { public: MVCCManager(TxnManager * txn); ~MVCCManager() {}; bool is_read_only() { return _is_read_only; } RC get_row(row_t * row, access_t type, uint64_t key); RC get_row(row_t * row, access_t type, uint64_t key, uint64_t wts); RC get_row(row_t * row, access_t type, char * &data, uint64_t key); char * get_data(uint64_t key, uint32_t table_id); RC register_remote_access(uint32_t remote_node_id, access_t type, uint64_t key, uint32_t table_id); RC register_remote_access(uint32_t remote_node_id, access_t type, uint64_t key, uint32_t table_id, uint32_t &msg_size, char * &msg_data); RC index_get_permission(access_t type, INDEX * index, uint64_t key, uint32_t limit = -1); RC index_read(INDEX * index, uint64_t key, set<row_t *> * &rows, uint32_t limit = -1); RC index_insert(INDEX * index, uint64_t key); RC index_delete(INDEX * index, uint64_t key); void cleanup(RC rc); // normal execution void add_remote_req_header(UnstructuredBuffer * buffer); uint32_t process_remote_req_header(UnstructuredBuffer * buffer); void get_resp_data(uint32_t &size, char * &data); void process_remote_resp(uint32_t node_id, uint32_t size, char * resp_data); // prepare phase RC validate(); RC process_prepare_phase_coord(); void get_remote_nodes(set<uint32_t> * remote_nodes); bool need_prepare_req(uint32_t remote_node_id, uint32_t &size, char * &data); RC process_prepare_req(uint32_t size, char * data, uint32_t &resp_size, char * &resp_data ); void process_prepare_resp(RC rc, uint32_t node_id, char * data); // commit phase void process_commit_phase_coord(RC rc); RC commit_insdel(); bool need_commit_req(RC rc, uint32_t node_id, uint32_t &size, char * &data); void process_commit_req(RC rc, uint32_t size, char * data); void abort(); void commit(); // handle WAIT_DIE validation void set_ts(uint64_t timestamp) { _timestamp = timestamp; } uint64_t get_priority() { return _timestamp; } void set_txn_ready(RC rc); bool is_txn_ready(); bool is_signal_abort() { return _signal_abort; } uint64_t commit_ts; uint64_t LEASE; private: bool _is_read_only; struct IndexAccessMVCC : IndexAccess { uint64_t wts; uint64_t rts; }; struct AccessMVCC : Access { AccessMVCC() { locked = false; row = NULL; local_data = NULL; }; bool locked; uint64_t wts; uint64_t rts; uint32_t data_size; char * local_data; }; static bool compare(AccessMVCC * ac1, AccessMVCC * ac2); vector<IndexAccessMVCC> _index_access_set; vector<AccessMVCC> _access_set; vector<AccessMVCC> _remote_set; vector<AccessMVCC *> _read_set; vector<AccessMVCC *> _write_set; AccessMVCC * _last_access; // For the coordinator, _min_commit_ts is the final commit time // For subordinator, it is the minimal commit ts based on local info ////////// Only used in the coordinator struct RemoteNodeInfo { uint32_t node_id; bool readonly; uint64_t commit_ts; }; vector<RemoteNodeInfo> _remote_node_info; AccessMVCC * find_access(uint64_t key, uint32_t table_id, vector<AccessMVCC> * set); void split_read_write_set(); RC lock_write_set(); RC lock_read_set(); void unlock_write_set(RC rc); void unlock_read_set(); void compute_commit_ts(); RC validate_read_set(uint64_t commit_ts); RC validate_write_set(uint64_t commit_ts); RC handle_pre_abort(); bool _write_copy_ptr; static bool _pre_abort; bool _validation_no_wait; bool _atomic_timestamp; uint64_t _max_wts; RC validate_MVCC(); // For OCC_LOCK_TYPE == WAIT_DIE // txn start time, serves as the priority of the txn bool _signal_abort; }; #endif
35.523077
115
0.601776
[ "vector" ]
a167fe1eda5012273fb7fd2af272c17ea196f204
4,577
h
C
Chapter18/Activity18.01/Project/MultiplayerFPS/Source/MultiplayerFPS/FPSCharacter.h
PacktPublishing/Elevating-Game-Experiences-with-Unreal-Engine-5-Second-Edition
f17a52b8e310c981b4750fb7716cc039517b2a38
[ "MIT" ]
41
2020-11-14T07:18:27.000Z
2022-03-28T13:42:02.000Z
Chapter18/Activity18.01/Project/MultiplayerFPS/Source/MultiplayerFPS/FPSCharacter.h
fghaddar/Game-Development-Projects-with-Unreal-Engine
79a987c01dd672b6e8b95bdd15f1d17380044bf8
[ "MIT" ]
null
null
null
Chapter18/Activity18.01/Project/MultiplayerFPS/Source/MultiplayerFPS/FPSCharacter.h
fghaddar/Game-Development-Projects-with-Unreal-Engine
79a987c01dd672b6e8b95bdd15f1d17380044bf8
[ "MIT" ]
23
2021-01-20T07:05:38.000Z
2022-03-15T05:25:54.000Z
#pragma once #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "MultiplayerFPS.h" #include "EnumTypes.h" #include "Camera/CameraComponent.h" #include "Weapon.h" #include "FPSCharacter.generated.h" UCLASS() class MULTIPLAYERFPS_API AFPSCharacter : public ACharacter { GENERATED_BODY() protected: // Components UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "FPS Character") class UCameraComponent* Camera; // Health UPROPERTY(Replicated, BlueprintReadOnly, Category = "FPS Character") float Health = 0.0f; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "FPS Character") float MaxHealth = 100.0f; // Armor UPROPERTY(Replicated, BlueprintReadOnly, Category = "FPS Character") float Armor = 0.0f; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "FPS Character") float MaxArmor = 100.0f; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "FPS Character") float ArmorAbsorption = 0.5; // Ammo UPROPERTY(Replicated, BlueprintReadOnly, Category = "FPS Character") TArray<int32> Ammo; // Weapons UPROPERTY(Replicated, BlueprintReadOnly, Category = "FPS Character") TArray<AWeapon*> Weapons; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "FPS Character") TArray<TSubclassOf<AWeapon>> WeaponClasses; UPROPERTY(Replicated, BlueprintReadOnly, Category = "FPS Character") AWeapon* Weapon; int32 WeaponIndex = INDEX_NONE; // Sounds UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "FPS Character") USoundBase* SpawnSound; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "FPS Character") USoundBase* HitSound; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "FPS Character") USoundBase* WeaponChangeSound; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "FPS Character") USoundBase* PainSound; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "FPS Character") USoundBase* LandSound; // Game Mode UPROPERTY() class AMultiplayerFPSGameModeBase* GameMode; // Constructor and overrided AFPSCharacter(); virtual void BeginPlay() override; virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; virtual void FellOutOfWorld(const UDamageType& DmgType) override; virtual void Landed(const FHitResult& Hit) override; // Input void OnPressedJump(); void OnPressedFire(); void OnReleasedFire(); void OnPressedPistol(); void OnPressedMachineGun(); void OnPressedRailgun(); void OnPressedPreviousWeapon(); void OnPressedNextWeapon(); void OnPressedScoreboard(); void OnAxisMoveForward(float Value); void OnAxisMoveRight(float Value); void OnAxisLookUp(float Value); void OnAxisTurn(float Value); // RPCs UFUNCTION(Server, Reliable) void ServerCycleWeapons(int32 Direction); UFUNCTION(Server, Reliable) void ServerEquipWeapon(EWeaponType WeaponType); // Weapons bool EquipWeapon(EWeaponType WeaponType, bool bPlaySound = true); public: // Damage void ApplyDamage(float Damage, AFPSCharacter* DamageCauser); // RPCs UFUNCTION(NetMulticast, Unreliable) void MulticastPlayAnimMontage(UAnimMontage* AnimMontage); UFUNCTION(Client, Unreliable) void ClientPlaySound2D(USoundBase* Sound); // Health void AddHealth(float Amount) { SetHealth(Health + Amount); } void RemoveHealth(float Amount) { SetHealth(Health - Amount); } void SetHealth(float NewHealth) { Health = FMath::Clamp(NewHealth, 0.0f, MaxHealth); } bool IsDead() const { return Health == 0.0f; } // Armor void AddArmor(float Amount) { SetArmor(Armor + Amount); } void SetArmor(float Amount) { Armor = FMath::Clamp(Amount, 0.0f, MaxArmor); } void ArmorAbsorbDamage(float& Damage); // Weapons void AddWeapon(EWeaponType WeaponType); // Ammo UFUNCTION(BlueprintCallable, Category = "FPS Character") int32 GetWeaponAmmo() const { return Weapon != nullptr ? Ammo[ENUM_TO_INT32(Weapon->GetAmmoType())] : 0; } void AddAmmo(EAmmoType AmmoType, int32 Amount) { SetAmmo(AmmoType, GetAmmo(AmmoType) + Amount); } void ConsumeAmmo(EAmmoType AmmoType, int32 Amount) { SetAmmo(AmmoType, GetAmmo(AmmoType) - Amount); } int32 GetAmmo(EAmmoType AmmoType) const { return Ammo[ENUM_TO_INT32(AmmoType)]; } void SetAmmo(EAmmoType AmmoType, int32 Amount) { Ammo[ENUM_TO_INT32(AmmoType)] = FMath::Max(0, Amount); } // Camera FVector GetCameraLocation() const { return Camera->GetComponentLocation(); } FVector GetCameraDirection() const { return GetControlRotation().Vector(); } };
25.858757
107
0.76513
[ "vector" ]
a2502b7fe09bb9550a238ab83262874aa3e4bbad
776
h
C
aliyun-api-rds_region/2014-08-15/include/ali_rdsregion_add_tags_to_resource_types.h
zcy421593/aliyun-openapi-cpp-sdk
8af0a59dedf303fa6c6911a61c356237fa6105a1
[ "Apache-2.0" ]
1
2015-11-28T16:46:56.000Z
2015-11-28T16:46:56.000Z
aliyun-api-rds_region/2014-08-15/include/ali_rdsregion_add_tags_to_resource_types.h
zcy421593/aliyun-openapi-cpp-sdk
8af0a59dedf303fa6c6911a61c356237fa6105a1
[ "Apache-2.0" ]
null
null
null
aliyun-api-rds_region/2014-08-15/include/ali_rdsregion_add_tags_to_resource_types.h
zcy421593/aliyun-openapi-cpp-sdk
8af0a59dedf303fa6c6911a61c356237fa6105a1
[ "Apache-2.0" ]
null
null
null
#ifndef ALI_RDSREGION_ADD_TAGS_TO_RESOURCE_TYPESH #define ALI_RDSREGION_ADD_TAGS_TO_RESOURCE_TYPESH #include <stdio.h> #include <string> #include <vector> namespace aliyun { struct RdsRegionAddTagsToResourceRequestType { std::string owner_id; std::string resource_owner_account; std::string resource_owner_id; std::string client_token; std::string proxy_id; std::string db_instance_id; std::string tag1key; std::string tag2key; std::string tag3key; std::string tag4key; std::string tag5key; std::string tag1value; std::string tag2value; std::string tag3value; std::string tag4value; std::string tag5value; std::string owner_account; }; struct RdsRegionAddTagsToResourceResponseType { }; } // end namespace #endif
25.866667
50
0.746134
[ "vector" ]
a25316ecfe8a42328f4598a4feedcdd38ecf341c
1,087
h
C
cases/surfers_in_channel_flow_z/param/env/objects/static/surfer__us_0o05__surftimeconst_1o25/group/homogeneous/_member/agent/_behaviour/_sensor/direction/choice.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
cases/surfers_in_channel_flow_z/param/env/objects/static/surfer__us_0o05__surftimeconst_1o25/group/homogeneous/_member/agent/_behaviour/_sensor/direction/choice.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
cases/surfers_in_channel_flow_z/param/env/objects/static/surfer__us_0o05__surftimeconst_1o25/group/homogeneous/_member/agent/_behaviour/_sensor/direction/choice.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
#ifndef C0P_PARAM_OBJECTS_SURFER__US_0O05__SURFTIMECONST_1O25_GROUP_HOMOGENEOUS_MEMBER_AGENT_BEHAVIOUR_SENSOR_DIRECTION_CHOICE_H #define C0P_PARAM_OBJECTS_SURFER__US_0O05__SURFTIMECONST_1O25_GROUP_HOMOGENEOUS_MEMBER_AGENT_BEHAVIOUR_SENSOR_DIRECTION_CHOICE_H #pragma once // THIS FILE SHOULD NOT BE EDITED DIRECTLY BY THE USERS. // THIS FILE WILL BE AUTOMATICALLY EDITED WHEN THE // CHOOSE COMMAND IS USED // choose your behaviour #include "core/env/objects/object/agent/behaviour/sensor/direction/accurate/core.h" #include "param/env/objects/static/surfer__us_0o05__surftimeconst_1o25/group/homogeneous/_member/agent/_behaviour/_sensor/direction/accurate/parameters.h" namespace c0p { template<typename SurferUs0O05Surftimeconst1O25GroupHomogeneousMemberAgentActiveStep> using SurferUs0O05Surftimeconst1O25GroupHomogeneousMemberAgentBehaviourSensorDirection = AgentBehaviourSensorDirectionAccurate<SurferUs0O05Surftimeconst1O25GroupHomogeneousMemberAgentBehaviourSensorDirectionAccurateParameters, SurferUs0O05Surftimeconst1O25GroupHomogeneousMemberAgentActiveStep>; } #endif
60.388889
299
0.895124
[ "object" ]
a25c224cea8f23f5cf52b117ac5e3c5c091afe06
5,280
h
C
OpenSim/Common/Signal.h
MariaHammer/opensim-core_HaeufleMuscle
96257e9449d9ac430bbb54e56cd13aaebeee1242
[ "Apache-2.0" ]
532
2015-03-13T18:51:10.000Z
2022-03-27T08:08:29.000Z
OpenSim/Common/Signal.h
MariaHammer/opensim-core_HaeufleMuscle
96257e9449d9ac430bbb54e56cd13aaebeee1242
[ "Apache-2.0" ]
2,701
2015-01-03T21:33:34.000Z
2022-03-30T07:13:41.000Z
OpenSim/Common/Signal.h
MariaHammer/opensim-core_HaeufleMuscle
96257e9449d9ac430bbb54e56cd13aaebeee1242
[ "Apache-2.0" ]
271
2015-02-16T23:25:29.000Z
2022-03-30T20:12:17.000Z
#ifndef _Signal_h_ #define _Signal_h_ /* -------------------------------------------------------------------------- * * OpenSim: Signal.h * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Frank C. Anderson * * * * 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. * * -------------------------------------------------------------------------- */ /* Note: This code was originally developed by Realistic Dynamics Inc. * Author: Frank C. Anderson */ #include "osimCommonDLL.h" #include <vector> namespace OpenSim { template <class T> class Array; //============================================================================= //============================================================================= /** * A class for signal processing. */ class OSIMCOMMON_API Signal { //============================================================================= // DATA //============================================================================= //============================================================================= // METHODS //============================================================================= public: //-------------------------------------------------------------------------- // CONSTRUCTION //-------------------------------------------------------------------------- //Signal(); //virtual ~Signal(); //-------------------------------------------------------------------------- // FILTERS //-------------------------------------------------------------------------- static int SmoothSpline(int aDegree,double aDeltaT,double aCutOffFrequency, int aN,double *aTimes,double *aSignal,double *rFilteredSignal); static int LowpassIIR(double aDeltaT,double aCutOffFrequency, int aN,const double *aSignal,double *rFilteredSignal); static int LowpassFIR(int aOrder,double aDeltaT,double aCutoffFrequency, int aN,double *aSignal,double *rFilteredSignal); static int BandpassFIR(int aOrder,double aDeltaT, double aLowFrequency,double aHighFrequency, int aN,double *aSignal,double *aFilteredSignal); //-------------------------------------------------------------------------- // PADDING //-------------------------------------------------------------------------- /// Pad a signal with a specified number of data points. /// /// The signal is prepended and appended with a reflected and negated /// portion of the signal of the appropriate size so as to preserve the /// value and slope of the signal. /// /// @param aPad Size of the pad-- number of points to prepend and append. /// @param aN Number of data points in the signal. /// @param aSignal Signal to be padded. /// @return Padded signal. The size is aN + 2*aPad. static std::vector<double> Pad(int aPad, int aN, const double aSignal[]); static void Pad(int aPad, OpenSim::Array<double>& aSignal); //-------------------------------------------------------------------------- // POINT REDUCTION //-------------------------------------------------------------------------- static int ReduceNumberOfPoints(double aDistance, Array<double> &rTime,Array<double> &rSignal); //-------------------------------------------------------------------------- // CORE MATH //-------------------------------------------------------------------------- static double sinc(double x); static double hamming(int k,int M); //============================================================================= }; // END class Signal }; //namespace //============================================================================= //============================================================================= #endif // __Signal_h__
46.725664
80
0.399621
[ "vector" ]
a2654ef1f7aed7a55f6d84f01087a77b01bf1205
4,899
h
C
gdl2/GDL2Testing.h
gnustep/tests-testsuite
204de459e76dba238c5e40cbe78ca715a2523101
[ "FSFUL" ]
null
null
null
gdl2/GDL2Testing.h
gnustep/tests-testsuite
204de459e76dba238c5e40cbe78ca715a2523101
[ "FSFUL" ]
null
null
null
gdl2/GDL2Testing.h
gnustep/tests-testsuite
204de459e76dba238c5e40cbe78ca715a2523101
[ "FSFUL" ]
null
null
null
/* -*-objc-*- */ #ifdef GNUSTEP_TESTING #include <GNUstepBase/GSTesting.h> #else #include "ObjectTesting.h" #endif #include <Foundation/Foundation.h> #include <EOAccess/EOAccess.h> NSString *TSTTradingModelName = @"TSTTradingModel"; static EOAttribute *attributeWith(NSString *name, NSString *columnName, NSString *externalType, NSString *valueClassName) __attribute__ ((unused)); static EOAttribute *attributeWith(NSString *name, NSString *columnName, NSString *externalType, NSString *valueClassName) { EOAttribute *att = [[EOAttribute new] autorelease]; [att setName: name]; [att setColumnName: columnName]; [att setExternalType: externalType]; [att setValueClassName: valueClassName]; return att; } static EOModel *globalModelForKey(NSString *key) __attribute__ ((unused)); static EOModel * globalModelForKey(NSString *key) { static NSMutableDictionary *globalModelDictionary = nil; EOModel *model; if (globalModelDictionary == nil) globalModelDictionary = [NSMutableDictionary new]; model = [globalModelDictionary objectForKey: key]; if (model == nil) { NSString *path = [NSString stringWithFormat: @"../%@", key]; model = [[EOModel alloc] initWithContentsOfFile: path]; if (model) [globalModelDictionary setObject: model forKey: key]; [model release]; } return model; } static void setupModelForAdaptorNamed(EOModel *model, NSString *adaptorName) __attribute__((unused)); static void setupModelForAdaptorNamed(EOModel *model, NSString *adaptorName) { NSString *tmp = [NSString stringWithFormat:@"%@ConnectionDictionary", adaptorName]; [model setConnectionDictionary:[[model userInfo] objectForKey:tmp]]; [model setAdaptorName:adaptorName]; return; } static NSString *setupModel(EOModel *model) __attribute__((unused)); static NSString *setupModel(EOModel *model) { static NSString *adaptorName; if (adaptorName) return adaptorName; adaptorName = [[[NSProcessInfo processInfo] environment] objectForKey:@"TEST_ADAPTOR"]; if (!adaptorName) adaptorName = [[NSUserDefaults standardUserDefaults] stringForKey:@"GDL2TestAdaptorName"]; if (!adaptorName) adaptorName = @"PostgreSQL"; setupModelForAdaptorNamed(model, adaptorName); return adaptorName; } static void createDatabaseWithModel(EOModel *model) __attribute__ ((unused)); static void createDatabaseWithModel(EOModel *model) { NSAutoreleasePool *pool = [NSAutoreleasePool new]; NSArray *entities = [model entities]; EOAdaptor *adaptor = [EOAdaptor adaptorWithModel: model]; EOAdaptorContext *context = [adaptor createAdaptorContext]; EOAdaptorChannel *channel = [context createAdaptorChannel]; Class exprClass = [adaptor expressionClass]; NSDictionary *createOptDict = [NSDictionary dictionaryWithObjectsAndKeys: @"NO", @"EODropTablesKey", @"NO", @"EODropPrimaryKeySupportKey", nil]; NSDictionary *dropOptDict = [NSDictionary dictionaryWithObjectsAndKeys: @"NO", @"EOPrimaryKeyConstraintsKey", @"NO", @"EOCreatePrimaryKeySupportKey", @"NO", @"EOCreateTablesKey", nil]; NSArray *exprs; EOSQLExpression *expr; unsigned i,c; exprs = [exprClass schemaCreationStatementsForEntities: entities options: dropOptDict]; [channel openChannel]; for (i=0, c=[exprs count]; i<c; i++) { expr = [exprs objectAtIndex: i]; NS_DURING { [channel evaluateExpression: expr]; } NS_HANDLER; NS_ENDHANDLER; } exprs = [exprClass schemaCreationStatementsForEntities: entities options: createOptDict]; for (i=0, c=[exprs count]; i<c; i++) { expr = [exprs objectAtIndex: i]; [channel evaluateExpression: expr]; } [channel closeChannel]; [pool release]; } static void dropDatabaseWithModel(EOModel *model) __attribute__ ((unused)); static void dropDatabaseWithModel(EOModel *model) { NSAutoreleasePool *pool = [NSAutoreleasePool new]; NSArray *entities = [model entities]; EOAdaptor *adaptor = [EOAdaptor adaptorWithModel: model]; EOAdaptorContext *context = [adaptor createAdaptorContext]; EOAdaptorChannel *channel = [context createAdaptorChannel]; Class exprClass = [adaptor expressionClass]; NSDictionary *dropOptDict = [NSDictionary dictionaryWithObjectsAndKeys: @"NO", @"EOPrimaryKeyConstraintsKey", @"NO", @"EOCreatePrimaryKeySupportKey", @"NO", @"EOCreateTablesKey", nil]; NSArray *exprs; EOSQLExpression *expr; unsigned i,c; exprs = [exprClass schemaCreationStatementsForEntities: entities options: dropOptDict]; [channel openChannel]; for (i=0, c=[exprs count]; i<c; i++) { expr = [exprs objectAtIndex: i]; NS_DURING { [channel evaluateExpression: expr]; } NS_HANDLER; NS_ENDHANDLER; } [channel closeChannel]; [pool release]; }
28.817647
101
0.712799
[ "model" ]
a26a2aed369b0825a2c19b3b66ad63a79c9dec53
18,110
c
C
binutils-2.21.1/gcc-4.5.1/gcc/tree-ssa-uncprop.c
cberner12/xv6
53c4dfef0d48287ca0d0f9d27eab7a6ed7fee845
[ "MIT-0" ]
null
null
null
binutils-2.21.1/gcc-4.5.1/gcc/tree-ssa-uncprop.c
cberner12/xv6
53c4dfef0d48287ca0d0f9d27eab7a6ed7fee845
[ "MIT-0" ]
null
null
null
binutils-2.21.1/gcc-4.5.1/gcc/tree-ssa-uncprop.c
cberner12/xv6
53c4dfef0d48287ca0d0f9d27eab7a6ed7fee845
[ "MIT-0" ]
null
null
null
/* Routines for discovering and unpropagating edge equivalences. Copyright (C) 2005, 2007, 2008, 2010 Free Software Foundation, Inc. This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "tree.h" #include "flags.h" #include "rtl.h" #include "tm_p.h" #include "ggc.h" #include "basic-block.h" #include "output.h" #include "expr.h" #include "function.h" #include "diagnostic.h" #include "timevar.h" #include "tree-dump.h" #include "tree-flow.h" #include "domwalk.h" #include "real.h" #include "tree-pass.h" #include "tree-ssa-propagate.h" #include "langhooks.h" /* The basic structure describing an equivalency created by traversing an edge. Traversing the edge effectively means that we can assume that we've seen an assignment LHS = RHS. */ struct edge_equivalency { tree rhs; tree lhs; }; /* This routine finds and records edge equivalences for every edge in the CFG. When complete, each edge that creates an equivalency will have an EDGE_EQUIVALENCY structure hanging off the edge's AUX field. The caller is responsible for freeing the AUX fields. */ static void associate_equivalences_with_edges (void) { basic_block bb; /* Walk over each block. If the block ends with a control statement, then it might create a useful equivalence. */ FOR_EACH_BB (bb) { gimple_stmt_iterator gsi = gsi_last_bb (bb); gimple stmt; /* If the block does not end with a COND_EXPR or SWITCH_EXPR then there is nothing to do. */ if (gsi_end_p (gsi)) continue; stmt = gsi_stmt (gsi); if (!stmt) continue; /* A COND_EXPR may create an equivalency in a variety of different ways. */ if (gimple_code (stmt) == GIMPLE_COND) { edge true_edge; edge false_edge; struct edge_equivalency *equivalency; enum tree_code code = gimple_cond_code (stmt); extract_true_false_edges_from_block (bb, &true_edge, &false_edge); /* Equality tests may create one or two equivalences. */ if (code == EQ_EXPR || code == NE_EXPR) { tree op0 = gimple_cond_lhs (stmt); tree op1 = gimple_cond_rhs (stmt); /* Special case comparing booleans against a constant as we know the value of OP0 on both arms of the branch. i.e., we can record an equivalence for OP0 rather than COND. */ if (TREE_CODE (op0) == SSA_NAME && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op0) && TREE_CODE (TREE_TYPE (op0)) == BOOLEAN_TYPE && is_gimple_min_invariant (op1)) { if (code == EQ_EXPR) { equivalency = XNEW (struct edge_equivalency); equivalency->lhs = op0; equivalency->rhs = (integer_zerop (op1) ? boolean_false_node : boolean_true_node); true_edge->aux = equivalency; equivalency = XNEW (struct edge_equivalency); equivalency->lhs = op0; equivalency->rhs = (integer_zerop (op1) ? boolean_true_node : boolean_false_node); false_edge->aux = equivalency; } else { equivalency = XNEW (struct edge_equivalency); equivalency->lhs = op0; equivalency->rhs = (integer_zerop (op1) ? boolean_true_node : boolean_false_node); true_edge->aux = equivalency; equivalency = XNEW (struct edge_equivalency); equivalency->lhs = op0; equivalency->rhs = (integer_zerop (op1) ? boolean_false_node : boolean_true_node); false_edge->aux = equivalency; } } else if (TREE_CODE (op0) == SSA_NAME && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op0) && (is_gimple_min_invariant (op1) || (TREE_CODE (op1) == SSA_NAME && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op1)))) { /* For IEEE, -0.0 == 0.0, so we don't necessarily know the sign of a variable compared against zero. If we're honoring signed zeros, then we cannot record this value unless we know that the value is nonzero. */ if (HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (op0))) && (TREE_CODE (op1) != REAL_CST || REAL_VALUES_EQUAL (dconst0, TREE_REAL_CST (op1)))) continue; equivalency = XNEW (struct edge_equivalency); equivalency->lhs = op0; equivalency->rhs = op1; if (code == EQ_EXPR) true_edge->aux = equivalency; else false_edge->aux = equivalency; } } /* ??? TRUTH_NOT_EXPR can create an equivalence too. */ } /* For a SWITCH_EXPR, a case label which represents a single value and which is the only case label which reaches the target block creates an equivalence. */ else if (gimple_code (stmt) == GIMPLE_SWITCH) { tree cond = gimple_switch_index (stmt); if (TREE_CODE (cond) == SSA_NAME && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (cond)) { int i, n_labels = gimple_switch_num_labels (stmt); tree *info = XCNEWVEC (tree, last_basic_block); /* Walk over the case label vector. Record blocks which are reached by a single case label which represents a single value. */ for (i = 0; i < n_labels; i++) { tree label = gimple_switch_label (stmt, i); basic_block bb = label_to_block (CASE_LABEL (label)); if (CASE_HIGH (label) || !CASE_LOW (label) || info[bb->index]) info[bb->index] = error_mark_node; else info[bb->index] = label; } /* Now walk over the blocks to determine which ones were marked as being reached by a useful case label. */ for (i = 0; i < n_basic_blocks; i++) { tree node = info[i]; if (node != NULL && node != error_mark_node) { tree x = fold_convert (TREE_TYPE (cond), CASE_LOW (node)); struct edge_equivalency *equivalency; /* Record an equivalency on the edge from BB to basic block I. */ equivalency = XNEW (struct edge_equivalency); equivalency->rhs = x; equivalency->lhs = cond; find_edge (bb, BASIC_BLOCK (i))->aux = equivalency; } } free (info); } } } } /* Translating out of SSA sometimes requires inserting copies and constant initializations on edges to eliminate PHI nodes. In some cases those copies and constant initializations are redundant because the target already has the value on the RHS of the assignment. We previously tried to catch these cases after translating out of SSA form. However, that code often missed cases. Worse yet, the cases it missed were also often missed by the RTL optimizers. Thus the resulting code had redundant instructions. This pass attempts to detect these situations before translating out of SSA form. The key concept that this pass is built upon is that these redundant copies and constant initializations often occur due to constant/copy propagating equivalences resulting from COND_EXPRs and SWITCH_EXPRs. We want to do those propagations as they can sometimes allow the SSA optimizers to do a better job. However, in the cases where such propagations do not result in further optimization, we would like to "undo" the propagation to avoid the redundant copies and constant initializations. This pass works by first associating equivalences with edges in the CFG. For example, the edge leading from a SWITCH_EXPR to its associated CASE_LABEL will have an equivalency between SWITCH_COND and the value in the case label. Once we have found the edge equivalences, we proceed to walk the CFG in dominator order. As we traverse edges we record equivalences associated with those edges we traverse. When we encounter a PHI node, we walk its arguments to see if we have an equivalence for the PHI argument. If so, then we replace the argument. Equivalences are looked up based on their value (think of it as the RHS of an assignment). A value may be an SSA_NAME or an invariant. We may have several SSA_NAMEs with the same value, so with each value we have a list of SSA_NAMEs that have the same value. */ /* As we enter each block we record the value for any edge equivalency leading to this block. If no such edge equivalency exists, then we record NULL. These equivalences are live until we leave the dominator subtree rooted at the block where we record the equivalency. */ static VEC(tree,heap) *equiv_stack; /* Global hash table implementing a mapping from invariant values to a list of SSA_NAMEs which have the same value. We might be able to reuse tree-vn for this code. */ static htab_t equiv; /* Main structure for recording equivalences into our hash table. */ struct equiv_hash_elt { /* The value/key of this entry. */ tree value; /* List of SSA_NAMEs which have the same value/key. */ VEC(tree,heap) *equivalences; }; static void uncprop_enter_block (struct dom_walk_data *, basic_block); static void uncprop_leave_block (struct dom_walk_data *, basic_block); static void uncprop_into_successor_phis (basic_block); /* Hashing and equality routines for the hash table. */ static hashval_t equiv_hash (const void *p) { tree const value = ((const struct equiv_hash_elt *)p)->value; return iterative_hash_expr (value, 0); } static int equiv_eq (const void *p1, const void *p2) { tree value1 = ((const struct equiv_hash_elt *)p1)->value; tree value2 = ((const struct equiv_hash_elt *)p2)->value; return operand_equal_p (value1, value2, 0); } /* Free an instance of equiv_hash_elt. */ static void equiv_free (void *p) { struct equiv_hash_elt *elt = (struct equiv_hash_elt *) p; VEC_free (tree, heap, elt->equivalences); free (elt); } /* Remove the most recently recorded equivalency for VALUE. */ static void remove_equivalence (tree value) { struct equiv_hash_elt equiv_hash_elt, *equiv_hash_elt_p; void **slot; equiv_hash_elt.value = value; equiv_hash_elt.equivalences = NULL; slot = htab_find_slot (equiv, &equiv_hash_elt, NO_INSERT); equiv_hash_elt_p = (struct equiv_hash_elt *) *slot; VEC_pop (tree, equiv_hash_elt_p->equivalences); } /* Record EQUIVALENCE = VALUE into our hash table. */ static void record_equiv (tree value, tree equivalence) { struct equiv_hash_elt *equiv_hash_elt; void **slot; equiv_hash_elt = XNEW (struct equiv_hash_elt); equiv_hash_elt->value = value; equiv_hash_elt->equivalences = NULL; slot = htab_find_slot (equiv, equiv_hash_elt, INSERT); if (*slot == NULL) *slot = (void *) equiv_hash_elt; else free (equiv_hash_elt); equiv_hash_elt = (struct equiv_hash_elt *) *slot; VEC_safe_push (tree, heap, equiv_hash_elt->equivalences, equivalence); } /* Main driver for un-cprop. */ static unsigned int tree_ssa_uncprop (void) { struct dom_walk_data walk_data; basic_block bb; associate_equivalences_with_edges (); /* Create our global data structures. */ equiv = htab_create (1024, equiv_hash, equiv_eq, equiv_free); equiv_stack = VEC_alloc (tree, heap, 2); /* We're going to do a dominator walk, so ensure that we have dominance information. */ calculate_dominance_info (CDI_DOMINATORS); /* Setup callbacks for the generic dominator tree walker. */ walk_data.dom_direction = CDI_DOMINATORS; walk_data.initialize_block_local_data = NULL; walk_data.before_dom_children = uncprop_enter_block; walk_data.after_dom_children = uncprop_leave_block; walk_data.global_data = NULL; walk_data.block_local_data_size = 0; /* Now initialize the dominator walker. */ init_walk_dominator_tree (&walk_data); /* Recursively walk the dominator tree undoing unprofitable constant/copy propagations. */ walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR); /* Finalize and clean up. */ fini_walk_dominator_tree (&walk_data); /* EQUIV_STACK should already be empty at this point, so we just need to empty elements out of the hash table, free EQUIV_STACK, and cleanup the AUX field on the edges. */ htab_delete (equiv); VEC_free (tree, heap, equiv_stack); FOR_EACH_BB (bb) { edge e; edge_iterator ei; FOR_EACH_EDGE (e, ei, bb->succs) { if (e->aux) { free (e->aux); e->aux = NULL; } } } return 0; } /* We have finished processing the dominator children of BB, perform any finalization actions in preparation for leaving this node in the dominator tree. */ static void uncprop_leave_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED, basic_block bb ATTRIBUTE_UNUSED) { /* Pop the topmost value off the equiv stack. */ tree value = VEC_pop (tree, equiv_stack); /* If that value was non-null, then pop the topmost equivalency off its equivalency stack. */ if (value != NULL) remove_equivalence (value); } /* Unpropagate values from PHI nodes in successor blocks of BB. */ static void uncprop_into_successor_phis (basic_block bb) { edge e; edge_iterator ei; /* For each successor edge, first temporarily record any equivalence on that edge. Then unpropagate values in any PHI nodes at the destination of the edge. Then remove the temporary equivalence. */ FOR_EACH_EDGE (e, ei, bb->succs) { gimple_seq phis = phi_nodes (e->dest); gimple_stmt_iterator gsi; /* If there are no PHI nodes in this destination, then there is no sense in recording any equivalences. */ if (gimple_seq_empty_p (phis)) continue; /* Record any equivalency associated with E. */ if (e->aux) { struct edge_equivalency *equiv = (struct edge_equivalency *) e->aux; record_equiv (equiv->rhs, equiv->lhs); } /* Walk over the PHI nodes, unpropagating values. */ for (gsi = gsi_start (phis) ; !gsi_end_p (gsi); gsi_next (&gsi)) { gimple phi = gsi_stmt (gsi); tree arg = PHI_ARG_DEF (phi, e->dest_idx); struct equiv_hash_elt equiv_hash_elt; void **slot; /* If the argument is not an invariant, or refers to the same underlying variable as the PHI result, then there's no point in un-propagating the argument. */ if (!is_gimple_min_invariant (arg) && SSA_NAME_VAR (arg) != SSA_NAME_VAR (PHI_RESULT (phi))) continue; /* Lookup this argument's value in the hash table. */ equiv_hash_elt.value = arg; equiv_hash_elt.equivalences = NULL; slot = htab_find_slot (equiv, &equiv_hash_elt, NO_INSERT); if (slot) { struct equiv_hash_elt *elt = (struct equiv_hash_elt *) *slot; int j; /* Walk every equivalence with the same value. If we find one with the same underlying variable as the PHI result, then replace the value in the argument with its equivalent SSA_NAME. Use the most recent equivalence as hopefully that results in shortest lifetimes. */ for (j = VEC_length (tree, elt->equivalences) - 1; j >= 0; j--) { tree equiv = VEC_index (tree, elt->equivalences, j); if (SSA_NAME_VAR (equiv) == SSA_NAME_VAR (PHI_RESULT (phi))) { SET_PHI_ARG_DEF (phi, e->dest_idx, equiv); break; } } } } /* If we had an equivalence associated with this edge, remove it. */ if (e->aux) { struct edge_equivalency *equiv = (struct edge_equivalency *) e->aux; remove_equivalence (equiv->rhs); } } } /* Ignoring loop backedges, if BB has precisely one incoming edge then return that edge. Otherwise return NULL. */ static edge single_incoming_edge_ignoring_loop_edges (basic_block bb) { edge retval = NULL; edge e; edge_iterator ei; FOR_EACH_EDGE (e, ei, bb->preds) { /* A loop back edge can be identified by the destination of the edge dominating the source of the edge. */ if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest)) continue; /* If we have already seen a non-loop edge, then we must have multiple incoming non-loop edges and thus we return NULL. */ if (retval) return NULL; /* This is the first non-loop incoming edge we have found. Record it. */ retval = e; } return retval; } static void uncprop_enter_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED, basic_block bb) { basic_block parent; edge e; bool recorded = false; /* If this block is dominated by a single incoming edge and that edge has an equivalency, then record the equivalency and push the VALUE onto EQUIV_STACK. Else push a NULL entry on EQUIV_STACK. */ parent = get_immediate_dominator (CDI_DOMINATORS, bb); if (parent) { e = single_incoming_edge_ignoring_loop_edges (bb); if (e && e->src == parent && e->aux) { struct edge_equivalency *equiv = (struct edge_equivalency *) e->aux; record_equiv (equiv->rhs, equiv->lhs); VEC_safe_push (tree, heap, equiv_stack, equiv->rhs); recorded = true; } } if (!recorded) VEC_safe_push (tree, heap, equiv_stack, NULL_TREE); uncprop_into_successor_phis (bb); } static bool gate_uncprop (void) { return flag_tree_dom != 0; } struct gimple_opt_pass pass_uncprop = { { GIMPLE_PASS, "uncprop", /* name */ gate_uncprop, /* gate */ tree_ssa_uncprop, /* execute */ NULL, /* sub */ NULL, /* next */ 0, /* static_pass_number */ TV_TREE_SSA_UNCPROP, /* tv_id */ PROP_cfg | PROP_ssa, /* properties_required */ 0, /* properties_provided */ 0, /* properties_destroyed */ 0, /* todo_flags_start */ TODO_dump_func | TODO_verify_ssa /* todo_flags_finish */ } };
29.786184
75
0.686748
[ "vector" ]
a26c1586c028b4118f769178e197b68db4334d91
3,688
h
C
runtime/vm/pointer_tagging.h
n0npax/sdk
b683098fde9611cea472cb081da2cea7ba15bc8b
[ "BSD-3-Clause" ]
1
2021-09-26T13:34:27.000Z
2021-09-26T13:34:27.000Z
runtime/vm/pointer_tagging.h
Hector096/sdk
e7644d9a4c6f400680206f6d03135f24d0480052
[ "BSD-3-Clause" ]
null
null
null
runtime/vm/pointer_tagging.h
Hector096/sdk
e7644d9a4c6f400680206f6d03135f24d0480052
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #ifndef RUNTIME_VM_POINTER_TAGGING_H_ #define RUNTIME_VM_POINTER_TAGGING_H_ #include "platform/assert.h" #include "platform/globals.h" // This header defines constants associated with pointer tagging: // // * which bits determine whether or not this is a Smi value or a heap // pointer; // * which bits determine whether this is a pointer into a new or an old // space. namespace dart { // Dart VM aligns all objects by 2 words in in the old space and misaligns them // in new space. This allows to distinguish new and old pointers by their bits. // // Note: these bits depend on the word size. template <intptr_t word_size, intptr_t word_size_log2> struct ObjectAlignment { // Alignment offsets are used to determine object age. static constexpr intptr_t kNewObjectAlignmentOffset = word_size; static constexpr intptr_t kOldObjectAlignmentOffset = 0; static constexpr intptr_t kNewObjectBitPosition = word_size_log2; // Object sizes are aligned to kObjectAlignment. static constexpr intptr_t kObjectAlignment = 2 * word_size; static constexpr intptr_t kObjectAlignmentLog2 = word_size_log2 + 1; static constexpr intptr_t kObjectAlignmentMask = kObjectAlignment - 1; // Discriminate between true and false based on the alignment bit. static constexpr intptr_t kBoolValueBitPosition = kObjectAlignmentLog2; static constexpr intptr_t kBoolValueMask = 1 << kBoolValueBitPosition; static constexpr intptr_t kTrueOffsetFromNull = kObjectAlignment * 2; static constexpr intptr_t kFalseOffsetFromNull = kObjectAlignment * 3; }; using HostObjectAlignment = ObjectAlignment<kWordSize, kWordSizeLog2>; static constexpr intptr_t kNewObjectAlignmentOffset = HostObjectAlignment::kNewObjectAlignmentOffset; static constexpr intptr_t kOldObjectAlignmentOffset = HostObjectAlignment::kOldObjectAlignmentOffset; static constexpr intptr_t kNewObjectBitPosition = HostObjectAlignment::kNewObjectBitPosition; static constexpr intptr_t kObjectAlignment = HostObjectAlignment::kObjectAlignment; static constexpr intptr_t kObjectAlignmentLog2 = HostObjectAlignment::kObjectAlignmentLog2; static constexpr intptr_t kObjectAlignmentMask = HostObjectAlignment::kObjectAlignmentMask; static constexpr intptr_t kBoolValueBitPosition = HostObjectAlignment::kBoolValueBitPosition; static constexpr intptr_t kBoolValueMask = HostObjectAlignment::kBoolValueMask; static constexpr intptr_t kTrueOffsetFromNull = HostObjectAlignment::kTrueOffsetFromNull; static constexpr intptr_t kFalseOffsetFromNull = HostObjectAlignment::kFalseOffsetFromNull; // The largest value of kObjectAlignment across all configurations. static constexpr intptr_t kMaxObjectAlignment = 16; COMPILE_ASSERT(kMaxObjectAlignment >= kObjectAlignment); // On all targets heap pointers are tagged by set least significant bit. // // To recover address of the actual heap object kHeapObjectTag needs to be // subtracted from the tagged pointer value. // // Smi-s (small integers) have least significant bit cleared. // // To recover the integer value tagged pointer value needs to be shifted // right by kSmiTagShift. enum { kSmiTag = 0, kHeapObjectTag = 1, kSmiTagSize = 1, kSmiTagMask = 1, kSmiTagShift = 1, }; #if !defined(DART_COMPRESSED_POINTERS) static constexpr uintptr_t kHeapBaseMask = 0; #else static constexpr uintptr_t kHeapBaseMask = ~(4LL * GB - 1); #endif } // namespace dart #endif // RUNTIME_VM_POINTER_TAGGING_H_
38.416667
79
0.795553
[ "object" ]
a26dafa9dd783efd7452156c2a966f2e350b1eb4
753
h
C
RealTimeFaceMaskDetector/LogViewer/Filter.h
ita-social-projects/FaceRecognizer-Back-End
50a4ac6ebe602668171c48d38b1e245c250154cc
[ "MIT" ]
1
2021-04-21T11:22:43.000Z
2021-04-21T11:22:43.000Z
RealTimeFaceMaskDetector/LogViewer/Filter.h
ita-social-projects/FaceRecognizer-Back-End
50a4ac6ebe602668171c48d38b1e245c250154cc
[ "MIT" ]
8
2021-02-02T08:41:37.000Z
2021-05-21T02:43:44.000Z
RealTimeFaceMaskDetector/LogViewer/Filter.h
ita-social-projects/FaceRecognizer-Back-End
50a4ac6ebe602668171c48d38b1e245c250154cc
[ "MIT" ]
12
2021-01-25T08:56:52.000Z
2021-07-14T03:43:25.000Z
#ifndef LOGVIEWER_FILTER_H #define LOGVIEWER_FILTER_H #include <string> #include "structures.h" namespace logger { // Class which provides methods to filter logs class Filter { public: Filter(const std::vector<LogOptions>&, const std::string&, const std::string&); Filter() = default; void operator=(const Filter&); bool option_filter(const LogOptions) const; bool from_datetime_filter(DateTime&) const; bool till_datetime_filter(DateTime&) const; void set_options(const std::vector<LogOptions>&); void set_from_datetime(const std::string&); void set_till_datetime(const std::string&); size_t options_size(); private: std::vector<LogOptions> options; DateTime from; DateTime till; }; } #endif // !LOGVIEWER_FILTER_H
23.53125
81
0.743692
[ "vector" ]
a26ed67c7059afbaf656aa814e9df697aee914ec
1,869
h
C
projects/biogears/include/biogears/cdm/utils/testing/SETestCase.h
timhoer/core
f3af359ecdb88b8b8e3b976fa11c3075e0ca7c11
[ "Apache-2.0" ]
null
null
null
projects/biogears/include/biogears/cdm/utils/testing/SETestCase.h
timhoer/core
f3af359ecdb88b8b8e3b976fa11c3075e0ca7c11
[ "Apache-2.0" ]
null
null
null
projects/biogears/include/biogears/cdm/utils/testing/SETestCase.h
timhoer/core
f3af359ecdb88b8b8e3b976fa11c3075e0ca7c11
[ "Apache-2.0" ]
null
null
null
/************************************************************************************** Copyright 2015 Applied Research Associates, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **************************************************************************************/ #pragma once #include <biogears/cdm/properties/SEScalarTime.h> #include <biogears/cdm/utils/testing/SETestErrorStatistics.h> class SETestSuite; CDM_BIND_DECL(TestCase) class BIOGEARS_API SETestCase : public Loggable { friend SETestSuite; protected: SETestCase(Logger* logger); SETestCase(const std::string& name, Logger* logger); public: virtual ~SETestCase(); virtual void Reset(); //reset values virtual void Clear(); //clear memory bool Load(const CDM::TestCase& in); std::unique_ptr<CDM::TestCase> Unload() const; protected: void Unload(CDM::TestCase& data) const; public: void SetName(const std::string& name); std::string GetName() const; SEScalarTime& GetDuration(); void AddFailure(std::stringstream& msg); void AddFailure(const std::string& err); const std::vector<std::string>& GetFailures(); SETestErrorStatistics& CreateErrorStatistic(); const std::vector<SETestErrorStatistics*>& GetErrorStatistics() const; protected: std::string m_Name; SEScalarTime m_Duration; std::vector<std::string> m_Failure; std::vector<SETestErrorStatistics*> m_CaseEqualsErrors; };
33.375
87
0.695024
[ "vector" ]
a2719f65488e883785ccdcf4de49e286bdbb43b2
335,911
c
C
dlls/dinput8/tests/hid.c
besentv/wine
ffea2b95f697074509744b31234e01cba881b421
[ "MIT" ]
null
null
null
dlls/dinput8/tests/hid.c
besentv/wine
ffea2b95f697074509744b31234e01cba881b421
[ "MIT" ]
null
null
null
dlls/dinput8/tests/hid.c
besentv/wine
ffea2b95f697074509744b31234e01cba881b421
[ "MIT" ]
1
2021-02-28T16:20:32.000Z
2021-02-28T16:20:32.000Z
/* * Copyright 2021 Rémi Bernon for CodeWeavers * * 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; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #define DIRECTINPUT_VERSION 0x0800 #include <stdarg.h> #include <stddef.h> #include "ntstatus.h" #define WIN32_NO_STATUS #include "windef.h" #include "winbase.h" #include "winioctl.h" #include "winternl.h" #include "wincrypt.h" #include "winreg.h" #include "winsvc.h" #include "winuser.h" #include "winnls.h" #include "mscat.h" #include "mssip.h" #include "ntsecapi.h" #include "setupapi.h" #include "cfgmgr32.h" #include "newdev.h" #include "objbase.h" #define COBJMACROS #include "wingdi.h" #include "dinput.h" #include "dinputd.h" #include "initguid.h" #include "ddk/wdm.h" #include "ddk/hidclass.h" #include "ddk/hidsdi.h" #include "ddk/hidpi.h" #include "ddk/hidport.h" #include "hidusage.h" #include "devguid.h" #include "wine/test.h" #include "wine/mssign.h" #include "wine/hid.h" #include "driver_hid.h" static HINSTANCE instance; static BOOL localized; /* object names get translated */ #define EXPECT_VIDPID MAKELONG( 0x1209, 0x0001 ) static const WCHAR expect_vidpid_str[] = L"VID_1209&PID_0001"; static const GUID expect_guid_product = {EXPECT_VIDPID,0x0000,0x0000,{0x00,0x00,'P','I','D','V','I','D'}}; static const WCHAR expect_path[] = L"\\\\?\\hid#winetest#1&2fafeb0&"; static const WCHAR expect_path_end[] = L"&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}"; static struct winetest_shared_data *test_data; static HANDLE okfile; static HRESULT (WINAPI *pSignerSign)( SIGNER_SUBJECT_INFO *subject, SIGNER_CERT *cert, SIGNER_SIGNATURE_INFO *signature, SIGNER_PROVIDER_INFO *provider, const WCHAR *timestamp, CRYPT_ATTRIBUTES *attr, void *sip_data ); static const WCHAR container_name[] = L"wine_testsign"; static const CERT_CONTEXT *testsign_sign( const WCHAR *filename ) { BYTE encoded_name[100], encoded_key_id[200], public_key_info_buffer[1000]; BYTE hash_buffer[16], cert_buffer[1000], provider_nameA[100], serial[16]; CERT_PUBLIC_KEY_INFO *public_key_info = (CERT_PUBLIC_KEY_INFO *)public_key_info_buffer; SIGNER_SIGNATURE_INFO signature = {sizeof(SIGNER_SIGNATURE_INFO)}; SIGNER_CERT_STORE_INFO store = {sizeof(SIGNER_CERT_STORE_INFO)}; SIGNER_ATTR_AUTHCODE authcode = {sizeof(SIGNER_ATTR_AUTHCODE)}; SIGNER_SUBJECT_INFO subject = {sizeof(SIGNER_SUBJECT_INFO)}; SIGNER_FILE_INFO file = {sizeof(SIGNER_FILE_INFO)}; SIGNER_CERT signer = {sizeof(SIGNER_CERT)}; CRYPT_KEY_PROV_INFO provider_info = {0}; CRYPT_ALGORITHM_IDENTIFIER algid = {0}; CERT_AUTHORITY_KEY_ID_INFO key_info; HCERTSTORE root_store, pub_store; CERT_INFO cert_info = {0}; WCHAR provider_nameW[100]; const CERT_CONTEXT *cert; CERT_EXTENSION extension; DWORD size, index = 0; HCRYPTPROV provider; HCRYPTKEY key; HRESULT hr; BOOL ret; ret = CryptAcquireContextW( &provider, container_name, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET ); if (!ret && GetLastError() == NTE_EXISTS) { ret = CryptAcquireContextW( &provider, container_name, NULL, PROV_RSA_FULL, CRYPT_DELETEKEYSET ); ok( ret, "Failed to delete container, error %#x\n", GetLastError() ); ret = CryptAcquireContextW( &provider, container_name, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET ); } ok( ret, "Failed to create container, error %#x\n", GetLastError() ); ret = CryptGenKey( provider, AT_SIGNATURE, CRYPT_EXPORTABLE, &key ); ok( ret, "Failed to create key, error %#x\n", GetLastError() ); ret = CryptDestroyKey( key ); ok( ret, "Failed to destroy key, error %#x\n", GetLastError() ); ret = CryptGetUserKey( provider, AT_SIGNATURE, &key ); ok( ret, "Failed to get user key, error %#x\n", GetLastError() ); ret = CryptDestroyKey( key ); ok( ret, "Failed to destroy key, error %#x\n", GetLastError() ); size = sizeof(encoded_name); ret = CertStrToNameW( X509_ASN_ENCODING, L"CN=winetest_cert", CERT_X500_NAME_STR, NULL, encoded_name, &size, NULL ); ok( ret, "Failed to convert name, error %#x\n", GetLastError() ); key_info.CertIssuer.cbData = size; key_info.CertIssuer.pbData = encoded_name; size = sizeof(public_key_info_buffer); ret = CryptExportPublicKeyInfo( provider, AT_SIGNATURE, X509_ASN_ENCODING, public_key_info, &size ); ok( ret, "Failed to export public key, error %#x\n", GetLastError() ); cert_info.SubjectPublicKeyInfo = *public_key_info; size = sizeof(hash_buffer); ret = CryptHashPublicKeyInfo( provider, CALG_MD5, 0, X509_ASN_ENCODING, public_key_info, hash_buffer, &size ); ok( ret, "Failed to hash public key, error %#x\n", GetLastError() ); key_info.KeyId.cbData = size; key_info.KeyId.pbData = hash_buffer; RtlGenRandom( serial, sizeof(serial) ); key_info.CertSerialNumber.cbData = sizeof(serial); key_info.CertSerialNumber.pbData = serial; size = sizeof(encoded_key_id); ret = CryptEncodeObject( X509_ASN_ENCODING, X509_AUTHORITY_KEY_ID, &key_info, encoded_key_id, &size ); ok( ret, "Failed to convert name, error %#x\n", GetLastError() ); extension.pszObjId = (char *)szOID_AUTHORITY_KEY_IDENTIFIER; extension.fCritical = TRUE; extension.Value.cbData = size; extension.Value.pbData = encoded_key_id; cert_info.dwVersion = CERT_V3; cert_info.SerialNumber = key_info.CertSerialNumber; cert_info.SignatureAlgorithm.pszObjId = (char *)szOID_RSA_SHA1RSA; cert_info.Issuer = key_info.CertIssuer; GetSystemTimeAsFileTime( &cert_info.NotBefore ); GetSystemTimeAsFileTime( &cert_info.NotAfter ); cert_info.NotAfter.dwHighDateTime += 1; cert_info.Subject = key_info.CertIssuer; cert_info.cExtension = 1; cert_info.rgExtension = &extension; algid.pszObjId = (char *)szOID_RSA_SHA1RSA; size = sizeof(cert_buffer); ret = CryptSignAndEncodeCertificate( provider, AT_SIGNATURE, X509_ASN_ENCODING, X509_CERT_TO_BE_SIGNED, &cert_info, &algid, NULL, cert_buffer, &size ); ok( ret, "Failed to create certificate, error %#x\n", GetLastError() ); cert = CertCreateCertificateContext( X509_ASN_ENCODING, cert_buffer, size ); ok( !!cert, "Failed to create context, error %#x\n", GetLastError() ); size = sizeof(provider_nameA); ret = CryptGetProvParam( provider, PP_NAME, provider_nameA, &size, 0 ); ok( ret, "Failed to get prov param, error %#x\n", GetLastError() ); MultiByteToWideChar( CP_ACP, 0, (char *)provider_nameA, -1, provider_nameW, ARRAY_SIZE(provider_nameW) ); provider_info.pwszContainerName = (WCHAR *)container_name; provider_info.pwszProvName = provider_nameW; provider_info.dwProvType = PROV_RSA_FULL; provider_info.dwKeySpec = AT_SIGNATURE; ret = CertSetCertificateContextProperty( cert, CERT_KEY_PROV_INFO_PROP_ID, 0, &provider_info ); ok( ret, "Failed to set provider info, error %#x\n", GetLastError() ); ret = CryptReleaseContext( provider, 0 ); ok( ret, "failed to release context, error %u\n", GetLastError() ); root_store = CertOpenStore( CERT_STORE_PROV_SYSTEM_REGISTRY_W, 0, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, L"root" ); if (!root_store && GetLastError() == ERROR_ACCESS_DENIED) { win_skip( "Failed to open root store.\n" ); ret = CertFreeCertificateContext( cert ); ok( ret, "Failed to free certificate, error %u\n", GetLastError() ); return NULL; } ok( !!root_store, "Failed to open store, error %u\n", GetLastError() ); ret = CertAddCertificateContextToStore( root_store, cert, CERT_STORE_ADD_ALWAYS, NULL ); if (!ret && GetLastError() == ERROR_ACCESS_DENIED) { win_skip( "Failed to add self-signed certificate to store.\n" ); ret = CertFreeCertificateContext( cert ); ok( ret, "Failed to free certificate, error %u\n", GetLastError() ); ret = CertCloseStore( root_store, CERT_CLOSE_STORE_CHECK_FLAG ); ok( ret, "Failed to close store, error %u\n", GetLastError() ); return NULL; } ok( ret, "Failed to add certificate, error %u\n", GetLastError() ); ret = CertCloseStore( root_store, CERT_CLOSE_STORE_CHECK_FLAG ); ok( ret, "Failed to close store, error %u\n", GetLastError() ); pub_store = CertOpenStore( CERT_STORE_PROV_SYSTEM_REGISTRY_W, 0, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, L"trustedpublisher" ); ok( !!pub_store, "Failed to open store, error %u\n", GetLastError() ); ret = CertAddCertificateContextToStore( pub_store, cert, CERT_STORE_ADD_ALWAYS, NULL ); ok( ret, "Failed to add certificate, error %u\n", GetLastError() ); ret = CertCloseStore( pub_store, CERT_CLOSE_STORE_CHECK_FLAG ); ok( ret, "Failed to close store, error %u\n", GetLastError() ); subject.dwSubjectChoice = 1; subject.pdwIndex = &index; subject.pSignerFileInfo = &file; file.pwszFileName = (WCHAR *)filename; signer.dwCertChoice = 2; signer.pCertStoreInfo = &store; store.pSigningCert = cert; store.dwCertPolicy = 0; signature.algidHash = CALG_SHA_256; signature.dwAttrChoice = SIGNER_AUTHCODE_ATTR; signature.pAttrAuthcode = &authcode; authcode.pwszName = L""; authcode.pwszInfo = L""; hr = pSignerSign( &subject, &signer, &signature, NULL, NULL, NULL, NULL ); todo_wine ok( hr == S_OK || broken( hr == NTE_BAD_ALGID ) /* < 7 */, "Failed to sign, hr %#x\n", hr ); return cert; } static void testsign_cleanup( const CERT_CONTEXT *cert ) { HCERTSTORE root_store, pub_store; const CERT_CONTEXT *store_cert; HCRYPTPROV provider; BOOL ret; root_store = CertOpenStore( CERT_STORE_PROV_SYSTEM_REGISTRY_W, 0, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, L"root" ); ok( !!root_store, "Failed to open store, error %u\n", GetLastError() ); store_cert = CertFindCertificateInStore( root_store, X509_ASN_ENCODING, 0, CERT_FIND_EXISTING, cert, NULL ); ok( !!store_cert, "Failed to find root certificate, error %u\n", GetLastError() ); ret = CertDeleteCertificateFromStore( store_cert ); ok( ret, "Failed to remove certificate, error %u\n", GetLastError() ); ret = CertCloseStore( root_store, CERT_CLOSE_STORE_CHECK_FLAG ); ok( ret, "Failed to close store, error %u\n", GetLastError() ); pub_store = CertOpenStore( CERT_STORE_PROV_SYSTEM_REGISTRY_W, 0, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, L"trustedpublisher" ); ok( !!pub_store, "Failed to open store, error %u\n", GetLastError() ); store_cert = CertFindCertificateInStore( pub_store, X509_ASN_ENCODING, 0, CERT_FIND_EXISTING, cert, NULL ); ok( !!store_cert, "Failed to find publisher certificate, error %u\n", GetLastError() ); ret = CertDeleteCertificateFromStore( store_cert ); ok( ret, "Failed to remove certificate, error %u\n", GetLastError() ); ret = CertCloseStore( pub_store, CERT_CLOSE_STORE_CHECK_FLAG ); ok( ret, "Failed to close store, error %u\n", GetLastError() ); ret = CertFreeCertificateContext( cert ); ok( ret, "Failed to free certificate, error %u\n", GetLastError() ); ret = CryptAcquireContextW( &provider, container_name, NULL, PROV_RSA_FULL, CRYPT_DELETEKEYSET ); ok( ret, "Failed to delete container, error %#x\n", GetLastError() ); } static void load_resource( const WCHAR *name, WCHAR *filename ) { static WCHAR path[MAX_PATH]; DWORD written; HANDLE file; HRSRC res; void *ptr; GetTempPathW( ARRAY_SIZE(path), path ); GetTempFileNameW( path, name, 0, filename ); file = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0 ); ok( file != INVALID_HANDLE_VALUE, "failed to create %s, error %u\n", debugstr_w(filename), GetLastError() ); res = FindResourceW( NULL, name, L"TESTDLL" ); ok( res != 0, "couldn't find resource\n" ); ptr = LockResource( LoadResource( GetModuleHandleW( NULL ), res ) ); WriteFile( file, ptr, SizeofResource( GetModuleHandleW( NULL ), res ), &written, NULL ); ok( written == SizeofResource( GetModuleHandleW( NULL ), res ), "couldn't write resource\n" ); CloseHandle( file ); } #ifdef __i386__ #define EXT "x86" #elif defined(__x86_64__) #define EXT "amd64" #elif defined(__arm__) #define EXT "arm" #elif defined(__aarch64__) #define EXT "arm64" #else #define EXT #endif static const char inf_text[] = "[Version]\n" "Signature=$Chicago$\n" "ClassGuid={4d36e97d-e325-11ce-bfc1-08002be10318}\n" "CatalogFile=winetest.cat\n" "DriverVer=09/21/2006,6.0.5736.1\n" "[Manufacturer]\n" "Wine=mfg_section,NT" EXT "\n" "[mfg_section.NT" EXT "]\n" "Wine test root driver=device_section,test_hardware_id\n" "[device_section.NT" EXT "]\n" "CopyFiles=file_section\n" "[device_section.NT" EXT ".Services]\n" "AddService=winetest,0x2,svc_section\n" "[file_section]\n" "winetest.sys\n" "[SourceDisksFiles]\n" "winetest.sys=1\n" "[SourceDisksNames]\n" "1=,winetest.sys\n" "[DestinationDirs]\n" "DefaultDestDir=12\n" "[svc_section]\n" "ServiceBinary=%12%\\winetest.sys\n" "ServiceType=1\n" "StartType=3\n" "ErrorControl=1\n" "LoadOrderGroup=Extended Base\n" "DisplayName=\"winetest bus driver\"\n" "; they don't sleep anymore, on the beach\n"; static void add_file_to_catalog( HANDLE catalog, const WCHAR *file ) { SIP_SUBJECTINFO subject_info = {sizeof(SIP_SUBJECTINFO)}; SIP_INDIRECT_DATA *indirect_data; const WCHAR *filepart = file; CRYPTCATMEMBER *member; WCHAR hash_buffer[100]; GUID subject_guid; unsigned int i; DWORD size; BOOL ret; ret = CryptSIPRetrieveSubjectGuidForCatalogFile( file, NULL, &subject_guid ); todo_wine ok( ret, "Failed to get subject guid, error %u\n", GetLastError() ); size = 0; subject_info.pgSubjectType = &subject_guid; subject_info.pwsFileName = file; subject_info.DigestAlgorithm.pszObjId = (char *)szOID_OIWSEC_sha1; subject_info.dwFlags = SPC_INC_PE_RESOURCES_FLAG | SPC_INC_PE_IMPORT_ADDR_TABLE_FLAG | SPC_EXC_PE_PAGE_HASHES_FLAG | 0x10000; ret = CryptSIPCreateIndirectData( &subject_info, &size, NULL ); todo_wine ok( ret, "Failed to get indirect data size, error %u\n", GetLastError() ); indirect_data = malloc( size ); ret = CryptSIPCreateIndirectData( &subject_info, &size, indirect_data ); todo_wine ok( ret, "Failed to get indirect data, error %u\n", GetLastError() ); if (ret) { memset( hash_buffer, 0, sizeof(hash_buffer) ); for (i = 0; i < indirect_data->Digest.cbData; ++i) swprintf( &hash_buffer[i * 2], 2, L"%02X", indirect_data->Digest.pbData[i] ); member = CryptCATPutMemberInfo( catalog, (WCHAR *)file, hash_buffer, &subject_guid, 0, size, (BYTE *)indirect_data ); ok( !!member, "Failed to write member, error %u\n", GetLastError() ); if (wcsrchr( file, '\\' )) filepart = wcsrchr( file, '\\' ) + 1; ret = !!CryptCATPutAttrInfo( catalog, member, (WCHAR *)L"File", CRYPTCAT_ATTR_NAMEASCII | CRYPTCAT_ATTR_DATAASCII | CRYPTCAT_ATTR_AUTHENTICATED, (wcslen( filepart ) + 1) * 2, (BYTE *)filepart ); ok( ret, "Failed to write attr, error %u\n", GetLastError() ); ret = !!CryptCATPutAttrInfo( catalog, member, (WCHAR *)L"OSAttr", CRYPTCAT_ATTR_NAMEASCII | CRYPTCAT_ATTR_DATAASCII | CRYPTCAT_ATTR_AUTHENTICATED, sizeof(L"2:6.0"), (BYTE *)L"2:6.0" ); ok( ret, "Failed to write attr, error %u\n", GetLastError() ); } } static void unload_driver( SC_HANDLE service ) { SERVICE_STATUS status; ControlService( service, SERVICE_CONTROL_STOP, &status ); while (status.dwCurrentState == SERVICE_STOP_PENDING) { BOOL ret; Sleep( 100 ); ret = QueryServiceStatus( service, &status ); ok( ret, "QueryServiceStatus failed: %u\n", GetLastError() ); } ok( status.dwCurrentState == SERVICE_STOPPED, "expected SERVICE_STOPPED, got %d\n", status.dwCurrentState ); DeleteService( service ); CloseServiceHandle( service ); } static void pnp_driver_stop(void) { SP_DEVINFO_DATA device = {sizeof(SP_DEVINFO_DATA)}; WCHAR path[MAX_PATH], dest[MAX_PATH], *filepart; SC_HANDLE manager, service; char buffer[512]; HDEVINFO set; HANDLE file; DWORD size; BOOL ret; set = SetupDiCreateDeviceInfoList( NULL, NULL ); ok( set != INVALID_HANDLE_VALUE, "failed to create device list, error %u\n", GetLastError() ); ret = SetupDiOpenDeviceInfoW( set, L"root\\winetest\\0", NULL, 0, &device ); if (!ret && GetLastError() == ERROR_NO_SUCH_DEVINST) { ret = SetupDiDestroyDeviceInfoList( set ); ok( ret, "failed to destroy set, error %u\n", GetLastError() ); return; } ok( ret, "failed to open device, error %u\n", GetLastError() ); ret = SetupDiCallClassInstaller( DIF_REMOVE, set, &device ); ok( ret, "failed to remove device, error %u\n", GetLastError() ); file = CreateFileW( L"\\\\?\\root#winetest#0#{deadbeef-29ef-4538-a5fd-b69573a362c0}", 0, 0, NULL, OPEN_EXISTING, 0, NULL ); ok( file == INVALID_HANDLE_VALUE, "expected failure\n" ); ok( GetLastError() == ERROR_FILE_NOT_FOUND, "got error %u\n", GetLastError() ); ret = SetupDiDestroyDeviceInfoList( set ); ok( ret, "failed to destroy set, error %u\n", GetLastError() ); /* Windows stops the service but does not delete it. */ manager = OpenSCManagerW( NULL, NULL, SC_MANAGER_CONNECT ); ok( !!manager, "failed to open service manager, error %u\n", GetLastError() ); service = OpenServiceW( manager, L"winetest", SERVICE_STOP | DELETE ); if (service) unload_driver( service ); else ok( GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST, "got error %u\n", GetLastError() ); CloseServiceHandle( manager ); SetFilePointer( okfile, 0, NULL, FILE_BEGIN ); do { ReadFile( okfile, buffer, sizeof(buffer), &size, NULL ); printf( "%.*s", size, buffer ); } while (size == sizeof(buffer)); SetFilePointer( okfile, 0, NULL, FILE_BEGIN ); SetEndOfFile( okfile ); winetest_add_failures( InterlockedExchange( &test_data->failures, 0 ) ); winetest_add_failures( InterlockedExchange( &test_data->todo_failures, 0 ) ); GetFullPathNameW( L"winetest.inf", ARRAY_SIZE(path), path, NULL ); ret = SetupCopyOEMInfW( path, NULL, 0, 0, dest, ARRAY_SIZE(dest), NULL, &filepart ); ok( ret, "Failed to copy INF, error %u\n", GetLastError() ); ret = SetupUninstallOEMInfW( filepart, 0, NULL ); ok( ret, "Failed to uninstall INF, error %u\n", GetLastError() ); ret = DeleteFileW( L"winetest.cat" ); ok( ret, "Failed to delete file, error %u\n", GetLastError() ); ret = DeleteFileW( L"winetest.inf" ); ok( ret, "Failed to delete file, error %u\n", GetLastError() ); ret = DeleteFileW( L"winetest.sys" ); ok( ret, "Failed to delete file, error %u\n", GetLastError() ); /* Windows 10 apparently deletes the image in SetupUninstallOEMInf(). */ ret = DeleteFileW( L"C:/windows/system32/drivers/winetest.sys" ); ok( ret || GetLastError() == ERROR_FILE_NOT_FOUND, "Failed to delete file, error %u\n", GetLastError() ); } static BOOL pnp_driver_start( const WCHAR *resource ) { static const WCHAR hardware_id[] = L"test_hardware_id\0"; SP_DEVINFO_DATA device = {sizeof(SP_DEVINFO_DATA)}; WCHAR path[MAX_PATH], filename[MAX_PATH]; SC_HANDLE manager, service; const CERT_CONTEXT *cert; int old_mute_threshold; BOOL ret, need_reboot; HANDLE catalog; HDEVINFO set; FILE *f; old_mute_threshold = winetest_mute_threshold; winetest_mute_threshold = 1; load_resource( resource, filename ); ret = MoveFileExW( filename, L"winetest.sys", MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING ); ok( ret, "failed to move file, error %u\n", GetLastError() ); f = fopen( "winetest.inf", "w" ); ok( !!f, "failed to open winetest.inf: %s\n", strerror( errno ) ); fputs( inf_text, f ); fclose( f ); /* Create the catalog file. */ catalog = CryptCATOpen( (WCHAR *)L"winetest.cat", CRYPTCAT_OPEN_CREATENEW, 0, CRYPTCAT_VERSION_1, 0 ); ok( catalog != INVALID_HANDLE_VALUE, "Failed to create catalog, error %u\n", GetLastError() ); add_file_to_catalog( catalog, L"winetest.sys" ); add_file_to_catalog( catalog, L"winetest.inf" ); ret = CryptCATPersistStore( catalog ); todo_wine ok( ret, "Failed to write catalog, error %u\n", GetLastError() ); ret = CryptCATClose( catalog ); ok( ret, "Failed to close catalog, error %u\n", GetLastError() ); if (!(cert = testsign_sign( L"winetest.cat" ))) { ret = DeleteFileW( L"winetest.cat" ); ok( ret, "Failed to delete file, error %u\n", GetLastError() ); ret = DeleteFileW( L"winetest.inf" ); ok( ret, "Failed to delete file, error %u\n", GetLastError() ); ret = DeleteFileW( L"winetest.sys" ); ok( ret, "Failed to delete file, error %u\n", GetLastError() ); winetest_mute_threshold = old_mute_threshold; return FALSE; } /* Install the driver. */ set = SetupDiCreateDeviceInfoList( NULL, NULL ); ok( set != INVALID_HANDLE_VALUE, "failed to create device list, error %u\n", GetLastError() ); ret = SetupDiCreateDeviceInfoW( set, L"root\\winetest\\0", &GUID_NULL, NULL, NULL, 0, &device ); ok( ret, "failed to create device, error %#x\n", GetLastError() ); ret = SetupDiSetDeviceRegistryPropertyW( set, &device, SPDRP_HARDWAREID, (const BYTE *)hardware_id, sizeof(hardware_id) ); ok( ret, "failed to create set hardware ID, error %u\n", GetLastError() ); ret = SetupDiCallClassInstaller( DIF_REGISTERDEVICE, set, &device ); ok( ret, "failed to register device, error %u\n", GetLastError() ); ret = SetupDiDestroyDeviceInfoList( set ); ok( ret, "failed to destroy set, error %u\n", GetLastError() ); GetFullPathNameW( L"winetest.inf", ARRAY_SIZE(path), path, NULL ); ret = UpdateDriverForPlugAndPlayDevicesW( NULL, hardware_id, path, INSTALLFLAG_FORCE, &need_reboot ); ok( ret, "failed to install device, error %u\n", GetLastError() ); ok( !need_reboot, "expected no reboot necessary\n" ); testsign_cleanup( cert ); /* Check that the service is created and started. */ manager = OpenSCManagerW( NULL, NULL, SC_MANAGER_CONNECT ); ok( !!manager, "failed to open service manager, error %u\n", GetLastError() ); service = OpenServiceW( manager, L"winetest", SERVICE_START ); ok( !!service, "failed to open service, error %u\n", GetLastError() ); ret = StartServiceW( service, 0, NULL ); ok( !ret, "service didn't start automatically\n" ); if (!ret && GetLastError() != ERROR_SERVICE_ALREADY_RUNNING) { /* If Secure Boot is enabled or the machine is 64-bit, it will reject an unsigned driver. */ ok( GetLastError() == ERROR_DRIVER_BLOCKED || GetLastError() == ERROR_INVALID_IMAGE_HASH, "unexpected error %u\n", GetLastError() ); win_skip( "Failed to start service; probably your machine doesn't accept unsigned drivers.\n" ); } CloseServiceHandle( service ); CloseServiceHandle( manager ); winetest_mute_threshold = old_mute_threshold; return ret || GetLastError() == ERROR_SERVICE_ALREADY_RUNNING; } #define check_member_( file, line, val, exp, fmt, member ) \ ok_( file, line )((val).member == (exp).member, "got " #member " " fmt ", expected " fmt "\n", \ (val).member, (exp).member) #define check_member( val, exp, fmt, member ) \ check_member_( __FILE__, __LINE__, val, exp, fmt, member ) #define check_member_guid_( file, line, val, exp, member ) \ ok_( file, line )(IsEqualGUID( &(val).member, &(exp).member ), "got " #member " %s, expected %s\n", \ debugstr_guid( &(val).member ), debugstr_guid( &(exp).member )) #define check_member_guid( val, exp, member ) \ check_member_guid_( __FILE__, __LINE__, val, exp, member ) #define check_member_wstr_( file, line, val, exp, member ) \ ok_( file, line )(!wcscmp( (val).member, (exp).member ), "got " #member " %s, expected %s\n", \ debugstr_w((val).member), debugstr_w((exp).member)) #define check_member_wstr( val, exp, member ) \ check_member_wstr_( __FILE__, __LINE__, val, exp, member ) #define check_hidp_caps( a, b ) check_hidp_caps_( __LINE__, a, b ) static inline void check_hidp_caps_( int line, HIDP_CAPS *caps, const HIDP_CAPS *exp ) { check_member_( __FILE__, line, *caps, *exp, "%04x", Usage ); check_member_( __FILE__, line, *caps, *exp, "%04x", UsagePage ); check_member_( __FILE__, line, *caps, *exp, "%d", InputReportByteLength ); check_member_( __FILE__, line, *caps, *exp, "%d", OutputReportByteLength ); check_member_( __FILE__, line, *caps, *exp, "%d", FeatureReportByteLength ); check_member_( __FILE__, line, *caps, *exp, "%d", NumberLinkCollectionNodes ); check_member_( __FILE__, line, *caps, *exp, "%d", NumberInputButtonCaps ); check_member_( __FILE__, line, *caps, *exp, "%d", NumberInputValueCaps ); check_member_( __FILE__, line, *caps, *exp, "%d", NumberInputDataIndices ); check_member_( __FILE__, line, *caps, *exp, "%d", NumberOutputButtonCaps ); check_member_( __FILE__, line, *caps, *exp, "%d", NumberOutputValueCaps ); check_member_( __FILE__, line, *caps, *exp, "%d", NumberOutputDataIndices ); check_member_( __FILE__, line, *caps, *exp, "%d", NumberFeatureButtonCaps ); check_member_( __FILE__, line, *caps, *exp, "%d", NumberFeatureValueCaps ); check_member_( __FILE__, line, *caps, *exp, "%d", NumberFeatureDataIndices ); } #define check_hidp_link_collection_node( a, b ) check_hidp_link_collection_node_( __LINE__, a, b ) static inline void check_hidp_link_collection_node_( int line, HIDP_LINK_COLLECTION_NODE *node, const HIDP_LINK_COLLECTION_NODE *exp ) { check_member_( __FILE__, line, *node, *exp, "%04x", LinkUsage ); check_member_( __FILE__, line, *node, *exp, "%04x", LinkUsagePage ); check_member_( __FILE__, line, *node, *exp, "%d", Parent ); check_member_( __FILE__, line, *node, *exp, "%d", NumberOfChildren ); check_member_( __FILE__, line, *node, *exp, "%d", NextSibling ); check_member_( __FILE__, line, *node, *exp, "%d", FirstChild ); check_member_( __FILE__, line, *node, *exp, "%d", CollectionType ); check_member_( __FILE__, line, *node, *exp, "%d", IsAlias ); } #define check_hidp_button_caps( a, b ) check_hidp_button_caps_( __LINE__, a, b ) static inline void check_hidp_button_caps_( int line, HIDP_BUTTON_CAPS *caps, const HIDP_BUTTON_CAPS *exp ) { check_member_( __FILE__, line, *caps, *exp, "%04x", UsagePage ); check_member_( __FILE__, line, *caps, *exp, "%d", ReportID ); check_member_( __FILE__, line, *caps, *exp, "%d", IsAlias ); check_member_( __FILE__, line, *caps, *exp, "%d", BitField ); check_member_( __FILE__, line, *caps, *exp, "%d", LinkCollection ); check_member_( __FILE__, line, *caps, *exp, "%04x", LinkUsage ); check_member_( __FILE__, line, *caps, *exp, "%04x", LinkUsagePage ); check_member_( __FILE__, line, *caps, *exp, "%d", IsRange ); check_member_( __FILE__, line, *caps, *exp, "%d", IsStringRange ); check_member_( __FILE__, line, *caps, *exp, "%d", IsDesignatorRange ); check_member_( __FILE__, line, *caps, *exp, "%d", IsAbsolute ); if (!caps->IsRange && !exp->IsRange) { check_member_( __FILE__, line, *caps, *exp, "%04x", NotRange.Usage ); check_member_( __FILE__, line, *caps, *exp, "%d", NotRange.DataIndex ); } else if (caps->IsRange && exp->IsRange) { check_member_( __FILE__, line, *caps, *exp, "%04x", Range.UsageMin ); check_member_( __FILE__, line, *caps, *exp, "%04x", Range.UsageMax ); check_member_( __FILE__, line, *caps, *exp, "%d", Range.DataIndexMin ); check_member_( __FILE__, line, *caps, *exp, "%d", Range.DataIndexMax ); } if (!caps->IsRange && !exp->IsRange) check_member_( __FILE__, line, *caps, *exp, "%d", NotRange.StringIndex ); else if (caps->IsStringRange && exp->IsStringRange) { check_member_( __FILE__, line, *caps, *exp, "%d", Range.StringMin ); check_member_( __FILE__, line, *caps, *exp, "%d", Range.StringMax ); } if (!caps->IsDesignatorRange && !exp->IsDesignatorRange) check_member_( __FILE__, line, *caps, *exp, "%d", NotRange.DesignatorIndex ); else if (caps->IsDesignatorRange && exp->IsDesignatorRange) { check_member_( __FILE__, line, *caps, *exp, "%d", Range.DesignatorMin ); check_member_( __FILE__, line, *caps, *exp, "%d", Range.DesignatorMax ); } } #define check_hidp_value_caps( a, b ) check_hidp_value_caps_( __LINE__, a, b ) static inline void check_hidp_value_caps_( int line, HIDP_VALUE_CAPS *caps, const HIDP_VALUE_CAPS *exp ) { check_member_( __FILE__, line, *caps, *exp, "%04x", UsagePage ); check_member_( __FILE__, line, *caps, *exp, "%d", ReportID ); check_member_( __FILE__, line, *caps, *exp, "%d", IsAlias ); check_member_( __FILE__, line, *caps, *exp, "%d", BitField ); check_member_( __FILE__, line, *caps, *exp, "%d", LinkCollection ); check_member_( __FILE__, line, *caps, *exp, "%d", LinkUsage ); check_member_( __FILE__, line, *caps, *exp, "%d", LinkUsagePage ); check_member_( __FILE__, line, *caps, *exp, "%d", IsRange ); check_member_( __FILE__, line, *caps, *exp, "%d", IsStringRange ); check_member_( __FILE__, line, *caps, *exp, "%d", IsDesignatorRange ); check_member_( __FILE__, line, *caps, *exp, "%d", IsAbsolute ); check_member_( __FILE__, line, *caps, *exp, "%d", HasNull ); check_member_( __FILE__, line, *caps, *exp, "%d", BitSize ); check_member_( __FILE__, line, *caps, *exp, "%d", ReportCount ); check_member_( __FILE__, line, *caps, *exp, "%d", UnitsExp ); check_member_( __FILE__, line, *caps, *exp, "%d", Units ); check_member_( __FILE__, line, *caps, *exp, "%d", LogicalMin ); check_member_( __FILE__, line, *caps, *exp, "%d", LogicalMax ); check_member_( __FILE__, line, *caps, *exp, "%d", PhysicalMin ); check_member_( __FILE__, line, *caps, *exp, "%d", PhysicalMax ); if (!caps->IsRange && !exp->IsRange) { check_member_( __FILE__, line, *caps, *exp, "%04x", NotRange.Usage ); check_member_( __FILE__, line, *caps, *exp, "%d", NotRange.DataIndex ); } else if (caps->IsRange && exp->IsRange) { check_member_( __FILE__, line, *caps, *exp, "%04x", Range.UsageMin ); check_member_( __FILE__, line, *caps, *exp, "%04x", Range.UsageMax ); check_member_( __FILE__, line, *caps, *exp, "%d", Range.DataIndexMin ); check_member_( __FILE__, line, *caps, *exp, "%d", Range.DataIndexMax ); } if (!caps->IsRange && !exp->IsRange) check_member_( __FILE__, line, *caps, *exp, "%d", NotRange.StringIndex ); else if (caps->IsStringRange && exp->IsStringRange) { check_member_( __FILE__, line, *caps, *exp, "%d", Range.StringMin ); check_member_( __FILE__, line, *caps, *exp, "%d", Range.StringMax ); } if (!caps->IsDesignatorRange && !exp->IsDesignatorRange) check_member_( __FILE__, line, *caps, *exp, "%d", NotRange.DesignatorIndex ); else if (caps->IsDesignatorRange && exp->IsDesignatorRange) { check_member_( __FILE__, line, *caps, *exp, "%d", Range.DesignatorMin ); check_member_( __FILE__, line, *caps, *exp, "%d", Range.DesignatorMax ); } } static BOOL sync_ioctl( HANDLE file, DWORD code, void *in_buf, DWORD in_len, void *out_buf, DWORD *ret_len ) { OVERLAPPED ovl = {0}; DWORD out_len = ret_len ? *ret_len : 0; BOOL ret; ovl.hEvent = CreateEventW( NULL, TRUE, FALSE, NULL ); ret = DeviceIoControl( file, code, in_buf, in_len, out_buf, out_len, &out_len, &ovl ); if (!ret && GetLastError() == ERROR_IO_PENDING) ret = GetOverlappedResult( file, &ovl, &out_len, TRUE ); CloseHandle( ovl.hEvent ); if (ret_len) *ret_len = out_len; return ret; } #define set_hid_expect( a, b, c ) set_hid_expect_( __LINE__, a, b, c ) static void set_hid_expect_( int line, HANDLE file, struct hid_expect *expect, DWORD expect_size ) { const char *source_file; BOOL ret; int i; source_file = strrchr( __FILE__, '/' ); if (!source_file) source_file = strrchr( __FILE__, '\\' ); if (!source_file) source_file = __FILE__; else source_file++; for (i = 0; i < expect_size / sizeof(struct hid_expect); ++i) snprintf( expect[i].context, ARRAY_SIZE(expect[i].context), "%s:%d", source_file, line ); ret = sync_ioctl( file, IOCTL_WINETEST_HID_SET_EXPECT, expect, expect_size, NULL, 0 ); ok( ret, "IOCTL_WINETEST_HID_SET_EXPECT failed, last error %u\n", GetLastError() ); } #define send_hid_input( a, b, c ) send_hid_input_( __LINE__, a, b, c ) static void send_hid_input_( int line, HANDLE file, struct hid_expect *expect, DWORD expect_size ) { const char *source_file; BOOL ret; int i; source_file = strrchr( __FILE__, '/' ); if (!source_file) source_file = strrchr( __FILE__, '\\' ); if (!source_file) source_file = __FILE__; else source_file++; for (i = 0; i < expect_size / sizeof(struct hid_expect); ++i) snprintf( expect[i].context, ARRAY_SIZE(expect[i].context), "%s:%d", source_file, line ); ret = sync_ioctl( file, IOCTL_WINETEST_HID_SEND_INPUT, expect, expect_size, NULL, 0 ); ok( ret, "IOCTL_WINETEST_HID_SEND_INPUT failed, last error %u\n", GetLastError() ); } static void test_hidp_get_input( HANDLE file, int report_id, ULONG report_len, PHIDP_PREPARSED_DATA preparsed ) { struct hid_expect expect[] = { { .code = IOCTL_HID_GET_INPUT_REPORT, .report_id = report_id, .report_len = report_len - (report_id ? 0 : 1), .report_buf = {report_id ? report_id : 0xa5,0xa5,2}, .ret_length = 3, .ret_status = STATUS_SUCCESS, }, { .code = IOCTL_HID_GET_INPUT_REPORT, .report_id = report_id, .report_len = 2 * report_len - (report_id ? 0 : 1), .report_buf = {report_id ? report_id : 0xa5,0xa5,1}, .ret_length = 3, .ret_status = STATUS_SUCCESS, }, }; char buffer[200], report[200]; NTSTATUS status; ULONG length; BOOL ret; memset( report, 0xcd, sizeof(report) ); status = HidP_InitializeReportForID( HidP_Input, report_id, preparsed, report, report_len ); ok( status == HIDP_STATUS_SUCCESS, "HidP_InitializeReportForID returned %#x\n", status ); SetLastError( 0xdeadbeef ); ret = HidD_GetInputReport( file, report, 0 ); ok( !ret, "HidD_GetInputReport succeeded\n" ); ok( GetLastError() == ERROR_INVALID_USER_BUFFER, "HidD_GetInputReport returned error %u\n", GetLastError() ); SetLastError( 0xdeadbeef ); ret = HidD_GetInputReport( file, report, report_len - 1 ); ok( !ret, "HidD_GetInputReport succeeded\n" ); ok( GetLastError() == ERROR_INVALID_PARAMETER || broken( GetLastError() == ERROR_CRC ), "HidD_GetInputReport returned error %u\n", GetLastError() ); if (!report_id) { struct hid_expect broken_expect = { .code = IOCTL_HID_GET_INPUT_REPORT, .broken = TRUE, .report_len = report_len - 1, .report_buf = { 0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a, 0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a, 0x5a,0x5a,0x5a,0x5a,0x5a, }, .ret_length = 3, .ret_status = STATUS_SUCCESS, }; set_hid_expect( file, &broken_expect, sizeof(broken_expect) ); } SetLastError( 0xdeadbeef ); memset( buffer, 0x5a, sizeof(buffer) ); ret = HidD_GetInputReport( file, buffer, report_len ); if (report_id || broken( !ret ) /* w7u */) { ok( !ret, "HidD_GetInputReport succeeded, last error %u\n", GetLastError() ); ok( GetLastError() == ERROR_INVALID_PARAMETER || broken( GetLastError() == ERROR_CRC ), "HidD_GetInputReport returned error %u\n", GetLastError() ); } else { ok( ret, "HidD_GetInputReport failed, last error %u\n", GetLastError() ); ok( buffer[0] == 0x5a, "got buffer[0] %x, expected 0x5a\n", (BYTE)buffer[0] ); } set_hid_expect( file, expect, sizeof(expect) ); SetLastError( 0xdeadbeef ); ret = HidD_GetInputReport( file, report, report_len ); ok( ret, "HidD_GetInputReport failed, last error %u\n", GetLastError() ); ok( report[0] == report_id, "got report[0] %02x, expected %02x\n", report[0], report_id ); SetLastError( 0xdeadbeef ); length = report_len * 2; ret = sync_ioctl( file, IOCTL_HID_GET_INPUT_REPORT, NULL, 0, report, &length ); ok( ret, "IOCTL_HID_GET_INPUT_REPORT failed, last error %u\n", GetLastError() ); ok( length == 3, "got length %u, expected 3\n", length ); ok( report[0] == report_id, "got report[0] %02x, expected %02x\n", report[0], report_id ); set_hid_expect( file, NULL, 0 ); } static void test_hidp_get_feature( HANDLE file, int report_id, ULONG report_len, PHIDP_PREPARSED_DATA preparsed ) { struct hid_expect expect[] = { { .code = IOCTL_HID_GET_FEATURE, .report_id = report_id, .report_len = report_len - (report_id ? 0 : 1), .report_buf = {report_id ? report_id : 0xa5,0xa5,0xa5}, .ret_length = 3, .ret_status = STATUS_SUCCESS, }, { .code = IOCTL_HID_GET_FEATURE, .report_id = report_id, .report_len = 2 * report_len - (report_id ? 0 : 1), .report_buf = {report_id ? report_id : 0xa5,0xa5,0xa5}, .ret_length = 3, .ret_status = STATUS_SUCCESS, }, }; char buffer[200], report[200]; NTSTATUS status; ULONG length; BOOL ret; memset( report, 0xcd, sizeof(report) ); status = HidP_InitializeReportForID( HidP_Feature, report_id, preparsed, report, report_len ); ok( status == HIDP_STATUS_SUCCESS, "HidP_InitializeReportForID returned %#x\n", status ); SetLastError( 0xdeadbeef ); ret = HidD_GetFeature( file, report, 0 ); ok( !ret, "HidD_GetFeature succeeded\n" ); ok( GetLastError() == ERROR_INVALID_USER_BUFFER, "HidD_GetFeature returned error %u\n", GetLastError() ); SetLastError( 0xdeadbeef ); ret = HidD_GetFeature( file, report, report_len - 1 ); ok( !ret, "HidD_GetFeature succeeded\n" ); ok( GetLastError() == ERROR_INVALID_PARAMETER || broken( GetLastError() == ERROR_CRC ), "HidD_GetFeature returned error %u\n", GetLastError() ); if (!report_id) { struct hid_expect broken_expect = { .code = IOCTL_HID_GET_FEATURE, .broken = TRUE, .report_len = report_len - 1, .report_buf = { 0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a, 0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a, 0x5a,0x5a,0x5a,0x5a,0x5a, }, .ret_length = 3, .ret_status = STATUS_SUCCESS, }; set_hid_expect( file, &broken_expect, sizeof(broken_expect) ); } SetLastError( 0xdeadbeef ); memset( buffer, 0x5a, sizeof(buffer) ); ret = HidD_GetFeature( file, buffer, report_len ); if (report_id || broken( !ret )) { ok( !ret, "HidD_GetFeature succeeded, last error %u\n", GetLastError() ); ok( GetLastError() == ERROR_INVALID_PARAMETER || broken( GetLastError() == ERROR_CRC ), "HidD_GetFeature returned error %u\n", GetLastError() ); } else { ok( ret, "HidD_GetFeature failed, last error %u\n", GetLastError() ); ok( buffer[0] == 0x5a, "got buffer[0] %x, expected 0x5a\n", (BYTE)buffer[0] ); } set_hid_expect( file, expect, sizeof(expect) ); SetLastError( 0xdeadbeef ); ret = HidD_GetFeature( file, report, report_len ); ok( ret, "HidD_GetFeature failed, last error %u\n", GetLastError() ); ok( report[0] == report_id, "got report[0] %02x, expected %02x\n", report[0], report_id ); length = report_len * 2; SetLastError( 0xdeadbeef ); ret = sync_ioctl( file, IOCTL_HID_GET_FEATURE, NULL, 0, report, &length ); ok( ret, "IOCTL_HID_GET_FEATURE failed, last error %u\n", GetLastError() ); ok( length == 3, "got length %u, expected 3\n", length ); ok( report[0] == report_id, "got report[0] %02x, expected %02x\n", report[0], report_id ); set_hid_expect( file, NULL, 0 ); } static void test_hidp_set_feature( HANDLE file, int report_id, ULONG report_len, PHIDP_PREPARSED_DATA preparsed ) { struct hid_expect expect[] = { { .code = IOCTL_HID_SET_FEATURE, .report_id = report_id, .report_len = report_len - (report_id ? 0 : 1), .report_buf = {report_id}, .ret_length = 3, .ret_status = STATUS_SUCCESS, }, { .code = IOCTL_HID_SET_FEATURE, .report_id = report_id, .report_len = report_len - (report_id ? 0 : 1), .report_buf = { report_id,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd, 0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd,0xcd, }, .ret_length = 3, .ret_status = STATUS_SUCCESS, }, }; char buffer[200], report[200]; NTSTATUS status; ULONG length; BOOL ret; memset( report, 0xcd, sizeof(report) ); status = HidP_InitializeReportForID( HidP_Feature, report_id, preparsed, report, report_len ); ok( status == HIDP_STATUS_SUCCESS, "HidP_InitializeReportForID returned %#x\n", status ); SetLastError( 0xdeadbeef ); ret = HidD_SetFeature( file, report, 0 ); ok( !ret, "HidD_SetFeature succeeded\n" ); ok( GetLastError() == ERROR_INVALID_USER_BUFFER, "HidD_SetFeature returned error %u\n", GetLastError() ); SetLastError( 0xdeadbeef ); ret = HidD_SetFeature( file, report, report_len - 1 ); ok( !ret, "HidD_SetFeature succeeded\n" ); ok( GetLastError() == ERROR_INVALID_PARAMETER || broken( GetLastError() == ERROR_CRC ), "HidD_SetFeature returned error %u\n", GetLastError() ); if (!report_id) { struct hid_expect broken_expect = { .code = IOCTL_HID_SET_FEATURE, .broken = TRUE, .report_len = report_len - 1, .report_buf = { 0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a, 0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a, 0x5a,0x5a,0x5a,0x5a,0x5a, }, .ret_length = 3, .ret_status = STATUS_SUCCESS, }; set_hid_expect( file, &broken_expect, sizeof(broken_expect) ); } SetLastError( 0xdeadbeef ); memset( buffer, 0x5a, sizeof(buffer) ); ret = HidD_SetFeature( file, buffer, report_len ); if (report_id || broken( !ret )) { ok( !ret, "HidD_SetFeature succeeded, last error %u\n", GetLastError() ); ok( GetLastError() == ERROR_INVALID_PARAMETER || broken( GetLastError() == ERROR_CRC ), "HidD_SetFeature returned error %u\n", GetLastError() ); } else { ok( ret, "HidD_SetFeature failed, last error %u\n", GetLastError() ); } set_hid_expect( file, expect, sizeof(expect) ); SetLastError( 0xdeadbeef ); ret = HidD_SetFeature( file, report, report_len ); ok( ret, "HidD_SetFeature failed, last error %u\n", GetLastError() ); length = report_len * 2; SetLastError( 0xdeadbeef ); ret = sync_ioctl( file, IOCTL_HID_SET_FEATURE, NULL, 0, report, &length ); ok( !ret, "IOCTL_HID_SET_FEATURE succeeded\n" ); ok( GetLastError() == ERROR_INVALID_USER_BUFFER, "IOCTL_HID_SET_FEATURE returned error %u\n", GetLastError() ); length = 0; SetLastError( 0xdeadbeef ); ret = sync_ioctl( file, IOCTL_HID_SET_FEATURE, report, report_len * 2, NULL, &length ); ok( ret, "IOCTL_HID_SET_FEATURE failed, last error %u\n", GetLastError() ); ok( length == 3, "got length %u, expected 3\n", length ); set_hid_expect( file, NULL, 0 ); } static void test_hidp_set_output( HANDLE file, int report_id, ULONG report_len, PHIDP_PREPARSED_DATA preparsed ) { struct hid_expect expect[] = { { .code = IOCTL_HID_SET_OUTPUT_REPORT, .report_id = report_id, .report_len = report_len - (report_id ? 0 : 1), .report_buf = {report_id}, .ret_length = 3, .ret_status = STATUS_SUCCESS, }, { .code = IOCTL_HID_SET_OUTPUT_REPORT, .report_id = report_id, .report_len = report_len - (report_id ? 0 : 1), .report_buf = {report_id,0,0xcd,0xcd,0xcd}, .ret_length = 3, .ret_status = STATUS_SUCCESS, }, }; char buffer[200], report[200]; NTSTATUS status; ULONG length; BOOL ret; memset( report, 0xcd, sizeof(report) ); status = HidP_InitializeReportForID( HidP_Output, report_id, preparsed, report, report_len ); ok( status == HIDP_STATUS_REPORT_DOES_NOT_EXIST, "HidP_InitializeReportForID returned %#x\n", status ); memset( report, 0, report_len ); report[0] = report_id; SetLastError( 0xdeadbeef ); ret = HidD_SetOutputReport( file, report, 0 ); ok( !ret, "HidD_SetOutputReport succeeded\n" ); ok( GetLastError() == ERROR_INVALID_USER_BUFFER, "HidD_SetOutputReport returned error %u\n", GetLastError() ); SetLastError( 0xdeadbeef ); ret = HidD_SetOutputReport( file, report, report_len - 1 ); ok( !ret, "HidD_SetOutputReport succeeded\n" ); ok( GetLastError() == ERROR_INVALID_PARAMETER || broken( GetLastError() == ERROR_CRC ), "HidD_SetOutputReport returned error %u\n", GetLastError() ); if (!report_id) { struct hid_expect broken_expect = { .code = IOCTL_HID_SET_OUTPUT_REPORT, .broken = TRUE, .report_len = report_len - 1, .report_buf = {0x5a,0x5a}, .ret_length = 3, .ret_status = STATUS_SUCCESS, }; set_hid_expect( file, &broken_expect, sizeof(broken_expect) ); } SetLastError( 0xdeadbeef ); memset( buffer, 0x5a, sizeof(buffer) ); ret = HidD_SetOutputReport( file, buffer, report_len ); if (report_id || broken( !ret )) { ok( !ret, "HidD_SetOutputReport succeeded, last error %u\n", GetLastError() ); ok( GetLastError() == ERROR_INVALID_PARAMETER || broken( GetLastError() == ERROR_CRC ), "HidD_SetOutputReport returned error %u\n", GetLastError() ); } else { ok( ret, "HidD_SetOutputReport failed, last error %u\n", GetLastError() ); } set_hid_expect( file, expect, sizeof(expect) ); SetLastError( 0xdeadbeef ); ret = HidD_SetOutputReport( file, report, report_len ); ok( ret, "HidD_SetOutputReport failed, last error %u\n", GetLastError() ); length = report_len * 2; SetLastError( 0xdeadbeef ); ret = sync_ioctl( file, IOCTL_HID_SET_OUTPUT_REPORT, NULL, 0, report, &length ); ok( !ret, "IOCTL_HID_SET_OUTPUT_REPORT succeeded\n" ); ok( GetLastError() == ERROR_INVALID_USER_BUFFER, "IOCTL_HID_SET_OUTPUT_REPORT returned error %u\n", GetLastError() ); length = 0; SetLastError( 0xdeadbeef ); ret = sync_ioctl( file, IOCTL_HID_SET_OUTPUT_REPORT, report, report_len * 2, NULL, &length ); ok( ret, "IOCTL_HID_SET_OUTPUT_REPORT failed, last error %u\n", GetLastError() ); ok( length == 3, "got length %u, expected 3\n", length ); set_hid_expect( file, NULL, 0 ); } static void test_write_file( HANDLE file, int report_id, ULONG report_len ) { struct hid_expect expect = { .code = IOCTL_HID_WRITE_REPORT, .report_id = report_id, .report_len = report_len - (report_id ? 0 : 1), .report_buf = {report_id ? report_id : 0xcd,0xcd,0xcd,0xcd,0xcd}, .ret_length = 3, .ret_status = STATUS_SUCCESS, }; char report[200]; ULONG length; BOOL ret; SetLastError( 0xdeadbeef ); ret = WriteFile( file, report, 0, &length, NULL ); ok( !ret, "WriteFile succeeded\n" ); ok( GetLastError() == ERROR_INVALID_USER_BUFFER, "WriteFile returned error %u\n", GetLastError() ); ok( length == 0, "WriteFile returned %x\n", length ); SetLastError( 0xdeadbeef ); ret = WriteFile( file, report, report_len - 1, &length, NULL ); ok( !ret, "WriteFile succeeded\n" ); ok( GetLastError() == ERROR_INVALID_PARAMETER || GetLastError() == ERROR_INVALID_USER_BUFFER, "WriteFile returned error %u\n", GetLastError() ); ok( length == 0, "WriteFile returned %x\n", length ); set_hid_expect( file, &expect, sizeof(expect) ); memset( report, 0xcd, sizeof(report) ); report[0] = 0xa5; SetLastError( 0xdeadbeef ); ret = WriteFile( file, report, report_len * 2, &length, NULL ); if (report_id || broken( !ret ) /* w7u */) { ok( !ret, "WriteFile succeeded\n" ); ok( GetLastError() == ERROR_INVALID_PARAMETER, "WriteFile returned error %u\n", GetLastError() ); ok( length == 0, "WriteFile wrote %u\n", length ); SetLastError( 0xdeadbeef ); report[0] = report_id; ret = WriteFile( file, report, report_len, &length, NULL ); } if (report_id) { ok( ret, "WriteFile failed, last error %u\n", GetLastError() ); ok( length == 2, "WriteFile wrote %u\n", length ); } else { ok( ret, "WriteFile failed, last error %u\n", GetLastError() ); ok( length == 3, "WriteFile wrote %u\n", length ); } set_hid_expect( file, NULL, 0 ); } static void test_hidp( HANDLE file, HANDLE async_file, int report_id, BOOL polled, const HIDP_CAPS *expect_caps ) { const HIDP_BUTTON_CAPS expect_button_caps[] = { { .UsagePage = HID_USAGE_PAGE_BUTTON, .ReportID = report_id, .BitField = 2, .LinkUsage = HID_USAGE_GENERIC_JOYSTICK, .LinkUsagePage = HID_USAGE_PAGE_GENERIC, .LinkCollection = 1, .IsRange = TRUE, .IsAbsolute = TRUE, .Range.UsageMin = 1, .Range.UsageMax = 8, .Range.DataIndexMin = 2, .Range.DataIndexMax = 9, }, { .UsagePage = HID_USAGE_PAGE_BUTTON, .ReportID = report_id, .BitField = 3, .LinkCollection = 1, .LinkUsage = HID_USAGE_GENERIC_JOYSTICK, .LinkUsagePage = HID_USAGE_PAGE_GENERIC, .IsRange = TRUE, .IsAbsolute = TRUE, .Range.UsageMin = 0x18, .Range.UsageMax = 0x1f, .Range.DataIndexMin = 10, .Range.DataIndexMax = 17, }, { .UsagePage = HID_USAGE_PAGE_KEYBOARD, .ReportID = report_id, .BitField = 0x1fc, .LinkCollection = 1, .LinkUsage = HID_USAGE_GENERIC_JOYSTICK, .LinkUsagePage = HID_USAGE_PAGE_GENERIC, .IsRange = TRUE, .IsAbsolute = FALSE, .Range.UsageMin = 0x8, .Range.UsageMax = 0xf, .Range.DataIndexMin = 18, .Range.DataIndexMax = 25, }, { .UsagePage = HID_USAGE_PAGE_BUTTON, .ReportID = report_id, .BitField = 2, .LinkCollection = 1, .LinkUsage = HID_USAGE_GENERIC_JOYSTICK, .LinkUsagePage = HID_USAGE_PAGE_GENERIC, .IsRange = FALSE, .IsAbsolute = TRUE, .NotRange.Usage = 0x20, .NotRange.Reserved1 = 0x20, .NotRange.DataIndex = 26, .NotRange.Reserved4 = 26, }, }; const HIDP_VALUE_CAPS expect_value_caps[] = { { .UsagePage = HID_USAGE_PAGE_GENERIC, .ReportID = report_id, .BitField = 2, .LinkUsage = HID_USAGE_GENERIC_JOYSTICK, .LinkUsagePage = HID_USAGE_PAGE_GENERIC, .LinkCollection = 1, .IsAbsolute = TRUE, .BitSize = 8, .ReportCount = 1, .LogicalMin = -128, .LogicalMax = 127, .NotRange.Usage = HID_USAGE_GENERIC_Y, .NotRange.Reserved1 = HID_USAGE_GENERIC_Y, }, { .UsagePage = HID_USAGE_PAGE_GENERIC, .ReportID = report_id, .BitField = 2, .LinkUsage = HID_USAGE_GENERIC_JOYSTICK, .LinkUsagePage = HID_USAGE_PAGE_GENERIC, .LinkCollection = 1, .IsAbsolute = TRUE, .BitSize = 8, .ReportCount = 1, .LogicalMin = -128, .LogicalMax = 127, .NotRange.Usage = HID_USAGE_GENERIC_X, .NotRange.Reserved1 = HID_USAGE_GENERIC_X, .NotRange.DataIndex = 1, .NotRange.Reserved4 = 1, }, { .UsagePage = HID_USAGE_PAGE_BUTTON, .ReportID = report_id, .BitField = 2, .LinkUsage = HID_USAGE_GENERIC_JOYSTICK, .LinkUsagePage = HID_USAGE_PAGE_GENERIC, .LinkCollection = 1, .IsAbsolute = TRUE, .ReportCount = 1, .LogicalMax = 1, .IsRange = TRUE, .Range.UsageMin = 0x21, .Range.UsageMax = 0x22, .Range.DataIndexMin = 27, .Range.DataIndexMax = 28, }, { .UsagePage = HID_USAGE_PAGE_GENERIC, .ReportID = report_id, .BitField = 2, .LinkUsage = HID_USAGE_GENERIC_JOYSTICK, .LinkUsagePage = HID_USAGE_PAGE_GENERIC, .LinkCollection = 1, .IsAbsolute = TRUE, .BitSize = 4, .ReportCount = 2, .LogicalMin = 1, .LogicalMax = 8, .NotRange.Usage = HID_USAGE_GENERIC_HATSWITCH, .NotRange.Reserved1 = HID_USAGE_GENERIC_HATSWITCH, .NotRange.DataIndex = 29, .NotRange.Reserved4 = 29, }, }; static const HIDP_LINK_COLLECTION_NODE expect_collections[] = { { .LinkUsage = HID_USAGE_GENERIC_JOYSTICK, .LinkUsagePage = HID_USAGE_PAGE_GENERIC, .CollectionType = 1, .NumberOfChildren = 7, .FirstChild = 9, }, { .LinkUsage = HID_USAGE_GENERIC_JOYSTICK, .LinkUsagePage = HID_USAGE_PAGE_GENERIC, .CollectionType = 2, }, }; static const HIDP_DATA expect_data[] = { { .DataIndex = 0, }, { .DataIndex = 1, }, { .DataIndex = 5, .RawValue = 1, }, { .DataIndex = 7, .RawValue = 1, }, { .DataIndex = 19, .RawValue = 1, }, { .DataIndex = 21, .RawValue = 1, }, { .DataIndex = 30, }, { .DataIndex = 31, }, { .DataIndex = 32, .RawValue = 0xfeedcafe, }, { .DataIndex = 37, .RawValue = 1, }, { .DataIndex = 39, .RawValue = 1, }, }; OVERLAPPED overlapped = {0}, overlapped2 = {0}; HIDP_LINK_COLLECTION_NODE collections[16]; PHIDP_PREPARSED_DATA preparsed_data; USAGE_AND_PAGE usage_and_pages[16]; HIDP_BUTTON_CAPS button_caps[32]; HIDP_VALUE_CAPS value_caps[16]; char buffer[200], report[200]; DWORD collection_count; DWORD waveform_list; HIDP_DATA data[64]; USAGE usages[16]; ULONG off, value; NTSTATUS status; HIDP_CAPS caps; unsigned int i; USHORT count; BOOL ret; ret = HidD_GetPreparsedData( file, &preparsed_data ); ok( ret, "HidD_GetPreparsedData failed with error %u\n", GetLastError() ); memset( buffer, 0, sizeof(buffer) ); status = HidP_GetCaps( (PHIDP_PREPARSED_DATA)buffer, &caps ); ok( status == HIDP_STATUS_INVALID_PREPARSED_DATA, "HidP_GetCaps returned %#x\n", status ); status = HidP_GetCaps( preparsed_data, &caps ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetCaps returned %#x\n", status ); check_hidp_caps( &caps, expect_caps ); collection_count = 0; status = HidP_GetLinkCollectionNodes( collections, &collection_count, preparsed_data ); ok( status == HIDP_STATUS_BUFFER_TOO_SMALL, "HidP_GetLinkCollectionNodes returned %#x\n", status ); ok( collection_count == caps.NumberLinkCollectionNodes, "got %d collection nodes, expected %d\n", collection_count, caps.NumberLinkCollectionNodes ); collection_count = ARRAY_SIZE(collections); status = HidP_GetLinkCollectionNodes( collections, &collection_count, (PHIDP_PREPARSED_DATA)buffer ); ok( status == HIDP_STATUS_INVALID_PREPARSED_DATA, "HidP_GetLinkCollectionNodes returned %#x\n", status ); status = HidP_GetLinkCollectionNodes( collections, &collection_count, preparsed_data ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetLinkCollectionNodes returned %#x\n", status ); ok( collection_count == caps.NumberLinkCollectionNodes, "got %d collection nodes, expected %d\n", collection_count, caps.NumberLinkCollectionNodes ); for (i = 0; i < ARRAY_SIZE(expect_collections); ++i) { winetest_push_context( "collections[%d]", i ); check_hidp_link_collection_node( &collections[i], &expect_collections[i] ); winetest_pop_context(); } count = ARRAY_SIZE(button_caps); status = HidP_GetButtonCaps( HidP_Output, button_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_GetButtonCaps returned %#x\n", status ); status = HidP_GetButtonCaps( HidP_Feature + 1, button_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_INVALID_REPORT_TYPE, "HidP_GetButtonCaps returned %#x\n", status ); count = 0; status = HidP_GetButtonCaps( HidP_Input, button_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_BUFFER_TOO_SMALL, "HidP_GetButtonCaps returned %#x\n", status ); ok( count == caps.NumberInputButtonCaps, "HidP_GetButtonCaps returned count %d, expected %d\n", count, caps.NumberInputButtonCaps ); count = ARRAY_SIZE(button_caps); status = HidP_GetButtonCaps( HidP_Input, button_caps, &count, (PHIDP_PREPARSED_DATA)buffer ); ok( status == HIDP_STATUS_INVALID_PREPARSED_DATA, "HidP_GetButtonCaps returned %#x\n", status ); memset( button_caps, 0, sizeof(button_caps) ); status = HidP_GetButtonCaps( HidP_Input, button_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetButtonCaps returned %#x\n", status ); ok( count == caps.NumberInputButtonCaps, "HidP_GetButtonCaps returned count %d, expected %d\n", count, caps.NumberInputButtonCaps ); for (i = 0; i < ARRAY_SIZE(expect_button_caps); ++i) { winetest_push_context( "button_caps[%d]", i ); check_hidp_button_caps( &button_caps[i], &expect_button_caps[i] ); winetest_pop_context(); } count = ARRAY_SIZE(button_caps) - 1; status = HidP_GetSpecificButtonCaps( HidP_Output, 0, 0, 0, button_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_GetSpecificButtonCaps returned %#x\n", status ); status = HidP_GetSpecificButtonCaps( HidP_Feature + 1, 0, 0, 0, button_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_INVALID_REPORT_TYPE, "HidP_GetSpecificButtonCaps returned %#x\n", status ); count = 0; status = HidP_GetSpecificButtonCaps( HidP_Input, 0, 0, 0, button_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_BUFFER_TOO_SMALL, "HidP_GetSpecificButtonCaps returned %#x\n", status ); ok( count == caps.NumberInputButtonCaps, "HidP_GetSpecificButtonCaps returned count %d, expected %d\n", count, caps.NumberInputButtonCaps ); count = ARRAY_SIZE(button_caps) - 1; status = HidP_GetSpecificButtonCaps( HidP_Input, 0, 0, 0, button_caps, &count, (PHIDP_PREPARSED_DATA)buffer ); ok( status == HIDP_STATUS_INVALID_PREPARSED_DATA, "HidP_GetSpecificButtonCaps returned %#x\n", status ); status = HidP_GetSpecificButtonCaps( HidP_Input, 0, 0, 0, button_caps + 1, &count, preparsed_data ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetSpecificButtonCaps returned %#x\n", status ); ok( count == caps.NumberInputButtonCaps, "HidP_GetSpecificButtonCaps returned count %d, expected %d\n", count, caps.NumberInputButtonCaps ); check_hidp_button_caps( &button_caps[1], &button_caps[0] ); status = HidP_GetSpecificButtonCaps( HidP_Input, HID_USAGE_PAGE_BUTTON, 0, 5, button_caps + 1, &count, preparsed_data ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetSpecificButtonCaps returned %#x\n", status ); ok( count == 1, "HidP_GetSpecificButtonCaps returned count %d, expected %d\n", count, 1 ); check_hidp_button_caps( &button_caps[1], &button_caps[0] ); count = 0xbeef; status = HidP_GetSpecificButtonCaps( HidP_Input, 0xfffe, 0, 0, button_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_GetSpecificButtonCaps returned %#x\n", status ); ok( count == 0, "HidP_GetSpecificButtonCaps returned count %d, expected %d\n", count, 0 ); count = 0xbeef; status = HidP_GetSpecificButtonCaps( HidP_Input, 0, 0xfffe, 0, button_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_GetSpecificButtonCaps returned %#x\n", status ); ok( count == 0, "HidP_GetSpecificButtonCaps returned count %d, expected %d\n", count, 0 ); count = 0xbeef; status = HidP_GetSpecificButtonCaps( HidP_Input, 0, 0, 0xfffe, button_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_GetSpecificButtonCaps returned %#x\n", status ); ok( count == 0, "HidP_GetSpecificButtonCaps returned count %d, expected %d\n", count, 0 ); count = ARRAY_SIZE(value_caps); status = HidP_GetValueCaps( HidP_Output, value_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_GetValueCaps returned %#x\n", status ); status = HidP_GetValueCaps( HidP_Feature + 1, value_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_INVALID_REPORT_TYPE, "HidP_GetValueCaps returned %#x\n", status ); count = 0; status = HidP_GetValueCaps( HidP_Input, value_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_BUFFER_TOO_SMALL, "HidP_GetValueCaps returned %#x\n", status ); ok( count == caps.NumberInputValueCaps, "HidP_GetValueCaps returned count %d, expected %d\n", count, caps.NumberInputValueCaps ); count = ARRAY_SIZE(value_caps); status = HidP_GetValueCaps( HidP_Input, value_caps, &count, (PHIDP_PREPARSED_DATA)buffer ); ok( status == HIDP_STATUS_INVALID_PREPARSED_DATA, "HidP_GetValueCaps returned %#x\n", status ); status = HidP_GetValueCaps( HidP_Input, value_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetValueCaps returned %#x\n", status ); ok( count == caps.NumberInputValueCaps, "HidP_GetValueCaps returned count %d, expected %d\n", count, caps.NumberInputValueCaps ); for (i = 0; i < ARRAY_SIZE(expect_value_caps); ++i) { winetest_push_context( "value_caps[%d]", i ); check_hidp_value_caps( &value_caps[i], &expect_value_caps[i] ); winetest_pop_context(); } count = ARRAY_SIZE(value_caps) - 4; status = HidP_GetSpecificValueCaps( HidP_Output, 0, 0, 0, value_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_GetSpecificValueCaps returned %#x\n", status ); status = HidP_GetSpecificValueCaps( HidP_Feature + 1, 0, 0, 0, value_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_INVALID_REPORT_TYPE, "HidP_GetSpecificValueCaps returned %#x\n", status ); count = 0; status = HidP_GetSpecificValueCaps( HidP_Input, 0, 0, 0, value_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_BUFFER_TOO_SMALL, "HidP_GetSpecificValueCaps returned %#x\n", status ); ok( count == caps.NumberInputValueCaps, "HidP_GetSpecificValueCaps returned count %d, expected %d\n", count, caps.NumberInputValueCaps ); count = ARRAY_SIZE(value_caps) - 4; status = HidP_GetSpecificValueCaps( HidP_Input, 0, 0, 0, value_caps + 4, &count, (PHIDP_PREPARSED_DATA)buffer ); ok( status == HIDP_STATUS_INVALID_PREPARSED_DATA, "HidP_GetSpecificValueCaps returned %#x\n", status ); status = HidP_GetSpecificValueCaps( HidP_Input, 0, 0, 0, value_caps + 4, &count, preparsed_data ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetSpecificValueCaps returned %#x\n", status ); ok( count == caps.NumberInputValueCaps, "HidP_GetSpecificValueCaps returned count %d, expected %d\n", count, caps.NumberInputValueCaps ); check_hidp_value_caps( &value_caps[4], &value_caps[0] ); check_hidp_value_caps( &value_caps[5], &value_caps[1] ); check_hidp_value_caps( &value_caps[6], &value_caps[2] ); check_hidp_value_caps( &value_caps[7], &value_caps[3] ); count = 1; status = HidP_GetSpecificValueCaps( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_HATSWITCH, value_caps + 4, &count, preparsed_data ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetSpecificValueCaps returned %#x\n", status ); ok( count == 1, "HidP_GetSpecificValueCaps returned count %d, expected %d\n", count, 1 ); check_hidp_value_caps( &value_caps[4], &value_caps[3] ); count = 0xdead; status = HidP_GetSpecificValueCaps( HidP_Input, 0xfffe, 0, 0, value_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_GetSpecificValueCaps returned %#x\n", status ); ok( count == 0, "HidP_GetSpecificValueCaps returned count %d, expected %d\n", count, 0 ); count = 0xdead; status = HidP_GetSpecificValueCaps( HidP_Input, 0, 0xfffe, 0, value_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_GetSpecificValueCaps returned %#x\n", status ); ok( count == 0, "HidP_GetSpecificValueCaps returned count %d, expected %d\n", count, 0 ); count = 0xdead; status = HidP_GetSpecificValueCaps( HidP_Input, 0, 0, 0xfffe, value_caps, &count, preparsed_data ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_GetSpecificValueCaps returned %#x\n", status ); ok( count == 0, "HidP_GetSpecificValueCaps returned count %d, expected %d\n", count, 0 ); status = HidP_InitializeReportForID( HidP_Input, 0, (PHIDP_PREPARSED_DATA)buffer, report, sizeof(report) ); ok( status == HIDP_STATUS_INVALID_PREPARSED_DATA, "HidP_InitializeReportForID returned %#x\n", status ); status = HidP_InitializeReportForID( HidP_Feature + 1, 0, preparsed_data, report, sizeof(report) ); ok( status == HIDP_STATUS_INVALID_REPORT_TYPE, "HidP_InitializeReportForID returned %#x\n", status ); status = HidP_InitializeReportForID( HidP_Input, 0, preparsed_data, report, sizeof(report) ); ok( status == HIDP_STATUS_INVALID_REPORT_LENGTH, "HidP_InitializeReportForID returned %#x\n", status ); status = HidP_InitializeReportForID( HidP_Input, 0, preparsed_data, report, caps.InputReportByteLength + 1 ); ok( status == HIDP_STATUS_INVALID_REPORT_LENGTH, "HidP_InitializeReportForID returned %#x\n", status ); status = HidP_InitializeReportForID( HidP_Input, 1 - report_id, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_REPORT_DOES_NOT_EXIST, "HidP_InitializeReportForID returned %#x\n", status ); memset( report, 0xcd, sizeof(report) ); status = HidP_InitializeReportForID( HidP_Input, report_id, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_InitializeReportForID returned %#x\n", status ); memset( buffer, 0xcd, sizeof(buffer) ); memset( buffer, 0, caps.InputReportByteLength ); buffer[0] = report_id; ok( !memcmp( buffer, report, sizeof(buffer) ), "unexpected report data\n" ); status = HidP_SetUsageValueArray( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_X, buffer, sizeof(buffer), preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_NOT_VALUE_ARRAY, "HidP_SetUsageValueArray returned %#x\n", status ); memset( buffer, 0xcd, sizeof(buffer) ); status = HidP_SetUsageValueArray( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_HATSWITCH, buffer, 0, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_BUFFER_TOO_SMALL, "HidP_SetUsageValueArray returned %#x\n", status ); status = HidP_SetUsageValueArray( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_HATSWITCH, buffer, 8, preparsed_data, report, caps.InputReportByteLength ); todo_wine ok( status == HIDP_STATUS_NOT_IMPLEMENTED, "HidP_SetUsageValueArray returned %#x\n", status ); status = HidP_GetUsageValueArray( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_X, buffer, sizeof(buffer), preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_NOT_VALUE_ARRAY, "HidP_GetUsageValueArray returned %#x\n", status ); memset( buffer, 0xcd, sizeof(buffer) ); status = HidP_GetUsageValueArray( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_HATSWITCH, buffer, 0, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_BUFFER_TOO_SMALL, "HidP_GetUsageValueArray returned %#x\n", status ); status = HidP_GetUsageValueArray( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_HATSWITCH, buffer, 8, preparsed_data, report, caps.InputReportByteLength ); todo_wine ok( status == HIDP_STATUS_NOT_IMPLEMENTED, "HidP_GetUsageValueArray returned %#x\n", status ); value = -128; status = HidP_SetUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_X, value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsageValue returned %#x\n", status ); value = 0xdeadbeef; status = HidP_GetUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_X, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetUsageValue returned %#x\n", status ); ok( value == 0x80, "got value %x, expected %#x\n", value, 0x80 ); value = 0xdeadbeef; status = HidP_GetScaledUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_X, (LONG *)&value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetScaledUsageValue returned %#x\n", status ); ok( value == -128, "got value %x, expected %#x\n", value, -128 ); value = 127; status = HidP_SetUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_X, value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsageValue returned %#x\n", status ); value = 0xdeadbeef; status = HidP_GetScaledUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_X, (LONG *)&value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetScaledUsageValue returned %#x\n", status ); ok( value == 127, "got value %x, expected %#x\n", value, 127 ); value = 0; status = HidP_SetUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_X, value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsageValue returned %#x\n", status ); value = 0xdeadbeef; status = HidP_GetScaledUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_X, (LONG *)&value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetScaledUsageValue returned %#x\n", status ); ok( value == 0, "got value %x, expected %#x\n", value, 0 ); value = 0x7fffffff; status = HidP_SetUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsageValue returned %#x\n", status ); value = 0xdeadbeef; status = HidP_GetScaledUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, (LONG *)&value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_VALUE_OUT_OF_RANGE, "HidP_GetScaledUsageValue returned %#x\n", status ); ok( value == 0, "got value %x, expected %#x\n", value, 0 ); value = 0xdeadbeef; status = HidP_GetUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetUsageValue returned %#x\n", status ); ok( value == 0x7fffffff, "got value %x, expected %#x\n", value, 0x7fffffff ); value = 0x3fffffff; status = HidP_SetUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsageValue returned %#x\n", status ); value = 0xdeadbeef; status = HidP_GetScaledUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, (LONG *)&value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetScaledUsageValue returned %#x\n", status ); ok( value == 0x7fffffff, "got value %x, expected %#x\n", value, 0x7fffffff ); value = 0; status = HidP_SetUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsageValue returned %#x\n", status ); value = 0xdeadbeef; status = HidP_GetScaledUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, (LONG *)&value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetScaledUsageValue returned %#x\n", status ); ok( value == 0x80000000, "got value %x, expected %#x\n", value, 0x80000000 ); value = 0; status = HidP_SetUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_RX, value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsageValue returned %#x\n", status ); value = 0xdeadbeef; status = HidP_GetScaledUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_RX, (LONG *)&value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetScaledUsageValue returned %#x\n", status ); ok( value == 0, "got value %x, expected %#x\n", value, 0 ); value = 0xfeedcafe; status = HidP_SetUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_RY, value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsageValue returned %#x\n", status ); value = 0xdeadbeef; status = HidP_GetScaledUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_RY, (LONG *)&value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_BAD_LOG_PHY_VALUES, "HidP_GetScaledUsageValue returned %#x\n", status ); ok( value == 0, "got value %x, expected %#x\n", value, 0 ); status = HidP_SetScaledUsageValue( HidP_Input, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_RY, 0, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_BAD_LOG_PHY_VALUES, "HidP_GetScaledUsageValue returned %#x\n", status ); ok( value == 0, "got value %x, expected %#x\n", value, 0 ); value = HidP_MaxUsageListLength( HidP_Feature + 1, 0, preparsed_data ); ok( value == 0, "HidP_MaxUsageListLength(HidP_Feature + 1, 0) returned %d, expected %d\n", value, 0 ); value = HidP_MaxUsageListLength( HidP_Input, 0, preparsed_data ); ok( value == 50, "HidP_MaxUsageListLength(HidP_Input, 0) returned %d, expected %d\n", value, 50 ); value = HidP_MaxUsageListLength( HidP_Input, HID_USAGE_PAGE_BUTTON, preparsed_data ); ok( value == 32, "HidP_MaxUsageListLength(HidP_Input, HID_USAGE_PAGE_BUTTON) returned %d, expected %d\n", value, 32 ); value = HidP_MaxUsageListLength( HidP_Input, HID_USAGE_PAGE_LED, preparsed_data ); ok( value == 8, "HidP_MaxUsageListLength(HidP_Input, HID_USAGE_PAGE_LED) returned %d, expected %d\n", value, 8 ); value = HidP_MaxUsageListLength( HidP_Feature, HID_USAGE_PAGE_BUTTON, preparsed_data ); ok( value == 8, "HidP_MaxUsageListLength(HidP_Feature, HID_USAGE_PAGE_BUTTON) returned %d, expected %d\n", value, 8 ); value = HidP_MaxUsageListLength( HidP_Feature, HID_USAGE_PAGE_LED, preparsed_data ); ok( value == 0, "HidP_MaxUsageListLength(HidP_Feature, HID_USAGE_PAGE_LED) returned %d, expected %d\n", value, 0 ); usages[0] = 0xff; value = 1; status = HidP_SetUsages( HidP_Input, HID_USAGE_PAGE_BUTTON, 0, usages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_SetUsages returned %#x\n", status ); usages[1] = 2; usages[2] = 0xff; value = 3; status = HidP_SetUsages( HidP_Input, HID_USAGE_PAGE_BUTTON, 0, usages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_SetUsages returned %#x\n", status ); usages[0] = 4; usages[1] = 6; value = 2; status = HidP_SetUsages( HidP_Input, HID_USAGE_PAGE_BUTTON, 0, usages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsages returned %#x\n", status ); usages[0] = 4; usages[1] = 6; value = 2; status = HidP_SetUsages( HidP_Input, HID_USAGE_PAGE_LED, 0, usages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsages returned %#x\n", status ); value = ARRAY_SIZE(usages); status = HidP_GetUsages( HidP_Input, HID_USAGE_PAGE_KEYBOARD, 0, usages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetUsages returned %#x\n", status ); ok( value == 0, "got usage count %d, expected %d\n", value, 2 ); usages[0] = 0x9; usages[1] = 0xb; usages[2] = 0xa; value = 3; ok( report[6] == 0, "got report[6] %x expected 0\n", report[6] ); ok( report[7] == 0, "got report[7] %x expected 0\n", report[7] ); memcpy( buffer, report, caps.InputReportByteLength ); status = HidP_SetUsages( HidP_Input, HID_USAGE_PAGE_KEYBOARD, 0, usages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_BUFFER_TOO_SMALL, "HidP_SetUsages returned %#x\n", status ); buffer[13] = 2; buffer[14] = 4; ok( !memcmp( buffer, report, caps.InputReportByteLength ), "unexpected report data\n" ); status = HidP_SetUsageValue( HidP_Input, HID_USAGE_PAGE_LED, 0, 6, 1, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_SetUsageValue returned %#x\n", status ); value = 0xdeadbeef; status = HidP_GetUsageValue( HidP_Input, HID_USAGE_PAGE_LED, 0, 6, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_SetUsageValue returned %#x\n", status ); ok( value == 0xdeadbeef, "got value %x, expected %#x\n", value, 0xdeadbeef ); value = 1; status = HidP_GetUsages( HidP_Input, HID_USAGE_PAGE_BUTTON, 0, usages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_BUFFER_TOO_SMALL, "HidP_GetUsages returned %#x\n", status ); ok( value == 2, "got usage count %d, expected %d\n", value, 2 ); value = ARRAY_SIZE(usages); memset( usages, 0xcd, sizeof(usages) ); status = HidP_GetUsages( HidP_Input, HID_USAGE_PAGE_BUTTON, 0, usages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetUsages returned %#x\n", status ); ok( value == 2, "got usage count %d, expected %d\n", value, 2 ); ok( usages[0] == 4, "got usages[0] %x, expected %x\n", usages[0], 4 ); ok( usages[1] == 6, "got usages[1] %x, expected %x\n", usages[1], 6 ); value = ARRAY_SIZE(usages); memset( usages, 0xcd, sizeof(usages) ); status = HidP_GetUsages( HidP_Input, HID_USAGE_PAGE_LED, 0, usages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetUsages returned %#x\n", status ); ok( value == 2, "got usage count %d, expected %d\n", value, 2 ); ok( usages[0] == 6, "got usages[0] %x, expected %x\n", usages[0], 6 ); ok( usages[1] == 4, "got usages[1] %x, expected %x\n", usages[1], 4 ); value = ARRAY_SIZE(usage_and_pages); memset( usage_and_pages, 0xcd, sizeof(usage_and_pages) ); status = HidP_GetUsagesEx( HidP_Input, 0, usage_and_pages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetUsagesEx returned %#x\n", status ); ok( value == 6, "got usage count %d, expected %d\n", value, 4 ); ok( usage_and_pages[0].UsagePage == HID_USAGE_PAGE_BUTTON, "got usage_and_pages[0] UsagePage %x, expected %x\n", usage_and_pages[0].UsagePage, HID_USAGE_PAGE_BUTTON ); ok( usage_and_pages[1].UsagePage == HID_USAGE_PAGE_BUTTON, "got usage_and_pages[1] UsagePage %x, expected %x\n", usage_and_pages[1].UsagePage, HID_USAGE_PAGE_BUTTON ); ok( usage_and_pages[2].UsagePage == HID_USAGE_PAGE_KEYBOARD, "got usage_and_pages[2] UsagePage %x, expected %x\n", usage_and_pages[2].UsagePage, HID_USAGE_PAGE_KEYBOARD ); ok( usage_and_pages[3].UsagePage == HID_USAGE_PAGE_KEYBOARD, "got usage_and_pages[3] UsagePage %x, expected %x\n", usage_and_pages[3].UsagePage, HID_USAGE_PAGE_KEYBOARD ); ok( usage_and_pages[4].UsagePage == HID_USAGE_PAGE_LED, "got usage_and_pages[4] UsagePage %x, expected %x\n", usage_and_pages[4].UsagePage, HID_USAGE_PAGE_LED ); ok( usage_and_pages[5].UsagePage == HID_USAGE_PAGE_LED, "got usage_and_pages[5] UsagePage %x, expected %x\n", usage_and_pages[5].UsagePage, HID_USAGE_PAGE_LED ); ok( usage_and_pages[0].Usage == 4, "got usage_and_pages[0] Usage %x, expected %x\n", usage_and_pages[0].Usage, 4 ); ok( usage_and_pages[1].Usage == 6, "got usage_and_pages[1] Usage %x, expected %x\n", usage_and_pages[1].Usage, 6 ); ok( usage_and_pages[2].Usage == 9, "got usage_and_pages[2] Usage %x, expected %x\n", usage_and_pages[2].Usage, 9 ); ok( usage_and_pages[3].Usage == 11, "got usage_and_pages[3] Usage %x, expected %x\n", usage_and_pages[3].Usage, 11 ); ok( usage_and_pages[4].Usage == 6, "got usage_and_pages[4] Usage %x, expected %x\n", usage_and_pages[4].Usage, 6 ); ok( usage_and_pages[5].Usage == 4, "got usage_and_pages[5] Usage %x, expected %x\n", usage_and_pages[5].Usage, 4 ); value = HidP_MaxDataListLength( HidP_Feature + 1, preparsed_data ); ok( value == 0, "HidP_MaxDataListLength(HidP_Feature + 1) returned %d, expected %d\n", value, 0 ); value = HidP_MaxDataListLength( HidP_Input, preparsed_data ); ok( value == 58, "HidP_MaxDataListLength(HidP_Input) returned %d, expected %d\n", value, 58 ); value = HidP_MaxDataListLength( HidP_Output, preparsed_data ); ok( value == 0, "HidP_MaxDataListLength(HidP_Output) returned %d, expected %d\n", value, 0 ); value = HidP_MaxDataListLength( HidP_Feature, preparsed_data ); ok( value == 14, "HidP_MaxDataListLength(HidP_Feature) returned %d, expected %d\n", value, 14 ); value = 1; status = HidP_GetData( HidP_Input, data, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_BUFFER_TOO_SMALL, "HidP_GetData returned %#x\n", status ); ok( value == 11, "got data count %d, expected %d\n", value, 11 ); memset( data, 0, sizeof(data) ); status = HidP_GetData( HidP_Input, data, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetData returned %#x\n", status ); for (i = 0; i < ARRAY_SIZE(expect_data); ++i) { winetest_push_context( "data[%d]", i ); check_member( data[i], expect_data[i], "%d", DataIndex ); check_member( data[i], expect_data[i], "%d", RawValue ); winetest_pop_context(); } /* HID nary usage collections are set with 1-based usage index in their declaration order */ memset( report, 0, caps.InputReportByteLength ); status = HidP_InitializeReportForID( HidP_Input, report_id, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_InitializeReportForID returned %#x\n", status ); value = 2; usages[0] = 0x8e; usages[1] = 0x8f; status = HidP_SetUsages( HidP_Input, HID_USAGE_PAGE_KEYBOARD, 0, usages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsages returned %#x\n", status ); ok( report[caps.InputReportByteLength - 2] == 3, "unexpected usage index %d, expected 3\n", report[caps.InputReportByteLength - 2] ); ok( report[caps.InputReportByteLength - 1] == 4, "unexpected usage index %d, expected 4\n", report[caps.InputReportByteLength - 1] ); status = HidP_UnsetUsages( HidP_Input, HID_USAGE_PAGE_KEYBOARD, 0, usages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_UnsetUsages returned %#x\n", status ); ok( report[caps.InputReportByteLength - 2] == 0, "unexpected usage index %d, expected 0\n", report[caps.InputReportByteLength - 2] ); ok( report[caps.InputReportByteLength - 1] == 0, "unexpected usage index %d, expected 0\n", report[caps.InputReportByteLength - 1] ); status = HidP_UnsetUsages( HidP_Input, HID_USAGE_PAGE_KEYBOARD, 0, usages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_BUTTON_NOT_PRESSED, "HidP_UnsetUsages returned %#x\n", status ); value = 1; usages[0] = 0x8c; status = HidP_SetUsages( HidP_Input, HID_USAGE_PAGE_KEYBOARD, 0, usages, &value, preparsed_data, report, caps.InputReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsages returned %#x\n", status ); ok( report[caps.InputReportByteLength - 2] == 1, "unexpected usage index %d, expected 1\n", report[caps.InputReportByteLength - 2] ); memset( report, 0xcd, sizeof(report) ); status = HidP_InitializeReportForID( HidP_Feature, 3, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_REPORT_DOES_NOT_EXIST, "HidP_InitializeReportForID returned %#x\n", status ); memset( report, 0xcd, sizeof(report) ); status = HidP_InitializeReportForID( HidP_Feature, report_id, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_InitializeReportForID returned %#x\n", status ); memset( buffer, 0xcd, sizeof(buffer) ); memset( buffer, 0, caps.FeatureReportByteLength ); buffer[0] = report_id; ok( !memcmp( buffer, report, sizeof(buffer) ), "unexpected report data\n" ); for (i = 0; i < caps.NumberLinkCollectionNodes; ++i) { if (collections[i].LinkUsagePage != HID_USAGE_PAGE_HAPTICS) continue; if (collections[i].LinkUsage == HID_USAGE_HAPTICS_WAVEFORM_LIST) break; } ok( i < caps.NumberLinkCollectionNodes, "HID_USAGE_HAPTICS_WAVEFORM_LIST collection not found\n" ); waveform_list = i; status = HidP_SetUsageValue( HidP_Feature, HID_USAGE_PAGE_ORDINAL, waveform_list, 3, HID_USAGE_HAPTICS_WAVEFORM_RUMBLE, (PHIDP_PREPARSED_DATA)buffer, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_INVALID_PREPARSED_DATA, "HidP_SetUsageValue returned %#x\n", status ); status = HidP_SetUsageValue( HidP_Feature + 1, HID_USAGE_PAGE_ORDINAL, waveform_list, 3, HID_USAGE_HAPTICS_WAVEFORM_RUMBLE, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_INVALID_REPORT_TYPE, "HidP_SetUsageValue returned %#x\n", status ); status = HidP_SetUsageValue( HidP_Feature, HID_USAGE_PAGE_ORDINAL, waveform_list, 3, HID_USAGE_HAPTICS_WAVEFORM_RUMBLE, preparsed_data, report, caps.FeatureReportByteLength + 1 ); ok( status == HIDP_STATUS_INVALID_REPORT_LENGTH, "HidP_SetUsageValue returned %#x\n", status ); report[0] = 1 - report_id; status = HidP_SetUsageValue( HidP_Feature, HID_USAGE_PAGE_ORDINAL, waveform_list, 3, HID_USAGE_HAPTICS_WAVEFORM_RUMBLE, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == (report_id ? HIDP_STATUS_SUCCESS : HIDP_STATUS_INCOMPATIBLE_REPORT_ID), "HidP_SetUsageValue returned %#x\n", status ); report[0] = 2; status = HidP_SetUsageValue( HidP_Feature, HID_USAGE_PAGE_ORDINAL, waveform_list, 3, HID_USAGE_HAPTICS_WAVEFORM_RUMBLE, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_INCOMPATIBLE_REPORT_ID, "HidP_SetUsageValue returned %#x\n", status ); report[0] = report_id; status = HidP_SetUsageValue( HidP_Feature, HID_USAGE_PAGE_ORDINAL, 0xdead, 3, HID_USAGE_HAPTICS_WAVEFORM_RUMBLE, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_SetUsageValue returned %#x\n", status ); status = HidP_SetUsageValue( HidP_Feature, HID_USAGE_PAGE_ORDINAL, waveform_list, 3, HID_USAGE_HAPTICS_WAVEFORM_RUMBLE, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsageValue returned %#x\n", status ); memset( buffer, 0xcd, sizeof(buffer) ); memset( buffer, 0, caps.FeatureReportByteLength ); buffer[0] = report_id; value = HID_USAGE_HAPTICS_WAVEFORM_RUMBLE; memcpy( buffer + 1, &value, 2 ); ok( !memcmp( buffer, report, sizeof(buffer) ), "unexpected report data\n" ); status = HidP_GetUsageValue( HidP_Feature, HID_USAGE_PAGE_ORDINAL, waveform_list, 3, &value, (PHIDP_PREPARSED_DATA)buffer, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_INVALID_PREPARSED_DATA, "HidP_GetUsageValue returned %#x\n", status ); status = HidP_GetUsageValue( HidP_Feature + 1, HID_USAGE_PAGE_ORDINAL, waveform_list, 3, &value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_INVALID_REPORT_TYPE, "HidP_GetUsageValue returned %#x\n", status ); status = HidP_GetUsageValue( HidP_Feature, HID_USAGE_PAGE_ORDINAL, waveform_list, 3, &value, preparsed_data, report, caps.FeatureReportByteLength + 1 ); ok( status == HIDP_STATUS_INVALID_REPORT_LENGTH, "HidP_GetUsageValue returned %#x\n", status ); report[0] = 1 - report_id; status = HidP_GetUsageValue( HidP_Feature, HID_USAGE_PAGE_ORDINAL, waveform_list, 3, &value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == (report_id ? HIDP_STATUS_SUCCESS : HIDP_STATUS_INCOMPATIBLE_REPORT_ID), "HidP_GetUsageValue returned %#x\n", status ); report[0] = 2; status = HidP_GetUsageValue( HidP_Feature, HID_USAGE_PAGE_ORDINAL, waveform_list, 3, &value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_INCOMPATIBLE_REPORT_ID, "HidP_GetUsageValue returned %#x\n", status ); report[0] = report_id; status = HidP_GetUsageValue( HidP_Feature, HID_USAGE_PAGE_ORDINAL, 0xdead, 3, &value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_USAGE_NOT_FOUND, "HidP_GetUsageValue returned %#x\n", status ); value = 0xdeadbeef; status = HidP_GetUsageValue( HidP_Feature, HID_USAGE_PAGE_ORDINAL, waveform_list, 3, &value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetUsageValue returned %#x\n", status ); ok( value == HID_USAGE_HAPTICS_WAVEFORM_RUMBLE, "got value %x, expected %#x\n", value, HID_USAGE_HAPTICS_WAVEFORM_RUMBLE ); memset( buffer, 0xff, sizeof(buffer) ); status = HidP_SetUsageValueArray( HidP_Feature, HID_USAGE_PAGE_HAPTICS, 0, HID_USAGE_HAPTICS_WAVEFORM_CUTOFF_TIME, buffer, 0, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_BUFFER_TOO_SMALL, "HidP_SetUsageValueArray returned %#x\n", status ); status = HidP_SetUsageValueArray( HidP_Feature, HID_USAGE_PAGE_HAPTICS, 0, HID_USAGE_HAPTICS_WAVEFORM_CUTOFF_TIME, buffer, 64, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsageValueArray returned %#x\n", status ); ok( !memcmp( report + 9, buffer, 8 ), "unexpected report data\n" ); memset( buffer, 0, sizeof(buffer) ); status = HidP_GetUsageValueArray( HidP_Feature, HID_USAGE_PAGE_HAPTICS, 0, HID_USAGE_HAPTICS_WAVEFORM_CUTOFF_TIME, buffer, 0, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_BUFFER_TOO_SMALL, "HidP_GetUsageValueArray returned %#x\n", status ); status = HidP_GetUsageValueArray( HidP_Feature, HID_USAGE_PAGE_HAPTICS, 0, HID_USAGE_HAPTICS_WAVEFORM_CUTOFF_TIME, buffer, 64, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetUsageValueArray returned %#x\n", status ); memset( buffer + 16, 0xff, 8 ); ok( !memcmp( buffer, buffer + 16, 16 ), "unexpected report value\n" ); value = 0x7fffffff; status = HidP_SetUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsageValue returned %#x\n", status ); value = 0xdeadbeef; status = HidP_GetScaledUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, (LONG *)&value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_VALUE_OUT_OF_RANGE, "HidP_GetScaledUsageValue returned %#x\n", status ); ok( value == 0, "got value %x, expected %#x\n", value, 0 ); value = 0xdeadbeef; status = HidP_GetUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, &value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetUsageValue returned %#x\n", status ); ok( value == 0x7fffffff, "got value %x, expected %#x\n", value, 0x7fffffff ); value = 0x7fff; status = HidP_SetUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsageValue returned %#x\n", status ); value = 0xdeadbeef; status = HidP_GetScaledUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, (LONG *)&value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetScaledUsageValue returned %#x\n", status ); ok( value == 0x0003ffff, "got value %x, expected %#x\n", value, 0x0003ffff ); value = 0; status = HidP_SetUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetUsageValue returned %#x\n", status ); value = 0xdeadbeef; status = HidP_GetScaledUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, (LONG *)&value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetScaledUsageValue returned %#x\n", status ); ok( value == 0xfff90000, "got value %x, expected %#x\n", value, 0xfff90000 ); status = HidP_SetScaledUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, 0x1000, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetScaledUsageValue returned %#x\n", status ); value = 0; status = HidP_GetUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, &value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetUsageValue returned %#x\n", status ); ok( value == 0xfffff518, "got value %x, expected %#x\n", value, 0xfffff518 ); status = HidP_SetScaledUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, 0, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetScaledUsageValue returned %#x\n", status ); value = 0; status = HidP_GetUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, &value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetUsageValue returned %#x\n", status ); ok( value == 0xfffff45e, "got value %x, expected %#x\n", value, 0xfffff45e ); status = HidP_SetScaledUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, 0xdead, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetScaledUsageValue returned %#x\n", status ); value = 0; status = HidP_GetUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, &value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetUsageValue returned %#x\n", status ); ok( value == 0xfffffe7d, "got value %x, expected %#x\n", value, 0xfffffe7d ); status = HidP_SetScaledUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, 0xbeef, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_SetScaledUsageValue returned %#x\n", status ); value = 0; status = HidP_GetUsageValue( HidP_Feature, HID_USAGE_PAGE_GENERIC, 0, HID_USAGE_GENERIC_Z, &value, preparsed_data, report, caps.FeatureReportByteLength ); ok( status == HIDP_STATUS_SUCCESS, "HidP_GetUsageValue returned %#x\n", status ); ok( value == 0xfffffd0b, "got value %x, expected %#x\n", value, 0xfffffd0b ); test_hidp_get_input( file, report_id, caps.InputReportByteLength, preparsed_data ); test_hidp_get_feature( file, report_id, caps.FeatureReportByteLength, preparsed_data ); test_hidp_set_feature( file, report_id, caps.FeatureReportByteLength, preparsed_data ); test_hidp_set_output( file, report_id, caps.OutputReportByteLength, preparsed_data ); test_write_file( file, report_id, caps.OutputReportByteLength ); memset( report, 0xcd, sizeof(report) ); SetLastError( 0xdeadbeef ); ret = ReadFile( file, report, 0, &value, NULL ); ok( !ret && GetLastError() == ERROR_INVALID_USER_BUFFER, "ReadFile failed, last error %u\n", GetLastError() ); ok( value == 0, "ReadFile returned %x\n", value ); SetLastError( 0xdeadbeef ); ret = ReadFile( file, report, caps.InputReportByteLength - 1, &value, NULL ); ok( !ret && GetLastError() == ERROR_INVALID_USER_BUFFER, "ReadFile failed, last error %u\n", GetLastError() ); ok( value == 0, "ReadFile returned %x\n", value ); if (polled) { struct hid_expect expect[] = { { .code = IOCTL_HID_READ_REPORT, .report_len = caps.InputReportByteLength - (report_id ? 0 : 1), .report_buf = {report_id ? report_id : 0x5a,0x5a,0}, .ret_length = 3, .ret_status = STATUS_SUCCESS, }, { .code = IOCTL_HID_READ_REPORT, .report_len = caps.InputReportByteLength - (report_id ? 0 : 1), .report_buf = {report_id ? report_id : 0x5a,0x5a,1}, .ret_length = 3, .ret_status = STATUS_SUCCESS, }, }; send_hid_input( file, expect, sizeof(expect) ); memset( report, 0xcd, sizeof(report) ); SetLastError( 0xdeadbeef ); ret = ReadFile( file, report, caps.InputReportByteLength, &value, NULL ); ok( ret, "ReadFile failed, last error %u\n", GetLastError() ); ok( value == (report_id ? 3 : 4), "ReadFile returned %x\n", value ); ok( report[0] == report_id, "unexpected report data\n" ); overlapped.hEvent = CreateEventW( NULL, FALSE, FALSE, NULL ); overlapped2.hEvent = CreateEventW( NULL, FALSE, FALSE, NULL ); /* drain available input reports */ SetLastError( 0xdeadbeef ); while (ReadFile( async_file, report, caps.InputReportByteLength, NULL, &overlapped )) ResetEvent( overlapped.hEvent ); ok( GetLastError() == ERROR_IO_PENDING, "ReadFile returned error %u\n", GetLastError() ); ret = GetOverlappedResult( async_file, &overlapped, &value, TRUE ); ok( ret, "GetOverlappedResult failed, last error %u\n", GetLastError() ); ok( value == (report_id ? 3 : 4), "GetOverlappedResult returned length %u, expected %u\n", value, (report_id ? 3 : 4) ); ResetEvent( overlapped.hEvent ); memcpy( buffer, report, caps.InputReportByteLength ); memcpy( buffer + caps.InputReportByteLength, report, caps.InputReportByteLength ); SetLastError( 0xdeadbeef ); ret = ReadFile( async_file, report, caps.InputReportByteLength, NULL, &overlapped ); ok( !ret, "ReadFile succeeded\n" ); ok( GetLastError() == ERROR_IO_PENDING, "ReadFile returned error %u\n", GetLastError() ); SetLastError( 0xdeadbeef ); ret = ReadFile( async_file, buffer, caps.InputReportByteLength, NULL, &overlapped2 ); ok( !ret, "ReadFile succeeded\n" ); ok( GetLastError() == ERROR_IO_PENDING, "ReadFile returned error %u\n", GetLastError() ); /* wait for second report to be ready */ ret = GetOverlappedResult( async_file, &overlapped2, &value, TRUE ); ok( ret, "GetOverlappedResult failed, last error %u\n", GetLastError() ); ok( value == (report_id ? 3 : 4), "GetOverlappedResult returned length %u, expected %u\n", value, (report_id ? 3 : 4) ); /* first report should be ready and the same */ ret = GetOverlappedResult( async_file, &overlapped, &value, FALSE ); ok( ret, "GetOverlappedResult failed, last error %u\n", GetLastError() ); ok( value == (report_id ? 3 : 4), "GetOverlappedResult returned length %u, expected %u\n", value, (report_id ? 3 : 4) ); ok( memcmp( report, buffer + caps.InputReportByteLength, caps.InputReportByteLength ), "expected different report\n" ); ok( !memcmp( report, buffer, caps.InputReportByteLength ), "expected identical reports\n" ); value = 10; SetLastError( 0xdeadbeef ); ret = sync_ioctl( file, IOCTL_HID_SET_POLL_FREQUENCY_MSEC, &value, sizeof(ULONG), NULL, NULL ); ok( ret, "IOCTL_HID_SET_POLL_FREQUENCY_MSEC failed last error %u\n", GetLastError() ); Sleep( 600 ); SetLastError( 0xdeadbeef ); ret = ReadFile( async_file, report, caps.InputReportByteLength, NULL, &overlapped ); ok( !ret, "ReadFile succeeded\n" ); ok( GetLastError() == ERROR_IO_PENDING, "ReadFile returned error %u\n", GetLastError() ); SetLastError( 0xdeadbeef ); ret = ReadFile( async_file, buffer, caps.InputReportByteLength, NULL, &overlapped2 ); ok( !ret, "ReadFile succeeded\n" ); ok( GetLastError() == ERROR_IO_PENDING, "ReadFile returned error %u\n", GetLastError() ); /* wait for second report to be ready */ ret = GetOverlappedResult( async_file, &overlapped2, &value, TRUE ); ok( ret, "GetOverlappedResult failed, last error %u\n", GetLastError() ); ok( value == (report_id ? 3 : 4), "GetOverlappedResult returned length %u, expected %u\n", value, (report_id ? 3 : 4) ); /* first report should be ready and the same */ ret = GetOverlappedResult( async_file, &overlapped, &value, FALSE ); ok( ret, "GetOverlappedResult failed, last error %u\n", GetLastError() ); ok( value == (report_id ? 3 : 4), "GetOverlappedResult returned length %u, expected %u\n", value, (report_id ? 3 : 4) ); ok( !memcmp( report, buffer, caps.InputReportByteLength ), "expected identical reports\n" ); CloseHandle( overlapped.hEvent ); CloseHandle( overlapped2.hEvent ); } else { struct hid_expect expect[] = { { .code = IOCTL_HID_READ_REPORT, .report_len = caps.InputReportByteLength - (report_id ? 0 : 1), .report_buf = {report_id ? report_id : 0x5a,0x5a,0x5a}, .ret_length = 3, .ret_status = STATUS_SUCCESS, }, { .code = IOCTL_HID_READ_REPORT, .report_len = caps.InputReportByteLength - (report_id ? 0 : 1), .report_buf = {report_id ? report_id : 0xa5,0xa5,0xa5,0xa5,0xa5}, .ret_length = caps.InputReportByteLength - (report_id ? 0 : 1), .ret_status = STATUS_SUCCESS, }, }; overlapped.hEvent = CreateEventW( NULL, FALSE, FALSE, NULL ); overlapped2.hEvent = CreateEventW( NULL, FALSE, FALSE, NULL ); SetLastError( 0xdeadbeef ); memset( report, 0, sizeof(report) ); ret = ReadFile( async_file, report, caps.InputReportByteLength, NULL, &overlapped ); ok( !ret, "ReadFile succeeded\n" ); ok( GetLastError() == ERROR_IO_PENDING, "ReadFile returned error %u\n", GetLastError() ); Sleep( 50 ); ret = GetOverlappedResult( async_file, &overlapped, &value, FALSE ); ok( !ret, "GetOverlappedResult succeeded\n" ); ok( GetLastError() == ERROR_IO_INCOMPLETE, "GetOverlappedResult returned error %u\n", GetLastError() ); SetLastError( 0xdeadbeef ); memset( buffer, 0, sizeof(buffer) ); ret = ReadFile( async_file, buffer, caps.InputReportByteLength, NULL, &overlapped2 ); ok( !ret, "ReadFile succeeded\n" ); ok( GetLastError() == ERROR_IO_PENDING, "ReadFile returned error %u\n", GetLastError() ); Sleep( 50 ); ret = GetOverlappedResult( async_file, &overlapped2, &value, FALSE ); ok( !ret, "GetOverlappedResult succeeded\n" ); ok( GetLastError() == ERROR_IO_INCOMPLETE, "GetOverlappedResult returned error %u\n", GetLastError() ); memset( report + caps.InputReportByteLength, 0xa5, 5 ); if (report_id) report[caps.InputReportByteLength] = report_id; send_hid_input( file, expect, sizeof(expect) ); /* first read should be completed */ ret = GetOverlappedResult( async_file, &overlapped, &value, TRUE ); ok( ret, "GetOverlappedResult failed, last error %u\n", GetLastError() ); ok( value == caps.InputReportByteLength, "got length %u, expected %u\n", value, caps.InputReportByteLength ); /* second read should still be pending */ Sleep( 50 ); ret = GetOverlappedResult( async_file, &overlapped2, &value, FALSE ); ok( !ret, "GetOverlappedResult succeeded\n" ); ok( GetLastError() == ERROR_IO_INCOMPLETE, "GetOverlappedResult returned error %u\n", GetLastError() ); memset( buffer + caps.InputReportByteLength, 0x3b, 5 ); if (report_id) buffer[caps.InputReportByteLength] = report_id; memset( expect[1].report_buf, 0x3b, 5 ); if (report_id) expect[1].report_buf[0] = report_id; send_hid_input( file, expect, sizeof(expect) ); ret = GetOverlappedResult( async_file, &overlapped2, &value, TRUE ); ok( ret, "GetOverlappedResult failed, last error %u\n", GetLastError() ); ok( value == caps.InputReportByteLength, "got length %u, expected %u\n", value, caps.InputReportByteLength ); off = report_id ? 0 : 1; ok( memcmp( report, buffer, caps.InputReportByteLength ), "expected different report\n" ); ok( !memcmp( report + off, report + caps.InputReportByteLength, caps.InputReportByteLength - off ), "expected identical reports\n" ); ok( !memcmp( buffer + off, buffer + caps.InputReportByteLength, caps.InputReportByteLength - off ), "expected identical reports\n" ); CloseHandle( overlapped.hEvent ); CloseHandle( overlapped2.hEvent ); } HidD_FreePreparsedData( preparsed_data ); } static void test_hid_device( DWORD report_id, DWORD polled, const HIDP_CAPS *expect_caps ) { char buffer[FIELD_OFFSET( SP_DEVICE_INTERFACE_DETAIL_DATA_W, DevicePath[MAX_PATH] )]; SP_DEVICE_INTERFACE_DATA iface = {sizeof(SP_DEVICE_INTERFACE_DATA)}; SP_DEVICE_INTERFACE_DETAIL_DATA_W *iface_detail = (void *)buffer; SP_DEVINFO_DATA device = {sizeof(SP_DEVINFO_DATA)}; ULONG count, poll_freq, out_len; HANDLE file, async_file; BOOL ret, found = FALSE; OBJECT_ATTRIBUTES attr; UNICODE_STRING string; IO_STATUS_BLOCK io; NTSTATUS status; unsigned int i; HDEVINFO set; winetest_push_context( "id %d%s", report_id, polled ? " poll" : "" ); set = SetupDiGetClassDevsW( &GUID_DEVINTERFACE_HID, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT ); ok( set != INVALID_HANDLE_VALUE, "failed to get device list, error %#x\n", GetLastError() ); for (i = 0; SetupDiEnumDeviceInfo( set, i, &device ); ++i) { ret = SetupDiEnumDeviceInterfaces( set, &device, &GUID_DEVINTERFACE_HID, 0, &iface ); ok( ret, "failed to get interface, error %#x\n", GetLastError() ); ok( IsEqualGUID( &iface.InterfaceClassGuid, &GUID_DEVINTERFACE_HID ), "wrong class %s\n", debugstr_guid( &iface.InterfaceClassGuid ) ); ok( iface.Flags == SPINT_ACTIVE, "got flags %#x\n", iface.Flags ); iface_detail->cbSize = sizeof(*iface_detail); ret = SetupDiGetDeviceInterfaceDetailW( set, &iface, iface_detail, sizeof(buffer), NULL, NULL ); ok( ret, "failed to get interface path, error %#x\n", GetLastError() ); if (wcsstr( iface_detail->DevicePath, L"\\\\?\\hid#winetest#1" )) { found = TRUE; break; } } SetupDiDestroyDeviceInfoList( set ); todo_wine ok( found, "didn't find device\n" ); file = CreateFileW( iface_detail->DevicePath, FILE_READ_ACCESS | FILE_WRITE_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL ); ok( file != INVALID_HANDLE_VALUE, "got error %u\n", GetLastError() ); count = 0xdeadbeef; SetLastError( 0xdeadbeef ); ret = HidD_GetNumInputBuffers( file, &count ); ok( ret, "HidD_GetNumInputBuffers failed last error %u\n", GetLastError() ); ok( count == 32, "HidD_GetNumInputBuffers returned %u\n", count ); SetLastError( 0xdeadbeef ); ret = HidD_SetNumInputBuffers( file, 1 ); ok( !ret, "HidD_SetNumInputBuffers succeeded\n" ); ok( GetLastError() == ERROR_INVALID_PARAMETER, "HidD_SetNumInputBuffers returned error %u\n", GetLastError() ); SetLastError( 0xdeadbeef ); ret = HidD_SetNumInputBuffers( file, 513 ); ok( !ret, "HidD_SetNumInputBuffers succeeded\n" ); ok( GetLastError() == ERROR_INVALID_PARAMETER, "HidD_SetNumInputBuffers returned error %u\n", GetLastError() ); SetLastError( 0xdeadbeef ); ret = HidD_SetNumInputBuffers( file, 16 ); ok( ret, "HidD_SetNumInputBuffers failed last error %u\n", GetLastError() ); count = 0xdeadbeef; SetLastError( 0xdeadbeef ); ret = HidD_GetNumInputBuffers( file, &count ); ok( ret, "HidD_GetNumInputBuffers failed last error %u\n", GetLastError() ); ok( count == 16, "HidD_GetNumInputBuffers returned %u\n", count ); async_file = CreateFileW( iface_detail->DevicePath, FILE_READ_ACCESS | FILE_WRITE_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, NULL ); ok( async_file != INVALID_HANDLE_VALUE, "got error %u\n", GetLastError() ); count = 0xdeadbeef; SetLastError( 0xdeadbeef ); ret = HidD_GetNumInputBuffers( async_file, &count ); ok( ret, "HidD_GetNumInputBuffers failed last error %u\n", GetLastError() ); ok( count == 32, "HidD_GetNumInputBuffers returned %u\n", count ); SetLastError( 0xdeadbeef ); ret = HidD_SetNumInputBuffers( async_file, 2 ); ok( ret, "HidD_SetNumInputBuffers failed last error %u\n", GetLastError() ); count = 0xdeadbeef; SetLastError( 0xdeadbeef ); ret = HidD_GetNumInputBuffers( async_file, &count ); ok( ret, "HidD_GetNumInputBuffers failed last error %u\n", GetLastError() ); ok( count == 2, "HidD_GetNumInputBuffers returned %u\n", count ); count = 0xdeadbeef; SetLastError( 0xdeadbeef ); ret = HidD_GetNumInputBuffers( file, &count ); ok( ret, "HidD_GetNumInputBuffers failed last error %u\n", GetLastError() ); ok( count == 16, "HidD_GetNumInputBuffers returned %u\n", count ); if (polled) { out_len = sizeof(ULONG); SetLastError( 0xdeadbeef ); ret = sync_ioctl( file, IOCTL_HID_GET_POLL_FREQUENCY_MSEC, NULL, 0, &poll_freq, &out_len ); ok( ret, "IOCTL_HID_GET_POLL_FREQUENCY_MSEC failed last error %u\n", GetLastError() ); ok( out_len == sizeof(ULONG), "got out_len %u, expected sizeof(ULONG)\n", out_len ); todo_wine ok( poll_freq == 5, "got poll_freq %u, expected 5\n", poll_freq ); out_len = 0; poll_freq = 500; SetLastError( 0xdeadbeef ); ret = sync_ioctl( file, IOCTL_HID_SET_POLL_FREQUENCY_MSEC, &poll_freq, sizeof(ULONG), NULL, &out_len ); ok( ret, "IOCTL_HID_SET_POLL_FREQUENCY_MSEC failed last error %u\n", GetLastError() ); ok( out_len == 0, "got out_len %u, expected 0\n", out_len ); out_len = 0; poll_freq = 10001; SetLastError( 0xdeadbeef ); ret = sync_ioctl( file, IOCTL_HID_SET_POLL_FREQUENCY_MSEC, &poll_freq, sizeof(ULONG), NULL, &out_len ); ok( ret, "IOCTL_HID_SET_POLL_FREQUENCY_MSEC failed last error %u\n", GetLastError() ); ok( out_len == 0, "got out_len %u, expected 0\n", out_len ); out_len = 0; poll_freq = 0; SetLastError( 0xdeadbeef ); ret = sync_ioctl( file, IOCTL_HID_SET_POLL_FREQUENCY_MSEC, &poll_freq, sizeof(ULONG), NULL, &out_len ); ok( ret, "IOCTL_HID_SET_POLL_FREQUENCY_MSEC failed last error %u\n", GetLastError() ); ok( out_len == 0, "got out_len %u, expected 0\n", out_len ); out_len = sizeof(ULONG); SetLastError( 0xdeadbeef ); ret = sync_ioctl( file, IOCTL_HID_GET_POLL_FREQUENCY_MSEC, NULL, 0, &poll_freq, &out_len ); ok( ret, "IOCTL_HID_GET_POLL_FREQUENCY_MSEC failed last error %u\n", GetLastError() ); ok( out_len == sizeof(ULONG), "got out_len %u, expected sizeof(ULONG)\n", out_len ); ok( poll_freq == 10000, "got poll_freq %u, expected 10000\n", poll_freq ); out_len = 0; poll_freq = 500; SetLastError( 0xdeadbeef ); ret = sync_ioctl( file, IOCTL_HID_SET_POLL_FREQUENCY_MSEC, &poll_freq, sizeof(ULONG), NULL, &out_len ); ok( ret, "IOCTL_HID_SET_POLL_FREQUENCY_MSEC failed last error %u\n", GetLastError() ); ok( out_len == 0, "got out_len %u, expected 0\n", out_len ); out_len = sizeof(ULONG); SetLastError( 0xdeadbeef ); ret = sync_ioctl( async_file, IOCTL_HID_GET_POLL_FREQUENCY_MSEC, NULL, 0, &poll_freq, &out_len ); ok( ret, "IOCTL_HID_GET_POLL_FREQUENCY_MSEC failed last error %u\n", GetLastError() ); ok( out_len == sizeof(ULONG), "got out_len %u, expected sizeof(ULONG)\n", out_len ); ok( poll_freq == 500, "got poll_freq %u, expected 500\n", poll_freq ); } test_hidp( file, async_file, report_id, polled, expect_caps ); CloseHandle( async_file ); CloseHandle( file ); RtlInitUnicodeString( &string, L"\\??\\root#winetest#0#{deadbeef-29ef-4538-a5fd-b69573a362c0}" ); InitializeObjectAttributes( &attr, &string, OBJ_CASE_INSENSITIVE, NULL, NULL ); status = NtOpenFile( &file, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT ); todo_wine ok( status == STATUS_UNSUCCESSFUL, "got %#x\n", status ); winetest_pop_context(); } static void test_hid_driver( DWORD report_id, DWORD polled ) { #include "psh_hid_macros.h" /* Replace REPORT_ID with USAGE_PAGE when id is 0 */ #define REPORT_ID_OR_USAGE_PAGE(size, id, off) SHORT_ITEM_1((id ? 8 : 0), 1, (id + off)) const unsigned char report_desc[] = { USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Application), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Logical), REPORT_ID_OR_USAGE_PAGE(1, report_id, 0), USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_X), USAGE(1, HID_USAGE_GENERIC_Y), LOGICAL_MINIMUM(1, -128), LOGICAL_MAXIMUM(1, 127), REPORT_SIZE(1, 8), REPORT_COUNT(1, 2), INPUT(1, Data|Var|Abs), USAGE_PAGE(1, HID_USAGE_PAGE_BUTTON), USAGE_MINIMUM(1, 1), USAGE_MAXIMUM(1, 8), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), REPORT_COUNT(1, 8), REPORT_SIZE(1, 1), INPUT(1, Data|Var|Abs), USAGE_MINIMUM(1, 0x18), USAGE_MAXIMUM(1, 0x1f), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), REPORT_COUNT(1, 8), REPORT_SIZE(1, 1), INPUT(1, Cnst|Var|Abs), REPORT_SIZE(1, 8), INPUT(1, Cnst|Var|Abs), /* needs to be 8 bit aligned as next has Buff */ USAGE_MINIMUM(4, (HID_USAGE_PAGE_KEYBOARD<<16)|0x8), USAGE_MAXIMUM(4, (HID_USAGE_PAGE_KEYBOARD<<16)|0xf), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 8), REPORT_COUNT(1, 2), REPORT_SIZE(1, 8), INPUT(2, Data|Ary|Rel|Wrap|Lin|Pref|Null|Vol|Buff), /* needs to be 8 bit aligned as previous has Buff */ USAGE(1, 0x20), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), REPORT_COUNT(1, 8), REPORT_SIZE(1, 1), INPUT(1, Data|Var|Abs), USAGE_MINIMUM(1, 0x21), USAGE_MAXIMUM(1, 0x22), REPORT_COUNT(1, 2), REPORT_SIZE(1, 0), INPUT(1, Data|Var|Abs), USAGE(1, 0x23), REPORT_COUNT(1, 0), REPORT_SIZE(1, 1), INPUT(1, Data|Var|Abs), USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_HATSWITCH), LOGICAL_MINIMUM(1, 1), LOGICAL_MAXIMUM(1, 8), REPORT_SIZE(1, 4), REPORT_COUNT(1, 2), INPUT(1, Data|Var|Abs), USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_Z), LOGICAL_MINIMUM(4, 0x00000000), LOGICAL_MAXIMUM(4, 0x3fffffff), PHYSICAL_MINIMUM(4, 0x80000000), PHYSICAL_MAXIMUM(4, 0x7fffffff), REPORT_SIZE(1, 32), REPORT_COUNT(1, 1), INPUT(1, Data|Var|Abs), /* reset physical range to its default interpretation */ USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_RX), PHYSICAL_MINIMUM(4, 0), PHYSICAL_MAXIMUM(4, 0), REPORT_SIZE(1, 32), REPORT_COUNT(1, 1), INPUT(1, Data|Var|Abs), USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_RY), LOGICAL_MINIMUM(4, 0x7fff), LOGICAL_MAXIMUM(4, 0x0000), PHYSICAL_MINIMUM(4, 0x0000), PHYSICAL_MAXIMUM(4, 0x7fff), REPORT_SIZE(1, 32), REPORT_COUNT(1, 1), INPUT(1, Data|Var|Abs), END_COLLECTION, USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Report), REPORT_ID_OR_USAGE_PAGE(1, report_id, 1), USAGE_PAGE(1, HID_USAGE_PAGE_BUTTON), USAGE_MINIMUM(1, 9), USAGE_MAXIMUM(1, 10), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), REPORT_COUNT(1, 8), REPORT_SIZE(1, 1), INPUT(1, Data|Var|Abs), END_COLLECTION, USAGE_PAGE(1, HID_USAGE_PAGE_LED), USAGE(1, HID_USAGE_LED_GREEN), COLLECTION(1, Report), REPORT_ID_OR_USAGE_PAGE(1, report_id, 0), USAGE_PAGE(1, HID_USAGE_PAGE_LED), USAGE(1, 1), USAGE(1, 2), USAGE(1, 3), USAGE(1, 4), USAGE(1, 5), USAGE(1, 6), USAGE(1, 7), USAGE(1, 8), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 1), REPORT_COUNT(1, 8), REPORT_SIZE(1, 1), INPUT(1, Data|Var|Abs), USAGE(4, (HID_USAGE_PAGE_KEYBOARD<<16)|0x8c), USAGE(4, (HID_USAGE_PAGE_KEYBOARD<<16)|0x8d), USAGE(4, (HID_USAGE_PAGE_KEYBOARD<<16)|0x8e), USAGE(4, (HID_USAGE_PAGE_KEYBOARD<<16)|0x8f), LOGICAL_MINIMUM(1, 1), LOGICAL_MAXIMUM(1, 16), REPORT_COUNT(1, 2), REPORT_SIZE(1, 8), INPUT(1, Data|Ary|Abs), END_COLLECTION, USAGE_PAGE(2, HID_USAGE_PAGE_HAPTICS), USAGE(1, HID_USAGE_HAPTICS_SIMPLE_CONTROLLER), COLLECTION(1, Logical), REPORT_ID_OR_USAGE_PAGE(1, report_id, 0), USAGE_PAGE(2, HID_USAGE_PAGE_HAPTICS), USAGE(1, HID_USAGE_HAPTICS_WAVEFORM_LIST), COLLECTION(1, NamedArray), USAGE_PAGE(1, HID_USAGE_PAGE_ORDINAL), USAGE(1, 3), /* HID_USAGE_HAPTICS_WAVEFORM_RUMBLE */ USAGE(1, 4), /* HID_USAGE_HAPTICS_WAVEFORM_BUZZ */ LOGICAL_MINIMUM(2, 0x0000), LOGICAL_MAXIMUM(2, 0xffff), REPORT_COUNT(1, 2), REPORT_SIZE(1, 16), FEATURE(1, Data|Var|Abs|Null), END_COLLECTION, USAGE_PAGE(2, HID_USAGE_PAGE_HAPTICS), USAGE(1, HID_USAGE_HAPTICS_DURATION_LIST), COLLECTION(1, NamedArray), USAGE_PAGE(1, HID_USAGE_PAGE_ORDINAL), USAGE(1, 3), /* 0 (HID_USAGE_HAPTICS_WAVEFORM_RUMBLE) */ USAGE(1, 4), /* 0 (HID_USAGE_HAPTICS_WAVEFORM_BUZZ) */ LOGICAL_MINIMUM(2, 0x0000), LOGICAL_MAXIMUM(2, 0xffff), REPORT_COUNT(1, 2), REPORT_SIZE(1, 16), FEATURE(1, Data|Var|Abs|Null), END_COLLECTION, USAGE_PAGE(2, HID_USAGE_PAGE_HAPTICS), USAGE(1, HID_USAGE_HAPTICS_WAVEFORM_CUTOFF_TIME), UNIT(2, 0x1001), /* seconds */ UNIT_EXPONENT(1, -3), /* 10^-3 */ LOGICAL_MINIMUM(2, 0x8000), LOGICAL_MAXIMUM(2, 0x7fff), PHYSICAL_MINIMUM(4, 0x00000000), PHYSICAL_MAXIMUM(4, 0xffffffff), REPORT_SIZE(1, 32), REPORT_COUNT(1, 2), FEATURE(1, Data|Var|Abs), /* reset global items */ UNIT(1, 0), /* None */ UNIT_EXPONENT(1, 0), USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_Z), LOGICAL_MINIMUM(4, 0x0000), LOGICAL_MAXIMUM(4, 0x7fff), PHYSICAL_MINIMUM(4, 0xfff90000), PHYSICAL_MAXIMUM(4, 0x0003ffff), REPORT_SIZE(1, 32), REPORT_COUNT(1, 1), FEATURE(1, Data|Var|Abs), END_COLLECTION, USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Report), REPORT_ID_OR_USAGE_PAGE(1, report_id, 1), USAGE_PAGE(1, HID_USAGE_PAGE_BUTTON), USAGE_MINIMUM(1, 9), USAGE_MAXIMUM(1, 10), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 1), REPORT_COUNT(1, 8), REPORT_SIZE(1, 1), FEATURE(1, Data|Var|Abs), END_COLLECTION, USAGE_PAGE(1, HID_USAGE_PAGE_LED), USAGE(1, HID_USAGE_LED_GREEN), COLLECTION(1, Report), REPORT_ID_OR_USAGE_PAGE(1, report_id, 0), USAGE_PAGE(1, HID_USAGE_PAGE_LED), REPORT_COUNT(1, 8), REPORT_SIZE(1, 1), OUTPUT(1, Cnst|Var|Abs), END_COLLECTION, USAGE_PAGE(1, HID_USAGE_PAGE_LED), USAGE(1, HID_USAGE_LED_RED), COLLECTION(1, Report), REPORT_ID_OR_USAGE_PAGE(1, report_id, 1), USAGE_PAGE(1, HID_USAGE_PAGE_LED), REPORT_COUNT(1, 8), REPORT_SIZE(1, 1), OUTPUT(1, Cnst|Var|Abs), END_COLLECTION, END_COLLECTION, }; #undef REPORT_ID_OR_USAGE_PAGE #include "pop_hid_macros.h" static const HID_DEVICE_ATTRIBUTES attributes = { .Size = sizeof(HID_DEVICE_ATTRIBUTES), .VendorID = 0x1209, .ProductID = 0x0001, .VersionNumber = 0x0100, }; const HIDP_CAPS caps = { .Usage = HID_USAGE_GENERIC_JOYSTICK, .UsagePage = HID_USAGE_PAGE_GENERIC, .InputReportByteLength = report_id ? 32 : 33, .OutputReportByteLength = report_id ? 2 : 3, .FeatureReportByteLength = report_id ? 21 : 22, .NumberLinkCollectionNodes = 10, .NumberInputButtonCaps = 17, .NumberInputValueCaps = 7, .NumberInputDataIndices = 47, .NumberFeatureButtonCaps = 1, .NumberFeatureValueCaps = 6, .NumberFeatureDataIndices = 8, }; const struct hid_expect expect_in = { .code = IOCTL_HID_READ_REPORT, .report_len = caps.InputReportByteLength - (report_id ? 0 : 1), .report_buf = {report_id ? report_id : 0x5a,0x5a,0x5a}, .ret_length = 3, .ret_status = STATUS_SUCCESS, }; WCHAR cwd[MAX_PATH], tempdir[MAX_PATH]; LSTATUS status; HKEY hkey; GetCurrentDirectoryW( ARRAY_SIZE(cwd), cwd ); GetTempPathW( ARRAY_SIZE(tempdir), tempdir ); SetCurrentDirectoryW( tempdir ); status = RegCreateKeyExW( HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Services\\winetest", 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &hkey, NULL ); ok( !status, "RegCreateKeyExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"ReportID", 0, REG_DWORD, (void *)&report_id, sizeof(report_id) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"PolledMode", 0, REG_DWORD, (void *)&polled, sizeof(polled) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Descriptor", 0, REG_BINARY, (void *)report_desc, sizeof(report_desc) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Attributes", 0, REG_BINARY, (void *)&attributes, sizeof(attributes) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Caps", 0, REG_BINARY, (void *)&caps, sizeof(caps) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Expect", 0, REG_BINARY, NULL, 0 ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Input", 0, REG_BINARY, (void *)&expect_in, polled ? sizeof(expect_in) : 0 ); ok( !status, "RegSetValueExW returned %#x\n", status ); if (pnp_driver_start( L"driver_hid.dll" )) test_hid_device( report_id, polled, &caps ); pnp_driver_stop(); SetCurrentDirectoryW( cwd ); } /* undocumented HID internal preparsed data structure */ struct hidp_kdr_caps { USHORT usage_page; UCHAR report_id; UCHAR start_bit; USHORT bit_size; USHORT report_count; USHORT start_byte; USHORT total_bits; ULONG bit_field; USHORT end_byte; USHORT link_collection; USAGE link_usage_page; USAGE link_usage; ULONG flags; ULONG padding[8]; USAGE usage_min; USAGE usage_max; USHORT string_min; USHORT string_max; USHORT designator_min; USHORT designator_max; USHORT data_index_min; USHORT data_index_max; USHORT null_value; USHORT unknown; LONG logical_min; LONG logical_max; LONG physical_min; LONG physical_max; LONG units; LONG units_exp; }; /* named array continues on next caps */ #define HIDP_KDR_CAPS_ARRAY_HAS_MORE 0x01 #define HIDP_KDR_CAPS_IS_CONSTANT 0x02 #define HIDP_KDR_CAPS_IS_BUTTON 0x04 #define HIDP_KDR_CAPS_IS_ABSOLUTE 0x08 #define HIDP_KDR_CAPS_IS_RANGE 0x10 #define HIDP_KDR_CAPS_IS_STRING_RANGE 0x40 #define HIDP_KDR_CAPS_IS_DESIGNATOR_RANGE 0x80 struct hidp_kdr_node { USAGE usage; USAGE usage_page; USHORT parent; USHORT number_of_children; USHORT next_sibling; USHORT first_child; ULONG collection_type; }; struct hidp_kdr { char magic[8]; USAGE usage; USAGE usage_page; USHORT unknown[2]; USHORT input_caps_start; USHORT input_caps_count; USHORT input_caps_end; USHORT input_report_byte_length; USHORT output_caps_start; USHORT output_caps_count; USHORT output_caps_end; USHORT output_report_byte_length; USHORT feature_caps_start; USHORT feature_caps_count; USHORT feature_caps_end; USHORT feature_report_byte_length; USHORT caps_size; USHORT number_link_collection_nodes; struct hidp_kdr_caps caps[1]; /* struct hidp_kdr_node nodes[1] */ }; static void test_hidp_kdr(void) { #include "psh_hid_macros.h" const unsigned char report_desc[] = { USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Application), USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), LOGICAL_MINIMUM(1, 1), LOGICAL_MAXIMUM(1, 127), PHYSICAL_MINIMUM(1, -128), PHYSICAL_MAXIMUM(1, 127), USAGE(1, HID_USAGE_GENERIC_RZ), REPORT_SIZE(1, 16), REPORT_COUNT(1, 0), FEATURE(1, Data|Var|Abs), USAGE(1, HID_USAGE_GENERIC_SLIDER), REPORT_SIZE(1, 16), REPORT_COUNT(1, 1), FEATURE(1, Data|Var|Abs), USAGE(1, HID_USAGE_GENERIC_X), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), UNIT(1, 0x100e), UNIT_EXPONENT(1, -3), INPUT(1, Data|Var|Abs), UNIT_EXPONENT(1, 0), UNIT(1, 0), USAGE(1, HID_USAGE_GENERIC_Y), DESIGNATOR_MINIMUM(1, 1), DESIGNATOR_MAXIMUM(1, 4), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), INPUT(1, Cnst|Var|Abs), USAGE(1, HID_USAGE_GENERIC_Z), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), INPUT(1, Data|Var|Rel), USAGE(1, HID_USAGE_GENERIC_RX), USAGE(1, HID_USAGE_GENERIC_RY), REPORT_SIZE(1, 16), REPORT_COUNT(1, 2), LOGICAL_MINIMUM(1, 7), INPUT(1, Data|Var|Abs|Null), COLLECTION(1, Application), USAGE(4, (HID_USAGE_PAGE_BUTTON << 16)|1), USAGE(4, (HID_USAGE_PAGE_BUTTON << 16)|2), REPORT_SIZE(1, 1), REPORT_COUNT(1, 8), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), INPUT(1, Data|Var|Abs), USAGE_MINIMUM(4, (HID_USAGE_PAGE_BUTTON << 16)|3), USAGE_MAXIMUM(4, (HID_USAGE_PAGE_BUTTON << 16)|8), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), LOGICAL_MINIMUM(1, 3), LOGICAL_MAXIMUM(1, 8), INPUT(1, Data|Ary|Abs), USAGE_MINIMUM(4, (HID_USAGE_PAGE_BUTTON << 16)|9), USAGE_MAXIMUM(4, (HID_USAGE_PAGE_BUTTON << 16)|12), REPORT_SIZE(1, 8), REPORT_COUNT(1, 4), LOGICAL_MINIMUM(1, 9), LOGICAL_MAXIMUM(1, 12), INPUT(2, Data|Ary|Abs|Buff), USAGE(4, (HID_USAGE_PAGE_BUTTON << 16)|13), USAGE(4, (HID_USAGE_PAGE_BUTTON << 16)|14), USAGE(4, (HID_USAGE_PAGE_BUTTON << 16)|15), USAGE(4, (HID_USAGE_PAGE_BUTTON << 16)|16), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), LOGICAL_MINIMUM(1, 13), LOGICAL_MAXIMUM(1, 16), INPUT(1, Data|Ary|Abs), END_COLLECTION, END_COLLECTION, }; #include "pop_hid_macros.h" static const HIDP_CAPS expect_hidp_caps = { .Usage = HID_USAGE_GENERIC_JOYSTICK, .UsagePage = HID_USAGE_PAGE_GENERIC, .InputReportByteLength = 15, }; static const HID_DEVICE_ATTRIBUTES attributes = { .Size = sizeof(HID_DEVICE_ATTRIBUTES), .VendorID = 0x1209, .ProductID = 0x0001, .VersionNumber = 0x0100, }; static const struct hidp_kdr expect_kdr = { .magic = "HidP KDR", .usage = 0x04, .usage_page = 0x01, .input_caps_count = 13, .input_caps_end = 13, .input_report_byte_length = 15, .output_caps_start = 13, .output_caps_end = 13, .feature_caps_start = 13, .feature_caps_count = 2, .feature_caps_end = 14, .feature_report_byte_length = 3, .caps_size = 1560, .number_link_collection_nodes = 2, }; static const struct hidp_kdr_caps expect_caps[] = { { .usage_page = 0x01, .bit_size = 0x08, .report_count = 0x1, .start_byte = 0x1, .total_bits = 0x08, .bit_field = 0x002, .end_byte = 0x2, .link_usage_page = 0x01, .link_usage = 0x04, .flags = 0x08, .usage_min = 0x30, .usage_max = 0x30, .logical_min = 1, .logical_max = 127, .physical_min = -128, .physical_max = 127, .units = 0xe, .units_exp = -3 }, { .usage_page = 0x01, .bit_size = 0x08, .report_count = 0x1, .start_byte = 0x2, .total_bits = 0x08, .bit_field = 0x003, .end_byte = 0x3, .link_usage_page = 0x01, .link_usage = 0x04, .flags = 0x8a, .usage_min = 0x31, .usage_max = 0x31, .designator_min = 1, .designator_max = 4, .data_index_min = 0x01, .data_index_max = 0x01, .logical_min = 1, .logical_max = 127, .physical_min = -128, .physical_max = 127 }, { .usage_page = 0x01, .bit_size = 0x08, .report_count = 0x1, .start_byte = 0x3, .total_bits = 0x08, .bit_field = 0x006, .end_byte = 0x4, .link_usage_page = 0x01, .link_usage = 0x04, .usage_min = 0x32, .usage_max = 0x32, .data_index_min = 0x02, .data_index_max = 0x02, .logical_min = 1, .logical_max = 127, .physical_min = -128, .physical_max = 127 }, { .usage_page = 0x01, .bit_size = 0x10, .report_count = 0x1, .start_byte = 0x6, .total_bits = 0x10, .bit_field = 0x042, .end_byte = 0x8, .link_usage_page = 0x01, .link_usage = 0x04, .flags = 0x08, .usage_min = 0x34, .usage_max = 0x34, .data_index_min = 0x03, .data_index_max = 0x03, .null_value = 1, .logical_min = 7, .logical_max = 127, .physical_min = -128, .physical_max = 127 }, { .usage_page = 0x01, .bit_size = 0x10, .report_count = 0x1, .start_byte = 0x4, .total_bits = 0x10, .bit_field = 0x042, .end_byte = 0x6, .link_usage_page = 0x01, .link_usage = 0x04, .flags = 0x08, .usage_min = 0x33, .usage_max = 0x33, .data_index_min = 0x04, .data_index_max = 0x04, .null_value = 1, .logical_min = 7, .logical_max = 127, .physical_min = -128, .physical_max = 127 }, { .usage_page = 0x09, .start_bit = 1, .bit_size = 0x01, .report_count = 0x7, .start_byte = 0x8, .total_bits = 0x07, .bit_field = 0x002, .end_byte = 0x9, .link_collection = 1, .link_usage_page = 0x01, .flags = 0x0c, .usage_min = 0x02, .usage_max = 0x02, .data_index_min = 0x05, .data_index_max = 0x05, }, { .usage_page = 0x09, .bit_size = 0x01, .report_count = 0x1, .start_byte = 0x8, .total_bits = 0x01, .bit_field = 0x002, .end_byte = 0x9, .link_collection = 1, .link_usage_page = 0x01, .flags = 0x0c, .usage_min = 0x01, .usage_max = 0x01, .data_index_min = 0x06, .data_index_max = 0x06, }, { .usage_page = 0x09, .bit_size = 0x08, .report_count = 0x1, .start_byte = 0x9, .total_bits = 0x08, .bit_field = 0x000, .end_byte = 0xa, .link_collection = 1, .link_usage_page = 0x01, .flags = 0x1c, .usage_min = 0x03, .usage_max = 0x08, .data_index_min = 0x07, .data_index_max = 0x0c, .null_value = 3, .logical_min = 8 }, { .usage_page = 0x09, .bit_size = 0x08, .report_count = 0x4, .start_byte = 0xa, .total_bits = 0x20, .bit_field = 0x100, .end_byte = 0xe, .link_collection = 1, .link_usage_page = 0x01, .flags = 0x1c, .usage_min = 0x09, .usage_max = 0x0c, .data_index_min = 0x0d, .data_index_max = 0x10, .null_value = 9, .logical_min = 12 }, { .usage_page = 0x09, .bit_size = 0x08, .report_count = 0x1, .start_byte = 0xe, .total_bits = 0x08, .bit_field = 0x000, .end_byte = 0xf, .link_collection = 1, .link_usage_page = 0x01, .flags = 0x0d, .usage_min = 0x10, .usage_max = 0x10, .data_index_min = 0x14, .data_index_max = 0x14, .null_value = 13, .logical_min = 16 }, { .usage_page = 0x09, .bit_size = 0x08, .report_count = 0x1, .start_byte = 0xe, .total_bits = 0x08, .bit_field = 0x000, .end_byte = 0xf, .link_collection = 1, .link_usage_page = 0x01, .flags = 0x0d, .usage_min = 0x0f, .usage_max = 0x0f, .data_index_min = 0x13, .data_index_max = 0x13, .null_value = 13, .logical_min = 16 }, { .usage_page = 0x09, .bit_size = 0x08, .report_count = 0x1, .start_byte = 0xe, .total_bits = 0x08, .bit_field = 0x000, .end_byte = 0xf, .link_collection = 1, .link_usage_page = 0x01, .flags = 0x0d, .usage_min = 0x0e, .usage_max = 0x0e, .data_index_min = 0x12, .data_index_max = 0x12, .null_value = 13, .logical_min = 16 }, { .usage_page = 0x09, .bit_size = 0x08, .report_count = 0x1, .start_byte = 0xe, .total_bits = 0x08, .bit_field = 0x000, .end_byte = 0xf, .link_collection = 1, .link_usage_page = 0x01, .flags = 0x0c, .usage_min = 0x0d, .usage_max = 0x0d, .data_index_min = 0x11, .data_index_max = 0x11, .null_value = 13, .logical_min = 16 }, { .usage_page = 0x01, .bit_size = 0x10, .report_count = 0x1, .start_byte = 0x1, .total_bits = 0x10, .bit_field = 0x002, .end_byte = 0x3, .link_usage_page = 0x01, .link_usage = 0x04, .flags = 0x08, .usage_min = 0x36, .usage_max = 0x36, .logical_min = 1, .logical_max = 127, .physical_min = -128, .physical_max = 127 }, { }, }; static const struct hidp_kdr_node expect_nodes[] = { { .usage = 0x04, .usage_page = 0x01, .parent = 0, .number_of_children = 0x1, .next_sibling = 0, .first_child = 0x1, .collection_type = 0x1, }, { .usage = 0x00, .usage_page = 0x01, .parent = 0, .number_of_children = 0, .next_sibling = 0, .first_child = 0, .collection_type = 0x1, }, }; char buffer[FIELD_OFFSET( SP_DEVICE_INTERFACE_DETAIL_DATA_W, DevicePath[MAX_PATH] )]; SP_DEVICE_INTERFACE_DATA iface = {sizeof(SP_DEVICE_INTERFACE_DATA)}; SP_DEVICE_INTERFACE_DETAIL_DATA_W *iface_detail = (void *)buffer; SP_DEVINFO_DATA device = {sizeof(SP_DEVINFO_DATA)}; WCHAR cwd[MAX_PATH], tempdir[MAX_PATH]; PHIDP_PREPARSED_DATA preparsed_data; DWORD i, report_id = 0, polled = 0; struct hidp_kdr *kdr; LSTATUS status; HDEVINFO set; HANDLE file; HKEY hkey; BOOL ret; GetCurrentDirectoryW( ARRAY_SIZE(cwd), cwd ); GetTempPathW( ARRAY_SIZE(tempdir), tempdir ); SetCurrentDirectoryW( tempdir ); status = RegCreateKeyExW( HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Services\\winetest", 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &hkey, NULL ); ok( !status, "RegCreateKeyExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"ReportID", 0, REG_DWORD, (void *)&report_id, sizeof(report_id) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"PolledMode", 0, REG_DWORD, (void *)&polled, sizeof(polled) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Descriptor", 0, REG_BINARY, (void *)report_desc, sizeof(report_desc) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Attributes", 0, REG_BINARY, (void *)&attributes, sizeof(attributes) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Caps", 0, REG_BINARY, (void *)&expect_hidp_caps, sizeof(expect_hidp_caps) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Expect", 0, REG_BINARY, NULL, 0 ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Input", 0, REG_BINARY, NULL, 0 ); ok( !status, "RegSetValueExW returned %#x\n", status ); if (!pnp_driver_start( L"driver_hid.dll" )) goto done; set = SetupDiGetClassDevsW( &GUID_DEVINTERFACE_HID, NULL, NULL, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT ); ok( set != INVALID_HANDLE_VALUE, "failed to get device list, error %#x\n", GetLastError() ); for (i = 0; SetupDiEnumDeviceInfo( set, i, &device ); ++i) { ret = SetupDiEnumDeviceInterfaces( set, &device, &GUID_DEVINTERFACE_HID, 0, &iface ); ok( ret, "failed to get interface, error %#x\n", GetLastError() ); ok( IsEqualGUID( &iface.InterfaceClassGuid, &GUID_DEVINTERFACE_HID ), "wrong class %s\n", debugstr_guid( &iface.InterfaceClassGuid ) ); ok( iface.Flags == SPINT_ACTIVE, "got flags %#x\n", iface.Flags ); iface_detail->cbSize = sizeof(*iface_detail); ret = SetupDiGetDeviceInterfaceDetailW( set, &iface, iface_detail, sizeof(buffer), NULL, NULL ); ok( ret, "failed to get interface path, error %#x\n", GetLastError() ); if (wcsstr( iface_detail->DevicePath, L"\\\\?\\hid#winetest#1" )) break; } SetupDiDestroyDeviceInfoList( set ); file = CreateFileW( iface_detail->DevicePath, FILE_READ_ACCESS | FILE_WRITE_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL ); ok( file != INVALID_HANDLE_VALUE, "got error %u\n", GetLastError() ); ret = HidD_GetPreparsedData( file, &preparsed_data ); ok( ret, "HidD_GetPreparsedData failed with error %u\n", GetLastError() ); kdr = (struct hidp_kdr *)preparsed_data; ok( !strncmp( kdr->magic, expect_kdr.magic, 8 ), "got %s expected %s\n", debugstr_an(kdr->magic, 8), debugstr_an(expect_kdr.magic, 8) ); if (!strncmp( kdr->magic, expect_kdr.magic, 8 )) { check_member( *kdr, expect_kdr, "%04x", usage ); check_member( *kdr, expect_kdr, "%04x", usage_page ); check_member( *kdr, expect_kdr, "%#x", unknown[0] ); check_member( *kdr, expect_kdr, "%#x", unknown[1] ); check_member( *kdr, expect_kdr, "%d", input_caps_start ); check_member( *kdr, expect_kdr, "%d", input_caps_count ); check_member( *kdr, expect_kdr, "%d", input_caps_end ); check_member( *kdr, expect_kdr, "%d", input_report_byte_length ); check_member( *kdr, expect_kdr, "%d", output_caps_start ); check_member( *kdr, expect_kdr, "%d", output_caps_count ); check_member( *kdr, expect_kdr, "%d", output_caps_end ); check_member( *kdr, expect_kdr, "%d", output_report_byte_length ); check_member( *kdr, expect_kdr, "%d", feature_caps_start ); todo_wine check_member( *kdr, expect_kdr, "%d", feature_caps_count ); check_member( *kdr, expect_kdr, "%d", feature_caps_end ); check_member( *kdr, expect_kdr, "%d", feature_report_byte_length ); todo_wine check_member( *kdr, expect_kdr, "%d", caps_size ); check_member( *kdr, expect_kdr, "%d", number_link_collection_nodes ); for (i = 0; i < min( ARRAY_SIZE(expect_caps), kdr->caps_size / sizeof(struct hidp_kdr_caps) ); ++i) { winetest_push_context( "caps[%d]", i ); check_member( kdr->caps[i], expect_caps[i], "%04x", usage_page ); check_member( kdr->caps[i], expect_caps[i], "%d", report_id ); check_member( kdr->caps[i], expect_caps[i], "%d", start_bit ); check_member( kdr->caps[i], expect_caps[i], "%d", bit_size ); check_member( kdr->caps[i], expect_caps[i], "%d", report_count ); check_member( kdr->caps[i], expect_caps[i], "%d", start_byte ); check_member( kdr->caps[i], expect_caps[i], "%d", total_bits ); check_member( kdr->caps[i], expect_caps[i], "%#x", bit_field ); check_member( kdr->caps[i], expect_caps[i], "%d", end_byte ); check_member( kdr->caps[i], expect_caps[i], "%d", link_collection ); check_member( kdr->caps[i], expect_caps[i], "%04x", link_usage_page ); check_member( kdr->caps[i], expect_caps[i], "%04x", link_usage ); check_member( kdr->caps[i], expect_caps[i], "%#x", flags ); check_member( kdr->caps[i], expect_caps[i], "%#x", padding[0] ); check_member( kdr->caps[i], expect_caps[i], "%#x", padding[1] ); check_member( kdr->caps[i], expect_caps[i], "%#x", padding[2] ); check_member( kdr->caps[i], expect_caps[i], "%#x", padding[3] ); check_member( kdr->caps[i], expect_caps[i], "%#x", padding[4] ); check_member( kdr->caps[i], expect_caps[i], "%#x", padding[5] ); check_member( kdr->caps[i], expect_caps[i], "%#x", padding[6] ); check_member( kdr->caps[i], expect_caps[i], "%#x", padding[7] ); check_member( kdr->caps[i], expect_caps[i], "%04x", usage_min ); check_member( kdr->caps[i], expect_caps[i], "%04x", usage_max ); check_member( kdr->caps[i], expect_caps[i], "%d", string_min ); check_member( kdr->caps[i], expect_caps[i], "%d", string_max ); check_member( kdr->caps[i], expect_caps[i], "%d", designator_min ); check_member( kdr->caps[i], expect_caps[i], "%d", designator_max ); check_member( kdr->caps[i], expect_caps[i], "%#x", data_index_min ); check_member( kdr->caps[i], expect_caps[i], "%#x", data_index_max ); check_member( kdr->caps[i], expect_caps[i], "%d", null_value ); check_member( kdr->caps[i], expect_caps[i], "%d", unknown ); check_member( kdr->caps[i], expect_caps[i], "%d", logical_min ); check_member( kdr->caps[i], expect_caps[i], "%d", logical_max ); check_member( kdr->caps[i], expect_caps[i], "%d", physical_min ); check_member( kdr->caps[i], expect_caps[i], "%d", physical_max ); check_member( kdr->caps[i], expect_caps[i], "%#x", units ); check_member( kdr->caps[i], expect_caps[i], "%#x", units_exp ); winetest_pop_context(); } for (i = 0; i < ARRAY_SIZE(expect_nodes); ++i) { struct hidp_kdr_node *nodes = (struct hidp_kdr_node *)((char *)kdr->caps + kdr->caps_size); winetest_push_context( "nodes[%d]", i ); check_member( nodes[i], expect_nodes[i], "%04x", usage ); check_member( nodes[i], expect_nodes[i], "%04x", usage_page ); check_member( nodes[i], expect_nodes[i], "%d", parent ); check_member( nodes[i], expect_nodes[i], "%d", number_of_children ); check_member( nodes[i], expect_nodes[i], "%d", next_sibling ); check_member( nodes[i], expect_nodes[i], "%d", first_child ); check_member( nodes[i], expect_nodes[i], "%#x", collection_type ); winetest_pop_context(); } } HidD_FreePreparsedData( preparsed_data ); CloseHandle( file ); done: pnp_driver_stop(); SetCurrentDirectoryW( cwd ); } static void cleanup_registry_keys(void) { static const WCHAR joystick_oem_path[] = L"System\\CurrentControlSet\\Control\\MediaProperties\\" "PrivateProperties\\Joystick\\OEM"; static const WCHAR dinput_path[] = L"System\\CurrentControlSet\\Control\\MediaProperties\\" "PrivateProperties\\DirectInput"; HKEY root_key; /* These keys are automatically created by DInput and they store the list of supported force-feedback effects. OEM drivers are supposed to provide a list in HKLM for the vendor-specific force-feedback support. We need to clean them up, or DInput will not refresh the list of effects from the PID report changes. */ RegCreateKeyExW( HKEY_CURRENT_USER, joystick_oem_path, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &root_key, NULL ); RegDeleteTreeW( root_key, expect_vidpid_str ); RegCloseKey( root_key ); RegCreateKeyExW( HKEY_CURRENT_USER, dinput_path, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &root_key, NULL ); RegDeleteTreeW( root_key, expect_vidpid_str ); RegCloseKey( root_key ); RegCreateKeyExW( HKEY_LOCAL_MACHINE, joystick_oem_path, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &root_key, NULL ); RegDeleteTreeW( root_key, expect_vidpid_str ); RegCloseKey( root_key ); RegCreateKeyExW( HKEY_LOCAL_MACHINE, dinput_path, 0, NULL, 0, KEY_ALL_ACCESS, NULL, &root_key, NULL ); RegDeleteTreeW( root_key, expect_vidpid_str ); RegCloseKey( root_key ); } static BOOL dinput_driver_start( const BYTE *desc_buf, ULONG desc_len, const HIDP_CAPS *caps ) { static const HID_DEVICE_ATTRIBUTES attributes = { .Size = sizeof(HID_DEVICE_ATTRIBUTES), .VendorID = LOWORD( EXPECT_VIDPID ), .ProductID = HIWORD( EXPECT_VIDPID ), .VersionNumber = 0x0100, }; DWORD report_id = 1; DWORD polled = 0; LSTATUS status; HKEY hkey; status = RegCreateKeyExW( HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Services\\winetest", 0, NULL, REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &hkey, NULL ); ok( !status, "RegCreateKeyExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"ReportID", 0, REG_DWORD, (void *)&report_id, sizeof(report_id) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"PolledMode", 0, REG_DWORD, (void *)&polled, sizeof(polled) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Descriptor", 0, REG_BINARY, (void *)desc_buf, desc_len ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Attributes", 0, REG_BINARY, (void *)&attributes, sizeof(attributes) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Caps", 0, REG_BINARY, (void *)caps, sizeof(*caps) ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Expect", 0, REG_BINARY, NULL, 0 ); ok( !status, "RegSetValueExW returned %#x\n", status ); status = RegSetValueExW( hkey, L"Input", 0, REG_BINARY, NULL, 0 ); ok( !status, "RegSetValueExW returned %#x\n", status ); return pnp_driver_start( L"driver_hid.dll" ); } static BOOL CALLBACK find_test_device( const DIDEVICEINSTANCEW *devinst, void *context ) { if (IsEqualGUID( &devinst->guidProduct, &expect_guid_product )) *(DIDEVICEINSTANCEW *)context = *devinst; return DIENUM_CONTINUE; } struct check_objects_params { UINT index; UINT expect_count; const DIDEVICEOBJECTINSTANCEW *expect_objs; }; static BOOL CALLBACK check_objects( const DIDEVICEOBJECTINSTANCEW *obj, void *args ) { static const DIDEVICEOBJECTINSTANCEW unexpected_obj = {0}; struct check_objects_params *params = args; const DIDEVICEOBJECTINSTANCEW *exp = params->expect_objs + params->index; winetest_push_context( "obj[%d]", params->index ); ok( params->index < params->expect_count, "unexpected extra object\n" ); if (params->index >= params->expect_count) exp = &unexpected_obj; check_member( *obj, *exp, "%u", dwSize ); check_member_guid( *obj, *exp, guidType ); check_member( *obj, *exp, "%#x", dwOfs ); check_member( *obj, *exp, "%#x", dwType ); check_member( *obj, *exp, "%#x", dwFlags ); if (!localized) todo_wine check_member_wstr( *obj, *exp, tszName ); check_member( *obj, *exp, "%u", dwFFMaxForce ); check_member( *obj, *exp, "%u", dwFFForceResolution ); check_member( *obj, *exp, "%u", wCollectionNumber ); check_member( *obj, *exp, "%u", wDesignatorIndex ); check_member( *obj, *exp, "%#04x", wUsagePage ); check_member( *obj, *exp, "%#04x", wUsage ); check_member( *obj, *exp, "%#04x", dwDimension ); check_member( *obj, *exp, "%#04x", wExponent ); check_member( *obj, *exp, "%u", wReportId ); winetest_pop_context(); params->index++; return DIENUM_CONTINUE; } static BOOL CALLBACK check_object_count( const DIDEVICEOBJECTINSTANCEW *obj, void *args ) { DWORD *count = args; *count = *count + 1; return DIENUM_CONTINUE; } struct check_effects_params { UINT index; UINT expect_count; const DIEFFECTINFOW *expect_effects; }; static BOOL CALLBACK check_effects( const DIEFFECTINFOW *effect, void *args ) { static const DIEFFECTINFOW unexpected_effect = {0}; struct check_effects_params *params = args; const DIEFFECTINFOW *exp = params->expect_effects + params->index; winetest_push_context( "effect[%d]", params->index ); ok( params->index < params->expect_count, "unexpected extra object\n" ); if (params->index >= params->expect_count) exp = &unexpected_effect; check_member( *effect, *exp, "%u", dwSize ); check_member_guid( *effect, *exp, guid ); todo_wine check_member( *effect, *exp, "%#x", dwEffType ); todo_wine check_member( *effect, *exp, "%#x", dwStaticParams ); todo_wine check_member( *effect, *exp, "%#x", dwDynamicParams ); check_member_wstr( *effect, *exp, tszName ); winetest_pop_context(); params->index++; return DIENUM_CONTINUE; } static BOOL CALLBACK check_effect_count( const DIEFFECTINFOW *effect, void *args ) { DWORD *count = args; *count = *count + 1; return DIENUM_CONTINUE; } static BOOL CALLBACK check_no_created_effect_objects( IDirectInputEffect *effect, void *context ) { ok( 0, "unexpected effect %p\n", effect ); return DIENUM_CONTINUE; } struct check_created_effect_params { IDirectInputEffect *expect_effect; DWORD count; }; static BOOL CALLBACK check_created_effect_objects( IDirectInputEffect *effect, void *context ) { struct check_created_effect_params *params = context; ULONG ref; ok( effect == params->expect_effect, "got effect %p, expected %p\n", effect, params->expect_effect ); params->count++; IDirectInputEffect_AddRef( effect ); ref = IDirectInputEffect_Release( effect ); ok( ref == 1, "got ref %u, expected 1\n", ref ); return DIENUM_CONTINUE; } static void test_simple_joystick(void) { #include "psh_hid_macros.h" static const unsigned char report_desc[] = { USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Application), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Report), REPORT_ID(1, 1), USAGE(1, HID_USAGE_GENERIC_WHEEL), USAGE(4, (0xff01u<<16)|(0x1234)), USAGE(1, HID_USAGE_GENERIC_X), USAGE(1, HID_USAGE_GENERIC_Y), LOGICAL_MINIMUM(1, 0xe7), LOGICAL_MAXIMUM(1, 0x38), PHYSICAL_MINIMUM(1, 0xe7), PHYSICAL_MAXIMUM(1, 0x38), REPORT_SIZE(1, 8), REPORT_COUNT(1, 4), INPUT(1, Data|Var|Abs), USAGE(1, HID_USAGE_GENERIC_HATSWITCH), LOGICAL_MINIMUM(1, 1), LOGICAL_MAXIMUM(1, 8), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 8), REPORT_SIZE(1, 4), REPORT_COUNT(1, 1), INPUT(1, Data|Var|Abs|Null), USAGE_PAGE(1, HID_USAGE_PAGE_BUTTON), USAGE_MINIMUM(1, 1), USAGE_MAXIMUM(1, 2), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 1), REPORT_SIZE(1, 1), REPORT_COUNT(1, 4), INPUT(1, Data|Var|Abs), END_COLLECTION, END_COLLECTION, }; #undef REPORT_ID_OR_USAGE_PAGE #include "pop_hid_macros.h" static const HIDP_CAPS hid_caps = { .InputReportByteLength = 6, }; static const DIDEVCAPS expect_caps = { .dwSize = sizeof(DIDEVCAPS), .dwFlags = DIDC_ATTACHED | DIDC_EMULATED, .dwDevType = DIDEVTYPE_HID | (DI8DEVTYPEJOYSTICK_LIMITED << 8) | DI8DEVTYPE_JOYSTICK, .dwAxes = 3, .dwPOVs = 1, .dwButtons = 2, }; struct hid_expect injected_input[] = { { .code = IOCTL_HID_READ_REPORT, .report_buf = {1,0x10,0x10,0x10,0x10,0}, }, { .code = IOCTL_HID_READ_REPORT, .report_buf = {1,0x10,0x10,0x38,0x38,0xf8}, }, { .code = IOCTL_HID_READ_REPORT, .report_buf = {1,0x10,0x10,0x01,0x01,0x00}, }, { .code = IOCTL_HID_READ_REPORT, .report_buf = {1,0x10,0x10,0x01,0x01,0x00}, }, { .code = IOCTL_HID_READ_REPORT, .report_buf = {1,0x10,0x10,0x80,0x80,0xff}, }, { .code = IOCTL_HID_READ_REPORT, .report_buf = {1,0x10,0x10,0x10,0xee,0x54}, }, }; static const struct DIJOYSTATE2 expect_state[] = { {.lX = 32767, .lY = 32767, .lZ = 32767, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0, 0}}, {.lX = 32767, .lY = 32767, .lZ = 32767, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0, 0}}, {.lX = 65535, .lY = 65535, .lZ = 32767, .rgdwPOV = {31500, -1, -1, -1}, .rgbButtons = {0x80, 0x80}}, {.lX = 20779, .lY = 20779, .lZ = 32767, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0, 0}}, {.lX = 20779, .lY = 20779, .lZ = 32767, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0, 0}}, {.lX = 0, .lY = 0, .lZ = 32767, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0x80, 0x80}}, {.lX = 32767, .lY = 5594, .lZ = 32767, .rgdwPOV = {13500, -1, -1, -1}, .rgbButtons = {0x80}}, }; static const struct DIJOYSTATE2 expect_state_abs[] = { {.lX = -9000, .lY = 26000, .lZ = 26000, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0, 0}}, {.lX = -9000, .lY = 26000, .lZ = 26000, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0, 0}}, {.lX = -4000, .lY = 51000, .lZ = 26000, .rgdwPOV = {31500, -1, -1, -1}, .rgbButtons = {0x80, 0x80}}, {.lX = -10667, .lY = 12905, .lZ = 26000, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0, 0}}, {.lX = -10667, .lY = 12905, .lZ = 26000, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0, 0}}, {.lX = -14000, .lY = 1000, .lZ = 26000, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0x80, 0x80}}, {.lX = -9000, .lY = 1000, .lZ = 26000, .rgdwPOV = {13500, -1, -1, -1}, .rgbButtons = {0x80}}, }; static const struct DIJOYSTATE2 expect_state_rel[] = { {.lX = 0, .lY = 0, .rgdwPOV = {13500, -1, -1, -1}, .rgbButtons = {0x80, 0}}, {.lX = 9016, .lY = -984, .lZ = -25984, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0, 0}}, {.lX = 40, .lY = 40, .rgdwPOV = {31500, -1, -1, -1}, .rgbButtons = {0x80, 0x80}}, {.lX = -55, .lY = -55, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0, 0}}, {.lX = 0, .lY = 0, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0, 0}}, {.lX = -129, .lY = -129, .rgdwPOV = {-1, -1, -1, -1}, .rgbButtons = {0x80, 0x80}}, {.lX = 144, .lY = 110, .rgdwPOV = {13500, -1, -1, -1}, .rgbButtons = {0x80}}, }; static const DIDEVICEOBJECTDATA expect_objdata[] = { {.dwOfs = 0x4, .dwData = 0xffff, .dwSequence = 0xa}, {.dwOfs = 0x4, .dwData = 0xffff, .dwSequence = 0xa}, {.dwOfs = 0, .dwData = 0xffff, .dwSequence = 0xa}, {.dwOfs = 0x20, .dwData = 31500, .dwSequence = 0xa}, {.dwOfs = 0x30, .dwData = 0x80, .dwSequence = 0xa}, {.dwOfs = 0x4, .dwData = 0x512b, .dwSequence = 0xd}, {.dwOfs = 0, .dwData = 0x512b, .dwSequence = 0xd}, {.dwOfs = 0x20, .dwData = -1, .dwSequence = 0xd}, {.dwOfs = 0x30, .dwData = 0, .dwSequence = 0xd}, {.dwOfs = 0x31, .dwData = 0, .dwSequence = 0xd}, {.dwOfs = 0x4, .dwData = 0, .dwSequence = 0xf}, {.dwOfs = 0, .dwData = 0, .dwSequence = 0xf}, {.dwOfs = 0x30, .dwData = 0x80, .dwSequence = 0xf}, {.dwOfs = 0x31, .dwData = 0x80, .dwSequence = 0xf}, }; const DIDEVICEINSTANCEW expect_devinst = { .dwSize = sizeof(DIDEVICEINSTANCEW), .guidInstance = expect_guid_product, .guidProduct = expect_guid_product, .dwDevType = DIDEVTYPE_HID | (DI8DEVTYPEJOYSTICK_LIMITED << 8) | DI8DEVTYPE_JOYSTICK, .tszInstanceName = L"Wine test root driver", .tszProductName = L"Wine test root driver", .guidFFDriver = GUID_NULL, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_JOYSTICK, }; const DIDEVICEOBJECTINSTANCEW expect_objects[] = { { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_YAxis, .dwType = DIDFT_ABSAXIS|DIDFT_MAKEINSTANCE(1), .dwFlags = DIDOI_ASPECTPOSITION, .tszName = L"Y Axis", .wCollectionNumber = 1, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_Y, .wReportId = 1, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_XAxis, .dwOfs = 0x4, .dwType = DIDFT_ABSAXIS|DIDFT_MAKEINSTANCE(0), .dwFlags = DIDOI_ASPECTPOSITION, .tszName = L"X Axis", .wCollectionNumber = 1, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_X, .wReportId = 1, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_ZAxis, .dwOfs = 0xc, .dwType = DIDFT_ABSAXIS|DIDFT_MAKEINSTANCE(2), .dwFlags = DIDOI_ASPECTPOSITION, .tszName = L"Wheel", .wCollectionNumber = 1, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_WHEEL, .wReportId = 1, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_POV, .dwOfs = 0x10, .dwType = DIDFT_POV|DIDFT_MAKEINSTANCE(0), .tszName = L"Hat Switch", .wCollectionNumber = 1, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_HATSWITCH, .wReportId = 1, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Button, .dwOfs = 0x14, .dwType = DIDFT_PSHBUTTON|DIDFT_MAKEINSTANCE(0), .tszName = L"Button 0", .wCollectionNumber = 1, .wUsagePage = HID_USAGE_PAGE_BUTTON, .wUsage = 0x1, .wReportId = 1, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Button, .dwOfs = 0x15, .dwType = DIDFT_PSHBUTTON|DIDFT_MAKEINSTANCE(1), .tszName = L"Button 1", .wCollectionNumber = 1, .wUsagePage = HID_USAGE_PAGE_BUTTON, .wUsage = 0x2, .wReportId = 1, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(0), .tszName = L"Collection 0 - Joystick", .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_JOYSTICK, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(1), .tszName = L"Collection 1 - Joystick", .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_JOYSTICK, }, }; const DIEFFECTINFOW expect_effects[] = {}; struct check_objects_params check_objects_params = { .expect_count = ARRAY_SIZE(expect_objects), .expect_objs = expect_objects, }; struct check_effects_params check_effects_params = { .expect_count = ARRAY_SIZE(expect_effects), .expect_effects = expect_effects, }; DIPROPGUIDANDPATH prop_guid_path = { .diph = { .dwSize = sizeof(DIPROPGUIDANDPATH), .dwHeaderSize = sizeof(DIPROPHEADER), .dwHow = DIPH_DEVICE, }, }; DIPROPSTRING prop_string = { .diph = { .dwSize = sizeof(DIPROPSTRING), .dwHeaderSize = sizeof(DIPROPHEADER), .dwHow = DIPH_DEVICE, }, }; DIPROPDWORD prop_dword = { .diph = { .dwSize = sizeof(DIPROPDWORD), .dwHeaderSize = sizeof(DIPROPHEADER), .dwHow = DIPH_DEVICE, }, }; DIPROPRANGE prop_range = { .diph = { .dwSize = sizeof(DIPROPRANGE), .dwHeaderSize = sizeof(DIPROPHEADER), .dwHow = DIPH_DEVICE, }, }; DIPROPPOINTER prop_pointer = { .diph = { .dwSize = sizeof(DIPROPPOINTER), .dwHeaderSize = sizeof(DIPROPHEADER), }, }; WCHAR cwd[MAX_PATH], tempdir[MAX_PATH]; DIDEVICEOBJECTDATA objdata[32] = {{0}}; DIDEVICEOBJECTINSTANCEW objinst = {0}; DIDEVICEINSTANCEW devinst = {0}; DIEFFECTINFOW effectinfo = {0}; DIDATAFORMAT dataformat = {0}; IDirectInputDevice8W *device; IDirectInputEffect *effect; DIEFFESCAPE escape = {0}; DIDEVCAPS caps = {0}; IDirectInput8W *di; HANDLE event, file; char buffer[1024]; DIJOYSTATE2 state; ULONG i, res, ref; HRESULT hr; WCHAR *tmp; GUID guid; HWND hwnd; GetCurrentDirectoryW( ARRAY_SIZE(cwd), cwd ); GetTempPathW( ARRAY_SIZE(tempdir), tempdir ); SetCurrentDirectoryW( tempdir ); cleanup_registry_keys(); if (!dinput_driver_start( report_desc, sizeof(report_desc), &hid_caps )) goto done; hr = DirectInput8Create( instance, DIRECTINPUT_VERSION, &IID_IDirectInput8W, (void **)&di, NULL ); if (FAILED(hr)) { win_skip( "DirectInput8Create returned %#x\n", hr ); goto done; } hr = IDirectInput8_EnumDevices( di, DI8DEVCLASS_ALL, find_test_device, &devinst, DIEDFL_ALLDEVICES ); ok( hr == DI_OK, "EnumDevices returned: %#x\n", hr ); if (!IsEqualGUID( &devinst.guidProduct, &expect_guid_product )) { win_skip( "device not found, skipping tests\n" ); IDirectInput8_Release( di ); goto done; } check_member( devinst, expect_devinst, "%d", dwSize ); check_member_guid( devinst, expect_devinst, guidProduct ); check_member( devinst, expect_devinst, "%#x", dwDevType ); todo_wine check_member_wstr( devinst, expect_devinst, tszInstanceName ); todo_wine check_member_wstr( devinst, expect_devinst, tszProductName ); check_member_guid( devinst, expect_devinst, guidFFDriver ); check_member( devinst, expect_devinst, "%04x", wUsagePage ); check_member( devinst, expect_devinst, "%04x", wUsage ); hr = IDirectInput8_CreateDevice( di, &devinst.guidInstance, NULL, NULL ); ok( hr == E_POINTER, "CreateDevice returned %#x\n", hr ); hr = IDirectInput8_CreateDevice( di, NULL, &device, NULL ); ok( hr == E_POINTER, "CreateDevice returned %#x\n", hr ); hr = IDirectInput8_CreateDevice( di, &GUID_NULL, &device, NULL ); ok( hr == DIERR_DEVICENOTREG, "CreateDevice returned %#x\n", hr ); hr = IDirectInput8_CreateDevice( di, &devinst.guidInstance, &device, NULL ); ok( hr == DI_OK, "CreateDevice returned %#x\n", hr ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_VIDPID, &prop_dword.diph ); ok( hr == DI_OK, "GetProperty DIPROP_VIDPID returned %#x\n", hr ); /* Wine may get the wrong device here, because the test driver creates another instance of hidclass.sys, and gets duplicate rawinput handles, which we use in the guidInstance */ todo_wine_if( prop_dword.dwData != EXPECT_VIDPID ) ok( prop_dword.dwData == EXPECT_VIDPID, "got %#x expected %#x\n", prop_dword.dwData, EXPECT_VIDPID ); ref = IDirectInputDevice8_Release( device ); ok( ref == 0, "Release returned %d\n", ref ); hr = IDirectInput8_CreateDevice( di, &expect_guid_product, &device, NULL ); ok( hr == DI_OK, "CreateDevice returned %#x\n", hr ); hr = IDirectInputDevice8_Initialize( device, instance, 0x0700, &GUID_NULL ); todo_wine ok( hr == DIERR_BETADIRECTINPUTVERSION, "Initialize returned %#x\n", hr ); hr = IDirectInputDevice8_Initialize( device, instance, DIRECTINPUT_VERSION, NULL ); todo_wine ok( hr == E_POINTER, "Initialize returned %#x\n", hr ); hr = IDirectInputDevice8_Initialize( device, NULL, DIRECTINPUT_VERSION, &GUID_NULL ); todo_wine ok( hr == DIERR_INVALIDPARAM, "Initialize returned %#x\n", hr ); hr = IDirectInputDevice8_Initialize( device, instance, DIRECTINPUT_VERSION, &GUID_NULL ); todo_wine ok( hr == REGDB_E_CLASSNOTREG, "Initialize returned %#x\n", hr ); hr = IDirectInputDevice8_Initialize( device, instance, DIRECTINPUT_VERSION, &devinst.guidInstance ); ok( hr == DI_OK, "Initialize returned %#x\n", hr ); guid = devinst.guidInstance; memset( &devinst, 0, sizeof(devinst) ); devinst.dwSize = sizeof(DIDEVICEINSTANCEW); hr = IDirectInputDevice8_GetDeviceInfo( device, &devinst ); ok( hr == DI_OK, "GetDeviceInfo returned %#x\n", hr ); ok( IsEqualGUID( &guid, &devinst.guidInstance ), "got %s expected %s\n", debugstr_guid( &guid ), debugstr_guid( &devinst.guidInstance ) ); hr = IDirectInputDevice8_Initialize( device, instance, DIRECTINPUT_VERSION, &devinst.guidProduct ); ok( hr == DI_OK, "Initialize returned %#x\n", hr ); hr = IDirectInputDevice8_GetDeviceInfo( device, NULL ); ok( hr == E_POINTER, "GetDeviceInfo returned %#x\n", hr ); devinst.dwSize = sizeof(DIDEVICEINSTANCEW) + 1; hr = IDirectInputDevice8_GetDeviceInfo( device, &devinst ); ok( hr == DIERR_INVALIDPARAM, "GetDeviceInfo returned %#x\n", hr ); devinst.dwSize = sizeof(DIDEVICEINSTANCE_DX3W); hr = IDirectInputDevice8_GetDeviceInfo( device, &devinst ); ok( hr == DI_OK, "GetDeviceInfo returned %#x\n", hr ); todo_wine check_member_guid( devinst, expect_devinst, guidInstance ); check_member_guid( devinst, expect_devinst, guidProduct ); check_member( devinst, expect_devinst, "%#x", dwDevType ); todo_wine check_member_wstr( devinst, expect_devinst, tszInstanceName ); todo_wine check_member_wstr( devinst, expect_devinst, tszProductName ); memset( &devinst, 0, sizeof(devinst) ); devinst.dwSize = sizeof(DIDEVICEINSTANCEW); hr = IDirectInputDevice8_GetDeviceInfo( device, &devinst ); ok( hr == DI_OK, "GetDeviceInfo returned %#x\n", hr ); check_member( devinst, expect_devinst, "%d", dwSize ); todo_wine check_member_guid( devinst, expect_devinst, guidInstance ); check_member_guid( devinst, expect_devinst, guidProduct ); check_member( devinst, expect_devinst, "%#x", dwDevType ); todo_wine check_member_wstr( devinst, expect_devinst, tszInstanceName ); todo_wine check_member_wstr( devinst, expect_devinst, tszProductName ); check_member_guid( devinst, expect_devinst, guidFFDriver ); check_member( devinst, expect_devinst, "%04x", wUsagePage ); check_member( devinst, expect_devinst, "%04x", wUsage ); hr = IDirectInputDevice8_GetCapabilities( device, NULL ); ok( hr == E_POINTER, "GetCapabilities returned %#x\n", hr ); hr = IDirectInputDevice8_GetCapabilities( device, &caps ); todo_wine ok( hr == DIERR_INVALIDPARAM, "GetCapabilities returned %#x\n", hr ); caps.dwSize = sizeof(DIDEVCAPS); hr = IDirectInputDevice8_GetCapabilities( device, &caps ); ok( hr == DI_OK, "GetCapabilities returned %#x\n", hr ); check_member( caps, expect_caps, "%d", dwSize ); check_member( caps, expect_caps, "%#x", dwFlags ); check_member( caps, expect_caps, "%#x", dwDevType ); check_member( caps, expect_caps, "%d", dwAxes ); check_member( caps, expect_caps, "%d", dwButtons ); check_member( caps, expect_caps, "%d", dwPOVs ); check_member( caps, expect_caps, "%d", dwFFSamplePeriod ); check_member( caps, expect_caps, "%d", dwFFMinTimeResolution ); check_member( caps, expect_caps, "%d", dwFirmwareRevision ); check_member( caps, expect_caps, "%d", dwHardwareRevision ); check_member( caps, expect_caps, "%d", dwFFDriverVersion ); hr = IDirectInputDevice8_GetProperty( device, NULL, NULL ); ok( hr == DIERR_INVALIDPARAM, "GetProperty returned %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, &GUID_NULL, NULL ); ok( hr == DIERR_INVALIDPARAM, "GetProperty returned %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_VIDPID, NULL ); ok( hr == DIERR_INVALIDPARAM, "GetProperty returned %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_VIDPID, &prop_string.diph ); ok( hr == DIERR_INVALIDPARAM, "GetProperty returned %#x\n", hr ); prop_dword.diph.dwHeaderSize = sizeof(DIPROPHEADER) - 1; hr = IDirectInputDevice8_GetProperty( device, DIPROP_VIDPID, &prop_dword.diph ); ok( hr == DIERR_INVALIDPARAM, "GetProperty returned %#x\n", hr ); prop_dword.diph.dwHeaderSize = sizeof(DIPROPHEADER); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_VIDPID, &prop_dword.diph ); ok( hr == DI_OK, "GetProperty DIPROP_VIDPID returned %#x\n", hr ); ok( prop_dword.dwData == EXPECT_VIDPID, "got %#x expected %#x\n", prop_dword.dwData, EXPECT_VIDPID ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_GUIDANDPATH, &prop_guid_path.diph ); ok( hr == DI_OK, "GetProperty DIPROP_GUIDANDPATH returned %#x\n", hr ); todo_wine ok( IsEqualGUID( &prop_guid_path.guidClass, &GUID_DEVCLASS_HIDCLASS ), "got guid %s\n", debugstr_guid( &prop_guid_path.guidClass ) ); todo_wine ok( !wcsncmp( prop_guid_path.wszPath, expect_path, wcslen( expect_path ) ), "got path %s\n", debugstr_w(prop_guid_path.wszPath) ); if (!(tmp = wcsrchr( prop_guid_path.wszPath, '&' ))) todo_wine ok( 0, "got path %s\n", debugstr_w(prop_guid_path.wszPath) ); else { ok( !wcscmp( wcsrchr( prop_guid_path.wszPath, '&' ), expect_path_end ), "got path %s\n", debugstr_w(prop_guid_path.wszPath) ); } hr = IDirectInputDevice8_GetProperty( device, DIPROP_INSTANCENAME, &prop_string.diph ); ok( hr == DI_OK, "GetProperty DIPROP_INSTANCENAME returned %#x\n", hr ); todo_wine ok( !wcscmp( prop_string.wsz, expect_devinst.tszInstanceName ), "got instance %s\n", debugstr_w(prop_string.wsz) ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_PRODUCTNAME, &prop_string.diph ); ok( hr == DI_OK, "GetProperty DIPROP_PRODUCTNAME returned %#x\n", hr ); todo_wine ok( !wcscmp( prop_string.wsz, expect_devinst.tszProductName ), "got product %s\n", debugstr_w(prop_string.wsz) ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_TYPENAME, &prop_string.diph ); todo_wine ok( hr == DI_OK, "GetProperty DIPROP_TYPENAME returned %#x\n", hr ); todo_wine ok( !wcscmp( prop_string.wsz, expect_vidpid_str ), "got type %s\n", debugstr_w(prop_string.wsz) ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_USERNAME, &prop_string.diph ); ok( hr == S_FALSE, "GetProperty DIPROP_USERNAME returned %#x\n", hr ); todo_wine ok( !wcscmp( prop_string.wsz, L"" ), "got user %s\n", debugstr_w(prop_string.wsz) ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_JOYSTICKID, &prop_dword.diph ); ok( hr == DI_OK, "GetProperty DIPROP_JOYSTICKID returned %#x\n", hr ); todo_wine ok( prop_dword.dwData == 0, "got %#x expected %#x\n", prop_dword.dwData, 0 ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_AXISMODE, &prop_dword.diph ); todo_wine ok( hr == DI_OK, "GetProperty DIPROP_AXISMODE returned %#x\n", hr ); todo_wine ok( prop_dword.dwData == DIPROPAXISMODE_ABS, "got %u expected %u\n", prop_dword.dwData, DIPROPAXISMODE_ABS ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_BUFFERSIZE, &prop_dword.diph ); ok( hr == DI_OK, "GetProperty DIPROP_BUFFERSIZE returned %#x\n", hr ); ok( prop_dword.dwData == 0, "got %#x expected %#x\n", prop_dword.dwData, 0 ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_FFGAIN, &prop_dword.diph ); todo_wine ok( hr == DI_OK, "GetProperty DIPROP_FFGAIN returned %#x\n", hr ); todo_wine ok( prop_dword.dwData == 10000, "got %u expected %u\n", prop_dword.dwData, 10000 ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_CALIBRATION, &prop_dword.diph ); ok( hr == DIERR_INVALIDPARAM, "GetProperty DIPROP_CALIBRATION returned %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_AUTOCENTER, &prop_dword.diph ); ok( hr == DIERR_UNSUPPORTED, "GetProperty DIPROP_AUTOCENTER returned %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_DEADZONE, &prop_dword.diph ); ok( hr == DIERR_UNSUPPORTED, "GetProperty DIPROP_DEADZONE returned %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_FFLOAD, &prop_dword.diph ); todo_wine ok( hr == DIERR_UNSUPPORTED, "GetProperty DIPROP_FFLOAD returned %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_GRANULARITY, &prop_dword.diph ); ok( hr == DIERR_UNSUPPORTED, "GetProperty DIPROP_GRANULARITY returned %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_SATURATION, &prop_dword.diph ); ok( hr == DIERR_UNSUPPORTED, "GetProperty DIPROP_SATURATION returned %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_RANGE, &prop_range.diph ); ok( hr == DIERR_UNSUPPORTED, "GetProperty DIPROP_RANGE returned %#x\n", hr ); prop_dword.diph.dwHow = DIPH_BYUSAGE; prop_dword.diph.dwObj = MAKELONG( HID_USAGE_GENERIC_X, HID_USAGE_PAGE_GENERIC ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_DEADZONE, &prop_dword.diph ); ok( hr == DI_OK, "GetProperty DIPROP_DEADZONE returned %#x\n", hr ); ok( prop_dword.dwData == 0, "got %u expected %u\n", prop_dword.dwData, 0 ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_GRANULARITY, &prop_dword.diph ); ok( hr == DI_OK, "GetProperty DIPROP_GRANULARITY returned %#x\n", hr ); ok( prop_dword.dwData == 1, "got %u expected %u\n", prop_dword.dwData, 1 ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_SATURATION, &prop_dword.diph ); ok( hr == DI_OK, "GetProperty DIPROP_SATURATION returned %#x\n", hr ); ok( prop_dword.dwData == 10000, "got %u expected %u\n", prop_dword.dwData, 10000 ); prop_range.diph.dwHow = DIPH_BYUSAGE; prop_range.diph.dwObj = MAKELONG( 0, 0 ); prop_range.lMin = 0xdeadbeef; prop_range.lMax = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_RANGE, &prop_range.diph ); ok( hr == DIERR_NOTFOUND, "GetProperty DIPROP_RANGE returned %#x\n", hr ); prop_range.diph.dwObj = MAKELONG( 0, HID_USAGE_PAGE_GENERIC ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_RANGE, &prop_range.diph ); ok( hr == DIERR_NOTFOUND, "GetProperty DIPROP_RANGE returned %#x\n", hr ); prop_range.diph.dwObj = MAKELONG( HID_USAGE_PAGE_GENERIC, HID_USAGE_GENERIC_X ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_RANGE, &prop_range.diph ); ok( hr == DIERR_NOTFOUND, "GetProperty DIPROP_RANGE returned %#x\n", hr ); prop_range.diph.dwObj = MAKELONG( HID_USAGE_GENERIC_X, HID_USAGE_PAGE_GENERIC ); prop_range.lMin = 0xdeadbeef; prop_range.lMax = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_RANGE, &prop_range.diph ); ok( hr == DI_OK, "GetProperty DIPROP_RANGE returned %#x\n", hr ); ok( prop_range.lMin == 0, "got %d expected %d\n", prop_range.lMin, 0 ); ok( prop_range.lMax == 65535, "got %d expected %d\n", prop_range.lMax, 65535 ); prop_pointer.diph.dwHow = DIPH_BYUSAGE; prop_pointer.diph.dwObj = MAKELONG( HID_USAGE_GENERIC_X, HID_USAGE_PAGE_GENERIC ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_APPDATA, &prop_pointer.diph ); todo_wine ok( hr == DIERR_NOTINITIALIZED, "GetProperty DIPROP_APPDATA returned %#x\n", hr ); hr = IDirectInputDevice8_EnumObjects( device, NULL, NULL, DIDFT_ALL ); ok( hr == DIERR_INVALIDPARAM, "EnumObjects returned %#x\n", hr ); hr = IDirectInputDevice8_EnumObjects( device, check_object_count, &res, 0x20 ); ok( hr == DIERR_INVALIDPARAM, "EnumObjects returned %#x\n", hr ); res = 0; hr = IDirectInputDevice8_EnumObjects( device, check_object_count, &res, DIDFT_AXIS | DIDFT_PSHBUTTON ); ok( hr == DI_OK, "EnumObjects returned %#x\n", hr ); ok( res == 5, "got %u expected %u\n", res, 5 ); hr = IDirectInputDevice8_EnumObjects( device, check_objects, &check_objects_params, DIDFT_ALL ); ok( hr == DI_OK, "EnumObjects returned %#x\n", hr ); ok( check_objects_params.index >= check_objects_params.expect_count, "missing %u objects\n", check_objects_params.expect_count - check_objects_params.index ); hr = IDirectInputDevice8_GetObjectInfo( device, NULL, 0, DIPH_DEVICE ); ok( hr == E_POINTER, "GetObjectInfo returned: %#x\n", hr ); hr = IDirectInputDevice8_GetObjectInfo( device, &objinst, 0, DIPH_DEVICE ); ok( hr == DIERR_INVALIDPARAM, "GetObjectInfo returned: %#x\n", hr ); objinst.dwSize = sizeof(DIDEVICEOBJECTINSTANCEW); hr = IDirectInputDevice8_GetObjectInfo( device, &objinst, 0, DIPH_DEVICE ); ok( hr == DIERR_INVALIDPARAM, "GetObjectInfo returned: %#x\n", hr ); res = MAKELONG( HID_USAGE_GENERIC_Z, HID_USAGE_PAGE_GENERIC ); hr = IDirectInputDevice8_GetObjectInfo( device, &objinst, res, DIPH_BYUSAGE ); ok( hr == DIERR_NOTFOUND, "GetObjectInfo returned: %#x\n", hr ); res = MAKELONG( HID_USAGE_GENERIC_X, HID_USAGE_PAGE_GENERIC ); hr = IDirectInputDevice8_GetObjectInfo( device, &objinst, res, DIPH_BYUSAGE ); ok( hr == DI_OK, "GetObjectInfo returned: %#x\n", hr ); check_member( objinst, expect_objects[1], "%u", dwSize ); check_member_guid( objinst, expect_objects[1], guidType ); check_member( objinst, expect_objects[1], "%#x", dwOfs ); check_member( objinst, expect_objects[1], "%#x", dwType ); check_member( objinst, expect_objects[1], "%#x", dwFlags ); if (!localized) todo_wine check_member_wstr( objinst, expect_objects[1], tszName ); check_member( objinst, expect_objects[1], "%u", dwFFMaxForce ); check_member( objinst, expect_objects[1], "%u", dwFFForceResolution ); check_member( objinst, expect_objects[1], "%u", wCollectionNumber ); check_member( objinst, expect_objects[1], "%u", wDesignatorIndex ); check_member( objinst, expect_objects[1], "%#04x", wUsagePage ); check_member( objinst, expect_objects[1], "%#04x", wUsage ); check_member( objinst, expect_objects[1], "%#04x", dwDimension ); check_member( objinst, expect_objects[1], "%#04x", wExponent ); check_member( objinst, expect_objects[1], "%u", wReportId ); hr = IDirectInputDevice8_GetObjectInfo( device, &objinst, 0x14, DIPH_BYOFFSET ); ok( hr == DIERR_NOTFOUND, "GetObjectInfo returned: %#x\n", hr ); hr = IDirectInputDevice8_GetObjectInfo( device, &objinst, 0, DIPH_BYOFFSET ); ok( hr == DIERR_NOTFOUND, "GetObjectInfo returned: %#x\n", hr ); res = DIDFT_PSHBUTTON | DIDFT_MAKEINSTANCE( 3 ); hr = IDirectInputDevice8_GetObjectInfo( device, &objinst, res, DIPH_BYID ); ok( hr == DIERR_NOTFOUND, "GetObjectInfo returned: %#x\n", hr ); res = DIDFT_PSHBUTTON | DIDFT_MAKEINSTANCE( 1 ); hr = IDirectInputDevice8_GetObjectInfo( device, &objinst, res, DIPH_BYID ); ok( hr == DI_OK, "GetObjectInfo returned: %#x\n", hr ); check_member( objinst, expect_objects[5], "%u", dwSize ); check_member_guid( objinst, expect_objects[5], guidType ); check_member( objinst, expect_objects[5], "%#x", dwOfs ); check_member( objinst, expect_objects[5], "%#x", dwType ); check_member( objinst, expect_objects[5], "%#x", dwFlags ); if (!localized) todo_wine check_member_wstr( objinst, expect_objects[5], tszName ); check_member( objinst, expect_objects[5], "%u", dwFFMaxForce ); check_member( objinst, expect_objects[5], "%u", dwFFForceResolution ); check_member( objinst, expect_objects[5], "%u", wCollectionNumber ); check_member( objinst, expect_objects[5], "%u", wDesignatorIndex ); check_member( objinst, expect_objects[5], "%#04x", wUsagePage ); check_member( objinst, expect_objects[5], "%#04x", wUsage ); check_member( objinst, expect_objects[5], "%#04x", dwDimension ); check_member( objinst, expect_objects[5], "%#04x", wExponent ); check_member( objinst, expect_objects[5], "%u", wReportId ); hr = IDirectInputDevice8_EnumEffects( device, NULL, NULL, DIEFT_ALL ); ok( hr == DIERR_INVALIDPARAM, "EnumEffects returned %#x\n", hr ); res = 0; hr = IDirectInputDevice8_EnumEffects( device, check_effect_count, &res, 0xfe ); ok( hr == DI_OK, "EnumEffects returned %#x\n", hr ); ok( res == 0, "got %u expected %u\n", res, 0 ); res = 0; hr = IDirectInputDevice8_EnumEffects( device, check_effect_count, &res, DIEFT_PERIODIC ); ok( hr == DI_OK, "EnumEffects returned %#x\n", hr ); ok( res == 0, "got %u expected %u\n", res, 0 ); hr = IDirectInputDevice8_EnumEffects( device, check_effects, &check_effects_params, DIEFT_ALL ); ok( hr == DI_OK, "EnumEffects returned %#x\n", hr ); ok( check_effects_params.index >= check_effects_params.expect_count, "missing %u effects\n", check_effects_params.expect_count - check_effects_params.index ); hr = IDirectInputDevice8_GetEffectInfo( device, NULL, &GUID_Sine ); ok( hr == E_POINTER, "GetEffectInfo returned %#x\n", hr ); effectinfo.dwSize = sizeof(DIEFFECTINFOW) + 1; hr = IDirectInputDevice8_GetEffectInfo( device, &effectinfo, &GUID_Sine ); ok( hr == DIERR_INVALIDPARAM, "GetEffectInfo returned %#x\n", hr ); effectinfo.dwSize = sizeof(DIEFFECTINFOW); hr = IDirectInputDevice8_GetEffectInfo( device, &effectinfo, &GUID_NULL ); ok( hr == DIERR_DEVICENOTREG, "GetEffectInfo returned %#x\n", hr ); hr = IDirectInputDevice8_GetEffectInfo( device, &effectinfo, &GUID_Sine ); ok( hr == DIERR_DEVICENOTREG, "GetEffectInfo returned %#x\n", hr ); hr = IDirectInputDevice8_SetDataFormat( device, NULL ); ok( hr == E_POINTER, "SetDataFormat returned: %#x\n", hr ); hr = IDirectInputDevice8_SetDataFormat( device, &dataformat ); ok( hr == DIERR_INVALIDPARAM, "SetDataFormat returned: %#x\n", hr ); dataformat.dwSize = sizeof(DIDATAFORMAT); hr = IDirectInputDevice8_SetDataFormat( device, &dataformat ); ok( hr == DIERR_INVALIDPARAM, "SetDataFormat returned: %#x\n", hr ); dataformat.dwObjSize = sizeof(DIOBJECTDATAFORMAT); hr = IDirectInputDevice8_SetDataFormat( device, &dataformat ); ok( hr == DI_OK, "SetDataFormat returned: %#x\n", hr ); hr = IDirectInputDevice8_SetDataFormat( device, &c_dfDIJoystick2 ); ok( hr == DI_OK, "SetDataFormat returned: %#x\n", hr ); hr = IDirectInputDevice8_GetObjectInfo( device, &objinst, DIJOFS_Y, DIPH_BYOFFSET ); ok( hr == DI_OK, "GetObjectInfo returned: %#x\n", hr ); check_member( objinst, expect_objects[0], "%u", dwSize ); check_member_guid( objinst, expect_objects[0], guidType ); check_member( objinst, expect_objects[0], "%#x", dwOfs ); check_member( objinst, expect_objects[0], "%#x", dwType ); check_member( objinst, expect_objects[0], "%#x", dwFlags ); if (!localized) todo_wine check_member_wstr( objinst, expect_objects[0], tszName ); check_member( objinst, expect_objects[0], "%u", dwFFMaxForce ); check_member( objinst, expect_objects[0], "%u", dwFFForceResolution ); check_member( objinst, expect_objects[0], "%u", wCollectionNumber ); check_member( objinst, expect_objects[0], "%u", wDesignatorIndex ); check_member( objinst, expect_objects[0], "%#04x", wUsagePage ); check_member( objinst, expect_objects[0], "%#04x", wUsage ); check_member( objinst, expect_objects[0], "%#04x", dwDimension ); check_member( objinst, expect_objects[0], "%#04x", wExponent ); check_member( objinst, expect_objects[0], "%u", wReportId ); hr = IDirectInputDevice8_SetEventNotification( device, (HANDLE)0xdeadbeef ); todo_wine ok( hr == E_HANDLE, "SetEventNotification returned: %#x\n", hr ); event = CreateEventW( NULL, FALSE, FALSE, NULL ); ok( event != NULL, "CreateEventW failed, last error %u\n", GetLastError() ); hr = IDirectInputDevice8_SetEventNotification( device, event ); ok( hr == DI_OK, "SetEventNotification returned: %#x\n", hr ); file = CreateFileW( prop_guid_path.wszPath, FILE_READ_ACCESS | FILE_WRITE_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL ); ok( file != INVALID_HANDLE_VALUE, "got error %u\n", GetLastError() ); hr = IDirectInputDevice8_SetCooperativeLevel( device, NULL, 0 ); ok( hr == DIERR_INVALIDPARAM, "SetCooperativeLevel returned: %#x\n", hr ); hr = IDirectInputDevice8_SetCooperativeLevel( device, NULL, DISCL_BACKGROUND ); ok( hr == DIERR_INVALIDPARAM, "SetCooperativeLevel returned: %#x\n", hr ); hr = IDirectInputDevice8_SetCooperativeLevel( device, NULL, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE ); ok( hr == E_HANDLE, "SetCooperativeLevel returned: %#x\n", hr ); hr = IDirectInputDevice8_SetCooperativeLevel( device, NULL, DISCL_BACKGROUND | DISCL_EXCLUSIVE ); ok( hr == E_HANDLE, "SetCooperativeLevel returned: %#x\n", hr ); hr = IDirectInputDevice8_SetCooperativeLevel( device, NULL, DISCL_FOREGROUND | DISCL_EXCLUSIVE ); ok( hr == E_HANDLE, "SetCooperativeLevel returned: %#x\n", hr ); hwnd = CreateWindowW( L"static", L"dinput", WS_OVERLAPPEDWINDOW | WS_VISIBLE, 10, 10, 200, 200, NULL, NULL, NULL, NULL ); hr = IDirectInputDevice8_SetCooperativeLevel( device, hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE ); ok( hr == DI_OK, "SetCooperativeLevel returned: %#x\n", hr ); hr = IDirectInputDevice8_SetCooperativeLevel( device, hwnd, DISCL_BACKGROUND | DISCL_EXCLUSIVE ); ok( hr == DI_OK, "SetCooperativeLevel returned: %#x\n", hr ); hr = IDirectInputDevice8_SetCooperativeLevel( device, hwnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE ); ok( hr == DI_OK, "SetCooperativeLevel returned: %#x\n", hr ); hr = IDirectInputDevice8_Unacquire( device ); ok( hr == DI_NOEFFECT, "Unacquire returned: %#x\n", hr ); hr = IDirectInputDevice8_Acquire( device ); ok( hr == DI_OK, "Acquire returned: %#x\n", hr ); hr = IDirectInputDevice8_SetCooperativeLevel( device, hwnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE ); ok( hr == DIERR_ACQUIRED, "SetCooperativeLevel returned: %#x\n", hr ); hr = IDirectInputDevice8_Unacquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); DestroyWindow( hwnd ); hr = IDirectInputDevice8_SetCooperativeLevel( device, NULL, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE ); ok( hr == DI_OK, "SetCooperativeLevel returned: %#x\n", hr ); hr = IDirectInputDevice8_GetDeviceState( device, sizeof(DIJOYSTATE2), &state ); ok( hr == DIERR_NOTACQUIRED, "GetDeviceState returned: %#x\n", hr ); hr = IDirectInputDevice8_Poll( device ); ok( hr == DIERR_NOTACQUIRED, "Poll returned: %#x\n", hr ); hr = IDirectInputDevice8_Acquire( device ); ok( hr == DI_OK, "Acquire returned: %#x\n", hr ); hr = IDirectInputDevice8_Poll( device ); ok( hr == DI_NOEFFECT, "Poll returned: %#x\n", hr ); hr = IDirectInputDevice8_GetDeviceState( device, sizeof(DIJOYSTATE2) + 1, &state ); ok( hr == DIERR_INVALIDPARAM, "GetDeviceState returned: %#x\n", hr ); for (i = 0; i < ARRAY_SIZE(injected_input); ++i) { winetest_push_context( "state[%d]", i ); hr = IDirectInputDevice8_GetDeviceState( device, sizeof(DIJOYSTATE2), &state ); ok( hr == DI_OK, "GetDeviceState returned: %#x\n", hr ); check_member( state, expect_state[i], "%d", lX ); check_member( state, expect_state[i], "%d", lY ); check_member( state, expect_state[i], "%d", lZ ); check_member( state, expect_state[i], "%d", lRx ); check_member( state, expect_state[i], "%#x", rgdwPOV[0] ); check_member( state, expect_state[i], "%#x", rgdwPOV[1] ); check_member( state, expect_state[i], "%#x", rgbButtons[0] ); check_member( state, expect_state[i], "%#x", rgbButtons[1] ); check_member( state, expect_state[i], "%#x", rgbButtons[2] ); send_hid_input( file, &injected_input[i], sizeof(*injected_input) ); res = WaitForSingleObject( event, 100 ); if (i == 0 || i == 3) ok( res == WAIT_TIMEOUT, "WaitForSingleObject succeeded\n" ); else ok( res == WAIT_OBJECT_0, "WaitForSingleObject failed\n" ); ResetEvent( event ); winetest_pop_context(); } hr = IDirectInputDevice8_GetDeviceState( device, sizeof(DIJOYSTATE2), &state ); ok( hr == DI_OK, "GetDeviceState returned: %#x\n", hr ); winetest_push_context( "state[%d]", i ); check_member( state, expect_state[i], "%d", lX ); check_member( state, expect_state[i], "%d", lY ); check_member( state, expect_state[i], "%d", lZ ); check_member( state, expect_state[i], "%d", lRx ); check_member( state, expect_state[i], "%#x", rgdwPOV[0] ); check_member( state, expect_state[i], "%#x", rgdwPOV[1] ); check_member( state, expect_state[i], "%#x", rgbButtons[0] ); check_member( state, expect_state[i], "%#x", rgbButtons[1] ); check_member( state, expect_state[i], "%#x", rgbButtons[2] ); winetest_pop_context(); res = 1; hr = IDirectInputDevice8_GetDeviceData( device, sizeof(DIDEVICEOBJECTDATA) - 1, objdata, &res, DIGDD_PEEK ); todo_wine ok( hr == DIERR_INVALIDPARAM, "GetDeviceData returned %#x\n", hr ); res = 1; hr = IDirectInputDevice8_GetDeviceData( device, sizeof(DIDEVICEOBJECTDATA), objdata, &res, DIGDD_PEEK ); ok( hr == DIERR_NOTBUFFERED, "GetDeviceData returned %#x\n", hr ); hr = IDirectInputDevice8_Unacquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); prop_dword.diph.dwHow = DIPH_DEVICE; prop_dword.diph.dwObj = 0; prop_dword.dwData = 1; hr = IDirectInputDevice8_SetProperty( device, DIPROP_BUFFERSIZE, &prop_dword.diph ); ok( hr == DI_OK, "SetProperty DIPROP_BUFFERSIZE returned %#x\n", hr ); hr = IDirectInputDevice8_Acquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); res = 1; hr = IDirectInputDevice8_GetDeviceData( device, sizeof(DIDEVICEOBJECTDATA), objdata, &res, DIGDD_PEEK ); ok( hr == DI_OK, "GetDeviceData returned %#x\n", hr ); ok( res == 0, "got %u expected %u\n", res, 0 ); send_hid_input( file, &injected_input[0], sizeof(*injected_input) ); res = WaitForSingleObject( event, 100 ); ok( res == WAIT_OBJECT_0, "WaitForSingleObject failed\n" ); ResetEvent( event ); res = 1; hr = IDirectInputDevice8_GetDeviceData( device, sizeof(DIDEVICEOBJECTDATA), objdata, &res, DIGDD_PEEK ); ok( hr == DI_BUFFEROVERFLOW, "GetDeviceData returned %#x\n", hr ); ok( res == 0, "got %u expected %u\n", res, 0 ); res = 1; hr = IDirectInputDevice8_GetDeviceData( device, sizeof(DIDEVICEOBJECTDATA), objdata, &res, 0 ); todo_wine ok( hr == DI_OK, "GetDeviceData returned %#x\n", hr ); ok( res == 0, "got %u expected %u\n", res, 0 ); hr = IDirectInputDevice8_Unacquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); prop_dword.diph.dwHow = DIPH_DEVICE; prop_dword.diph.dwObj = 0; prop_dword.dwData = 10; hr = IDirectInputDevice8_SetProperty( device, DIPROP_BUFFERSIZE, &prop_dword.diph ); ok( hr == DI_OK, "SetProperty DIPROP_BUFFERSIZE returned %#x\n", hr ); hr = IDirectInputDevice8_Acquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); send_hid_input( file, &injected_input[1], sizeof(*injected_input) ); res = WaitForSingleObject( event, 100 ); ok( res == WAIT_OBJECT_0, "WaitForSingleObject failed\n" ); ResetEvent( event ); res = 1; hr = IDirectInputDevice8_GetDeviceData( device, sizeof(DIDEVICEOBJECTDATA), objdata, &res, DIGDD_PEEK ); ok( hr == DI_OK, "GetDeviceData returned %#x\n", hr ); ok( res == 1, "got %u expected %u\n", res, 1 ); check_member( objdata[0], expect_objdata[0], "%#x", dwOfs ); check_member( objdata[0], expect_objdata[0], "%#x", dwData ); ok( objdata[0].uAppData == -1, "got %p, expected %p\n", (void *)objdata[0].uAppData, (void *)-1 ); res = 4; hr = IDirectInputDevice8_GetDeviceData( device, sizeof(DIDEVICEOBJECTDATA), objdata, &res, 0 ); ok( hr == DI_OK, "GetDeviceData returned %#x\n", hr ); ok( res == 4, "got %u expected %u\n", res, 4 ); for (i = 0; i < 4; ++i) { winetest_push_context( "objdata[%d]", i ); check_member( objdata[i], expect_objdata[1 + i], "%#x", dwOfs ); check_member( objdata[i], expect_objdata[1 + i], "%#x", dwData ); ok( objdata[i].uAppData == -1, "got %p, expected %p\n", (void *)objdata[i].uAppData, (void *)-1 ); winetest_pop_context(); } send_hid_input( file, &injected_input[2], sizeof(*injected_input) ); res = WaitForSingleObject( event, 100 ); ok( res == WAIT_OBJECT_0, "WaitForSingleObject failed\n" ); ResetEvent( event ); send_hid_input( file, &injected_input[4], sizeof(*injected_input) ); res = WaitForSingleObject( event, 100 ); ok( res == WAIT_OBJECT_0, "WaitForSingleObject failed\n" ); ResetEvent( event ); res = 1; hr = IDirectInputDevice8_GetDeviceData( device, sizeof(DIDEVICEOBJECTDATA), objdata, &res, 0 ); ok( hr == DI_BUFFEROVERFLOW, "GetDeviceData returned %#x\n", hr ); ok( res == 1, "got %u expected %u\n", res, 1 ); todo_wine check_member( objdata[0], expect_objdata[5], "%#x", dwOfs ); todo_wine check_member( objdata[0], expect_objdata[5], "%#x", dwData ); ok( objdata[0].uAppData == -1, "got %p, expected %p\n", (void *)objdata[0].uAppData, (void *)-1 ); res = ARRAY_SIZE(objdata); hr = IDirectInputDevice8_GetDeviceData( device, sizeof(DIDEVICEOBJECTDATA), objdata, &res, 0 ); ok( hr == DI_OK, "GetDeviceData returned %#x\n", hr ); ok( res == 8, "got %u expected %u\n", res, 8 ); for (i = 0; i < 8; ++i) { winetest_push_context( "objdata[%d]", i ); todo_wine check_member( objdata[i], expect_objdata[6 + i], "%#x", dwOfs ); todo_wine_if( i == 1 || i == 2 || i == 6 ) check_member( objdata[i], expect_objdata[6 + i], "%#x", dwData ); ok( objdata[i].uAppData == -1, "got %p, expected %p\n", (void *)objdata[i].uAppData, (void *)-1 ); winetest_pop_context(); } send_hid_input( file, &injected_input[3], sizeof(*injected_input) ); res = WaitForSingleObject( event, 100 ); ok( res == WAIT_OBJECT_0, "WaitForSingleObject failed\n" ); ResetEvent( event ); hr = IDirectInputDevice8_GetDeviceState( device, sizeof(DIJOYSTATE2), &state ); ok( hr == DI_OK, "GetDeviceState returned: %#x\n", hr ); check_member( state, expect_state[3], "%d", lX ); check_member( state, expect_state[3], "%d", lY ); check_member( state, expect_state[3], "%d", lZ ); check_member( state, expect_state[3], "%d", lRx ); check_member( state, expect_state[3], "%d", rgdwPOV[0] ); check_member( state, expect_state[3], "%d", rgdwPOV[1] ); check_member( state, expect_state[3], "%#x", rgbButtons[0] ); check_member( state, expect_state[3], "%#x", rgbButtons[1] ); check_member( state, expect_state[3], "%#x", rgbButtons[2] ); prop_range.diph.dwHow = DIPH_DEVICE; prop_range.diph.dwObj = 0; prop_range.lMin = 1000; prop_range.lMax = 51000; hr = IDirectInputDevice8_SetProperty( device, DIPROP_RANGE, &prop_range.diph ); ok( hr == DI_OK, "SetProperty DIPROP_RANGE returned %#x\n", hr ); prop_range.diph.dwHow = DIPH_BYUSAGE; prop_range.diph.dwObj = MAKELONG( HID_USAGE_GENERIC_X, HID_USAGE_PAGE_GENERIC ); prop_range.lMin = -4000; prop_range.lMax = -14000; hr = IDirectInputDevice8_SetProperty( device, DIPROP_RANGE, &prop_range.diph ); ok( hr == DIERR_INVALIDPARAM, "SetProperty DIPROP_RANGE returned %#x\n", hr ); prop_range.lMin = -14000; prop_range.lMax = -4000; hr = IDirectInputDevice8_SetProperty( device, DIPROP_RANGE, &prop_range.diph ); ok( hr == DI_OK, "SetProperty DIPROP_RANGE returned %#x\n", hr ); prop_range.diph.dwHow = DIPH_DEVICE; prop_range.diph.dwObj = 0; prop_range.lMin = 0xdeadbeef; prop_range.lMax = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_RANGE, &prop_range.diph ); ok( hr == DIERR_UNSUPPORTED, "GetProperty DIPROP_RANGE returned %#x\n", hr ); prop_range.diph.dwHow = DIPH_BYUSAGE; prop_range.diph.dwObj = MAKELONG( HID_USAGE_GENERIC_X, HID_USAGE_PAGE_GENERIC ); prop_range.lMin = 0xdeadbeef; prop_range.lMax = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_RANGE, &prop_range.diph ); ok( hr == DI_OK, "GetProperty DIPROP_RANGE returned %#x\n", hr ); ok( prop_range.lMin == -14000, "got %d expected %d\n", prop_range.lMin, -14000 ); ok( prop_range.lMax == -4000, "got %d expected %d\n", prop_range.lMax, -4000 ); prop_range.diph.dwHow = DIPH_BYUSAGE; prop_range.diph.dwObj = MAKELONG( HID_USAGE_GENERIC_Y, HID_USAGE_PAGE_GENERIC ); prop_range.lMin = 0xdeadbeef; prop_range.lMax = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_RANGE, &prop_range.diph ); ok( hr == DI_OK, "GetProperty DIPROP_RANGE returned %#x\n", hr ); ok( prop_range.lMin == 1000, "got %d expected %d\n", prop_range.lMin, 1000 ); ok( prop_range.lMax == 51000, "got %d expected %d\n", prop_range.lMax, 51000 ); hr = IDirectInputDevice8_GetDeviceState( device, sizeof(DIJOYSTATE2), &state ); ok( hr == DI_OK, "GetDeviceState returned: %#x\n", hr ); check_member( state, expect_state_abs[1], "%d", lX ); check_member( state, expect_state_abs[1], "%d", lY ); check_member( state, expect_state_abs[1], "%d", lZ ); check_member( state, expect_state_abs[1], "%d", lRx ); check_member( state, expect_state_abs[1], "%d", rgdwPOV[0] ); check_member( state, expect_state_abs[1], "%d", rgdwPOV[1] ); check_member( state, expect_state_abs[1], "%#x", rgbButtons[0] ); check_member( state, expect_state_abs[1], "%#x", rgbButtons[1] ); check_member( state, expect_state_abs[1], "%#x", rgbButtons[2] ); hr = IDirectInputDevice8_SetProperty( device, NULL, NULL ); ok( hr == DIERR_INVALIDPARAM, "SetProperty returned %#x\n", hr ); hr = IDirectInputDevice8_SetProperty( device, &GUID_NULL, NULL ); ok( hr == DIERR_INVALIDPARAM, "SetProperty returned %#x\n", hr ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_VIDPID, NULL ); ok( hr == DIERR_INVALIDPARAM, "SetProperty returned %#x\n", hr ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_VIDPID, &prop_string.diph ); ok( hr == DIERR_INVALIDPARAM, "SetProperty returned %#x\n", hr ); prop_dword.diph.dwHow = DIPH_DEVICE; prop_dword.diph.dwObj = 0; prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_SetProperty( device, DIPROP_VIDPID, &prop_dword.diph ); ok( hr == DIERR_READONLY, "SetProperty DIPROP_VIDPID returned %#x\n", hr ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_GUIDANDPATH, &prop_guid_path.diph ); ok( hr == DIERR_READONLY, "SetProperty DIPROP_GUIDANDPATH returned %#x\n", hr ); prop_string.diph.dwHow = DIPH_DEVICE; prop_string.diph.dwObj = 0; wcscpy( prop_string.wsz, L"instance name" ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_INSTANCENAME, &prop_string.diph ); ok( hr == DIERR_UNSUPPORTED, "SetProperty DIPROP_INSTANCENAME returned %#x\n", hr ); wcscpy( prop_string.wsz, L"product name" ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_PRODUCTNAME, &prop_string.diph ); todo_wine ok( hr == DI_OK, "SetProperty DIPROP_PRODUCTNAME returned %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_PRODUCTNAME, &prop_string.diph ); ok( hr == DI_OK, "GetProperty DIPROP_PRODUCTNAME returned %#x\n", hr ); todo_wine ok( !wcscmp( prop_string.wsz, expect_devinst.tszProductName ), "got product %s\n", debugstr_w(prop_string.wsz) ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_TYPENAME, &prop_string.diph ); ok( hr == DIERR_READONLY, "SetProperty DIPROP_TYPENAME returned %#x\n", hr ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_USERNAME, &prop_string.diph ); ok( hr == DIERR_READONLY, "SetProperty DIPROP_USERNAME returned %#x\n", hr ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_FFLOAD, &prop_dword.diph ); ok( hr == DIERR_READONLY, "SetProperty DIPROP_FFLOAD returned %#x\n", hr ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_GRANULARITY, &prop_dword.diph ); ok( hr == DIERR_READONLY, "SetProperty DIPROP_GRANULARITY returned %#x\n", hr ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_JOYSTICKID, &prop_dword.diph ); todo_wine ok( hr == DIERR_ACQUIRED, "SetProperty DIPROP_JOYSTICKID returned %#x\n", hr ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_AXISMODE, &prop_dword.diph ); ok( hr == DIERR_ACQUIRED, "SetProperty DIPROP_AXISMODE returned %#x\n", hr ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_BUFFERSIZE, &prop_dword.diph ); ok( hr == DIERR_ACQUIRED, "SetProperty DIPROP_BUFFERSIZE returned %#x\n", hr ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_AUTOCENTER, &prop_dword.diph ); ok( hr == DIERR_ACQUIRED, "SetProperty DIPROP_AUTOCENTER returned %#x\n", hr ); prop_pointer.diph.dwHow = DIPH_BYUSAGE; prop_pointer.diph.dwObj = MAKELONG( HID_USAGE_GENERIC_X, HID_USAGE_PAGE_GENERIC ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_APPDATA, &prop_pointer.diph ); todo_wine ok( hr == DIERR_ACQUIRED, "SetProperty DIPROP_APPDATA returned %#x\n", hr ); prop_dword.diph.dwHow = DIPH_DEVICE; prop_dword.diph.dwObj = 0; prop_dword.dwData = 10001; hr = IDirectInputDevice8_SetProperty( device, DIPROP_DEADZONE, &prop_dword.diph ); ok( hr == DIERR_INVALIDPARAM, "SetProperty DIPROP_DEADZONE returned %#x\n", hr ); hr = IDirectInputDevice8_SetProperty( device, DIPROP_SATURATION, &prop_dword.diph ); ok( hr == DIERR_INVALIDPARAM, "SetProperty DIPROP_SATURATION returned %#x\n", hr ); prop_dword.dwData = 1000; hr = IDirectInputDevice8_SetProperty( device, DIPROP_DEADZONE, &prop_dword.diph ); ok( hr == DI_OK, "SetProperty DIPROP_DEADZONE returned %#x\n", hr ); prop_dword.dwData = 6000; hr = IDirectInputDevice8_SetProperty( device, DIPROP_SATURATION, &prop_dword.diph ); ok( hr == DI_OK, "SetProperty DIPROP_SATURATION returned %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_DEADZONE, &prop_dword.diph ); ok( hr == DIERR_UNSUPPORTED, "GetProperty DIPROP_DEADZONE returned %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_SATURATION, &prop_dword.diph ); ok( hr == DIERR_UNSUPPORTED, "GetProperty DIPROP_SATURATION returned %#x\n", hr ); prop_dword.diph.dwHow = DIPH_BYUSAGE; prop_dword.diph.dwObj = MAKELONG( HID_USAGE_GENERIC_X, HID_USAGE_PAGE_GENERIC ); prop_dword.dwData = 2000; hr = IDirectInputDevice8_SetProperty( device, DIPROP_DEADZONE, &prop_dword.diph ); ok( hr == DI_OK, "SetProperty DIPROP_DEADZONE returned %#x\n", hr ); ok( prop_dword.dwData == 2000, "got %u expected %u\n", prop_dword.dwData, 2000 ); prop_dword.dwData = 7000; hr = IDirectInputDevice8_SetProperty( device, DIPROP_SATURATION, &prop_dword.diph ); ok( hr == DI_OK, "SetProperty DIPROP_SATURATION returned %#x\n", hr ); prop_dword.diph.dwHow = DIPH_BYUSAGE; prop_dword.diph.dwObj = MAKELONG( HID_USAGE_GENERIC_X, HID_USAGE_PAGE_GENERIC ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_DEADZONE, &prop_dword.diph ); ok( hr == DI_OK, "GetProperty DIPROP_DEADZONE returned %#x\n", hr ); ok( prop_dword.dwData == 2000, "got %u expected %u\n", prop_dword.dwData, 2000 ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_SATURATION, &prop_dword.diph ); ok( hr == DI_OK, "GetProperty DIPROP_SATURATION returned %#x\n", hr ); ok( prop_dword.dwData == 7000, "got %u expected %u\n", prop_dword.dwData, 7000 ); prop_dword.diph.dwHow = DIPH_BYUSAGE; prop_dword.diph.dwObj = MAKELONG( HID_USAGE_GENERIC_Y, HID_USAGE_PAGE_GENERIC ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_DEADZONE, &prop_dword.diph ); ok( hr == DI_OK, "GetProperty DIPROP_DEADZONE returned %#x\n", hr ); ok( prop_dword.dwData == 1000, "got %u expected %u\n", prop_dword.dwData, 1000 ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_SATURATION, &prop_dword.diph ); ok( hr == DI_OK, "GetProperty DIPROP_SATURATION returned %#x\n", hr ); ok( prop_dword.dwData == 6000, "got %u expected %u\n", prop_dword.dwData, 6000 ); for (i = 0; i < ARRAY_SIZE(injected_input); ++i) { winetest_push_context( "state[%d]", i ); hr = IDirectInputDevice8_GetDeviceState( device, sizeof(DIJOYSTATE2), &state ); ok( hr == DI_OK, "GetDeviceState returned: %#x\n", hr ); if (broken( state.lX == -10750 )) win_skip( "Ignoring 32-bit rounding\n" ); else { check_member( state, expect_state_abs[i], "%d", lX ); check_member( state, expect_state_abs[i], "%d", lY ); } check_member( state, expect_state_abs[i], "%d", lZ ); check_member( state, expect_state_abs[i], "%d", lRx ); check_member( state, expect_state_abs[i], "%d", rgdwPOV[0] ); check_member( state, expect_state_abs[i], "%d", rgdwPOV[1] ); check_member( state, expect_state_abs[i], "%#x", rgbButtons[0] ); check_member( state, expect_state_abs[i], "%#x", rgbButtons[1] ); check_member( state, expect_state_abs[i], "%#x", rgbButtons[2] ); send_hid_input( file, &injected_input[i], sizeof(*injected_input) ); res = WaitForSingleObject( event, 100 ); if (i == 0 || i == 3) ok( res == WAIT_TIMEOUT, "WaitForSingleObject succeeded\n" ); else ok( res == WAIT_OBJECT_0, "WaitForSingleObject failed\n" ); ResetEvent( event ); winetest_pop_context(); } hr = IDirectInputDevice8_GetDeviceState( device, sizeof(DIJOYSTATE2), &state ); ok( hr == DI_OK, "GetDeviceState returned: %#x\n", hr ); winetest_push_context( "state[%d]", i ); check_member( state, expect_state_abs[i], "%d", lX ); check_member( state, expect_state_abs[i], "%d", lY ); check_member( state, expect_state_abs[i], "%d", lZ ); check_member( state, expect_state_abs[i], "%d", lRx ); check_member( state, expect_state_abs[i], "%d", rgdwPOV[0] ); check_member( state, expect_state_abs[i], "%d", rgdwPOV[1] ); check_member( state, expect_state_abs[i], "%#x", rgbButtons[0] ); check_member( state, expect_state_abs[i], "%#x", rgbButtons[1] ); check_member( state, expect_state_abs[i], "%#x", rgbButtons[2] ); winetest_pop_context(); hr = IDirectInputDevice8_Unacquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); prop_dword.diph.dwHow = DIPH_DEVICE; prop_dword.diph.dwObj = 0; hr = IDirectInputDevice8_SetProperty( device, DIPROP_JOYSTICKID, &prop_dword.diph ); ok( hr == DIERR_UNSUPPORTED, "SetProperty DIPROP_JOYSTICKID returned %#x\n", hr ); prop_dword.dwData = 0x1000; hr = IDirectInputDevice8_SetProperty( device, DIPROP_BUFFERSIZE, &prop_dword.diph ); ok( hr == DI_OK, "SetProperty DIPROP_BUFFERSIZE returned %#x\n", hr ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_SetProperty( device, DIPROP_AUTOCENTER, &prop_dword.diph ); ok( hr == DIERR_INVALIDPARAM, "SetProperty DIPROP_AUTOCENTER returned %#x\n", hr ); prop_dword.dwData = DIPROPAUTOCENTER_ON; hr = IDirectInputDevice8_SetProperty( device, DIPROP_AUTOCENTER, &prop_dword.diph ); ok( hr == DIERR_UNSUPPORTED, "SetProperty DIPROP_AUTOCENTER returned %#x\n", hr ); prop_pointer.diph.dwHow = DIPH_BYUSAGE; prop_pointer.diph.dwObj = MAKELONG( HID_USAGE_GENERIC_X, HID_USAGE_PAGE_GENERIC ); prop_pointer.uData = 0xfeedcafe; hr = IDirectInputDevice8_SetProperty( device, DIPROP_APPDATA, &prop_pointer.diph ); todo_wine ok( hr == DI_OK, "SetProperty DIPROP_APPDATA returned %#x\n", hr ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_SetProperty( device, DIPROP_AXISMODE, &prop_dword.diph ); todo_wine ok( hr == DIERR_INVALIDPARAM, "SetProperty DIPROP_AXISMODE returned %#x\n", hr ); prop_dword.dwData = DIPROPAXISMODE_REL; hr = IDirectInputDevice8_SetProperty( device, DIPROP_AXISMODE, &prop_dword.diph ); ok( hr == DI_OK, "SetProperty DIPROP_AXISMODE returned %#x\n", hr ); hr = IDirectInputDevice8_Acquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_AXISMODE, &prop_dword.diph ); todo_wine ok( hr == DI_OK, "GetProperty DIPROP_AXISMODE returned %#x\n", hr ); todo_wine ok( prop_dword.dwData == DIPROPAXISMODE_REL, "got %u expected %u\n", prop_dword.dwData, DIPROPAXISMODE_REL ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_BUFFERSIZE, &prop_dword.diph ); ok( hr == DI_OK, "GetProperty DIPROP_BUFFERSIZE returned %#x\n", hr ); ok( prop_dword.dwData == 0x1000, "got %#x expected %#x\n", prop_dword.dwData, 0x1000 ); prop_pointer.diph.dwHow = DIPH_BYUSAGE; prop_pointer.diph.dwObj = MAKELONG( HID_USAGE_GENERIC_X, HID_USAGE_PAGE_GENERIC ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_APPDATA, &prop_pointer.diph ); todo_wine ok( hr == DI_OK, "GetProperty DIPROP_APPDATA returned %#x\n", hr ); ok( prop_pointer.uData == 0xfeedcafe, "got %p expected %p\n", (void *)prop_pointer.uData, (void *)0xfeedcafe ); prop_dword.diph.dwHow = DIPH_DEVICE; prop_dword.diph.dwObj = 0; prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_SetProperty( device, DIPROP_FFGAIN, &prop_dword.diph ); todo_wine ok( hr == DIERR_INVALIDPARAM, "SetProperty DIPROP_FFGAIN returned %#x\n", hr ); prop_dword.dwData = 1000; hr = IDirectInputDevice8_SetProperty( device, DIPROP_FFGAIN, &prop_dword.diph ); todo_wine ok( hr == DI_OK, "SetProperty DIPROP_FFGAIN returned %#x\n", hr ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_SetProperty( device, DIPROP_CALIBRATION, &prop_dword.diph ); todo_wine ok( hr == DIERR_INVALIDPARAM, "SetProperty DIPROP_CALIBRATION returned %#x\n", hr ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_SetProperty( device, DIPROP_DEADZONE, &prop_dword.diph ); ok( hr == DIERR_INVALIDPARAM, "SetProperty DIPROP_DEADZONE returned %#x\n", hr ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_SetProperty( device, DIPROP_SATURATION, &prop_dword.diph ); ok( hr == DIERR_INVALIDPARAM, "SetProperty DIPROP_SATURATION returned %#x\n", hr ); for (i = 0; i < ARRAY_SIZE(injected_input); ++i) { winetest_push_context( "state[%d]", i ); hr = IDirectInputDevice8_GetDeviceState( device, sizeof(DIJOYSTATE2), &state ); ok( hr == DI_OK, "GetDeviceState returned: %#x\n", hr ); todo_wine check_member( state, expect_state_rel[i], "%d", lX ); todo_wine check_member( state, expect_state_rel[i], "%d", lY ); todo_wine check_member( state, expect_state_rel[i], "%d", lZ ); check_member( state, expect_state_rel[i], "%d", lRx ); check_member( state, expect_state_rel[i], "%d", rgdwPOV[0] ); check_member( state, expect_state_rel[i], "%d", rgdwPOV[1] ); check_member( state, expect_state_rel[i], "%#x", rgbButtons[0] ); check_member( state, expect_state_rel[i], "%#x", rgbButtons[1] ); check_member( state, expect_state_rel[i], "%#x", rgbButtons[2] ); send_hid_input( file, &injected_input[i], sizeof(*injected_input) ); res = WaitForSingleObject( event, 100 ); if (i == 3) ok( res == WAIT_TIMEOUT, "WaitForSingleObject succeeded\n" ); else ok( res == WAIT_OBJECT_0, "WaitForSingleObject failed\n" ); ResetEvent( event ); winetest_pop_context(); } hr = IDirectInputDevice8_GetDeviceState( device, sizeof(DIJOYSTATE2), &state ); ok( hr == DI_OK, "GetDeviceState returned: %#x\n", hr ); winetest_push_context( "state[%d]", i ); todo_wine check_member( state, expect_state_rel[i], "%d", lX ); todo_wine check_member( state, expect_state_rel[i], "%d", lY ); todo_wine check_member( state, expect_state_rel[i], "%d", lZ ); check_member( state, expect_state_rel[i], "%d", lRx ); check_member( state, expect_state_rel[i], "%d", rgdwPOV[0] ); check_member( state, expect_state_rel[i], "%d", rgdwPOV[1] ); check_member( state, expect_state_rel[i], "%#x", rgbButtons[0] ); check_member( state, expect_state_rel[i], "%#x", rgbButtons[1] ); check_member( state, expect_state_rel[i], "%#x", rgbButtons[2] ); winetest_pop_context(); hr = IDirectInputDevice8_GetForceFeedbackState( device, NULL ); ok( hr == E_POINTER, "GetForceFeedbackState returned %#x\n", hr ); res = 0xdeadbeef; hr = IDirectInputDevice8_GetForceFeedbackState( device, &res ); ok( hr == DIERR_UNSUPPORTED, "GetForceFeedbackState returned %#x\n", hr ); hr = IDirectInputDevice8_SendForceFeedbackCommand( device, 0xdeadbeef ); ok( hr == DIERR_INVALIDPARAM, "SendForceFeedbackCommand returned %#x\n", hr ); hr = IDirectInputDevice8_SendForceFeedbackCommand( device, DISFFC_RESET ); ok( hr == DIERR_UNSUPPORTED, "SendForceFeedbackCommand returned %#x\n", hr ); objdata[0].dwOfs = 0xd; objdata[0].dwData = 0x80; res = 1; hr = IDirectInputDevice8_SendDeviceData( device, sizeof(DIDEVICEOBJECTDATA), objdata, &res, 0xdeadbeef ); todo_wine ok( hr == DIERR_INVALIDPARAM, "SendDeviceData returned %#x\n", hr ); res = 1; hr = IDirectInputDevice8_SendDeviceData( device, sizeof(DIDEVICEOBJECTDATA), objdata, &res, 1 /*DISDD_CONTINUE*/ ); todo_wine ok( hr == DIERR_INVALIDPARAM, "SendDeviceData returned %#x\n", hr ); res = 1; hr = IDirectInputDevice8_SendDeviceData( device, sizeof(DIDEVICEOBJECTDATA), objdata, &res, 0 ); todo_wine ok( hr == DIERR_INVALIDPARAM, "SendDeviceData returned %#x\n", hr ); hr = IDirectInputDevice8_CreateEffect( device, &GUID_Sine, NULL, NULL, NULL ); ok( hr == E_POINTER, "CreateEffect returned %#x\n", hr ); hr = IDirectInputDevice8_CreateEffect( device, NULL, NULL, &effect, NULL ); ok( hr == DIERR_UNSUPPORTED, "CreateEffect returned %#x\n", hr ); hr = IDirectInputDevice8_CreateEffect( device, &GUID_NULL, NULL, &effect, NULL ); ok( hr == DIERR_UNSUPPORTED, "CreateEffect returned %#x\n", hr ); hr = IDirectInputDevice8_CreateEffect( device, &GUID_Sine, NULL, &effect, NULL ); ok( hr == DIERR_UNSUPPORTED, "CreateEffect returned %#x\n", hr ); hr = IDirectInputDevice8_Unacquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); hr = IDirectInputDevice8_CreateEffect( device, &GUID_Sine, NULL, &effect, NULL ); ok( hr == DIERR_UNSUPPORTED, "CreateEffect returned %#x\n", hr ); hr = IDirectInputDevice8_EnumCreatedEffectObjects( device, NULL, effect, 0 ); ok( hr == DIERR_INVALIDPARAM, "EnumCreatedEffectObjects returned %#x\n", hr ); hr = IDirectInputDevice8_EnumCreatedEffectObjects( device, check_no_created_effect_objects, effect, 0xdeadbeef ); ok( hr == DIERR_INVALIDPARAM, "EnumCreatedEffectObjects returned %#x\n", hr ); hr = IDirectInputDevice8_EnumCreatedEffectObjects( device, check_no_created_effect_objects, (void *)0xdeadbeef, 0 ); ok( hr == DI_OK, "EnumCreatedEffectObjects returned %#x\n", hr ); hr = IDirectInputDevice8_Escape( device, NULL ); todo_wine ok( hr == E_POINTER, "Escape returned: %#x\n", hr ); hr = IDirectInputDevice8_Escape( device, &escape ); todo_wine ok( hr == DIERR_INVALIDPARAM, "Escape returned: %#x\n", hr ); escape.dwSize = sizeof(DIEFFESCAPE) + 1; hr = IDirectInputDevice8_Escape( device, &escape ); todo_wine ok( hr == DIERR_INVALIDPARAM, "Escape returned: %#x\n", hr ); escape.dwSize = sizeof(DIEFFESCAPE); escape.dwCommand = 0; escape.lpvInBuffer = buffer; escape.cbInBuffer = 10; escape.lpvOutBuffer = buffer + 10; escape.cbOutBuffer = 10; hr = IDirectInputDevice8_Escape( device, &escape ); todo_wine ok( hr == DIERR_UNSUPPORTED, "Escape returned: %#x\n", hr ); /* FIXME: we have to wait a bit because Wine DInput internal thread keeps a reference */ Sleep( 100 ); ref = IDirectInputDevice8_Release( device ); ok( ref == 0, "Release returned %d\n", ref ); CloseHandle( event ); CloseHandle( file ); ref = IDirectInput8_Release( di ); ok( ref == 0, "Release returned %d\n", ref ); done: pnp_driver_stop(); cleanup_registry_keys(); SetCurrentDirectoryW( cwd ); } struct device_desc { const BYTE *report_desc_buf; ULONG report_desc_len; HIDP_CAPS hid_caps; }; static BOOL test_device_types(void) { #include "psh_hid_macros.h" static const unsigned char unknown_desc[] = { USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Application), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Physical), USAGE_PAGE(1, HID_USAGE_PAGE_BUTTON), USAGE_MINIMUM(1, 1), USAGE_MAXIMUM(1, 6), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 1), REPORT_SIZE(1, 1), REPORT_COUNT(1, 8), INPUT(1, Data|Var|Abs), END_COLLECTION, END_COLLECTION, }; static const unsigned char limited_desc[] = { USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Application), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Physical), USAGE(1, HID_USAGE_GENERIC_X), USAGE(1, HID_USAGE_GENERIC_Y), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 127), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 127), REPORT_SIZE(1, 8), REPORT_COUNT(1, 2), INPUT(1, Data|Var|Abs), USAGE_PAGE(1, HID_USAGE_PAGE_BUTTON), USAGE_MINIMUM(1, 1), USAGE_MAXIMUM(1, 6), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 1), REPORT_SIZE(1, 1), REPORT_COUNT(1, 8), INPUT(1, Data|Var|Abs), END_COLLECTION, END_COLLECTION, }; static const unsigned char gamepad_desc[] = { USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_GAMEPAD), COLLECTION(1, Application), USAGE(1, HID_USAGE_GENERIC_GAMEPAD), COLLECTION(1, Physical), USAGE(1, HID_USAGE_GENERIC_X), USAGE(1, HID_USAGE_GENERIC_Y), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 127), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 127), REPORT_SIZE(1, 8), REPORT_COUNT(1, 2), INPUT(1, Data|Var|Abs), USAGE_PAGE(1, HID_USAGE_PAGE_BUTTON), USAGE_MINIMUM(1, 1), USAGE_MAXIMUM(1, 6), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 1), REPORT_SIZE(1, 1), REPORT_COUNT(1, 8), INPUT(1, Data|Var|Abs), END_COLLECTION, END_COLLECTION, }; static const unsigned char joystick_desc[] = { USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Application), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Physical), USAGE(1, HID_USAGE_GENERIC_X), USAGE(1, HID_USAGE_GENERIC_Y), USAGE(1, HID_USAGE_GENERIC_Z), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 127), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 127), REPORT_SIZE(1, 8), REPORT_COUNT(1, 3), INPUT(1, Data|Var|Abs), USAGE(1, HID_USAGE_GENERIC_HATSWITCH), LOGICAL_MINIMUM(1, 1), LOGICAL_MAXIMUM(1, 8), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 8), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), INPUT(1, Data|Var|Abs|Null), USAGE_PAGE(1, HID_USAGE_PAGE_BUTTON), USAGE_MINIMUM(1, 1), USAGE_MAXIMUM(1, 5), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 1), REPORT_SIZE(1, 1), REPORT_COUNT(1, 8), INPUT(1, Data|Var|Abs), END_COLLECTION, END_COLLECTION, }; #include "pop_hid_macros.h" static struct device_desc device_desc[] = { { .report_desc_buf = unknown_desc, .report_desc_len = sizeof(unknown_desc), .hid_caps = { .InputReportByteLength = 1, }, }, { .report_desc_buf = limited_desc, .report_desc_len = sizeof(limited_desc), .hid_caps = { .InputReportByteLength = 3, }, }, { .report_desc_buf = gamepad_desc, .report_desc_len = sizeof(gamepad_desc), .hid_caps = { .InputReportByteLength = 3, }, }, { .report_desc_buf = joystick_desc, .report_desc_len = sizeof(joystick_desc), .hid_caps = { .InputReportByteLength = 5, }, }, }; static const DIDEVCAPS expect_caps[] = { { .dwSize = sizeof(DIDEVCAPS), .dwFlags = DIDC_ATTACHED|DIDC_EMULATED, .dwDevType = DIDEVTYPE_HID|(DI8DEVTYPESUPPLEMENTAL_UNKNOWN << 8)|DI8DEVTYPE_SUPPLEMENTAL, .dwButtons = 6, }, { .dwSize = sizeof(DIDEVCAPS), .dwFlags = DIDC_ATTACHED|DIDC_EMULATED, .dwDevType = DIDEVTYPE_HID|(DI8DEVTYPEJOYSTICK_LIMITED << 8)|DI8DEVTYPE_JOYSTICK, .dwAxes = 2, .dwButtons = 6, }, { .dwSize = sizeof(DIDEVCAPS), .dwFlags = DIDC_ATTACHED|DIDC_EMULATED, .dwDevType = DIDEVTYPE_HID|(DI8DEVTYPEGAMEPAD_STANDARD << 8)|DI8DEVTYPE_GAMEPAD, .dwAxes = 2, .dwButtons = 6, }, { .dwSize = sizeof(DIDEVCAPS), .dwFlags = DIDC_ATTACHED|DIDC_EMULATED, .dwDevType = DIDEVTYPE_HID|(DI8DEVTYPEJOYSTICK_STANDARD << 8)|DI8DEVTYPE_JOYSTICK, .dwAxes = 3, .dwPOVs = 1, .dwButtons = 5, }, }; const DIDEVICEINSTANCEW expect_devinst[] = { { .dwSize = sizeof(DIDEVICEINSTANCEW), .guidInstance = expect_guid_product, .guidProduct = expect_guid_product, .dwDevType = DIDEVTYPE_HID|(DI8DEVTYPESUPPLEMENTAL_UNKNOWN << 8)|DI8DEVTYPE_SUPPLEMENTAL, .tszInstanceName = L"Wine test root driver", .tszProductName = L"Wine test root driver", .guidFFDriver = GUID_NULL, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_JOYSTICK, }, { .dwSize = sizeof(DIDEVICEINSTANCEW), .guidInstance = expect_guid_product, .guidProduct = expect_guid_product, .dwDevType = DIDEVTYPE_HID|(DI8DEVTYPEJOYSTICK_LIMITED << 8)|DI8DEVTYPE_JOYSTICK, .tszInstanceName = L"Wine test root driver", .tszProductName = L"Wine test root driver", .guidFFDriver = GUID_NULL, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_JOYSTICK, }, { .dwSize = sizeof(DIDEVICEINSTANCEW), .guidInstance = expect_guid_product, .guidProduct = expect_guid_product, .dwDevType = DIDEVTYPE_HID|(DI8DEVTYPEGAMEPAD_STANDARD << 8)|DI8DEVTYPE_GAMEPAD, .tszInstanceName = L"Wine test root driver", .tszProductName = L"Wine test root driver", .guidFFDriver = GUID_NULL, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_GAMEPAD, }, { .dwSize = sizeof(DIDEVICEINSTANCEW), .guidInstance = expect_guid_product, .guidProduct = expect_guid_product, .dwDevType = DIDEVTYPE_HID|(DI8DEVTYPEJOYSTICK_STANDARD << 8)|DI8DEVTYPE_JOYSTICK, .tszInstanceName = L"Wine test root driver", .tszProductName = L"Wine test root driver", .guidFFDriver = GUID_NULL, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_JOYSTICK, }, }; DIDEVICEINSTANCEW devinst = {.dwSize = sizeof(DIDEVICEINSTANCEW)}; DIDEVCAPS caps = {.dwSize = sizeof(DIDEVCAPS)}; WCHAR cwd[MAX_PATH], tempdir[MAX_PATH]; IDirectInputDevice8W *device; BOOL success = TRUE; IDirectInput8W *di; ULONG i, ref; HRESULT hr; for (i = 0; i < ARRAY_SIZE(device_desc) && success; ++i) { winetest_push_context( "desc[%d]", i ); GetCurrentDirectoryW( ARRAY_SIZE(cwd), cwd ); GetTempPathW( ARRAY_SIZE(tempdir), tempdir ); SetCurrentDirectoryW( tempdir ); cleanup_registry_keys(); if (!dinput_driver_start( device_desc[i].report_desc_buf, device_desc[i].report_desc_len, &device_desc[i].hid_caps )) { success = FALSE; goto done; } hr = DirectInput8Create( instance, DIRECTINPUT_VERSION, &IID_IDirectInput8W, (void **)&di, NULL ); if (FAILED(hr)) { win_skip( "DirectInput8Create returned %#x\n", hr ); success = FALSE; goto done; } hr = IDirectInput8_EnumDevices( di, DI8DEVCLASS_ALL, find_test_device, &devinst, DIEDFL_ALLDEVICES ); ok( hr == DI_OK, "EnumDevices returned: %#x\n", hr ); if (!IsEqualGUID( &devinst.guidProduct, &expect_guid_product )) { win_skip( "device not found, skipping tests\n" ); IDirectInput8_Release( di ); success = FALSE; goto done; } hr = IDirectInput8_CreateDevice( di, &expect_guid_product, &device, NULL ); ok( hr == DI_OK, "CreateDevice returned %#x\n", hr ); hr = IDirectInputDevice8_GetDeviceInfo( device, &devinst ); ok( hr == DI_OK, "GetDeviceInfo returned %#x\n", hr ); check_member( devinst, expect_devinst[i], "%d", dwSize ); todo_wine check_member_guid( devinst, expect_devinst[i], guidInstance ); check_member_guid( devinst, expect_devinst[i], guidProduct ); check_member( devinst, expect_devinst[i], "%#x", dwDevType ); todo_wine check_member_wstr( devinst, expect_devinst[i], tszInstanceName ); todo_wine check_member_wstr( devinst, expect_devinst[i], tszProductName ); check_member_guid( devinst, expect_devinst[i], guidFFDriver ); check_member( devinst, expect_devinst[i], "%04x", wUsagePage ); check_member( devinst, expect_devinst[i], "%04x", wUsage ); hr = IDirectInputDevice8_GetCapabilities( device, &caps ); ok( hr == DI_OK, "GetCapabilities returned %#x\n", hr ); check_member( caps, expect_caps[i], "%d", dwSize ); check_member( caps, expect_caps[i], "%#x", dwFlags ); check_member( caps, expect_caps[i], "%#x", dwDevType ); check_member( caps, expect_caps[i], "%d", dwAxes ); check_member( caps, expect_caps[i], "%d", dwButtons ); check_member( caps, expect_caps[i], "%d", dwPOVs ); check_member( caps, expect_caps[i], "%d", dwFFSamplePeriod ); check_member( caps, expect_caps[i], "%d", dwFFMinTimeResolution ); check_member( caps, expect_caps[i], "%d", dwFirmwareRevision ); check_member( caps, expect_caps[i], "%d", dwHardwareRevision ); check_member( caps, expect_caps[i], "%d", dwFFDriverVersion ); ref = IDirectInputDevice8_Release( device ); ok( ref == 0, "Release returned %d\n", ref ); ref = IDirectInput8_Release( di ); ok( ref == 0, "Release returned %d\n", ref ); done: pnp_driver_stop(); cleanup_registry_keys(); SetCurrentDirectoryW( cwd ); winetest_pop_context(); } return success; } static void test_periodic_effect( IDirectInputDevice8W *device, HANDLE file ) { struct hid_expect expect_download[] = { /* set periodic */ { .code = IOCTL_HID_WRITE_REPORT, .report_id = 5, .report_len = 2, .report_buf = {0x05,0x19}, }, /* set envelope */ { .code = IOCTL_HID_WRITE_REPORT, .report_id = 6, .report_len = 7, .report_buf = {0x06,0x19,0x4c,0x02,0x00,0x04,0x00}, }, /* update effect */ { .code = IOCTL_HID_WRITE_REPORT, .report_id = 3, .report_len = 11, .report_buf = {0x03,0x01,0x01,0x08,0x01,0x00,0x06,0x00,0x01,0x55,0xd5}, }, /* start command when DIEP_START is set */ { .code = IOCTL_HID_WRITE_REPORT, .report_id = 2, .report_len = 4, .report_buf = {0x02,0x01,0x01,0x01}, }, }; struct hid_expect expect_start = { .code = IOCTL_HID_WRITE_REPORT, .report_id = 2, .report_len = 4, .report_buf = {0x02, 0x01, 0x01, 0x01}, }; struct hid_expect expect_start_solo = { .code = IOCTL_HID_WRITE_REPORT, .report_id = 2, .report_len = 4, .report_buf = {0x02, 0x01, 0x02, 0x01}, }; struct hid_expect expect_start_0 = { .code = IOCTL_HID_WRITE_REPORT, .report_id = 2, .report_len = 4, .report_buf = {0x02, 0x01, 0x01, 0x00}, }; struct hid_expect expect_start_4 = { .code = IOCTL_HID_WRITE_REPORT, .report_id = 2, .report_len = 4, .report_buf = {0x02, 0x01, 0x01, 0x04}, }; struct hid_expect expect_stop = { .code = IOCTL_HID_WRITE_REPORT, .report_id = 2, .report_len = 4, .report_buf = {0x02, 0x01, 0x03, 0x00}, }; struct hid_expect expect_unload[] = { { .code = IOCTL_HID_WRITE_REPORT, .report_id = 2, .report_len = 4, .report_buf = {0x02,0x01,0x03,0x00}, }, /* device reset, when unloaded from Unacquire */ { .code = IOCTL_HID_WRITE_REPORT, .report_id = 1, .report_len = 2, .report_buf = {1,0x01}, }, }; struct hid_expect expect_dc_reset = { .code = IOCTL_HID_WRITE_REPORT, .report_id = 1, .report_len = 2, .report_buf = {1, 0x01}, }; static const DWORD expect_axes_init[2] = {0}; static const DIEFFECT expect_desc_init = { .dwSize = sizeof(DIEFFECT), .dwTriggerButton = -1, .rgdwAxes = (void *)expect_axes_init, }; static const DWORD expect_axes[3] = { DIDFT_ABSAXIS | DIDFT_MAKEINSTANCE( 2 ) | DIDFT_FFACTUATOR, DIDFT_ABSAXIS | DIDFT_MAKEINSTANCE( 0 ) | DIDFT_FFACTUATOR, DIDFT_ABSAXIS | DIDFT_MAKEINSTANCE( 1 ) | DIDFT_FFACTUATOR, }; static const LONG expect_directions[3] = { +3000, -6000, 0, }; static const DIENVELOPE expect_envelope = { .dwSize = sizeof(DIENVELOPE), .dwAttackLevel = 1000, .dwAttackTime = 2000, .dwFadeLevel = 3000, .dwFadeTime = 4000, }; static const DIPERIODIC expect_periodic = { .dwMagnitude = 1000, .lOffset = 2000, .dwPhase = 3000, .dwPeriod = 4000, }; static const DIEFFECT expect_desc = { .dwSize = sizeof(DIEFFECT), .dwFlags = DIEFF_SPHERICAL | DIEFF_OBJECTIDS, .dwDuration = 1000, .dwSamplePeriod = 2000, .dwGain = 3000, .dwTriggerButton = DIDFT_PSHBUTTON | DIDFT_MAKEINSTANCE( 0 ) | DIDFT_FFEFFECTTRIGGER, .dwTriggerRepeatInterval = 5000, .cAxes = 3, .rgdwAxes = (void *)expect_axes, .rglDirection = (void *)expect_directions, .lpEnvelope = (void *)&expect_envelope, .cbTypeSpecificParams = sizeof(DIPERIODIC), .lpvTypeSpecificParams = (void *)&expect_periodic, .dwStartDelay = 6000, }; struct check_created_effect_params check_params = {0}; IDirectInputEffect *effect; DIPERIODIC periodic = {0}; DIENVELOPE envelope = {0}; LONG directions[4] = {0}; DIEFFECT desc = {0}; DWORD axes[4] = {0}; ULONG ref, flags; HRESULT hr; GUID guid; hr = IDirectInputDevice8_CreateEffect( device, &GUID_Sine, NULL, NULL, NULL ); ok( hr == E_POINTER, "CreateEffect returned %#x\n", hr ); hr = IDirectInputDevice8_CreateEffect( device, NULL, NULL, &effect, NULL ); ok( hr == E_POINTER, "CreateEffect returned %#x\n", hr ); hr = IDirectInputDevice8_CreateEffect( device, &GUID_NULL, NULL, &effect, NULL ); ok( hr == DIERR_DEVICENOTREG, "CreateEffect returned %#x\n", hr ); hr = IDirectInputDevice8_CreateEffect( device, &GUID_Sine, NULL, &effect, NULL ); ok( hr == DI_OK, "CreateEffect returned %#x\n", hr ); if (hr != DI_OK) return; hr = IDirectInputDevice8_EnumCreatedEffectObjects( device, check_no_created_effect_objects, effect, 0xdeadbeef ); ok( hr == DIERR_INVALIDPARAM, "EnumCreatedEffectObjects returned %#x\n", hr ); check_params.expect_effect = effect; hr = IDirectInputDevice8_EnumCreatedEffectObjects( device, check_created_effect_objects, &check_params, 0 ); ok( hr == DI_OK, "EnumCreatedEffectObjects returned %#x\n", hr ); ok( check_params.count == 1, "got count %u, expected 1\n", check_params.count ); hr = IDirectInputEffect_Initialize( effect, NULL, DIRECTINPUT_VERSION, &GUID_Sine ); ok( hr == DIERR_INVALIDPARAM, "Initialize returned %#x\n", hr ); hr = IDirectInputEffect_Initialize( effect, instance, 0, &GUID_Sine ); todo_wine ok( hr == DIERR_NOTINITIALIZED, "Initialize returned %#x\n", hr ); hr = IDirectInputEffect_Initialize( effect, instance, DIRECTINPUT_VERSION, NULL ); ok( hr == E_POINTER, "Initialize returned %#x\n", hr ); hr = IDirectInputEffect_Initialize( effect, instance, DIRECTINPUT_VERSION, &GUID_NULL ); ok( hr == DIERR_DEVICENOTREG, "Initialize returned %#x\n", hr ); hr = IDirectInputEffect_Initialize( effect, instance, DIRECTINPUT_VERSION, &GUID_Sine ); ok( hr == DI_OK, "Initialize returned %#x\n", hr ); hr = IDirectInputEffect_Initialize( effect, instance, DIRECTINPUT_VERSION, &GUID_Square ); ok( hr == DI_OK, "Initialize returned %#x\n", hr ); hr = IDirectInputEffect_GetEffectGuid( effect, NULL ); ok( hr == E_POINTER, "GetEffectGuid returned %#x\n", hr ); hr = IDirectInputEffect_GetEffectGuid( effect, &guid ); ok( hr == DI_OK, "GetEffectGuid returned %#x\n", hr ); ok( IsEqualGUID( &guid, &GUID_Square ), "got guid %s, expected %s\n", debugstr_guid( &guid ), debugstr_guid( &GUID_Square ) ); hr = IDirectInputEffect_GetParameters( effect, NULL, 0 ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); hr = IDirectInputEffect_GetParameters( effect, NULL, DIEP_DURATION ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); hr = IDirectInputEffect_GetParameters( effect, &desc, 0 ); ok( hr == DIERR_INVALIDPARAM, "GetParameters returned %#x\n", hr ); desc.dwSize = sizeof(DIEFFECT); hr = IDirectInputEffect_GetParameters( effect, &desc, 0 ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); set_hid_expect( file, &expect_dc_reset, sizeof(expect_dc_reset) ); hr = IDirectInputDevice8_Unacquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); set_hid_expect( file, NULL, 0 ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DURATION ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); set_hid_expect( file, &expect_dc_reset, sizeof(expect_dc_reset) ); hr = IDirectInputDevice8_Acquire( device ); ok( hr == DI_OK, "Acquire returned: %#x\n", hr ); set_hid_expect( file, NULL, 0 ); desc.dwDuration = 0xdeadbeef; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DURATION ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc_init, "%u", dwDuration ); memset( &desc, 0xcd, sizeof(desc) ); desc.dwSize = sizeof(DIEFFECT); desc.dwFlags = 0; flags = DIEP_GAIN | DIEP_SAMPLEPERIOD | DIEP_STARTDELAY | DIEP_TRIGGERREPEATINTERVAL; hr = IDirectInputEffect_GetParameters( effect, &desc, flags ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc_init, "%u", dwSamplePeriod ); check_member( desc, expect_desc_init, "%u", dwGain ); check_member( desc, expect_desc_init, "%u", dwStartDelay ); check_member( desc, expect_desc_init, "%u", dwTriggerRepeatInterval ); memset( &desc, 0xcd, sizeof(desc) ); desc.dwSize = sizeof(DIEFFECT); desc.dwFlags = 0; desc.lpEnvelope = NULL; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_ENVELOPE ); ok( hr == E_POINTER, "GetParameters returned %#x\n", hr ); desc.lpEnvelope = &envelope; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_ENVELOPE ); ok( hr == DIERR_INVALIDPARAM, "GetParameters returned %#x\n", hr ); envelope.dwSize = sizeof(DIENVELOPE); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_ENVELOPE ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); desc.dwFlags = 0; desc.cAxes = 0; desc.rgdwAxes = NULL; desc.rglDirection = NULL; desc.lpEnvelope = NULL; desc.cbTypeSpecificParams = 0; desc.lpvTypeSpecificParams = NULL; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_ALLPARAMS ); ok( hr == DIERR_INVALIDPARAM, "GetParameters returned %#x\n", hr ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_TRIGGERBUTTON ); ok( hr == DIERR_INVALIDPARAM, "GetParameters returned %#x\n", hr ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_AXES ); ok( hr == DIERR_INVALIDPARAM, "GetParameters returned %#x\n", hr ); desc.dwFlags = DIEFF_OBJECTOFFSETS; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DIERR_INVALIDPARAM, "GetParameters returned %#x\n", hr ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_TRIGGERBUTTON ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc_init, "%#x", dwTriggerButton ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_AXES ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc_init, "%u", cAxes ); desc.dwFlags = DIEFF_OBJECTIDS; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DIERR_INVALIDPARAM, "GetParameters returned %#x\n", hr ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_TRIGGERBUTTON ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc_init, "%#x", dwTriggerButton ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_AXES ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc_init, "%u", cAxes ); desc.dwFlags |= DIEFF_CARTESIAN; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); ok( desc.dwFlags == DIEFF_OBJECTIDS, "got flags %#x, expected %#x\n", desc.dwFlags, DIEFF_OBJECTIDS ); desc.dwFlags |= DIEFF_POLAR; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DIERR_INVALIDPARAM, "GetParameters returned %#x\n", hr ); ok( desc.dwFlags == DIEFF_OBJECTIDS, "got flags %#x, expected %#x\n", desc.dwFlags, DIEFF_OBJECTIDS ); desc.dwFlags |= DIEFF_SPHERICAL; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc_init, "%u", cAxes ); ok( desc.dwFlags == DIEFF_OBJECTIDS, "got flags %#x, expected %#x\n", desc.dwFlags, DIEFF_OBJECTIDS ); desc.dwFlags |= DIEFF_SPHERICAL; desc.cAxes = 2; desc.rgdwAxes = axes; desc.rglDirection = directions; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_AXES | DIEP_DIRECTION ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc_init, "%u", cAxes ); check_member( desc, expect_desc_init, "%u", rgdwAxes[0] ); check_member( desc, expect_desc_init, "%u", rgdwAxes[1] ); check_member( desc, expect_desc_init, "%p", rglDirection ); ok( desc.dwFlags == DIEFF_OBJECTIDS, "got flags %#x, expected %#x\n", desc.dwFlags, DIEFF_OBJECTIDS ); desc.dwFlags |= DIEFF_SPHERICAL; desc.lpEnvelope = &envelope; desc.cbTypeSpecificParams = sizeof(periodic); desc.lpvTypeSpecificParams = &periodic; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_ALLPARAMS ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc_init, "%u", dwDuration ); check_member( desc, expect_desc_init, "%u", dwSamplePeriod ); check_member( desc, expect_desc_init, "%u", dwGain ); check_member( desc, expect_desc_init, "%#x", dwTriggerButton ); check_member( desc, expect_desc_init, "%u", dwTriggerRepeatInterval ); check_member( desc, expect_desc_init, "%u", cAxes ); check_member( desc, expect_desc_init, "%u", rgdwAxes[0] ); check_member( desc, expect_desc_init, "%u", rgdwAxes[1] ); check_member( desc, expect_desc_init, "%p", rglDirection ); todo_wine check_member( desc, expect_desc_init, "%p", lpEnvelope ); todo_wine check_member( desc, expect_desc_init, "%u", cbTypeSpecificParams ); check_member( desc, expect_desc_init, "%u", dwStartDelay ); set_hid_expect( file, &expect_dc_reset, sizeof(expect_dc_reset) ); hr = IDirectInputDevice8_Unacquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); set_hid_expect( file, NULL, 0 ); hr = IDirectInputEffect_Download( effect ); ok( hr == DIERR_NOTEXCLUSIVEACQUIRED, "Download returned %#x\n", hr ); set_hid_expect( file, &expect_dc_reset, sizeof(expect_dc_reset) ); hr = IDirectInputDevice8_Acquire( device ); ok( hr == DI_OK, "Acquire returned: %#x\n", hr ); set_hid_expect( file, NULL, 0 ); hr = IDirectInputEffect_Download( effect ); ok( hr == DIERR_INCOMPLETEEFFECT, "Download returned %#x\n", hr ); hr = IDirectInputEffect_Unload( effect ); ok( hr == DI_NOEFFECT, "Unload returned %#x\n", hr ); hr = IDirectInputEffect_SetParameters( effect, NULL, DIEP_NODOWNLOAD ); ok( hr == E_POINTER, "SetParameters returned %#x\n", hr ); memset( &desc, 0, sizeof(desc) ); hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_NODOWNLOAD ); ok( hr == DIERR_INVALIDPARAM, "SetParameters returned %#x\n", hr ); desc.dwSize = sizeof(DIEFFECT); hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_NODOWNLOAD ); ok( hr == DI_DOWNLOADSKIPPED, "SetParameters returned %#x\n", hr ); set_hid_expect( file, &expect_dc_reset, sizeof(expect_dc_reset) ); hr = IDirectInputDevice8_Unacquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); set_hid_expect( file, NULL, 0 ); hr = IDirectInputEffect_SetParameters( effect, &expect_desc, DIEP_DURATION | DIEP_NODOWNLOAD ); ok( hr == DI_DOWNLOADSKIPPED, "SetParameters returned %#x\n", hr ); set_hid_expect( file, &expect_dc_reset, sizeof(expect_dc_reset) ); hr = IDirectInputDevice8_Acquire( device ); ok( hr == DI_OK, "Acquire returned: %#x\n", hr ); set_hid_expect( file, NULL, 0 ); hr = IDirectInputEffect_SetParameters( effect, &expect_desc, DIEP_DURATION | DIEP_NODOWNLOAD ); ok( hr == DI_DOWNLOADSKIPPED, "SetParameters returned %#x\n", hr ); desc.dwTriggerButton = -1; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DURATION ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc, "%u", dwDuration ); check_member( desc, expect_desc_init, "%u", dwSamplePeriod ); check_member( desc, expect_desc_init, "%u", dwGain ); check_member( desc, expect_desc_init, "%#x", dwTriggerButton ); check_member( desc, expect_desc_init, "%u", dwTriggerRepeatInterval ); check_member( desc, expect_desc_init, "%u", cAxes ); check_member( desc, expect_desc_init, "%p", rglDirection ); check_member( desc, expect_desc_init, "%p", lpEnvelope ); check_member( desc, expect_desc_init, "%u", cbTypeSpecificParams ); check_member( desc, expect_desc_init, "%u", dwStartDelay ); hr = IDirectInputEffect_Download( effect ); ok( hr == DIERR_INCOMPLETEEFFECT, "Download returned %#x\n", hr ); hr = IDirectInputEffect_Unload( effect ); ok( hr == DI_NOEFFECT, "Unload returned %#x\n", hr ); hr = IDirectInputEffect_SetParameters( effect, &expect_desc, DIEP_GAIN | DIEP_SAMPLEPERIOD | DIEP_STARTDELAY | DIEP_TRIGGERREPEATINTERVAL | DIEP_NODOWNLOAD ); ok( hr == DI_DOWNLOADSKIPPED, "SetParameters returned %#x\n", hr ); desc.dwDuration = 0; flags = DIEP_DURATION | DIEP_GAIN | DIEP_SAMPLEPERIOD | DIEP_STARTDELAY | DIEP_TRIGGERREPEATINTERVAL; hr = IDirectInputEffect_GetParameters( effect, &desc, flags ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc, "%u", dwDuration ); check_member( desc, expect_desc, "%u", dwSamplePeriod ); check_member( desc, expect_desc, "%u", dwGain ); check_member( desc, expect_desc_init, "%#x", dwTriggerButton ); check_member( desc, expect_desc, "%u", dwTriggerRepeatInterval ); check_member( desc, expect_desc_init, "%u", cAxes ); check_member( desc, expect_desc_init, "%p", rglDirection ); check_member( desc, expect_desc_init, "%p", lpEnvelope ); check_member( desc, expect_desc_init, "%u", cbTypeSpecificParams ); check_member( desc, expect_desc, "%u", dwStartDelay ); hr = IDirectInputEffect_Download( effect ); ok( hr == DIERR_INCOMPLETEEFFECT, "Download returned %#x\n", hr ); hr = IDirectInputEffect_Unload( effect ); ok( hr == DI_NOEFFECT, "Unload returned %#x\n", hr ); desc.lpEnvelope = NULL; hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_ENVELOPE | DIEP_NODOWNLOAD ); ok( hr == DI_DOWNLOADSKIPPED, "SetParameters returned %#x\n", hr ); desc.lpEnvelope = &envelope; envelope.dwSize = 0; hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_ENVELOPE | DIEP_NODOWNLOAD ); ok( hr == DIERR_INVALIDPARAM, "SetParameters returned %#x\n", hr ); hr = IDirectInputEffect_SetParameters( effect, &expect_desc, DIEP_ENVELOPE | DIEP_NODOWNLOAD ); ok( hr == DI_DOWNLOADSKIPPED, "SetParameters returned %#x\n", hr ); desc.lpEnvelope = &envelope; envelope.dwSize = sizeof(DIENVELOPE); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_ENVELOPE ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( envelope, expect_envelope, "%u", dwAttackLevel ); check_member( envelope, expect_envelope, "%u", dwAttackTime ); check_member( envelope, expect_envelope, "%u", dwFadeLevel ); check_member( envelope, expect_envelope, "%u", dwFadeTime ); hr = IDirectInputEffect_Download( effect ); ok( hr == DIERR_INCOMPLETEEFFECT, "Download returned %#x\n", hr ); hr = IDirectInputEffect_Unload( effect ); ok( hr == DI_NOEFFECT, "Unload returned %#x\n", hr ); desc.dwFlags = 0; desc.cAxes = 0; desc.rgdwAxes = NULL; desc.rglDirection = NULL; desc.lpEnvelope = NULL; desc.cbTypeSpecificParams = 0; desc.lpvTypeSpecificParams = NULL; hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_ALLPARAMS | DIEP_NODOWNLOAD ); ok( hr == DIERR_INVALIDPARAM, "SetParameters returned %#x\n", hr ); hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_TRIGGERBUTTON | DIEP_NODOWNLOAD ); ok( hr == DIERR_INVALIDPARAM, "SetParameters returned %#x\n", hr ); hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_AXES | DIEP_NODOWNLOAD ); ok( hr == DIERR_INVALIDPARAM, "SetParameters returned %#x\n", hr ); desc.dwFlags = DIEFF_OBJECTOFFSETS; desc.cAxes = 1; desc.rgdwAxes = axes; desc.rgdwAxes[0] = DIJOFS_X; desc.dwTriggerButton = DIJOFS_BUTTON( 1 ); hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_DIRECTION | DIEP_NODOWNLOAD ); ok( hr == DIERR_INVALIDPARAM, "SetParameters returned %#x\n", hr ); hr = IDirectInputEffect_SetParameters( effect, &expect_desc, DIEP_AXES | DIEP_TRIGGERBUTTON | DIEP_NODOWNLOAD ); ok( hr == DI_DOWNLOADSKIPPED, "SetParameters returned %#x\n", hr ); hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_AXES | DIEP_TRIGGERBUTTON | DIEP_NODOWNLOAD ); ok( hr == DIERR_ALREADYINITIALIZED, "SetParameters returned %#x\n", hr ); desc.cAxes = 0; desc.dwFlags = DIEFF_OBJECTIDS; desc.rgdwAxes = axes; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_AXES | DIEP_TRIGGERBUTTON ); ok( hr == DIERR_MOREDATA, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc, "%u", cAxes ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_AXES | DIEP_TRIGGERBUTTON ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc, "%#x", dwTriggerButton ); check_member( desc, expect_desc, "%u", cAxes ); check_member( desc, expect_desc, "%u", rgdwAxes[0] ); check_member( desc, expect_desc, "%u", rgdwAxes[1] ); check_member( desc, expect_desc, "%u", rgdwAxes[2] ); desc.dwFlags = DIEFF_OBJECTOFFSETS; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_AXES | DIEP_TRIGGERBUTTON ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); ok( desc.dwTriggerButton == 0x30, "got %#x expected %#x\n", desc.dwTriggerButton, 0x30 ); ok( desc.rgdwAxes[0] == 8, "got %#x expected %#x\n", desc.rgdwAxes[0], 8 ); ok( desc.rgdwAxes[1] == 0, "got %#x expected %#x\n", desc.rgdwAxes[1], 0 ); ok( desc.rgdwAxes[2] == 4, "got %#x expected %#x\n", desc.rgdwAxes[2], 4 ); hr = IDirectInputEffect_Download( effect ); ok( hr == DIERR_INCOMPLETEEFFECT, "Download returned %#x\n", hr ); hr = IDirectInputEffect_Unload( effect ); ok( hr == DI_NOEFFECT, "Unload returned %#x\n", hr ); desc.dwFlags = DIEFF_CARTESIAN; desc.cAxes = 0; desc.rglDirection = directions; hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_DIRECTION | DIEP_NODOWNLOAD ); ok( hr == DIERR_INVALIDPARAM, "SetParameters returned %#x\n", hr ); desc.cAxes = 3; hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_DIRECTION | DIEP_NODOWNLOAD ); ok( hr == DI_DOWNLOADSKIPPED, "SetParameters returned %#x\n", hr ); desc.dwFlags = DIEFF_POLAR; desc.cAxes = 3; hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_DIRECTION | DIEP_NODOWNLOAD ); ok( hr == DIERR_INVALIDPARAM, "SetParameters returned %#x\n", hr ); hr = IDirectInputEffect_SetParameters( effect, &expect_desc, DIEP_DIRECTION | DIEP_NODOWNLOAD ); ok( hr == DI_DOWNLOADSKIPPED, "SetParameters returned %#x\n", hr ); desc.dwFlags = DIEFF_SPHERICAL; desc.cAxes = 1; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DIERR_MOREDATA, "GetParameters returned %#x\n", hr ); ok( desc.dwFlags == DIEFF_SPHERICAL, "got flags %#x, expected %#x\n", desc.dwFlags, DIEFF_SPHERICAL ); check_member( desc, expect_desc, "%u", cAxes ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc, "%u", cAxes ); ok( desc.rglDirection[0] == 3000, "got rglDirection[0] %d expected %d\n", desc.rglDirection[0], 3000 ); ok( desc.rglDirection[1] == 30000, "got rglDirection[1] %d expected %d\n", desc.rglDirection[1], 30000 ); ok( desc.rglDirection[2] == 0, "got rglDirection[2] %d expected %d\n", desc.rglDirection[2], 0 ); desc.dwFlags = DIEFF_CARTESIAN; desc.cAxes = 2; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DIERR_MOREDATA, "GetParameters returned %#x\n", hr ); ok( desc.dwFlags == DIEFF_CARTESIAN, "got flags %#x, expected %#x\n", desc.dwFlags, DIEFF_CARTESIAN ); check_member( desc, expect_desc, "%u", cAxes ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc, "%u", cAxes ); ok( desc.rglDirection[0] == 4330, "got rglDirection[0] %d expected %d\n", desc.rglDirection[0], 4330 ); ok( desc.rglDirection[1] == 2500, "got rglDirection[1] %d expected %d\n", desc.rglDirection[1], 2500 ); ok( desc.rglDirection[2] == -8660, "got rglDirection[2] %d expected %d\n", desc.rglDirection[2], -8660 ); desc.dwFlags = DIEFF_POLAR; desc.cAxes = 3; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DIERR_INVALIDPARAM, "GetParameters returned %#x\n", hr ); hr = IDirectInputEffect_Download( effect ); ok( hr == DIERR_INCOMPLETEEFFECT, "Download returned %#x\n", hr ); hr = IDirectInputEffect_Unload( effect ); ok( hr == DI_NOEFFECT, "Unload returned %#x\n", hr ); desc.cbTypeSpecificParams = 0; desc.lpvTypeSpecificParams = &periodic; hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_TYPESPECIFICPARAMS | DIEP_NODOWNLOAD ); ok( hr == DIERR_INVALIDPARAM, "SetParameters returned %#x\n", hr ); desc.cbTypeSpecificParams = sizeof(DIPERIODIC); hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_TYPESPECIFICPARAMS | DIEP_NODOWNLOAD ); ok( hr == DI_DOWNLOADSKIPPED, "SetParameters returned %#x\n", hr ); hr = IDirectInputEffect_SetParameters( effect, &expect_desc, DIEP_TYPESPECIFICPARAMS | DIEP_NODOWNLOAD ); ok( hr == DI_DOWNLOADSKIPPED, "SetParameters returned %#x\n", hr ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_TYPESPECIFICPARAMS ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( periodic, expect_periodic, "%u", dwMagnitude ); check_member( periodic, expect_periodic, "%d", lOffset ); check_member( periodic, expect_periodic, "%u", dwPhase ); check_member( periodic, expect_periodic, "%u", dwPeriod ); hr = IDirectInputEffect_Start( effect, 1, DIES_NODOWNLOAD ); ok( hr == DIERR_NOTDOWNLOADED, "Start returned %#x\n", hr ); hr = IDirectInputEffect_Stop( effect ); ok( hr == DIERR_NOTDOWNLOADED, "Stop returned %#x\n", hr ); set_hid_expect( file, expect_download, 3 * sizeof(struct hid_expect) ); hr = IDirectInputEffect_Download( effect ); ok( hr == DI_OK, "Download returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); hr = IDirectInputEffect_Download( effect ); ok( hr == DI_NOEFFECT, "Download returned %#x\n", hr ); hr = IDirectInputEffect_Start( effect, 1, 0xdeadbeef ); ok( hr == DIERR_INVALIDPARAM, "Start returned %#x\n", hr ); set_hid_expect( file, &expect_start_solo, sizeof(expect_start_solo) ); hr = IDirectInputEffect_Start( effect, 1, DIES_SOLO ); ok( hr == DI_OK, "Start returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); set_hid_expect( file, &expect_stop, sizeof(expect_stop) ); hr = IDirectInputEffect_Stop( effect ); ok( hr == DI_OK, "Stop returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); set_hid_expect( file, &expect_start, sizeof(expect_start) ); hr = IDirectInputEffect_Start( effect, 1, 0 ); ok( hr == DI_OK, "Start returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); set_hid_expect( file, &expect_start_4, sizeof(expect_start_4) ); hr = IDirectInputEffect_Start( effect, 4, 0 ); ok( hr == DI_OK, "Start returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); set_hid_expect( file, &expect_start_0, sizeof(expect_start_4) ); hr = IDirectInputEffect_Start( effect, 0, 0 ); ok( hr == DI_OK, "Start returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); set_hid_expect( file, expect_unload, sizeof(struct hid_expect) ); hr = IDirectInputEffect_Unload( effect ); ok( hr == DI_OK, "Unload returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); set_hid_expect( file, expect_download, 4 * sizeof(struct hid_expect) ); hr = IDirectInputEffect_SetParameters( effect, &expect_desc, DIEP_START ); ok( hr == DI_OK, "SetParameters returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); set_hid_expect( file, expect_unload, sizeof(struct hid_expect) ); hr = IDirectInputEffect_Unload( effect ); ok( hr == DI_OK, "Unload returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); set_hid_expect( file, expect_download, 3 * sizeof(struct hid_expect) ); hr = IDirectInputEffect_Download( effect ); ok( hr == DI_OK, "Download returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); set_hid_expect( file, expect_unload, 2 * sizeof(struct hid_expect) ); hr = IDirectInputDevice8_Unacquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); set_hid_expect( file, NULL, 0 ); hr = IDirectInputEffect_Start( effect, 1, DIES_NODOWNLOAD ); ok( hr == DIERR_NOTEXCLUSIVEACQUIRED, "Start returned %#x\n", hr ); hr = IDirectInputEffect_Stop( effect ); ok( hr == DIERR_NOTEXCLUSIVEACQUIRED, "Stop returned %#x\n", hr ); set_hid_expect( file, &expect_dc_reset, sizeof(expect_dc_reset) ); hr = IDirectInputDevice8_Acquire( device ); ok( hr == DI_OK, "Acquire returned: %#x\n", hr ); set_hid_expect( file, NULL, 0 ); hr = IDirectInputEffect_Unload( effect ); ok( hr == DI_NOEFFECT, "Unload returned %#x\n", hr ); ref = IDirectInputEffect_Release( effect ); ok( ref == 0, "Release returned %d\n", ref ); hr = IDirectInputDevice8_CreateEffect( device, &GUID_Sine, NULL, &effect, NULL ); ok( hr == DI_OK, "CreateEffect returned %#x\n", hr ); desc.dwFlags = DIEFF_POLAR | DIEFF_OBJECTIDS; desc.cAxes = 2; desc.rgdwAxes[0] = DIDFT_ABSAXIS | DIDFT_MAKEINSTANCE( 2 ) | DIDFT_FFACTUATOR; desc.rgdwAxes[1] = DIDFT_ABSAXIS | DIDFT_MAKEINSTANCE( 0 ) | DIDFT_FFACTUATOR; desc.rglDirection[0] = 3000; desc.rglDirection[1] = 0; desc.rglDirection[2] = 0; hr = IDirectInputEffect_SetParameters( effect, &desc, DIEP_AXES | DIEP_DIRECTION | DIEP_NODOWNLOAD ); ok( hr == DI_DOWNLOADSKIPPED, "SetParameters returned %#x\n", hr ); desc.rglDirection[0] = 0; desc.dwFlags = DIEFF_SPHERICAL; desc.cAxes = 1; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DIERR_MOREDATA, "GetParameters returned %#x\n", hr ); ok( desc.dwFlags == DIEFF_SPHERICAL, "got flags %#x, expected %#x\n", desc.dwFlags, DIEFF_SPHERICAL ); ok( desc.cAxes == 2, "got cAxes %u expected 2\n", desc.cAxes ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); ok( desc.cAxes == 2, "got cAxes %u expected 2\n", desc.cAxes ); ok( desc.rglDirection[0] == 30000, "got rglDirection[0] %d expected %d\n", desc.rglDirection[0], 30000 ); ok( desc.rglDirection[1] == 0, "got rglDirection[1] %d expected %d\n", desc.rglDirection[1], 0 ); ok( desc.rglDirection[2] == 0, "got rglDirection[2] %d expected %d\n", desc.rglDirection[2], 0 ); desc.dwFlags = DIEFF_CARTESIAN; desc.cAxes = 1; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DIERR_MOREDATA, "GetParameters returned %#x\n", hr ); ok( desc.dwFlags == DIEFF_CARTESIAN, "got flags %#x, expected %#x\n", desc.dwFlags, DIEFF_CARTESIAN ); ok( desc.cAxes == 2, "got cAxes %u expected 2\n", desc.cAxes ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); ok( desc.cAxes == 2, "got cAxes %u expected 2\n", desc.cAxes ); ok( desc.rglDirection[0] == 5000, "got rglDirection[0] %d expected %d\n", desc.rglDirection[0], 5000 ); ok( desc.rglDirection[1] == -8660, "got rglDirection[1] %d expected %d\n", desc.rglDirection[1], -8660 ); ok( desc.rglDirection[2] == 0, "got rglDirection[2] %d expected %d\n", desc.rglDirection[2], 0 ); desc.dwFlags = DIEFF_POLAR; desc.cAxes = 1; hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DIERR_MOREDATA, "GetParameters returned %#x\n", hr ); ok( desc.dwFlags == DIEFF_POLAR, "got flags %#x, expected %#x\n", desc.dwFlags, DIEFF_POLAR ); ok( desc.cAxes == 2, "got cAxes %u expected 2\n", desc.cAxes ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_DIRECTION ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); ok( desc.cAxes == 2, "got cAxes %u expected 2\n", desc.cAxes ); ok( desc.rglDirection[0] == 3000, "got rglDirection[0] %d expected %d\n", desc.rglDirection[0], 3000 ); ok( desc.rglDirection[1] == 0, "got rglDirection[1] %d expected %d\n", desc.rglDirection[1], 0 ); ok( desc.rglDirection[2] == 0, "got rglDirection[2] %d expected %d\n", desc.rglDirection[2], 0 ); ref = IDirectInputEffect_Release( effect ); ok( ref == 0, "Release returned %d\n", ref ); } static void test_condition_effect( IDirectInputDevice8W *device, HANDLE file ) { struct hid_expect expect_create[] = { /* set condition */ { .code = IOCTL_HID_WRITE_REPORT, .report_id = 7, .report_len = 8, .report_buf = {0x07,0x00,0xf9,0x19,0xd9,0xff,0xff,0x99}, }, /* set condition */ { .code = IOCTL_HID_WRITE_REPORT, .report_id = 7, .report_len = 8, .report_buf = {0x07,0x00,0x4c,0x3f,0xcc,0x4c,0x33,0x19}, }, /* update effect */ { .code = IOCTL_HID_WRITE_REPORT, .report_id = 3, .report_len = 11, .report_buf = {0x03,0x01,0x03,0x08,0x01,0x00,0x06,0x00,0x01,0x55,0x00}, }, }; struct hid_expect expect_create_1[] = { /* set condition */ { .code = IOCTL_HID_WRITE_REPORT, .report_id = 7, .report_len = 8, .report_buf = {0x07,0x00,0x4c,0x3f,0xcc,0x4c,0x33,0x19}, }, /* update effect */ { .code = IOCTL_HID_WRITE_REPORT, .report_id = 3, .report_len = 11, .report_buf = {0x03,0x01,0x03,0x08,0x01,0x00,0x06,0x00,0x01,0x00,0x00}, }, }; struct hid_expect expect_create_2[] = { /* set condition */ { .code = IOCTL_HID_WRITE_REPORT, .report_id = 7, .report_len = 8, .report_buf = {0x07,0x00,0x4c,0x3f,0xcc,0x4c,0x33,0x19}, }, /* update effect */ { .code = IOCTL_HID_WRITE_REPORT, .report_id = 3, .report_len = 11, .report_buf = {0x03,0x01,0x03,0x08,0x01,0x00,0x06,0x00,0x01,0x55,0x00}, }, }; struct hid_expect expect_destroy = { .code = IOCTL_HID_WRITE_REPORT, .report_id = 2, .report_len = 4, .report_buf = {0x02, 0x01, 0x03, 0x00}, }; static const DWORD expect_axes[3] = { DIDFT_ABSAXIS | DIDFT_MAKEINSTANCE( 2 ) | DIDFT_FFACTUATOR, DIDFT_ABSAXIS | DIDFT_MAKEINSTANCE( 1 ) | DIDFT_FFACTUATOR, DIDFT_ABSAXIS | DIDFT_MAKEINSTANCE( 0 ) | DIDFT_FFACTUATOR, }; static const LONG expect_directions[3] = { +3000, 0, 0, }; static const DIENVELOPE expect_envelope = { .dwSize = sizeof(DIENVELOPE), .dwAttackLevel = 1000, .dwAttackTime = 2000, .dwFadeLevel = 3000, .dwFadeTime = 4000, }; static const DICONDITION expect_condition[3] = { { .lOffset = -500, .lPositiveCoefficient = 2000, .lNegativeCoefficient = -3000, .dwPositiveSaturation = -4000, .dwNegativeSaturation = -5000, .lDeadBand = 6000, }, { .lOffset = 6000, .lPositiveCoefficient = 5000, .lNegativeCoefficient = -4000, .dwPositiveSaturation = 3000, .dwNegativeSaturation = 2000, .lDeadBand = 1000, }, { .lOffset = -7000, .lPositiveCoefficient = -8000, .lNegativeCoefficient = 9000, .dwPositiveSaturation = 10000, .dwNegativeSaturation = 11000, .lDeadBand = -12000, }, }; static const DIEFFECT expect_desc = { .dwSize = sizeof(DIEFFECT), .dwFlags = DIEFF_SPHERICAL | DIEFF_OBJECTIDS, .dwDuration = 1000, .dwSamplePeriod = 2000, .dwGain = 3000, .dwTriggerButton = DIDFT_PSHBUTTON | DIDFT_MAKEINSTANCE( 0 ) | DIDFT_FFEFFECTTRIGGER, .dwTriggerRepeatInterval = 5000, .cAxes = 2, .rgdwAxes = (void *)expect_axes, .rglDirection = (void *)expect_directions, .lpEnvelope = (void *)&expect_envelope, .cbTypeSpecificParams = 2 * sizeof(DICONDITION), .lpvTypeSpecificParams = (void *)expect_condition, .dwStartDelay = 6000, }; struct check_created_effect_params check_params = {0}; DIENVELOPE envelope = {.dwSize = sizeof(DIENVELOPE)}; DICONDITION condition[2] = {0}; IDirectInputEffect *effect; LONG directions[4] = {0}; DWORD axes[4] = {0}; DIEFFECT desc = { .dwSize = sizeof(DIEFFECT), .dwFlags = DIEFF_SPHERICAL | DIEFF_OBJECTIDS, .cAxes = 4, .rgdwAxes = axes, .rglDirection = directions, .lpEnvelope = &envelope, .cbTypeSpecificParams = 2 * sizeof(DICONDITION), .lpvTypeSpecificParams = condition, }; HRESULT hr; ULONG ref; GUID guid; set_hid_expect( file, expect_create, sizeof(expect_create) ); hr = IDirectInputDevice8_CreateEffect( device, &GUID_Spring, &expect_desc, &effect, NULL ); ok( hr == DI_OK, "CreateEffect returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); check_params.expect_effect = effect; hr = IDirectInputDevice8_EnumCreatedEffectObjects( device, check_created_effect_objects, &check_params, 0 ); ok( hr == DI_OK, "EnumCreatedEffectObjects returned %#x\n", hr ); ok( check_params.count == 1, "got count %u, expected 1\n", check_params.count ); hr = IDirectInputEffect_GetEffectGuid( effect, &guid ); ok( hr == DI_OK, "GetEffectGuid returned %#x\n", hr ); ok( IsEqualGUID( &guid, &GUID_Spring ), "got guid %s, expected %s\n", debugstr_guid( &guid ), debugstr_guid( &GUID_Spring ) ); hr = IDirectInputEffect_GetParameters( effect, &desc, DIEP_ALLPARAMS ); ok( hr == DI_OK, "GetParameters returned %#x\n", hr ); check_member( desc, expect_desc, "%u", dwDuration ); check_member( desc, expect_desc, "%u", dwSamplePeriod ); check_member( desc, expect_desc, "%u", dwGain ); check_member( desc, expect_desc, "%#x", dwTriggerButton ); check_member( desc, expect_desc, "%u", dwTriggerRepeatInterval ); check_member( desc, expect_desc, "%u", cAxes ); check_member( desc, expect_desc, "%#x", rgdwAxes[0] ); check_member( desc, expect_desc, "%#x", rgdwAxes[1] ); check_member( desc, expect_desc, "%d", rglDirection[0] ); check_member( desc, expect_desc, "%d", rglDirection[1] ); check_member( desc, expect_desc, "%u", cbTypeSpecificParams ); check_member( desc, expect_desc, "%u", dwStartDelay ); check_member( envelope, expect_envelope, "%u", dwAttackLevel ); check_member( envelope, expect_envelope, "%u", dwAttackTime ); check_member( envelope, expect_envelope, "%u", dwFadeLevel ); check_member( envelope, expect_envelope, "%u", dwFadeTime ); check_member( condition[0], expect_condition[0], "%d", lOffset ); check_member( condition[0], expect_condition[0], "%d", lPositiveCoefficient ); check_member( condition[0], expect_condition[0], "%d", lNegativeCoefficient ); check_member( condition[0], expect_condition[0], "%u", dwPositiveSaturation ); check_member( condition[0], expect_condition[0], "%u", dwNegativeSaturation ); check_member( condition[0], expect_condition[0], "%d", lDeadBand ); check_member( condition[1], expect_condition[1], "%d", lOffset ); check_member( condition[1], expect_condition[1], "%d", lPositiveCoefficient ); check_member( condition[1], expect_condition[1], "%d", lNegativeCoefficient ); check_member( condition[1], expect_condition[1], "%u", dwPositiveSaturation ); check_member( condition[1], expect_condition[1], "%u", dwNegativeSaturation ); check_member( condition[1], expect_condition[1], "%d", lDeadBand ); set_hid_expect( file, &expect_destroy, sizeof(expect_destroy) ); ref = IDirectInputEffect_Release( effect ); ok( ref == 0, "Release returned %d\n", ref ); set_hid_expect( file, NULL, 0 ); desc = expect_desc; desc.cAxes = 1; hr = IDirectInputDevice8_CreateEffect( device, &GUID_Spring, &desc, &effect, NULL ); ok( hr == DIERR_INVALIDPARAM, "CreateEffect returned %#x\n", hr ); desc.cbTypeSpecificParams = 1 * sizeof(DICONDITION); desc.lpvTypeSpecificParams = (void *)&expect_condition[1]; set_hid_expect( file, expect_create_1, sizeof(expect_create_1) ); hr = IDirectInputDevice8_CreateEffect( device, &GUID_Spring, &desc, &effect, NULL ); ok( hr == DI_OK, "CreateEffect returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); set_hid_expect( file, &expect_destroy, sizeof(expect_destroy) ); ref = IDirectInputEffect_Release( effect ); ok( ref == 0, "Release returned %d\n", ref ); set_hid_expect( file, NULL, 0 ); desc = expect_desc; desc.cAxes = 3; desc.cbTypeSpecificParams = 1 * sizeof(DICONDITION); desc.lpvTypeSpecificParams = (void *)&expect_condition[1]; set_hid_expect( file, expect_create_2, sizeof(expect_create_2) ); hr = IDirectInputDevice8_CreateEffect( device, &GUID_Spring, &desc, &effect, NULL ); ok( hr == DI_OK, "CreateEffect returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); set_hid_expect( file, &expect_destroy, sizeof(expect_destroy) ); ref = IDirectInputEffect_Release( effect ); ok( ref == 0, "Release returned %d\n", ref ); set_hid_expect( file, NULL, 0 ); } static void test_force_feedback_joystick( void ) { #include "psh_hid_macros.h" const unsigned char report_descriptor[] = { USAGE_PAGE(1, HID_USAGE_PAGE_GENERIC), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Application), USAGE(1, HID_USAGE_GENERIC_JOYSTICK), COLLECTION(1, Report), REPORT_ID(1, 1), USAGE(1, HID_USAGE_GENERIC_X), USAGE(1, HID_USAGE_GENERIC_Y), USAGE(1, HID_USAGE_GENERIC_Z), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 0x7f), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 0x7f), REPORT_SIZE(1, 8), REPORT_COUNT(1, 3), INPUT(1, Data|Var|Abs), USAGE_PAGE(1, HID_USAGE_PAGE_BUTTON), USAGE_MINIMUM(1, 1), USAGE_MAXIMUM(1, 2), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 1), REPORT_SIZE(1, 1), REPORT_COUNT(1, 2), INPUT(1, Data|Var|Abs), REPORT_COUNT(1, 6), INPUT(1, Cnst|Var|Abs), END_COLLECTION, USAGE_PAGE(1, HID_USAGE_PAGE_PID), USAGE(1, PID_USAGE_STATE_REPORT), COLLECTION(1, Report), REPORT_ID(1, 2), END_COLLECTION, USAGE_PAGE(1, HID_USAGE_PAGE_PID), USAGE(1, PID_USAGE_DEVICE_CONTROL_REPORT), COLLECTION(1, Report), REPORT_ID(1, 1), USAGE(1, PID_USAGE_DEVICE_CONTROL), COLLECTION(1, Logical), USAGE(1, PID_USAGE_DC_DEVICE_RESET), LOGICAL_MINIMUM(1, 1), LOGICAL_MAXIMUM(1, 2), PHYSICAL_MINIMUM(1, 1), PHYSICAL_MAXIMUM(1, 2), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), OUTPUT(1, Data|Ary|Abs), END_COLLECTION, END_COLLECTION, USAGE(1, PID_USAGE_EFFECT_OPERATION_REPORT), COLLECTION(1, Report), REPORT_ID(1, 2), USAGE(1, PID_USAGE_EFFECT_BLOCK_INDEX), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 0x7f), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 0x7f), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), OUTPUT(1, Data|Var|Abs), USAGE(1, PID_USAGE_EFFECT_OPERATION), COLLECTION(1, NamedArray), USAGE(1, PID_USAGE_OP_EFFECT_START), USAGE(1, PID_USAGE_OP_EFFECT_START_SOLO), USAGE(1, PID_USAGE_OP_EFFECT_STOP), LOGICAL_MINIMUM(1, 1), LOGICAL_MAXIMUM(1, 3), PHYSICAL_MINIMUM(1, 1), PHYSICAL_MAXIMUM(1, 3), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), OUTPUT(1, Data|Ary|Abs), END_COLLECTION, USAGE(1, PID_USAGE_LOOP_COUNT), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 0x7f), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 0x7f), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), OUTPUT(1, Data|Var|Abs), END_COLLECTION, USAGE(1, PID_USAGE_SET_EFFECT_REPORT), COLLECTION(1, Report), REPORT_ID(1, 3), USAGE(1, PID_USAGE_EFFECT_BLOCK_INDEX), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 0x7f), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 0x7f), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), OUTPUT(1, Data|Var|Abs), USAGE(1, PID_USAGE_EFFECT_TYPE), COLLECTION(1, NamedArray), USAGE(1, PID_USAGE_ET_SQUARE), USAGE(1, PID_USAGE_ET_SINE), USAGE(1, PID_USAGE_ET_SPRING), LOGICAL_MINIMUM(1, 1), LOGICAL_MAXIMUM(1, 3), PHYSICAL_MINIMUM(1, 1), PHYSICAL_MAXIMUM(1, 3), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), OUTPUT(1, Data|Ary|Abs), END_COLLECTION, USAGE(1, PID_USAGE_AXES_ENABLE), COLLECTION(1, Logical), USAGE(4, (HID_USAGE_PAGE_GENERIC << 16)|HID_USAGE_GENERIC_X), USAGE(4, (HID_USAGE_PAGE_GENERIC << 16)|HID_USAGE_GENERIC_Y), USAGE(4, (HID_USAGE_PAGE_GENERIC << 16)|HID_USAGE_GENERIC_Z), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 1), REPORT_SIZE(1, 1), REPORT_COUNT(1, 3), OUTPUT(1, Data|Var|Abs), END_COLLECTION, USAGE(1, PID_USAGE_DIRECTION_ENABLE), REPORT_COUNT(1, 1), OUTPUT(1, Data|Var|Abs), REPORT_COUNT(1, 4), OUTPUT(1, Cnst|Var|Abs), USAGE(1, PID_USAGE_DURATION), USAGE(1, PID_USAGE_START_DELAY), UNIT(2, 0x1003), /* Eng Lin:Time */ UNIT_EXPONENT(1, -3), /* 10^-3 */ LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(2, 0x7fff), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(2, 0x7fff), REPORT_SIZE(1, 16), REPORT_COUNT(1, 2), OUTPUT(1, Data|Var|Abs), UNIT(1, 0), UNIT_EXPONENT(1, 0), USAGE(1, PID_USAGE_TRIGGER_BUTTON), LOGICAL_MINIMUM(1, 1), LOGICAL_MAXIMUM(1, 0x08), PHYSICAL_MINIMUM(1, 1), PHYSICAL_MAXIMUM(1, 0x08), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), OUTPUT(1, Data|Var|Abs), USAGE(1, PID_USAGE_DIRECTION), COLLECTION(1, Logical), USAGE(4, (HID_USAGE_PAGE_ORDINAL << 16)|1), USAGE(4, (HID_USAGE_PAGE_ORDINAL << 16)|2), UNIT(1, 0x14), /* Eng Rot:Angular Pos */ UNIT_EXPONENT(1, -2), /* 10^-2 */ LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(2, 0x00ff), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(4, 0x00008ca0), UNIT(1, 0), REPORT_SIZE(1, 8), REPORT_COUNT(1, 2), OUTPUT(1, Data|Var|Abs), UNIT_EXPONENT(1, 0), UNIT(1, 0), END_COLLECTION, END_COLLECTION, USAGE(1, PID_USAGE_SET_PERIODIC_REPORT), COLLECTION(1, Logical), REPORT_ID(1, 5), USAGE(1, PID_USAGE_MAGNITUDE), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(2, 0x00ff), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(2, 0x2710), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), OUTPUT(1, Data|Var|Abs), END_COLLECTION, USAGE(1, PID_USAGE_SET_ENVELOPE_REPORT), COLLECTION(1, Logical), REPORT_ID(1, 6), USAGE(1, PID_USAGE_ATTACK_LEVEL), USAGE(1, PID_USAGE_FADE_LEVEL), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(2, 0x00ff), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(2, 0x2710), REPORT_SIZE(1, 8), REPORT_COUNT(1, 2), OUTPUT(1, Data|Var|Abs), USAGE(1, PID_USAGE_ATTACK_TIME), USAGE(1, PID_USAGE_FADE_TIME), UNIT(2, 0x1003), /* Eng Lin:Time */ UNIT_EXPONENT(1, -3), /* 10^-3 */ LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(2, 0x7fff), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(2, 0x7fff), REPORT_SIZE(1, 16), REPORT_COUNT(1, 2), OUTPUT(1, Data|Var|Abs), PHYSICAL_MAXIMUM(1, 0), UNIT_EXPONENT(1, 0), UNIT(1, 0), END_COLLECTION, USAGE(1, PID_USAGE_SET_CONDITION_REPORT), COLLECTION(1, Logical), REPORT_ID(1, 7), USAGE(1, PID_USAGE_TYPE_SPECIFIC_BLOCK_OFFSET), COLLECTION(1, Logical), USAGE(4, (HID_USAGE_PAGE_ORDINAL << 16)|1), USAGE(4, (HID_USAGE_PAGE_ORDINAL << 16)|2), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(1, 1), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(1, 1), REPORT_SIZE(1, 2), REPORT_COUNT(1, 2), OUTPUT(1, Data|Var|Abs), END_COLLECTION, REPORT_SIZE(1, 4), REPORT_COUNT(1, 1), OUTPUT(1, Cnst|Var|Abs), USAGE(1, PID_USAGE_CP_OFFSET), LOGICAL_MINIMUM(1, 0x80), LOGICAL_MAXIMUM(1, 0x7f), PHYSICAL_MINIMUM(2, 0xd8f0), PHYSICAL_MAXIMUM(2, 0x2710), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), OUTPUT(1, Data|Var|Abs), USAGE(1, PID_USAGE_POSITIVE_COEFFICIENT), USAGE(1, PID_USAGE_NEGATIVE_COEFFICIENT), LOGICAL_MINIMUM(1, 0x80), LOGICAL_MAXIMUM(1, 0x7f), PHYSICAL_MINIMUM(2, 0xd8f0), PHYSICAL_MAXIMUM(2, 0x2710), REPORT_SIZE(1, 8), REPORT_COUNT(1, 2), OUTPUT(1, Data|Var|Abs), USAGE(1, PID_USAGE_POSITIVE_SATURATION), USAGE(1, PID_USAGE_NEGATIVE_SATURATION), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(2, 0x00ff), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(2, 0x2710), REPORT_SIZE(1, 8), REPORT_COUNT(1, 2), OUTPUT(1, Data|Var|Abs), USAGE(1, PID_USAGE_DEAD_BAND), LOGICAL_MINIMUM(1, 0), LOGICAL_MAXIMUM(2, 0x00ff), PHYSICAL_MINIMUM(1, 0), PHYSICAL_MAXIMUM(2, 0x2710), REPORT_SIZE(1, 8), REPORT_COUNT(1, 1), OUTPUT(1, Data|Var|Abs), END_COLLECTION, END_COLLECTION, }; #undef REPORT_ID_OR_USAGE_PAGE #include "pop_hid_macros.h" static const HIDP_CAPS hid_caps = { .InputReportByteLength = 5, }; static const DIDEVCAPS expect_caps = { .dwSize = sizeof(DIDEVCAPS), .dwFlags = DIDC_FORCEFEEDBACK | DIDC_ATTACHED | DIDC_EMULATED | DIDC_STARTDELAY | DIDC_FFFADE | DIDC_FFATTACK | DIDC_DEADBAND | DIDC_SATURATION, .dwDevType = DIDEVTYPE_HID | (DI8DEVTYPEJOYSTICK_LIMITED << 8) | DI8DEVTYPE_JOYSTICK, .dwAxes = 3, .dwButtons = 2, .dwFFSamplePeriod = 1000000, .dwFFMinTimeResolution = 1000000, .dwHardwareRevision = 1, .dwFFDriverVersion = 1, }; struct hid_expect expect_dc_reset = { .code = IOCTL_HID_WRITE_REPORT, .report_id = 1, .report_len = 2, .report_buf = {1, 0x01}, }; const DIDEVICEINSTANCEW expect_devinst = { .dwSize = sizeof(DIDEVICEINSTANCEW), .guidInstance = expect_guid_product, .guidProduct = expect_guid_product, .dwDevType = DIDEVTYPE_HID | (DI8DEVTYPEJOYSTICK_LIMITED << 8) | DI8DEVTYPE_JOYSTICK, .tszInstanceName = L"Wine test root driver", .tszProductName = L"Wine test root driver", .guidFFDriver = IID_IDirectInputPIDDriver, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_JOYSTICK, }; const DIDEVICEOBJECTINSTANCEW expect_objects[] = { { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_ZAxis, .dwType = DIDFT_ABSAXIS|DIDFT_MAKEINSTANCE(2)|DIDFT_FFACTUATOR, .dwFlags = DIDOI_ASPECTPOSITION|DIDOI_FFACTUATOR, .tszName = L"Z Axis", .wCollectionNumber = 1, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_Z, .wReportId = 1, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_YAxis, .dwOfs = 0x4, .dwType = DIDFT_ABSAXIS|DIDFT_MAKEINSTANCE(1)|DIDFT_FFACTUATOR, .dwFlags = DIDOI_ASPECTPOSITION|DIDOI_FFACTUATOR, .tszName = L"Y Axis", .wCollectionNumber = 1, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_Y, .wReportId = 1, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_XAxis, .dwOfs = 0x8, .dwType = DIDFT_ABSAXIS|DIDFT_MAKEINSTANCE(0)|DIDFT_FFACTUATOR, .dwFlags = DIDOI_ASPECTPOSITION|DIDOI_FFACTUATOR, .tszName = L"X Axis", .wCollectionNumber = 1, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_X, .wReportId = 1, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Button, .dwOfs = 0x60, .dwType = DIDFT_PSHBUTTON|DIDFT_MAKEINSTANCE(0)|DIDFT_FFEFFECTTRIGGER, .dwFlags = DIDOI_FFEFFECTTRIGGER, .tszName = L"Button 0", .wCollectionNumber = 1, .wUsagePage = HID_USAGE_PAGE_BUTTON, .wUsage = 0x1, .wReportId = 1, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Button, .dwOfs = 0x61, .dwType = DIDFT_PSHBUTTON|DIDFT_MAKEINSTANCE(1)|DIDFT_FFEFFECTTRIGGER, .dwFlags = DIDOI_FFEFFECTTRIGGER, .tszName = L"Button 1", .wCollectionNumber = 1, .wUsagePage = HID_USAGE_PAGE_BUTTON, .wUsage = 0x2, .wReportId = 1, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x62, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(5)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"DC Device Reset", .wCollectionNumber = 4, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_DC_DEVICE_RESET, .wReportId = 1, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0xc, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(6)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Effect Block Index", .wCollectionNumber = 5, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_EFFECT_BLOCK_INDEX, .wReportId = 2, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x63, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(7)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Op Effect Start", .wCollectionNumber = 6, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_OP_EFFECT_START, .wReportId = 2, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x64, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(8)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Op Effect Start Solo", .wCollectionNumber = 6, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_OP_EFFECT_START_SOLO, .wReportId = 2, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x65, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(9)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Op Effect Stop", .wCollectionNumber = 6, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_OP_EFFECT_STOP, .wReportId = 2, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x10, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(10)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Loop Count", .wCollectionNumber = 5, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_LOOP_COUNT, .wReportId = 2, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x14, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(11)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Effect Block Index", .wCollectionNumber = 7, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_EFFECT_BLOCK_INDEX, .wReportId = 3, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x66, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(12)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"ET Square", .wCollectionNumber = 8, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_ET_SQUARE, .wReportId = 3, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x67, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(13)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"ET Sine", .wCollectionNumber = 8, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_ET_SINE, .wReportId = 3, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x68, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(14)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"ET Spring", .wCollectionNumber = 8, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_ET_SPRING, .wReportId = 3, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x69, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(15)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Z Axis", .wCollectionNumber = 9, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_Z, .wReportId = 3, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x6a, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(16)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Y Axis", .wCollectionNumber = 9, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_Y, .wReportId = 3, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x6b, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(17)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"X Axis", .wCollectionNumber = 9, .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_X, .wReportId = 3, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x6c, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(18)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Direction Enable", .wCollectionNumber = 7, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_DIRECTION_ENABLE, .wReportId = 3, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x18, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(19)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Start Delay", .wCollectionNumber = 7, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_START_DELAY, .wReportId = 3, .dwDimension = 0x1003, .wExponent = -3, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x1c, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(20)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Duration", .wCollectionNumber = 7, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_DURATION, .wReportId = 3, .dwDimension = 0x1003, .wExponent = -3, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x20, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(21)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Trigger Button", .wCollectionNumber = 7, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_TRIGGER_BUTTON, .wReportId = 3, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x24, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(22)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Unknown 22", .wCollectionNumber = 10, .wUsagePage = HID_USAGE_PAGE_ORDINAL, .wUsage = 2, .wReportId = 3, .wExponent = -2, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x28, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(23)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Unknown 23", .wCollectionNumber = 10, .wUsagePage = HID_USAGE_PAGE_ORDINAL, .wUsage = 1, .wReportId = 3, .wExponent = -2, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x2c, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(24)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Magnitude", .wCollectionNumber = 11, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_MAGNITUDE, .wReportId = 5, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x30, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(25)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Fade Level", .wCollectionNumber = 12, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_FADE_LEVEL, .wReportId = 6, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x34, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(26)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Attack Level", .wCollectionNumber = 12, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_ATTACK_LEVEL, .wReportId = 6, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x38, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(27)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Fade Time", .wCollectionNumber = 12, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_FADE_TIME, .wReportId = 6, .dwDimension = 0x1003, .wExponent = -3, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x3c, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(28)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Attack Time", .wCollectionNumber = 12, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_ATTACK_TIME, .wReportId = 6, .dwDimension = 0x1003, .wExponent = -3, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x40, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(29)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Unknown 29", .wCollectionNumber = 14, .wUsagePage = HID_USAGE_PAGE_ORDINAL, .wUsage = 2, .wReportId = 7, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x44, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(30)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Unknown 30", .wCollectionNumber = 14, .wUsagePage = HID_USAGE_PAGE_ORDINAL, .wUsage = 1, .wReportId = 7, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x48, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(31)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"CP Offset", .wCollectionNumber = 13, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_CP_OFFSET, .wReportId = 7, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x4c, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(32)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Negative Coefficient", .wCollectionNumber = 13, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_NEGATIVE_COEFFICIENT, .wReportId = 7, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x50, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(33)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Positive Coefficient", .wCollectionNumber = 13, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_POSITIVE_COEFFICIENT, .wReportId = 7, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x54, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(34)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Negative Saturation", .wCollectionNumber = 13, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_NEGATIVE_SATURATION, .wReportId = 7, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x58, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(35)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Positive Saturation", .wCollectionNumber = 13, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_POSITIVE_SATURATION, .wReportId = 7, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwOfs = 0x5c, .dwType = DIDFT_NODATA|DIDFT_MAKEINSTANCE(36)|DIDFT_OUTPUT, .dwFlags = 0x80008000, .tszName = L"Dead Band", .wCollectionNumber = 13, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_DEAD_BAND, .wReportId = 7, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(0), .tszName = L"Collection 0 - Joystick", .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_JOYSTICK, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(1), .tszName = L"Collection 1 - Joystick", .wUsagePage = HID_USAGE_PAGE_GENERIC, .wUsage = HID_USAGE_GENERIC_JOYSTICK, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(2), .tszName = L"Collection 2 - PID State Report", .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_STATE_REPORT, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(3), .tszName = L"Collection 3 - PID Device Control Report", .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_DEVICE_CONTROL_REPORT, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(4), .tszName = L"Collection 4 - PID Device Control", .wCollectionNumber = 3, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_DEVICE_CONTROL, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(5), .tszName = L"Collection 5 - Effect Operation Report", .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_EFFECT_OPERATION_REPORT, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(6), .tszName = L"Collection 6 - Effect Operation", .wCollectionNumber = 5, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_EFFECT_OPERATION, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(7), .tszName = L"Collection 7 - Set Effect Report", .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_SET_EFFECT_REPORT, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(8), .tszName = L"Collection 8 - Effect Type", .wCollectionNumber = 7, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_EFFECT_TYPE, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(9), .tszName = L"Collection 9 - Axes Enable", .wCollectionNumber = 7, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_AXES_ENABLE, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(10), .tszName = L"Collection 10 - Direction", .wCollectionNumber = 7, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_DIRECTION, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(11), .tszName = L"Collection 11 - Set Periodic Report", .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_SET_PERIODIC_REPORT, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(12), .tszName = L"Collection 12 - Set Envelope Report", .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_SET_ENVELOPE_REPORT, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(13), .tszName = L"Collection 13 - Set Condition Report", .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_SET_CONDITION_REPORT, }, { .dwSize = sizeof(DIDEVICEOBJECTINSTANCEW), .guidType = GUID_Unknown, .dwType = DIDFT_COLLECTION|DIDFT_NODATA|DIDFT_MAKEINSTANCE(14), .tszName = L"Collection 14 - Type Specific Block Offset", .wCollectionNumber = 13, .wUsagePage = HID_USAGE_PAGE_PID, .wUsage = PID_USAGE_TYPE_SPECIFIC_BLOCK_OFFSET, }, }; const DIEFFECTINFOW expect_effects[] = { { .dwSize = sizeof(DIEFFECTINFOW), .guid = GUID_Square, .dwEffType = DIEFT_PERIODIC | DIEFT_STARTDELAY | DIEFT_FFFADE | DIEFT_FFATTACK, .dwStaticParams = DIEP_AXES | DIEP_DIRECTION | DIEP_TYPESPECIFICPARAMS | DIEP_STARTDELAY | DIEP_DURATION | DIEP_TRIGGERBUTTON | DIEP_ENVELOPE, .dwDynamicParams = DIEP_AXES | DIEP_DIRECTION | DIEP_TYPESPECIFICPARAMS | DIEP_STARTDELAY | DIEP_DURATION | DIEP_TRIGGERBUTTON | DIEP_ENVELOPE, .tszName = L"GUID_Square", }, { .dwSize = sizeof(DIEFFECTINFOW), .guid = GUID_Sine, .dwEffType = DIEFT_PERIODIC | DIEFT_STARTDELAY | DIEFT_FFFADE | DIEFT_FFATTACK, .dwStaticParams = DIEP_AXES | DIEP_DIRECTION | DIEP_TYPESPECIFICPARAMS | DIEP_STARTDELAY | DIEP_DURATION | DIEP_TRIGGERBUTTON | DIEP_ENVELOPE, .dwDynamicParams = DIEP_AXES | DIEP_DIRECTION | DIEP_TYPESPECIFICPARAMS | DIEP_STARTDELAY | DIEP_DURATION | DIEP_TRIGGERBUTTON | DIEP_ENVELOPE, .tszName = L"GUID_Sine", }, { .dwSize = sizeof(DIEFFECTINFOW), .guid = GUID_Spring, .dwEffType = DIEFT_CONDITION | DIEFT_STARTDELAY | DIEFT_DEADBAND | DIEFT_SATURATION, .dwStaticParams = DIEP_AXES | DIEP_DIRECTION | DIEP_TYPESPECIFICPARAMS | DIEP_STARTDELAY | DIEP_DURATION, .dwDynamicParams = DIEP_AXES | DIEP_DIRECTION | DIEP_TYPESPECIFICPARAMS | DIEP_STARTDELAY | DIEP_DURATION, .tszName = L"GUID_Spring", } }; struct check_objects_params check_objects_params = { .expect_count = ARRAY_SIZE(expect_objects), .expect_objs = expect_objects, }; struct check_effects_params check_effects_params = { .expect_count = ARRAY_SIZE(expect_effects), .expect_effects = expect_effects, }; DIPROPDWORD prop_dword = { .diph = { .dwSize = sizeof(DIPROPDWORD), .dwHeaderSize = sizeof(DIPROPHEADER), .dwHow = DIPH_DEVICE, }, }; DIPROPGUIDANDPATH prop_guid_path = { .diph = { .dwSize = sizeof(DIPROPGUIDANDPATH), .dwHeaderSize = sizeof(DIPROPHEADER), .dwHow = DIPH_DEVICE, }, }; WCHAR cwd[MAX_PATH], tempdir[MAX_PATH]; DIDEVICEOBJECTDATA objdata = {0}; DIDEVICEINSTANCEW devinst = {0}; DIEFFECTINFOW effectinfo = {0}; IDirectInputDevice8W *device; DIEFFESCAPE escape = {0}; DIDEVCAPS caps = {0}; IDirectInput8W *di; char buffer[1024]; ULONG res, ref; HANDLE file; HRESULT hr; HWND hwnd; GetCurrentDirectoryW( ARRAY_SIZE(cwd), cwd ); GetTempPathW( ARRAY_SIZE(tempdir), tempdir ); SetCurrentDirectoryW( tempdir ); cleanup_registry_keys(); if (!dinput_driver_start( report_descriptor, sizeof(report_descriptor), &hid_caps )) goto done; hr = DirectInput8Create( instance, DIRECTINPUT_VERSION, &IID_IDirectInput8W, (void **)&di, NULL ); if (FAILED(hr)) { win_skip( "DirectInput8Create returned %#x\n", hr ); goto done; } hr = IDirectInput8_EnumDevices( di, DI8DEVCLASS_ALL, find_test_device, &devinst, DIEDFL_ALLDEVICES ); ok( hr == DI_OK, "EnumDevices returned: %#x\n", hr ); if (!IsEqualGUID( &devinst.guidProduct, &expect_guid_product )) { win_skip( "device not found, skipping tests\n" ); IDirectInput8_Release( di ); goto done; } hr = IDirectInput8_CreateDevice( di, &expect_guid_product, &device, NULL ); ok( hr == DI_OK, "CreateDevice returned %#x\n", hr ); hr = IDirectInputDevice8_GetDeviceInfo( device, &devinst ); ok( hr == DI_OK, "GetDeviceInfo returned %#x\n", hr ); check_member( devinst, expect_devinst, "%d", dwSize ); todo_wine check_member_guid( devinst, expect_devinst, guidInstance ); check_member_guid( devinst, expect_devinst, guidProduct ); check_member( devinst, expect_devinst, "%#x", dwDevType ); todo_wine check_member_wstr( devinst, expect_devinst, tszInstanceName ); todo_wine check_member_wstr( devinst, expect_devinst, tszProductName ); check_member_guid( devinst, expect_devinst, guidFFDriver ); check_member( devinst, expect_devinst, "%04x", wUsagePage ); check_member( devinst, expect_devinst, "%04x", wUsage ); caps.dwSize = sizeof(DIDEVCAPS); hr = IDirectInputDevice8_GetCapabilities( device, &caps ); ok( hr == DI_OK, "GetCapabilities returned %#x\n", hr ); check_member( caps, expect_caps, "%d", dwSize ); todo_wine check_member( caps, expect_caps, "%#x", dwFlags ); check_member( caps, expect_caps, "%#x", dwDevType ); check_member( caps, expect_caps, "%d", dwAxes ); check_member( caps, expect_caps, "%d", dwButtons ); check_member( caps, expect_caps, "%d", dwPOVs ); check_member( caps, expect_caps, "%d", dwFFSamplePeriod ); check_member( caps, expect_caps, "%d", dwFFMinTimeResolution ); check_member( caps, expect_caps, "%d", dwFirmwareRevision ); check_member( caps, expect_caps, "%d", dwHardwareRevision ); check_member( caps, expect_caps, "%d", dwFFDriverVersion ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_FFGAIN, &prop_dword.diph ); todo_wine ok( hr == DI_OK, "GetProperty DIPROP_FFGAIN returned %#x\n", hr ); todo_wine ok( prop_dword.dwData == 10000, "got %u expected %u\n", prop_dword.dwData, 10000 ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_FFLOAD, &prop_dword.diph ); todo_wine ok( hr == DIERR_NOTEXCLUSIVEACQUIRED, "GetProperty DIPROP_FFLOAD returned %#x\n", hr ); hr = IDirectInputDevice8_EnumObjects( device, check_objects, &check_objects_params, DIDFT_ALL ); ok( hr == DI_OK, "EnumObjects returned %#x\n", hr ); ok( check_objects_params.index >= check_objects_params.expect_count, "missing %u objects\n", check_objects_params.expect_count - check_objects_params.index ); res = 0; hr = IDirectInputDevice8_EnumEffects( device, check_effect_count, &res, 0xfe ); ok( hr == DI_OK, "EnumEffects returned %#x\n", hr ); ok( res == 0, "got %u expected %u\n", res, 0 ); res = 0; hr = IDirectInputDevice8_EnumEffects( device, check_effect_count, &res, DIEFT_PERIODIC ); ok( hr == DI_OK, "EnumEffects returned %#x\n", hr ); ok( res == 2, "got %u expected %u\n", res, 2 ); hr = IDirectInputDevice8_EnumEffects( device, check_effects, &check_effects_params, DIEFT_ALL ); ok( hr == DI_OK, "EnumEffects returned %#x\n", hr ); ok( check_effects_params.index >= check_effects_params.expect_count, "missing %u effects\n", check_effects_params.expect_count - check_effects_params.index ); effectinfo.dwSize = sizeof(DIEFFECTINFOW); hr = IDirectInputDevice8_GetEffectInfo( device, &effectinfo, &GUID_Sine ); ok( hr == DI_OK, "GetEffectInfo returned %#x\n", hr ); check_member_guid( effectinfo, expect_effects[1], guid ); todo_wine check_member( effectinfo, expect_effects[1], "%#x", dwEffType ); todo_wine check_member( effectinfo, expect_effects[1], "%#x", dwStaticParams ); todo_wine check_member( effectinfo, expect_effects[1], "%#x", dwDynamicParams ); check_member_wstr( effectinfo, expect_effects[1], tszName ); hr = IDirectInputDevice8_SetDataFormat( device, &c_dfDIJoystick2 ); ok( hr == DI_OK, "SetDataFormat returned: %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_GUIDANDPATH, &prop_guid_path.diph ); ok( hr == DI_OK, "GetProperty DIPROP_GUIDANDPATH returned %#x\n", hr ); file = CreateFileW( prop_guid_path.wszPath, FILE_READ_ACCESS | FILE_WRITE_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL ); ok( file != INVALID_HANDLE_VALUE, "got error %u\n", GetLastError() ); hwnd = CreateWindowW( L"static", L"dinput", WS_OVERLAPPEDWINDOW | WS_VISIBLE, 10, 10, 200, 200, NULL, NULL, NULL, NULL ); hr = IDirectInputDevice8_SetCooperativeLevel( device, hwnd, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE ); ok( hr == DI_OK, "SetCooperativeLevel returned: %#x\n", hr ); hr = IDirectInputDevice8_Acquire( device ); ok( hr == DI_OK, "Acquire returned: %#x\n", hr ); prop_dword.diph.dwHow = DIPH_DEVICE; prop_dword.diph.dwObj = 0; prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_SetProperty( device, DIPROP_FFGAIN, &prop_dword.diph ); todo_wine ok( hr == DIERR_INVALIDPARAM, "SetProperty DIPROP_FFGAIN returned %#x\n", hr ); prop_dword.dwData = 1000; hr = IDirectInputDevice8_SetProperty( device, DIPROP_FFGAIN, &prop_dword.diph ); todo_wine ok( hr == DI_OK, "SetProperty DIPROP_FFGAIN returned %#x\n", hr ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_SetProperty( device, DIPROP_FFLOAD, &prop_dword.diph ); ok( hr == DIERR_READONLY, "SetProperty DIPROP_FFLOAD returned %#x\n", hr ); hr = IDirectInputDevice8_GetProperty( device, DIPROP_FFLOAD, &prop_dword.diph ); todo_wine ok( hr == DIERR_NOTEXCLUSIVEACQUIRED, "GetProperty DIPROP_FFLOAD returned %#x\n", hr ); hr = IDirectInputDevice8_GetForceFeedbackState( device, &res ); todo_wine ok( hr == DIERR_NOTEXCLUSIVEACQUIRED, "GetForceFeedbackState returned %#x\n", hr ); hr = IDirectInputDevice8_SendForceFeedbackCommand( device, DISFFC_RESET ); ok( hr == DIERR_NOTEXCLUSIVEACQUIRED, "SendForceFeedbackCommand returned %#x\n", hr ); escape.dwSize = sizeof(DIEFFESCAPE); escape.dwCommand = 0; escape.lpvInBuffer = buffer; escape.cbInBuffer = 10; escape.lpvOutBuffer = buffer + 10; escape.cbOutBuffer = 10; hr = IDirectInputDevice8_Escape( device, &escape ); todo_wine ok( hr == DIERR_NOTEXCLUSIVEACQUIRED, "Escape returned: %#x\n", hr ); hr = IDirectInputDevice8_Unacquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); hr = IDirectInputDevice8_SetCooperativeLevel( device, hwnd, DISCL_BACKGROUND | DISCL_EXCLUSIVE ); ok( hr == DI_OK, "SetCooperativeLevel returned: %#x\n", hr ); set_hid_expect( file, &expect_dc_reset, sizeof(expect_dc_reset) ); hr = IDirectInputDevice8_Acquire( device ); ok( hr == DI_OK, "Acquire returned: %#x\n", hr ); set_hid_expect( file, NULL, 0 ); hr = IDirectInputDevice8_Escape( device, &escape ); todo_wine ok( hr == DIERR_UNSUPPORTED, "Escape returned: %#x\n", hr ); prop_dword.dwData = 0xdeadbeef; hr = IDirectInputDevice8_GetProperty( device, DIPROP_FFLOAD, &prop_dword.diph ); todo_wine ok( hr == 0x80040301, "GetProperty DIPROP_FFLOAD returned %#x\n", hr ); res = 0xdeadbeef; hr = IDirectInputDevice8_GetForceFeedbackState( device, &res ); todo_wine ok( hr == 0x80040301, "GetForceFeedbackState returned %#x\n", hr ); hr = IDirectInputDevice8_SendForceFeedbackCommand( device, 0xdeadbeef ); ok( hr == DIERR_INVALIDPARAM, "SendForceFeedbackCommand returned %#x\n", hr ); set_hid_expect( file, &expect_dc_reset, sizeof(expect_dc_reset) ); hr = IDirectInputDevice8_SendForceFeedbackCommand( device, DISFFC_RESET ); ok( hr == DI_OK, "SendForceFeedbackCommand returned %#x\n", hr ); set_hid_expect( file, NULL, 0 ); hr = IDirectInputDevice8_SendForceFeedbackCommand( device, DISFFC_STOPALL ); ok( hr == HIDP_STATUS_USAGE_NOT_FOUND, "SendForceFeedbackCommand returned %#x\n", hr ); hr = IDirectInputDevice8_SendForceFeedbackCommand( device, DISFFC_PAUSE ); ok( hr == HIDP_STATUS_USAGE_NOT_FOUND, "SendForceFeedbackCommand returned %#x\n", hr ); hr = IDirectInputDevice8_SendForceFeedbackCommand( device, DISFFC_CONTINUE ); ok( hr == HIDP_STATUS_USAGE_NOT_FOUND, "SendForceFeedbackCommand returned %#x\n", hr ); hr = IDirectInputDevice8_SendForceFeedbackCommand( device, DISFFC_SETACTUATORSON ); ok( hr == HIDP_STATUS_USAGE_NOT_FOUND, "SendForceFeedbackCommand returned %#x\n", hr ); hr = IDirectInputDevice8_SendForceFeedbackCommand( device, DISFFC_SETACTUATORSOFF ); ok( hr == HIDP_STATUS_USAGE_NOT_FOUND, "SendForceFeedbackCommand returned %#x\n", hr ); objdata.dwOfs = 0x1e; objdata.dwData = 0x80; res = 1; hr = IDirectInputDevice8_SendDeviceData( device, sizeof(DIDEVICEOBJECTDATA), &objdata, &res, 0 ); todo_wine ok( hr == DIERR_INVALIDPARAM, "SendDeviceData returned %#x\n", hr ); test_periodic_effect( device, file ); test_condition_effect( device, file ); set_hid_expect( file, &expect_dc_reset, sizeof(expect_dc_reset) ); hr = IDirectInputDevice8_Unacquire( device ); ok( hr == DI_OK, "Unacquire returned: %#x\n", hr ); set_hid_expect( file, NULL, 0 ); /* FIXME: we have to wait a bit because Wine DInput internal thread keeps a reference */ Sleep( 100 ); ref = IDirectInputDevice8_Release( device ); ok( ref == 0, "Release returned %d\n", ref ); DestroyWindow( hwnd ); CloseHandle( file ); ref = IDirectInput8_Release( di ); ok( ref == 0, "Release returned %d\n", ref ); done: pnp_driver_stop(); cleanup_registry_keys(); SetCurrentDirectoryW( cwd ); } START_TEST( hid ) { HANDLE mapping; BOOL is_wow64; instance = GetModuleHandleW( NULL ); localized = GetUserDefaultLCID() != MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT); pSignerSign = (void *)GetProcAddress( LoadLibraryW( L"mssign32" ), "SignerSign" ); if (IsWow64Process( GetCurrentProcess(), &is_wow64 ) && is_wow64) { skip( "Running in WoW64.\n" ); return; } mapping = CreateFileMappingW( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(*test_data), L"Global\\winetest_dinput_section" ); if (!mapping && GetLastError() == ERROR_ACCESS_DENIED) { win_skip( "Failed to create test data mapping.\n" ); return; } ok( !!mapping, "got error %u\n", GetLastError() ); test_data = MapViewOfFile( mapping, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 1024 ); test_data->running_under_wine = !strcmp( winetest_platform, "wine" ); test_data->winetest_report_success = winetest_report_success; test_data->winetest_debug = winetest_debug; okfile = CreateFileW( L"C:\\windows\\winetest_dinput_okfile", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL ); ok( okfile != INVALID_HANDLE_VALUE, "failed to create file, error %u\n", GetLastError() ); subtest( "driver_hid" ); test_hidp_kdr(); test_hid_driver( 0, FALSE ); test_hid_driver( 1, FALSE ); test_hid_driver( 0, TRUE ); test_hid_driver( 1, TRUE ); CoInitialize( NULL ); if (test_device_types()) { test_simple_joystick(); test_force_feedback_joystick(); } CoUninitialize(); UnmapViewOfFile( test_data ); CloseHandle( mapping ); CloseHandle( okfile ); DeleteFileW( L"C:\\windows\\winetest_dinput_okfile" ); }
46.008903
125
0.628285
[ "object" ]
a2720c6de0cada5288143e9692759d5219609f6d
16,527
h
C
fsa/src/vespa/fsa/segmenter.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2018-12-30T05:42:18.000Z
2018-12-30T05:42:18.000Z
fsa/src/vespa/fsa/segmenter.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2021-03-31T22:27:25.000Z
2021-03-31T22:27:25.000Z
fsa/src/vespa/fsa/segmenter.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2020-02-01T07:21:28.000Z
2020-02-01T07:21:28.000Z
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. /** * @author Peter Boros * @date 2004/09/13 * @version $Id$ * @file segmenter.h * @brief Query segmenter based on %FSA (%Finite %State %Automaton) * */ #pragma once #include <string> #include <map> #include <vector> #include <list> #include <stdio.h> #include "fsa.h" #include "ngram.h" #include "detector.h" namespace fsa { // {{{ class Segmenter /** * @class Segmenter * @brief Query segmenter based on %FSA. */ class Segmenter { public: // {{{ enum Segmenter::SegmentationMethod /** * @brief Enumerated type of supported segmentation method IDs * * The segmentation methods currently supported are the following: * - SEGMENTATION_WEIGHTED - gives the segmentation where the sum * of the scores of nontrivial (more than one word) segments is * the highest * - SEGMENTATION_WEIGHTED_BIASxx - (xx can be 10,20,50 or 100) * gives the segmentation where the sum of the scores of * nontrivial (more than one word) segments is the highest. The * scores are biased based on segment length, xx% extra for each * term over 2 * - SEGMENTATION_WEIGHTED_LEFTMOST - picks the segment with * highest score first, if there are several possibilities, picks * the leftmost, then repeats for the rest of the query * - SEGMENTATION_WEIGHTED_RIGHTMOST - picks the segment with * highest score first, if there are several possibilities, picks * the rightmost, then repeats for the rest of the query * - SEGMENTATION_WEIGHTED_LONGEST - picks the segment with * highest score first, if there are several possibilities, picks * the longest, then repeats for the rest of the query * - SEGMENTATION_LEFTMOST_LONGEST - picks the leftmost segment * first, if there are several possibilities, picks the longest, * then repeats for the rest of the query * - SEGMENTATION_LEFTMOST_WEIGHTED - picks the leftmost segment * first, if there are several possibilities, picks the one with * highest score, then repeats for the rest of the query * - SEGMENTATION_RIGHTMOST_LONGEST - picks the rightmost segment * first, if there are several possibilities, picks the longest, * then repeats for the rest of the query * - SEGMENTATION_RIGHTMOST_WEIGHTED - picks the rightmost segment * first, if there are several possibilities, picks the one with * highest score, then repeats for the rest of the query * - SEGMENTATION_LONGEST_WEIGHTED - picks the longest segment * first, if there are several possibilities, picks the one with * highest score, then repeats for the rest of the query * - SEGMENTATION_LONGEST_LEFTMOST - picks the longest segment * first, if there are several possibilities, picks leftmost, * then repeats for the rest of the query * - SEGMENTATION_LONGEST_RIGHTMOST - picks the longest segment * first, if there are several possibilities, picks the rightmost, * then repeats for the rest of the query */ enum SegmentationMethod { SEGMENTATION_WEIGHTED, SEGMENTATION_WEIGHTED_BIAS10, SEGMENTATION_WEIGHTED_BIAS20, SEGMENTATION_WEIGHTED_BIAS50, SEGMENTATION_WEIGHTED_BIAS100, SEGMENTATION_WEIGHTED_LEFTMOST, SEGMENTATION_WEIGHTED_RIGHTMOST, SEGMENTATION_WEIGHTED_LONGEST, SEGMENTATION_LEFTMOST_LONGEST, SEGMENTATION_LEFTMOST_WEIGHTED, SEGMENTATION_RIGHTMOST_LONGEST, SEGMENTATION_RIGHTMOST_WEIGHTED, SEGMENTATION_LONGEST_WEIGHTED, SEGMENTATION_LONGEST_LEFTMOST, SEGMENTATION_LONGEST_RIGHTMOST, SEGMENTATION_METHODS }; // }}} // {{{ typedef Segmenter::Segmentation /** %Segmentation type */ typedef std::list<int> Segmentation; /** Iterator for %segmentation type */ typedef std::list<int>::iterator SegmentationIterator; /** Const iterator for %segmentation type */ typedef std::list<int>::const_iterator SegmentationConstIterator; // }}} // {{{ class Segmenter::Segments /** * @class Segments * @brief Class for storing segmentation results. * * Class for storing segmentation results. It is a subclass of * Detector::Hits, so it can be used directly by a Detector. */ class Segments : public Detector::Hits { private: // {{{ class Segmenter::Segments::Segment /** * @class Segment * @brief Simple segment class. * * Simple segment class. A segment is defined by its beginning and * end, and it has a connexity. Beginning and end refer to indices * in the original text. */ class Segment { private: unsigned int _beg; /**< Beginning of the segment. */ unsigned int _end; /**< End of the segment. */ unsigned int _conn; /**< Connexity of the segment. */ public: /** * @brief Default constructor. * * Null segment at postion zero. */ Segment() : _beg(0), _end(0), _conn(0) {} /** * @brief Constructor. * * @param b Beginning of the segment. * @param e End of the segment (the position after the last term). * @param c Connexity of the segment. */ Segment(unsigned int b, unsigned int e, unsigned int c) : _beg(b), _end(e), _conn(c) {} /** * @brief Copy constructor. * * @param s Segment object to copy. */ Segment(const Segment &s) : _beg(s._beg), _end(s._end), _conn(s._conn) {} /** * @brief Destructor. */ ~Segment() {} /** * @brief Set the segment parameters. * * @param b Beginning of the segment. * @param e End of the segment (the position after the last term). * @param c Connexity of the segment. */ void set(unsigned int b, unsigned int e, unsigned int c) { _beg=b; _end=e; _conn=c; } public: /** * @brief Get the beginning of the segment. * * @return Beginning of the segment. */ unsigned int beg() const { return _beg; } /** * @brief Get the end of the segment. * * @return End of the segment. (Position after last term.) */ unsigned int end() const { return _end; } /** * @brief Get the length of the segment. * * @return Length of the segment (number of terms). */ unsigned int len() const { return _end-_beg; } /** * @brief Get the connexity of the segment. * * @return Connexity of the segment. */ unsigned int conn() const { return _conn; } }; // }}} // {{{ class Segmenter::Segments::SegmentMap /** * @class SegmentMap * @brief Class for mapping (beg,end) pairs to segment idx. */ class SegmentMap { private: /** Size of current map. */ unsigned int _size; /** %Segment map */ std::vector<int> _map; public: /** Default constructor, creates empty map of zero size. */ SegmentMap() : _size(0), _map() {} /** * @brief Constructor. * * Creates an empty map of given size. * * @param n Map size. */ SegmentMap(unsigned int n) : _size(n+1), _map(_size*_size,-1) {} /** Destructor */ ~SegmentMap() {} /** * @brief Initialize the map. * * Initialize the map to an empty map of given size. * * @param n Map size. */ void init(unsigned int n) { _size = n+1; _map.assign(_size*_size,-1); } /** * @brief Clear the map. * * Reset the map to an empty map of zero size. */ void clear() { _size = 0; _map.clear(); } /** * @brief Get current map size. * * @return Map size. */ unsigned int size() const { return _size; } /** * @brief Set an element in the map. * * @param i Beginning of the segment. * @param j End of the segment. * @param idx %Segment index. */ void set(unsigned int i, unsigned int j, int idx) { if(i<_size && j<_size) _map[i*_size+j] = idx; } /** * @brief Get an element from the map. * * @param i Beginning of the segment. * @param j End of the segment. * @return %Segment index (-1 if segment does not exist). */ int get(unsigned int i, unsigned int j) const { if(i<_size && j<_size) return _map[i*_size+j]; return -1; } /** * @brief Check if a segment exists. * * @param i Beginning of the segment. * @param j End of the segment. * @return True if segment exists. */ bool isValid(unsigned int i, unsigned int j) const { return i<_size && j<_size && _map[i*_size+j]!=-1; } }; // }}} private: NGram _text; /**< Tokenized text (e.g. query). */ std::vector<Segment> _segments; /**< Detected segments. */ SegmentMap _map; /**< Map of segments. */ std::vector<Segmentation*> _segmentation; /**< Pre-built segmentations. */ /** * @brief Insert all single term segments. * * Insert all single term segments as detected with zero * connexity. This is important for some of the segentation * algorithms. */ void initSingles(); /** * @brief Build a segmentation. * * @param method %Segmentation method. */ void buildSegmentation(Segmenter::SegmentationMethod method); /** * @brief Build a segmentation recursively. * * Some of the segmentation methods are implemented * recursively. * * @param method %Segmentation method. * @param segmentation Segmentation object which holds results. * @param beg Beginning of the subquery to process. * @param end End the subquery to process. */ void buildSegmentationRecursive(Segmenter::SegmentationMethod method, Segmentation& segmentation, unsigned int beg, unsigned int end); public: Segments(); ~Segments(); /** * @brief Set input text, and clear all results. * * @param text Input text. */ void setText(const NGram &text) { _text.set(text); clear(); } /** * @brief Set input text, and clear all results. * * @param text Input text. */ void setText(const std::string &text) { _text.set(text); clear(); } /** * @brief Set input text, and clear all results. * * @param text Input text. */ void setText(const char *text) { _text.set(text); clear(); } /** * @brief Get a reference to the input text. * * Get a reference to the input text. Valid as long as the * Segments object is valid and not modified. * * return Reference to input text. */ const NGram& getText() const { return _text; } /** * @brief Clear all detected segments and built segmentations. */ void clear(); /** * @brief Insert a detected segment. * * This method will be called by the detector for each detected * segment. * * @param text Input text. * @param from Index of first token. * @param length Number of tokens. * @param state Final state after detected phrase. */ void add(const NGram &text, unsigned int from, int length, const FSA::State &state) override { (void)text; unsigned int to=from+length; int id=_map.get(from,to); if(id==-1){ _map.set(from,to,_segments.size()); _segments.push_back(Segment(from,to,state.nData())); } else{ _segments[id].set(from,to,state.nData()); } } /** * @brief Get the size (number of segments). * * @return Number of segments. */ unsigned int size() const { return _segments.size(); } /** * @brief Get a segment as a string. * * @param i %Segment index. * @return %Segment string. */ const std::string operator[](unsigned int i) const { return sgm(i); } /** * @brief Get a segment as a string. * * @param i %Segment index. * @return %Segment string. */ const std::string sgm(unsigned int i) const { if(i<_segments.size()) return _text.join(" ",_segments[i].beg(),_segments[i].len()); return std::string(); } /** * @brief Get the beginning of a segment. * * @param i %Segment index. * @return Beginning of the segment. */ unsigned beg(unsigned int i) const { if(i<_segments.size()) return _segments[i].beg(); return 0; } /** * @brief Get the end of a segment. * * @param i %Segment index. * @return End of the segment. */ unsigned end(unsigned int i) const { if(i<_segments.size()) return _segments[i].end(); return 0; } /** * @brief Get the length of a segment. * * @param i %Segment index. * @return Length of the segment. */ unsigned len(unsigned int i) const { if(i<_segments.size()) return _segments[i].len(); return 0; } /** * @brief Get the connexity of a segment. * * @param i %Segment index. * @return Connexity of the segment. */ unsigned conn(unsigned int i) const { if(i<_segments.size()) return _segments[i].conn(); return 0; } /** * @brief Get the a segmentation of the query using the given method. * * @param method %Segmentation method * @return Pointer to the Segmentation object, valid as long as the * Segments object is valid and not modified. */ const Segmenter::Segmentation* segmentation(Segmenter::SegmentationMethod method) { if(method<SEGMENTATION_WEIGHTED || method>=SEGMENTATION_METHODS) method=SEGMENTATION_WEIGHTED; if(_segmentation[method]==NULL){ buildSegmentation(method); } return _segmentation[method]; } }; // }}} private: const FSA& _dictionary; /**< Dictionary. */ Detector _detector; /**< Detector. */ /** Unimplemented private default constructor */ Segmenter(); /** Unimplemented private copy constructor */ Segmenter(const Segmenter&); public: /** * @brief Constructor. * * Create Segmeneter object and initialize dictionary and detector. * * @param dict Dictionary to use. */ Segmenter(const FSA& dict) : _dictionary(dict), _detector(_dictionary) {} /** * @brief Constructor. * * Create Segmeneter object and initialize dictionary and detector. * * @param dict Dictionary to use. */ Segmenter(const FSA* dict) : _dictionary(*dict), _detector(_dictionary) {} /** Destructor */ ~Segmenter() {} /** * @brief %Segment a query. * * @param segments %Segments object, input text already initialized. */ void segment(Segmenter::Segments &segments) const; /** * @brief %Segment a query. * * @param text Input text. * @param segments %Segments object to hold the results. */ void segment(const NGram &text, Segmenter::Segments &segments) const; /** * @brief %Segment a query. * * @param text Input text. * @param segments %Segments object to hold the results. */ void segment(const std::string &text, Segmenter::Segments &segments) const; /** * @brief %Segment a query. * * @param text Input text. * @param segments %Segments object to hold the results. */ void segment(const char *text, Segmenter::Segments &segments) const; /** * @brief %Segment a query. * * @param text Input text. * @param segments %Segments object to hold the results. */ void segment(const char *text, Segmenter::Segments *segments) const { segment(text,*segments); } }; // }}} } // namespace fsa
26.485577
118
0.590307
[ "object", "vector" ]
a27bfa1fa940b7ea5aca86b163dbfd42f70a74a6
12,461
h
C
include/cfdcore/cfdcore_transaction.h
fujita-cg/cfd-core
9f3bbf0dfdfbc33dd4fd00cb6d81665dc98bffe2
[ "MIT" ]
null
null
null
include/cfdcore/cfdcore_transaction.h
fujita-cg/cfd-core
9f3bbf0dfdfbc33dd4fd00cb6d81665dc98bffe2
[ "MIT" ]
null
null
null
include/cfdcore/cfdcore_transaction.h
fujita-cg/cfd-core
9f3bbf0dfdfbc33dd4fd00cb6d81665dc98bffe2
[ "MIT" ]
null
null
null
// Copyright 2019 CryptoGarage /** * @file cfdcore_transaction.h * * @brief Transaction関連クラスを定義する。 * */ #ifndef CFD_CORE_INCLUDE_CFDCORE_CFDCORE_TRANSACTION_H_ #define CFD_CORE_INCLUDE_CFDCORE_CFDCORE_TRANSACTION_H_ #include <cstddef> #include <string> #include <vector> #include "cfdcore/cfdcore_address.h" #include "cfdcore/cfdcore_amount.h" #include "cfdcore/cfdcore_bytedata.h" #include "cfdcore/cfdcore_coin.h" #include "cfdcore/cfdcore_common.h" #include "cfdcore/cfdcore_script.h" #include "cfdcore/cfdcore_transaction_common.h" #include "cfdcore/cfdcore_util.h" namespace cfd { namespace core { /** * @brief TxOut情報を保持するクラス */ class CFD_CORE_EXPORT TxOut : public AbstractTxOut { public: /** * @brief コンストラクタ */ TxOut(); /** * @brief コンストラクタ * @param[in] value amount value. * @param[in] locking_script locking script. */ TxOut(const Amount& value, const Script& locking_script); /** * @brief コンストラクタ * @param[in] value amount value. * @param[in] address out address. */ TxOut(const Amount& value, const Address& address); /** * @brief デストラクタ */ virtual ~TxOut() { // do nothing } }; /** * @brief TxOut情報を参照するためのクラス */ class CFD_CORE_EXPORT TxOutReference : public AbstractTxOutReference { public: /** * @brief コンストラクタ * @param[in] tx_out 参照するTxOutインスタンス */ explicit TxOutReference(const TxOut& tx_out); /** * @brief デフォルトコンストラクタ. * * リスト作成用。 */ TxOutReference() : TxOutReference(TxOut()) { // do nothing } /** * @brief デストラクタ */ virtual ~TxOutReference() { // do nothing } }; /** * @brief TxIn情報を保持するクラス */ class CFD_CORE_EXPORT TxIn : public AbstractTxIn { public: /** * @brief 最小のTxInサイズ * @details 対象サイズ:txid(64), vout(4), sequence(4), scriptLength(1(仮)) */ static constexpr const size_t kMinimumTxInSize = 41; /** * @brief TxInのサイズを見積もる。 * @param[in] addr_type address type * @param[in] redeem_script redeem script * @param[out] witness_stack_size witness stack size * @return TxInのサイズ */ static uint32_t EstimateTxInSize( AddressType addr_type, Script redeem_script = Script(), uint32_t* witness_stack_size = nullptr); /** * @brief コンストラクタ. * @param[in] txid txid * @param[in] index txidのトランザクションのTxOutのIndex情報(vout) * @param[in] sequence sequence情報 */ TxIn(const Txid& txid, uint32_t index, uint32_t sequence); /** * @brief コンストラクタ. * @param[in] txid txid * @param[in] index txidのトランザクションのTxOutのIndex情報(vout) * @param[in] sequence sequence情報 * @param[in] unlocking_script unlocking script */ TxIn( const Txid& txid, uint32_t index, uint32_t sequence, const Script& unlocking_script); /** * @brief デストラクタ */ virtual ~TxIn() { // do nothing } }; /** * @brief TxIn情報を参照するためのクラス */ class CFD_CORE_EXPORT TxInReference : public AbstractTxInReference { public: /** * @brief コンストラクタ. * @param[in] tx_in 参照するTxInインスタンス */ explicit TxInReference(const TxIn& tx_in); /** * @brief デフォルトコンストラクタ. * * リスト作成用。 */ TxInReference() : TxInReference(TxIn(Txid(), 0, 0)) { // do nothing } /** * @brief デストラクタ */ virtual ~TxInReference() { // do nothing } }; /** * @brief トランザクション情報クラス */ class CFD_CORE_EXPORT Transaction : public AbstractTransaction { public: /** * @brief コンストラクタ. * * リスト作成用。 */ Transaction(); /** * @brief コンストラクタ * @param[in] version version * @param[in] lock_time lock time */ explicit Transaction(int32_t version, uint32_t lock_time); /** * @brief コンストラクタ * @param[in] hex_string txバイトデータのHEX文字列 */ explicit Transaction(const std::string& hex_string); /** * @brief コンストラクタ * @param[in] transaction トランザクション情報 */ explicit Transaction(const Transaction& transaction); /** * @brief デストラクタ */ virtual ~Transaction() { // do nothing } /** * @brief コピーコンストラクタ. * @param[in] transaction トランザクション情報 * @return Transactionオブジェクト */ Transaction& operator=(const Transaction& transaction) &; /** * @brief Transactionの合計バイトサイズを取得する. * @return 合計バイトサイズ */ virtual uint32_t GetTotalSize() const; /** * @brief Transactionのvsize情報を取得する. * @return vsize */ virtual uint32_t GetVsize() const; /** * @brief TransactionのWeight情報を取得する. * @return weight */ virtual uint32_t GetWeight() const; /** * @brief TxInを取得する. * @param[in] index 取得するindex位置 * @return 指定indexのTxInインスタンス */ const TxInReference GetTxIn(uint32_t index) const; /** * @brief TxInのindexを取得する. * @param[in] txid 取得するTxInのtxid * @param[in] vout 取得するTxInのvout * @return 条件に合致するTxInのindex番号 */ virtual uint32_t GetTxInIndex(const Txid& txid, uint32_t vout) const; /** * @brief 保持しているTxInの数を取得する. * @return TxIn数 */ uint32_t GetTxInCount() const; /** * @brief TxIn一覧を取得する. * @return TxInReference一覧 */ const std::vector<TxInReference> GetTxInList() const; /** * @brief TxInを追加する. * @param[in] txid txid * @param[in] index vout * @param[in] sequence sequence * @param[in] unlocking_script unlocking script (未指定時はEmptyを設定する. default Script::Empty) * @return 追加したTxInのindex位置 */ uint32_t AddTxIn( const Txid& txid, uint32_t index, uint32_t sequence, const Script& unlocking_script = Script::Empty); /** * @brief TxIn情報を削除する. * @param[in] index 削除するindex位置 */ void RemoveTxIn(uint32_t index); /** * @brief unlocking scriptを設定する. * @param[in] tx_in_index 設定するTxInのindex位置 * @param[in] unlocking_script TxInに設定するunlocking script (Push Op Only) */ void SetUnlockingScript( uint32_t tx_in_index, const Script& unlocking_script); /** * @brief unlocking scriptを設定する. * @param[in] tx_in_index 設定するTxInのindex位置 * @param[in] unlocking_script TxInに設定するunlocking scriptの構成要素リスト */ void SetUnlockingScript( uint32_t tx_in_index, const std::vector<ByteData>& unlocking_script); /** * @brief witness stackの現在の個数を取得する. * @param[in] tx_in_index 設定するTxInのindex位置 * @return witness stackの個数 */ uint32_t GetScriptWitnessStackNum(uint32_t tx_in_index) const; /** * @brief witness stackに追加する. * @param[in] tx_in_index 設定するTxInのindex位置 * @param[in] data witness stackに追加する情報 * @return witness stack */ const ScriptWitness AddScriptWitnessStack( uint32_t tx_in_index, const ByteData& data); /** * @brief witness stackに追加する. * @param[in] tx_in_index 設定するTxInのindex位置 * @param[in] data witness stackに追加する20byte情報 * @return witness stack */ const ScriptWitness AddScriptWitnessStack( uint32_t tx_in_index, const ByteData160& data); /** * @brief witness stackに追加する. * @param[in] tx_in_index 設定するTxInのindex位置 * @param[in] data witness stackに追加する32byte情報 * @return witness stack */ const ScriptWitness AddScriptWitnessStack( uint32_t tx_in_index, const ByteData256& data); /** * @brief witness stackの指定index位置を更新する. * @param[in] tx_in_index 設定するTxInのindex位置 * @param[in] witness_index witness stackのindex位置 * @param[in] data witness stackに追加する情報 * @return witness stack */ const ScriptWitness SetScriptWitnessStack( uint32_t tx_in_index, uint32_t witness_index, const ByteData& data); /** * @brief witness stackの指定index位置を更新する. * @param[in] tx_in_index 設定するTxInのindex位置 * @param[in] witness_index witness stackのindex位置 * @param[in] data witness stackに追加する20byte情報 * @return witness stack */ const ScriptWitness SetScriptWitnessStack( uint32_t tx_in_index, uint32_t witness_index, const ByteData160& data); /** * @brief witness stackの指定index位置を更新する. * @param[in] tx_in_index 設定するTxInのindex位置 * @param[in] witness_index witness stackのindex位置 * @param[in] data witness stackに追加する32byte情報 * @return witness stack */ const ScriptWitness SetScriptWitnessStack( uint32_t tx_in_index, uint32_t witness_index, const ByteData256& data); /** * @brief script witnessを全て削除する. * @param[in] tx_in_index 設定するTxInのindex位置 */ void RemoveScriptWitnessStackAll(uint32_t tx_in_index); /** * @brief TxOutを取得する. * @param[in] index 取得するindex位置 * @return TxOutReference */ const TxOutReference GetTxOut(uint32_t index) const; /** * @brief 保持しているTxOutの数を取得する. * @return TxOut数 */ uint32_t GetTxOutCount() const; /** * @brief TxOut一覧を取得する. * @return TxOutReference一覧 */ const std::vector<TxOutReference> GetTxOutList() const; /** * @brief TxOut情報を追加する. * @param[in] value amount * @param[in] locking_script locking script * @return 追加したTxOutのindex位置 */ uint32_t AddTxOut(const Amount& value, const Script& locking_script); /** * @brief TxOut情報を削除する. * @param[in] index 取得するindex位置 */ void RemoveTxOut(uint32_t index); /** * @brief signatureハッシュを取得する. * @param[in] txin_index TxInのindex値 * @param[in] script_data unlocking script もしくは witness_program. * @param[in] sighash_type SigHashType(@see cfdcore_util.h) * @param[in] value TxInのAmount値. * @param[in] version Witness version * @return signatureハッシュ */ ByteData256 GetSignatureHash( uint32_t txin_index, const ByteData& script_data, SigHashType sighash_type, const Amount& value = Amount(), WitnessVersion version = WitnessVersion::kVersionNone) const; /** * @brief witness情報かどうかを取得する. * @retval true witness * @retval false witnessではない */ virtual bool HasWitness() const; /** * @brief libwally処理用フラグを取得する。 * @return libwally用フラグ */ virtual uint32_t GetWallyFlag() const; private: std::vector<TxIn> vin_; ///< TxIn配列 std::vector<TxOut> vout_; ///< TxOut配列 /** * @brief TxIn配列のIndex範囲をチェックする. * @param[in] index TxIn配列のIndex値 * @param[in] line 行数 * @param[in] caller コール元関数名 */ virtual void CheckTxInIndex( uint32_t index, int line, const char* caller) const; /** * @brief TxOut配列のIndex範囲をチェックする. * @brief check TxOut array range. * @param[in] index TxOut配列のIndex値 * @param[in] line 行数 * @param[in] caller コール元関数名 */ virtual void CheckTxOutIndex( uint32_t index, int line, const char* caller) const; /** * @brief witness stackに情報を追加する. * @param[in] tx_in_index TxIn配列のindex値 * @param[in] data witness stackに追加するバイトデータ * @return witness stack */ const ScriptWitness AddScriptWitnessStack( uint32_t tx_in_index, const std::vector<uint8_t>& data); /** * @brief witness stackの指定index位置を更新する. * @param[in] tx_in_index 設定するTxInのindex位置 * @param[in] witness_index witness stackのindex位置 * @param[in] data witness stackに追加する32byte情報 * @return witness stack */ const ScriptWitness SetScriptWitnessStack( uint32_t tx_in_index, uint32_t witness_index, const std::vector<uint8_t>& data); /** * @brief Transactionのバイトデータを取得する. * @param[in] has_witness witnessを含めるかのフラグ * @return バイトデータ */ ByteData GetData(bool has_witness) const; /** * @brief HEX文字列からTransaction情報を設定する. * @param[in] hex_string TransactionバイトデータのHEX文字列 */ void SetFromHex(const std::string& hex_string); /** * @brief TxOut領域のByteDataの整合性チェックと、TxOutへの設定を行う. * * tx_pointerがNULLではない場合のみ、TxOutへの設定を行う. * tx_pointerがNULLの場合は整合性チェックのみ行う. * @param[in] buffer TxOut領域のByteData * @param[in] buf_size TxOut領域のByteDataサイズ * @param[in] txout_num TxOut領域のTxOut情報数 * @param[in] txout_num_size TxOut情報領域サイズ * @param[out] tx_pointer Transaction情報バッファ(NULL可) * @param[out] txout_list TxOut配列(nullptr可) * @retval true 整合性チェックOK、およびTxOut情報コピーOK * @retval false 整合性チェックNG、もしくはTxOut情報コピー失敗 */ static bool CheckTxOutBuffer( const uint8_t* buffer, size_t buf_size, uint64_t txout_num, size_t txout_num_size, void* tx_pointer = NULL, std::vector<TxOut>* txout_list = nullptr); }; } // namespace core } // namespace cfd #endif // CFD_CORE_INCLUDE_CFDCORE_CFDCORE_TRANSACTION_H_
27.386813
93
0.661343
[ "vector" ]
a27e5f7008083d0b5d3ec00c2708ebe2eb02bc71
4,400
h
C
Library_MMDAgent/include/Plugin.h
shirayukikitsune/xbeat
df1f0ea3ada18d9790ebf6a16cee9370d82b431b
[ "NCSA" ]
3
2015-03-02T13:27:00.000Z
2021-01-10T15:20:38.000Z
Library_MMDAgent/src/include/Plugin.h
shirayukikitsune/xbeat
df1f0ea3ada18d9790ebf6a16cee9370d82b431b
[ "NCSA" ]
null
null
null
Library_MMDAgent/src/include/Plugin.h
shirayukikitsune/xbeat
df1f0ea3ada18d9790ebf6a16cee9370d82b431b
[ "NCSA" ]
null
null
null
/* ----------------------------------------------------------------- */ /* The Toolkit for Building Voice Interaction Systems */ /* "MMDAgent" developed by MMDAgent Project Team */ /* http://www.mmdagent.jp/ */ /* ----------------------------------------------------------------- */ /* */ /* Copyright (c) 2009-2012 Nagoya Institute of Technology */ /* Department of Computer Science */ /* */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or */ /* without modification, are permitted provided that the following */ /* conditions are met: */ /* */ /* - Redistributions of source code 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 MMDAgent project team 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" 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. */ /* ----------------------------------------------------------------- */ /* DLLibrary: dynamic link library for MMDAgent */ typedef struct _DLLibrary { char *name; void *handle; void (*appStart)(MMDAgent *mmdagent); void (*appEnd)(MMDAgent *mmdagent); void (*procCommand)(MMDAgent *mmdagent, const char *type, const char *args); void (*procEvent)(MMDAgent *mmdagent, const char *type, const char *args); void (*update)(MMDAgent *mmdagent, double deltaFrame); void (*render)(MMDAgent *mmdagent); struct _DLLibrary *next; } DLLibrary; /* Plugin: plugin list */ class Plugin { private: DLLibrary *m_head; DLLibrary *m_tail; /* initialize: initialize plugin list */ void initialize(); /* clear: free plugin list */ void clear(); public: /* Plugin: constructor */ Plugin(); /* ~Plugin: destructor */ ~Plugin(); /* load: load all DLLs in a directory */ bool load(const char *dir); /* execAppStart: run when application is start */ void execAppStart(MMDAgent *mmdagent); /* execAppEnd: run when application is end */ void execAppEnd(MMDAgent *mmdagent); /* execProcCommand: process command message */ void execProcCommand(MMDAgent *mmdagent, const char *type, const char *args); /* execProcEvent: process event message */ void execProcEvent(MMDAgent *mmdagent, const char *type, const char *args); /* execUpdate: run when motion is updated */ void execUpdate(MMDAgent *mmdagent, double deltaFrame); /* execRender: run when scene is rendered */ void execRender(MMDAgent *mmdagent); };
44
80
0.544091
[ "render" ]
a28802f905caf5a3a150a6b225427c7df0f2d655
1,012
h
C
src/tor/src/feature/dircache/cached_dir_st.h
blondfrogs/tecracoin
8ede0a2f550a31e85634e2bf91b79bd1c9cfda7c
[ "MIT" ]
159
2020-11-09T22:39:58.000Z
2022-03-29T21:14:57.000Z
src/tor/src/feature/dircache/cached_dir_st.h
blondfrogs/tecracoin
8ede0a2f550a31e85634e2bf91b79bd1c9cfda7c
[ "MIT" ]
188
2020-11-09T09:47:18.000Z
2022-03-27T09:08:07.000Z
src/tor/src/feature/dircache/cached_dir_st.h
blondfrogs/tecracoin
8ede0a2f550a31e85634e2bf91b79bd1c9cfda7c
[ "MIT" ]
58
2020-11-17T14:40:13.000Z
2022-03-19T09:45:58.000Z
/* Copyright (c) 2001 Matej Pfajfar. * Copyright (c) 2001-2004, Roger Dingledine. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. * Copyright (c) 2007-2019, The Tor Project, Inc. */ /* See LICENSE for licensing information */ #ifndef CACHED_DIR_ST_H #define CACHED_DIR_ST_H /** A cached_dir_t represents a cacheable directory object, along with its * compressed form. */ struct cached_dir_t { char *dir; /**< Contents of this object, NUL-terminated. */ char *dir_compressed; /**< Compressed contents of this object. */ size_t dir_len; /**< Length of <b>dir</b> (not counting its NUL). */ size_t dir_compressed_len; /**< Length of <b>dir_compressed</b>. */ time_t published; /**< When was this object published. */ common_digests_t digests; /**< Digests of this object (networkstatus only) */ /** Sha3 digest (also ns only) */ uint8_t digest_sha3_as_signed[DIGEST256_LEN]; int refcnt; /**< Reference count for this cached_dir_t. */ }; #endif /* !defined(CACHED_DIR_ST_H) */
38.923077
79
0.706522
[ "object" ]
a28a6a1b5400f03da01022c256cd145a8f217b6d
2,076
h
C
src/sksl/ir/SkSLInterfaceBlock.h
longsf2010/skia
332b55954f92d51d60158d8142c68eb9c3ca296f
[ "BSD-3-Clause" ]
4
2019-10-18T05:53:30.000Z
2021-08-21T07:36:37.000Z
src/sksl/ir/SkSLInterfaceBlock.h
longsf2010/skia
332b55954f92d51d60158d8142c68eb9c3ca296f
[ "BSD-3-Clause" ]
null
null
null
src/sksl/ir/SkSLInterfaceBlock.h
longsf2010/skia
332b55954f92d51d60158d8142c68eb9c3ca296f
[ "BSD-3-Clause" ]
4
2018-10-14T00:17:11.000Z
2020-07-01T04:01:25.000Z
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SKSL_INTERFACEBLOCK #define SKSL_INTERFACEBLOCK #include "SkSLProgramElement.h" #include "SkSLSymbolTable.h" #include "SkSLVarDeclarations.h" namespace SkSL { /** * An interface block, as in: * * out gl_PerVertex { * layout(builtin=0) float4 gl_Position; * layout(builtin=1) float gl_PointSize; * }; * * At the IR level, this is represented by a single variable of struct type. */ struct InterfaceBlock : public ProgramElement { InterfaceBlock(Position position, const Variable* var, String typeName, String instanceName, std::vector<std::unique_ptr<Expression>> sizes, std::shared_ptr<SymbolTable> typeOwner) : INHERITED(position, kInterfaceBlock_Kind) , fVariable(*var) , fTypeName(std::move(typeName)) , fInstanceName(std::move(instanceName)) , fSizes(std::move(sizes)) , fTypeOwner(typeOwner) {} String description() const override { String result = fVariable.fModifiers.description() + fTypeName + " {\n"; const Type* structType = &fVariable.fType; while (structType->kind() == Type::kArray_Kind) { structType = &structType->componentType(); } for (const auto& f : structType->fields()) { result += f.description() + "\n"; } result += "}"; if (fInstanceName.size()) { result += " " + fInstanceName; for (const auto& size : fSizes) { result += "["; if (size) { result += size->description(); } result += "]"; } } return result + ";"; } const Variable& fVariable; const String fTypeName; const String fInstanceName; const std::vector<std::unique_ptr<Expression>> fSizes; const std::shared_ptr<SymbolTable> fTypeOwner; typedef ProgramElement INHERITED; }; } // namespace #endif
28.438356
96
0.6079
[ "vector" ]
a290b8a71c5bf52fa08a496b8c8f687ca19f3ada
916
h
C
assignment01/Application.h
mockingbird2/hci2-assignments
4b73a10b3a957e62593a1d05526f29d9cbd34204
[ "MIT" ]
null
null
null
assignment01/Application.h
mockingbird2/hci2-assignments
4b73a10b3a957e62593a1d05526f29d9cbd34204
[ "MIT" ]
null
null
null
assignment01/Application.h
mockingbird2/hci2-assignments
4b73a10b3a957e62593a1d05526f29d9cbd34204
[ "MIT" ]
null
null
null
#pragma once #include <opencv2/core/core.hpp> class DepthCamera; class KinectMotor; class Application { public: Application(); virtual ~Application(); void loop(); void processFrame(); void makeScreenshots(); void clearOutputImage(); bool isFinished(); void evaluateData(); static bool isFoot(std::vector<cv::Point> contour); void addToContacts(cv::RotatedRect); void drawLines(); void drawLastLine(); void drawEllipse(cv::RotatedRect); void handleNoContact(); protected: DepthCamera *m_depthCamera; KinectMotor *m_kinectMotor; cv::Mat m_bgrImage; cv::Mat m_depthImage; cv::Mat m_outputImage; cv::Mat m_backgroundImage; cv::Mat m_resultImage; cv::Mat m_resultSignImage; bool m_bBackgroundInitialized; std::vector<std::vector<cv::Point> > contacts; bool set_reference_image; bool m_isFinished; };
18.693878
57
0.682314
[ "vector" ]
a2934aa2b764d0566e524cc7fe7d8c55418ec2c5
728
h
C
aws-cpp-sdk-connect-contact-lens/include/aws/connect-contact-lens/model/SentimentValue.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-connect-contact-lens/include/aws/connect-contact-lens/model/SentimentValue.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-connect-contact-lens/include/aws/connect-contact-lens/model/SentimentValue.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/connect-contact-lens/ConnectContactLens_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace ConnectContactLens { namespace Model { enum class SentimentValue { NOT_SET, POSITIVE, NEUTRAL, NEGATIVE }; namespace SentimentValueMapper { AWS_CONNECTCONTACTLENS_API SentimentValue GetSentimentValueForName(const Aws::String& name); AWS_CONNECTCONTACTLENS_API Aws::String GetNameForSentimentValue(SentimentValue value); } // namespace SentimentValueMapper } // namespace Model } // namespace ConnectContactLens } // namespace Aws
22.060606
92
0.771978
[ "model" ]
a29e68aabe732d84853d035959b572dcbd9b59c0
4,251
h
C
PhysX-3.2.4_PC_SDK_Core/Include/geometry/PxTriangleMeshGeometry.h
emlowry/AIEFramework
8f1dd02105237e72cfe303ec4c541eea7debd1f7
[ "MIT" ]
null
null
null
PhysX-3.2.4_PC_SDK_Core/Include/geometry/PxTriangleMeshGeometry.h
emlowry/AIEFramework
8f1dd02105237e72cfe303ec4c541eea7debd1f7
[ "MIT" ]
null
null
null
PhysX-3.2.4_PC_SDK_Core/Include/geometry/PxTriangleMeshGeometry.h
emlowry/AIEFramework
8f1dd02105237e72cfe303ec4c541eea7debd1f7
[ "MIT" ]
3
2017-01-04T19:48:57.000Z
2020-03-24T03:05:27.000Z
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_NX_TRIANGLEMESH_GEOMETRY #define PX_PHYSICS_NX_TRIANGLEMESH_GEOMETRY /** \addtogroup geomutils @{ */ #include "geometry/PxGeometry.h" #include "geometry/PxMeshScale.h" #include "common/PxCoreUtilityTypes.h" #ifndef PX_DOXYGEN namespace physx { #endif class PxTriangleMesh; /** \brief Some flags to control the simulated behavior of the mesh geometry. Used in ::PxMeshGeometryFlags. */ struct PxMeshGeometryFlag { enum Enum { eDOUBLE_SIDED = (1<<1) //!< The mesh is double-sided. This is currently only used for raycasting. }; }; /** \brief collection of set bits defined in PxMeshGeometryFlag. @see PxMeshGeometryFlag */ typedef PxFlags<PxMeshGeometryFlag::Enum,PxU8> PxMeshGeometryFlags; PX_FLAGS_OPERATORS(PxMeshGeometryFlag::Enum,PxU8); /** \brief Triangle mesh geometry class. This class unifies a mesh object with a scaling transform, and lets the combined object be used anywhere a PxGeometry is needed. The scaling is a transform along arbitrary axes contained in the scale object. The vertices of the mesh in geometry (or shape) space is the PxMeshScale::toMat33() transform, multiplied by the vertex space vertices in the PxConvexMesh object. */ class PxTriangleMeshGeometry : public PxGeometry { public: PX_INLINE PxTriangleMeshGeometry() : PxGeometry(PxGeometryType::eTRIANGLEMESH), triangleMesh(NULL) { } PX_INLINE PxTriangleMeshGeometry(PxTriangleMesh* mesh, const PxMeshScale& scaling = PxMeshScale(), PxMeshGeometryFlags flags = PxMeshGeometryFlags()) : PxGeometry(PxGeometryType::eTRIANGLEMESH), scale(scaling), meshFlags(flags), triangleMesh(mesh) { } /** \brief Returns true if the geometry is valid. \return True if the current settings are valid. */ PX_INLINE bool isValid() const; public: PxMeshScale scale; //!< The scaling transformation. PxMeshGeometryFlags meshFlags; //!< Some flags to control the simulated behavior of the mesh geometry. PxPadding<3> paddingFromFlags; //!< padding for mesh flags PxTriangleMesh* triangleMesh; //!< A reference to the mesh object. }; PX_INLINE bool PxTriangleMeshGeometry::isValid() const { if (mType != PxGeometryType::eTRIANGLEMESH) return false; if (!scale.scale.isFinite() || !scale.rotation.isUnit()) return false; if (scale.scale.x <= 0.0f || scale.scale.y <= 0.0f || scale.scale.z <= 0.0f) return false; if (!triangleMesh) return false; return true; } #ifndef PX_DOXYGEN } // namespace physx #endif /** @} */ #endif
31.723881
103
0.764291
[ "mesh", "geometry", "object", "shape", "transform" ]
a2a598b408a04217132b4e63fe6c5b512b638f02
1,228
h
C
torchaudio/csrc/sox/effects.h
dvisockas/audio
7cae1cb9838ae747bea7b50273303c55b5a63905
[ "BSD-2-Clause" ]
1
2021-05-07T16:33:15.000Z
2021-05-07T16:33:15.000Z
torchaudio/csrc/sox/effects.h
dvisockas/audio
7cae1cb9838ae747bea7b50273303c55b5a63905
[ "BSD-2-Clause" ]
null
null
null
torchaudio/csrc/sox/effects.h
dvisockas/audio
7cae1cb9838ae747bea7b50273303c55b5a63905
[ "BSD-2-Clause" ]
null
null
null
#ifndef TORCHAUDIO_SOX_EFFECTS_H #define TORCHAUDIO_SOX_EFFECTS_H #ifdef TORCH_API_INCLUDE_EXTENSION_H #include <torch/extension.h> #endif // TORCH_API_INCLUDE_EXTENSION_H #include <torch/script.h> #include <torchaudio/csrc/sox/utils.h> namespace torchaudio { namespace sox_effects { void initialize_sox_effects(); void shutdown_sox_effects(); c10::intrusive_ptr<torchaudio::sox_utils::TensorSignal> apply_effects_tensor( const c10::intrusive_ptr<torchaudio::sox_utils::TensorSignal>& input_signal, std::vector<std::vector<std::string>> effects); c10::intrusive_ptr<torchaudio::sox_utils::TensorSignal> apply_effects_file( const std::string path, std::vector<std::vector<std::string>> effects, c10::optional<bool>& normalize, c10::optional<bool>& channels_first, c10::optional<std::string>& format); #ifdef TORCH_API_INCLUDE_EXTENSION_H std::tuple<torch::Tensor, int64_t> apply_effects_fileobj( py::object fileobj, std::vector<std::vector<std::string>> effects, c10::optional<bool>& normalize, c10::optional<bool>& channels_first, c10::optional<std::string>& format); #endif // TORCH_API_INCLUDE_EXTENSION_H } // namespace sox_effects } // namespace torchaudio #endif
27.909091
80
0.762215
[ "object", "vector" ]
a2aa3c86e52054700d999084c9b37b613397dae9
5,786
h
C
tools/synthesizer/app_comm.h
kyushick/cdruntime
de08c79aad373c9715922294c67a7482c62ba9f2
[ "Unlicense" ]
null
null
null
tools/synthesizer/app_comm.h
kyushick/cdruntime
de08c79aad373c9715922294c67a7482c62ba9f2
[ "Unlicense" ]
null
null
null
tools/synthesizer/app_comm.h
kyushick/cdruntime
de08c79aad373c9715922294c67a7482c62ba9f2
[ "Unlicense" ]
null
null
null
#include "cd_syn_common.h" #include <cassert> #include <mpi.h> #define check_flag(X,Y) (((X) & (Y)) == (Y)) namespace synthesizer { struct CommStat { int *send_buf_; int *recv_buf_; int rank_; MPI_Status *stat_; MPI_Request *mreq_; CommStat(void) : send_buf_(nullptr) , recv_buf_(nullptr) , rank_(0) { SYN_PRINT("CommStat Default Constructed\n"); } CommStat(const CommStat &that) : send_buf_(that.send_buf_) , recv_buf_(that.recv_buf_) , rank_(that.rank_) , stat_(that.stat_) , mreq_(that.mreq_) { SYN_PRINT("CommStat Copy Constructed\n"); } CommStat(int rank, int count, int tags) : rank_(rank) , send_buf_(new int[count]()) , recv_buf_(new int[count]()) , stat_(new MPI_Status[tags]) , mreq_(new MPI_Request[tags]) { SYN_PRINT("[%d] create %p %p\n", rank_, send_buf_, recv_buf_); } ~CommStat(void) { SYN_PRINT("[%d] delete %p %p\n", rank_, send_buf_, recv_buf_); delete [] send_buf_; delete [] recv_buf_; delete [] stat_; delete [] mreq_; } }; struct AppComm { int count_; std::vector<CommStat *> src_; std::vector<CommStat *> dst_; int tag_; int rank_; int size_; CommType comm_type_; MPI_Datatype datatype_; MPI_Comm comm_; void Print(const char *func) { SYN_PRINT_ONE(">> Comm: %s cnt:%d rank:%d size:%d src:%zu dst:%zu (Type) %x %x (MPI_INT)\n", func, count_, rank_, size_, src_.size(), dst_.size(), datatype_, MPI_INT); } void Init(void) { // set up src and dst for each rank // default: comm b/w i and i+i // //assert(size_ % 2 == 0); int target = (rank_ % 2 == 0) ? rank_ + 1 : rank_ - 1; src_.push_back(new CommStat(target, count_, tag_)); dst_.push_back(new CommStat(target, count_, tag_)); SYN_PRINT("AppComm %s\n", __func__); } ~AppComm(void) { for (auto &src : src_) delete src; for (auto &dst : dst_) delete dst; } AppComm(void) : count_(0) , tag_(0) , datatype_(MPI_INT) , comm_(MPI_COMM_WORLD) { assert(0); } AppComm(const AppComm &that) { count_ = that.count_; tag_ = that.tag_; rank_ = that.rank_; size_ = that.size_; comm_type_ = that.comm_type_; datatype_ = that.datatype_; comm_ = that.comm_; SYN_PRINT("datatype:%d\n", that.datatype_); that.Print("that"); Print("Copy"); //getchar(); } AppComm(double payload, int tags, const MPI_Comm &comm) : count_(static_cast<int>(payload / sizeof(int))) , tag_(tags) , datatype_(MPI_INT) , comm_(comm) { MPI_Comm_rank(comm_, &rank_); MPI_Comm_size(comm_, &size_); Init(); } AppComm(double payload, CommType comm_type, bool split, const AppComm &parent) : count_(static_cast<int>(payload / sizeof(int))) , comm_type_(comm_type) { if (split) { //if (check_flag(comm_type, kNewComm)) { // MPI_Comm_split(parent.comm_, group_id, id_in_group, &comm_); // MPI_Comm_rank(comm_, &rank_); // MPI_Comm_size(comm_, &size_); } else { comm_ = parent.comm_; rank_ = parent.rank_; size_ = parent.size_; } tag_ = parent.tag_; comm_type_ = parent.comm_type_; datatype_ = parent.datatype_; Init(); Print("Split"); //getchar(); } int Send(void) { Print(__func__); int ret = 0; if (count_ > 0) { for (auto &dst : dst_) { for (int i=0; i<tag_; i++) { ret = MPI_Send(dst->send_buf_, count_, datatype_, dst->rank_, i, comm_); } } } else { SYN_PRINT("count is zero\n"); assert(0); } return ret; } int Recv(void) { Print(__func__); int ret = 0; if (count_ > 0) { for (auto &src : src_) { for (int i=0; i<tag_; i++) { ret = MPI_Recv(src->recv_buf_, count_, datatype_, src->rank_, i, comm_, &(src->stat_[i])); } } } return ret; } int Isend(void) { Print(__func__); int ret = 0; if (count_ > 0) { for (auto &dst : dst_) { for (int i=0; i<tag_; i++) { ret = MPI_Isend(dst->send_buf_, count_, datatype_, dst->rank_, i, comm_, &(dst->mreq_[i])); } } } return ret; } int Irecv(void) { Print(__func__); int ret = 0; if (count_ > 0) { for (auto &src : src_) { for (int i=0; i<tag_; i++) { if (myRank == 0) printf("MPI_Irecv(%p, %d, %d, %d, %d, %lx, %d)\n", src->recv_buf_, count_, datatype_, src->rank_, i, comm_, &(src->mreq_[i])); ret = MPI_Irecv(src->recv_buf_, count_, datatype_, src->rank_, i, comm_, &(src->mreq_[i])); } } } return ret; } int Reduce(void) { Print(__func__); int ret = 0; if (count_ > 0) { for (int i=0; i<tag_; i++) { ret = MPI_Reduce(dst_[0]->send_buf_, src_[0]->recv_buf_, count_, datatype_, MPI_SUM, 0, comm_); } } return ret; } int Wait(bool for_recv=true) { Print(__func__); int ret = 0; if (count_ > 0) { if (for_recv) { for (auto &src : src_) { for (int i=0; i<tag_; i++) { ret = MPI_Wait(&(src->mreq_[i]), &(src->stat_[i])); } } } else { for (auto &dst : dst_) { for (int i=0; i<tag_; i++) { ret = MPI_Wait(&(dst->mreq_[i]), &(dst->stat_[i])); } } } } return ret; } int SendRecv(void) { Print(__func__); int ret = 0; if (count_ > 0) { for (int i=0; i<src_.size(); i++) { ret = MPI_Sendrecv(dst_[0]->send_buf_, count_, datatype_, dst_[0]->rank_, tag_, src_[0]->recv_buf_, count_, datatype_, src_[0]->rank_, tag_, comm_, &(src_[0]->stat_[i])); } } } }; }
25.377193
171
0.548566
[ "vector" ]
a2b141a6f3eabc8865fa13a76aace28af33ee134
4,856
h
C
AngryBurg/AngryBurg/GameObject.h
henry9836/AngryBurg
3adee97c668bedcfdea890116a68deb7968479d1
[ "MIT" ]
null
null
null
AngryBurg/AngryBurg/GameObject.h
henry9836/AngryBurg
3adee97c668bedcfdea890116a68deb7968479d1
[ "MIT" ]
null
null
null
AngryBurg/AngryBurg/GameObject.h
henry9836/AngryBurg
3adee97c668bedcfdea890116a68deb7968479d1
[ "MIT" ]
null
null
null
#pragma once #include "Util.h" #include "GameObject.h" #include "GameManager.h" #include "Physics.h" class GameObject; class CTextLabel; class RenderClass { public: virtual void Render(Transform* _transform) = 0; virtual void SetTexture(GLuint _tex) = 0; virtual void SetShader(GLuint _shader) = 0; }; class NoRender : public RenderClass { }; class RenderObject : public RenderClass { public: RenderObject(); RenderObject(std::shared_ptr<MESH> _mesh, GLuint _texture, Game* _game, GLuint _shaderProgram) : VAO(_mesh->VAO), indiceCount(_mesh->IndicesCount), texture(_texture), game(_game), shaderProgram(_shaderProgram) {}; ~RenderObject(); virtual void Render(Transform* _transform); virtual void SetTexture(GLuint _tex); virtual void SetShader(GLuint _shader); GLuint VAO; unsigned int indiceCount; GLuint texture; Game* game = nullptr; GLuint shaderProgram; }; class RenderText : public RenderClass { public: RenderText(CTextLabel* _text) : text(_text) {}; ~RenderText(); virtual void Render(Transform* _transform); virtual void SetTexture(GLuint _tex) {}; virtual void SetShader(GLuint _shader) {}; CTextLabel* text; }; class TickClass { public: virtual void Tick(float deltaTime, GameObject* _gameObject) = 0; }; class IdleTick : public TickClass { public: virtual void Tick(float deltaTime, GameObject* _gameObject) { return; }; }; class TickObject : public TickClass { public: virtual void Tick(float deltaTime, GameObject* _gameObject); }; class GameObject { public: GameObject(); GameObject(RenderClass* r, TickClass* t, Transform _trans, string _name) : _r(r), _t(t), transform(_trans), name(_name) { Console_OutputLog(to_wstring("Creating GameObject: " + _name), LOGINFO); }; virtual void Tick(float deltaTime, GameObject* _gameObject) { _t->Tick(deltaTime, _gameObject); }; virtual void Render() { _r->Render(&transform); }; virtual void SetTexture(GLuint _tex) { _r->SetTexture(_tex); }; virtual void SetShader(GLuint _shader) { _r->SetTexture(_shader); }; Transform& GetTransform() { return transform; }; WallPhysics* wall = nullptr; bool deathMark = false; Transform transform; string name; protected: RenderClass* _r = nullptr; TickClass* _t = nullptr; }; class BasicObject : public GameObject { public: BasicObject(); BasicObject(RenderClass* r, TickClass* t, Transform _trans, string _name); ~BasicObject(); virtual void Tick(float deltaTime, GameObject* _gameObject) { _t->Tick(deltaTime, _gameObject); }; virtual void Render() { _r->Render(&transform); }; virtual void SetTexture(GLuint _tex) { _r->SetTexture(_tex); }; virtual void SetShader(GLuint _shader) { _r->SetTexture(_shader); }; }; class WallObject : public GameObject { public: WallObject(); WallObject(RenderClass* r, TickClass* t, Transform _trans, string _name, WallPhysics* _wall); ~WallObject(); virtual void Tick(float deltaTime, GameObject* _gameObject) { _t->Tick(deltaTime, _gameObject); }; virtual void Render() { _r->Render(&transform); }; virtual void SetTexture(GLuint _tex) { _r->SetTexture(_tex); }; virtual void SetShader(GLuint _shader) { _r->SetTexture(_shader); }; }; class TickWall : public TickClass { public: virtual void Tick(float deltaTime, GameObject* _gameObject); }; class BirdObject : public GameObject { public: enum BIRDTYPE { DEFAULT }; BirdObject(); BirdObject(RenderClass* r, TickClass* t, Transform _trans, string _name, WallPhysics* _wall, BIRDTYPE _bird, Game* _game); ~BirdObject(); virtual void Tick(float deltaTime, GameObject* _gameObject) { _t->Tick(deltaTime, _gameObject); }; virtual void Render() { _r->Render(&transform); }; virtual void SetTexture(GLuint _tex) { _r->SetTexture(_tex); }; virtual void SetShader(GLuint _shader) { _r->SetTexture(_shader); }; WallPhysics* wall = nullptr; Game* game = nullptr; BIRDTYPE Birdtype = DEFAULT; }; class TickBird : public TickClass { public: virtual void Tick(float deltaTime, BirdObject* _gameObject); }; class PigObject : public GameObject { public: PigObject(); PigObject(RenderClass* r, TickClass* t, Transform _trans, string _name, WallPhysics* _wall, Game* _game); ~PigObject(); virtual void Tick(float deltaTime, GameObject* _gameObject) { _t->Tick(deltaTime, _gameObject); }; virtual void Render() { _r->Render(&transform); }; virtual void SetTexture(GLuint _tex) { _r->SetTexture(_tex); }; virtual void SetShader(GLuint _shader) { _r->SetTexture(_shader); }; WallPhysics* wall = nullptr; Game* game = nullptr; float health = 10; }; class TickPig : public TickClass { public: virtual void Tick(float deltaTime, PigObject* _gameObject); }; #include "TextManager.h"
26.681319
215
0.704283
[ "mesh", "render", "transform" ]
a2b4b8142a442d82104567cbf4e47a4ac835b158
8,448
c
C
sys/dev/ips/ips_disk.c
TrustedBSD/sebsd
fd5de6f587183087cf930779701d5713e8ca64cc
[ "Naumen", "Condor-1.1", "MS-PL" ]
4
2017-04-06T21:39:15.000Z
2019-10-09T17:34:14.000Z
sys/dev/ips/ips_disk.c
TrustedBSD/sebsd
fd5de6f587183087cf930779701d5713e8ca64cc
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
sys/dev/ips/ips_disk.c
TrustedBSD/sebsd
fd5de6f587183087cf930779701d5713e8ca64cc
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2020-01-04T06:36:39.000Z
2020-01-04T06:36:39.000Z
/*- * Written by: David Jeffery * Copyright (c) 2002 Adaptec Inc. * 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 AUTHOR 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. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: src/sys/dev/ips/ips_disk.c,v 1.10 2005/11/29 09:39:41 scottl Exp $"); #include <dev/ips/ipsreg.h> #include <dev/ips/ips.h> #include <dev/ips/ips_disk.h> #include <sys/stat.h> static int ipsd_probe(device_t dev); static int ipsd_attach(device_t dev); static int ipsd_detach(device_t dev); static int ipsd_dump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length); static void ipsd_dump_map_sg(void *arg, bus_dma_segment_t *segs, int nsegs, int error); static void ipsd_dump_block_complete(ips_command_t *command); static disk_open_t ipsd_open; static disk_close_t ipsd_close; static disk_strategy_t ipsd_strategy; static device_method_t ipsd_methods[] = { DEVMETHOD(device_probe, ipsd_probe), DEVMETHOD(device_attach, ipsd_attach), DEVMETHOD(device_detach, ipsd_detach), { 0, 0 } }; static driver_t ipsd_driver = { "ipsd", ipsd_methods, sizeof(ipsdisk_softc_t) }; static devclass_t ipsd_devclass; DRIVER_MODULE(ipsd, ips, ipsd_driver, ipsd_devclass, 0, 0); /* handle opening of disk device. It must set up all information about the geometry and size of the disk */ static int ipsd_open(struct disk *dp) { ipsdisk_softc_t *dsc = dp->d_drv1; dsc->state |= IPS_DEV_OPEN; DEVICE_PRINTF(2, dsc->dev, "I'm open\n"); return 0; } static int ipsd_close(struct disk *dp) { ipsdisk_softc_t *dsc = dp->d_drv1; dsc->state &= ~IPS_DEV_OPEN; DEVICE_PRINTF(2, dsc->dev, "I'm closed for the day\n"); return 0; } /* ipsd_finish is called to clean up and return a completed IO request */ void ipsd_finish(struct bio *iobuf) { ipsdisk_softc_t *dsc; dsc = iobuf->bio_disk->d_drv1; if (iobuf->bio_flags & BIO_ERROR) { ipsdisk_softc_t *dsc; dsc = iobuf->bio_disk->d_drv1; device_printf(dsc->dev, "iobuf error %d\n", iobuf->bio_error); } else iobuf->bio_resid = 0; biodone(iobuf); ips_start_io_request(dsc->sc); } static void ipsd_strategy(struct bio *iobuf) { ipsdisk_softc_t *dsc; dsc = iobuf->bio_disk->d_drv1; DEVICE_PRINTF(8,dsc->dev,"in strategy\n"); iobuf->bio_driver1 = (void *)(uintptr_t)dsc->sc->drives[dsc->disk_number].drivenum; mtx_lock(&dsc->sc->queue_mtx); bioq_insert_tail(&dsc->sc->queue, iobuf); ips_start_io_request(dsc->sc); mtx_unlock(&dsc->sc->queue_mtx); } static int ipsd_probe(device_t dev) { DEVICE_PRINTF(2,dev, "in probe\n"); device_set_desc(dev, "Logical Drive"); return 0; } static int ipsd_attach(device_t dev) { device_t adapter; ipsdisk_softc_t *dsc; u_int totalsectors; DEVICE_PRINTF(2,dev, "in attach\n"); dsc = (ipsdisk_softc_t *)device_get_softc(dev); bzero(dsc, sizeof(ipsdisk_softc_t)); adapter = device_get_parent(dev); dsc->dev = dev; dsc->sc = device_get_softc(adapter); dsc->unit = device_get_unit(dev); dsc->disk_number = (uintptr_t) device_get_ivars(dev); dsc->ipsd_disk = disk_alloc(); dsc->ipsd_disk->d_drv1 = dsc; dsc->ipsd_disk->d_name = "ipsd"; dsc->ipsd_disk->d_maxsize = IPS_MAX_IO_SIZE; dsc->ipsd_disk->d_open = ipsd_open; dsc->ipsd_disk->d_close = ipsd_close; dsc->ipsd_disk->d_strategy = ipsd_strategy; dsc->ipsd_disk->d_dump = ipsd_dump; totalsectors = dsc->sc->drives[dsc->disk_number].sector_count; if ((totalsectors > 0x400000) && ((dsc->sc->adapter_info.miscflags & 0x8) == 0)) { dsc->ipsd_disk->d_fwheads = IPS_NORM_HEADS; dsc->ipsd_disk->d_fwsectors = IPS_NORM_SECTORS; } else { dsc->ipsd_disk->d_fwheads = IPS_COMP_HEADS; dsc->ipsd_disk->d_fwsectors = IPS_COMP_SECTORS; } dsc->ipsd_disk->d_sectorsize = IPS_BLKSIZE; dsc->ipsd_disk->d_mediasize = (off_t)totalsectors * IPS_BLKSIZE; dsc->ipsd_disk->d_unit = dsc->unit; dsc->ipsd_disk->d_flags = 0; disk_create(dsc->ipsd_disk, DISK_VERSION); device_printf(dev, "Logical Drive (%dMB)\n", dsc->sc->drives[dsc->disk_number].sector_count >> 11); return 0; } static int ipsd_detach(device_t dev) { ipsdisk_softc_t *dsc; DEVICE_PRINTF(2, dev,"in detach\n"); dsc = (ipsdisk_softc_t *)device_get_softc(dev); if(dsc->state & IPS_DEV_OPEN) return (EBUSY); disk_destroy(dsc->ipsd_disk); return 0; } static int ipsd_dump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length) { ipsdisk_softc_t *dsc; ips_softc_t *sc; ips_command_t *command; ips_io_cmd *command_struct; struct disk *dp; void *va; off_t off; size_t len; int error = 0; dp = arg; dsc = dp->d_drv1; sc = dsc->sc; if (dsc == NULL) return (EINVAL); if (ips_get_free_cmd(sc, &command, 0) != 0) { printf("ipsd: failed to get cmd for dump\n"); return (ENOMEM); } command->data_dmatag = sc->sg_dmatag; command->callback = ipsd_dump_block_complete; command_struct = (ips_io_cmd *)command->command_buffer; command_struct->id = command->id; command_struct->drivenum= sc->drives[dsc->disk_number].drivenum; off = offset; va = virtual; while (length > 0) { len = (length > IPS_MAX_IO_SIZE) ? IPS_MAX_IO_SIZE : length; command_struct->lba = off / IPS_BLKSIZE; if (bus_dmamap_load(command->data_dmatag, command->data_dmamap, va, len, ipsd_dump_map_sg, command, BUS_DMA_NOWAIT) != 0) { error = EIO; break; } if (COMMAND_ERROR(command)) { error = EIO; break; } length -= len; off += len; va = (uint8_t *)va + len; } ips_insert_free_cmd(command->sc, command); return (error); } static void ipsd_dump_map_sg(void *arg, bus_dma_segment_t *segs, int nsegs, int error) { ips_softc_t *sc; ips_command_t *command; ips_sg_element_t *sg_list; ips_io_cmd *command_struct; int i, length; command = (ips_command_t *)arg; sc = command->sc; length = 0; if (error) { printf("ipsd_dump_map_sg: error %d\n", error); ips_set_error(command, error); return; } command_struct = (ips_io_cmd *)command->command_buffer; if (nsegs != 1) { command_struct->segnum = nsegs; sg_list = (ips_sg_element_t *)((uint8_t *) command->command_buffer + IPS_COMMAND_LEN); for (i = 0; i < nsegs; i++) { sg_list[i].addr = segs[i].ds_addr; sg_list[i].len = segs[i].ds_len; length += segs[i].ds_len; } command_struct->buffaddr = (uint32_t)command->command_phys_addr + IPS_COMMAND_LEN; command_struct->command = IPS_SG_WRITE_CMD; } else { command_struct->buffaddr = segs[0].ds_addr; length = segs[0].ds_len; command_struct->segnum = 0; command_struct->command = IPS_WRITE_CMD; } length = (length + IPS_BLKSIZE - 1) / IPS_BLKSIZE; command_struct->length = length; bus_dmamap_sync(sc->command_dmatag, command->command_dmamap, BUS_DMASYNC_PREWRITE); bus_dmamap_sync(command->data_dmatag, command->data_dmamap, BUS_DMASYNC_PREWRITE); sc->ips_issue_cmd(command); sc->ips_poll_cmd(command); return; } static void ipsd_dump_block_complete(ips_command_t *command) { if (COMMAND_ERROR(command)) printf("ipsd_dump completion error= 0x%x\n", command->status.value); bus_dmamap_sync(command->data_dmatag, command->data_dmamap, BUS_DMASYNC_POSTWRITE); bus_dmamap_unload(command->data_dmatag, command->data_dmamap); }
27.789474
89
0.718158
[ "geometry" ]
a2b61f8fa38cf09bb819f90f425f48dc21f4b1b5
4,221
h
C
vino_core_lib/include/vino_core_lib/inferences/head_pose_detection.h
GuoliangShiIntel/ros_openvino_toolkit
37a9a24dc15c37544a603d0903c7851a2c4286ad
[ "Apache-2.0" ]
null
null
null
vino_core_lib/include/vino_core_lib/inferences/head_pose_detection.h
GuoliangShiIntel/ros_openvino_toolkit
37a9a24dc15c37544a603d0903c7851a2c4286ad
[ "Apache-2.0" ]
null
null
null
vino_core_lib/include/vino_core_lib/inferences/head_pose_detection.h
GuoliangShiIntel/ros_openvino_toolkit
37a9a24dc15c37544a603d0903c7851a2c4286ad
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2018 Intel Corporation * * 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 A header file with declaration for FaceDetection Class * @file head_pose_detection.h */ #ifndef VINO_CORE_LIB__INFERENCES__HEAD_POSE_DETECTION_H #define VINO_CORE_LIB__INFERENCES__HEAD_POSE_DETECTION_H #include <memory> #include <string> #include <vector> #include "vino_core_lib/engines/engine.h" #include "vino_core_lib/inferences/base_inference.h" #include "vino_core_lib/models/head_pose_detection_model.h" #include "inference_engine.hpp" #include "opencv2/opencv.hpp" namespace vino_core_lib { /** * @class HeadPoseResult * @brief Class for storing and processing headpose detection result. */ class HeadPoseResult : public Result { public: friend class HeadPoseDetection; explicit HeadPoseResult(const cv::Rect& location); /** * @brief Get the yawl angle of the headpose. * @return The yawl value. */ float getAngleY() const { return angle_y_; } /** * @brief Get the pitch angle of the headpose. * @return The pitch value. */ float getAngleP() const { return angle_p_; } /** * @brief Get the roll angle of the headpose. * @return The roll value. */ float getAngleR() const { return angle_r_; } private: float angle_y_ = -1; float angle_p_ = -1; float angle_r_ = -1; }; /** * @class HeadPoseDetection * @brief Class to load headpose detection model and perform headpose detection. */ class HeadPoseDetection : public BaseInference { public: using Result = vino_core_lib::HeadPoseResult; HeadPoseDetection(); ~HeadPoseDetection() override; /** * @brief Load the headpose detection model. */ void loadNetwork(std::shared_ptr<Models::HeadPoseDetectionModel>); /** * @brief Enqueue a frame to this class. * The frame will be buffered but not infered yet. * @param[in] frame The frame to be enqueued. * @param[in] input_frame_loc The location of the enqueued frame with respect * to the frame generated by the input device. * @return Whether this operation is successful. */ bool enqueue(const cv::Mat& frame, const cv::Rect&) override; /** * @brief Start inference for all buffered frames. * @return Whether this operation is successful. */ bool submitRequest() override; /** * @brief This function will fetch the results of the previous inference and * stores the results in a result buffer array. All buffered frames will be * cleared. * @return Whether the Inference object fetches a result this time */ bool fetchResults() override; /** * @brief Get the length of the buffer result array. * @return The length of the buffer result array. */ int getResultsLength() const override; /** * @brief Get the location of result with respect * to the frame generated by the input device. * @param[in] idx The index of the result. */ const vino_core_lib::Result* getLocationResult(int idx) const override; /** * @brief Get the name of the Inference instance. * @return The name of the Inference instance. */ const std::string getName() const override; /** * @brief Show the observed detection result either through image window or ROS topic. */ void observeOutput(const std::shared_ptr<Outputs::BaseOutput>& output) override; std::vector<Result> getResults() { return results_; } const std::vector<cv::Rect> getFilteredROIs(const std::string filter_conditions) const override; private: std::shared_ptr<Models::HeadPoseDetectionModel> valid_model_; std::vector<Result> results_; }; } // namespace vino_core_lib #endif // VINO_CORE_LIB__INFERENCES__HEAD_POSE_DETECTION_H
29.110345
98
0.718076
[ "object", "vector", "model" ]
a2ba906ecfe4c190456404e5fa407b2cc7d14c24
3,687
h
C
Source/Urho3D/Urho2D/Constraint2D.h
lukadriel7/Urho3D
36a38f59b5e097ac36b7c1fb755d8fb42aa19d13
[ "MIT" ]
7
2021-01-27T15:05:38.000Z
2021-12-17T12:36:51.000Z
Source/Urho3D/Urho2D/Constraint2D.h
lukadriel7/Urho3D
36a38f59b5e097ac36b7c1fb755d8fb42aa19d13
[ "MIT" ]
1
2021-03-31T22:38:27.000Z
2021-04-01T12:49:16.000Z
Source/Urho3D/Urho2D/Constraint2D.h
lukadriel7/Urho3D
36a38f59b5e097ac36b7c1fb755d8fb42aa19d13
[ "MIT" ]
2
2018-11-25T19:07:30.000Z
2019-09-05T15:22:39.000Z
// // Copyright (c) 2008-2020 the Urho3D project. // // 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. // #pragma once #include "../Scene/Component.h" #include <Box2D/Box2D.h> namespace Urho3D { class RigidBody2D; class PhysicsWorld2D; /// 2D physics constraint component. class URHO3D_API Constraint2D : public Component { URHO3D_OBJECT(Constraint2D, Component); public: /// Construct. explicit Constraint2D(Context* context); /// Destruct. ~Constraint2D() override; /// Register object factory. static void RegisterObject(Context* context); /// Apply attribute changes that can not be applied immediately. Called after scene load or a network update. void ApplyAttributes() override; /// Handle enabled/disabled state change. void OnSetEnabled() override; /// Create joint. void CreateJoint(); /// Release joint. void ReleaseJoint(); /// Set other rigid body. void SetOtherBody(RigidBody2D* body); /// Set collide connected. void SetCollideConnected(bool collideConnected); /// Set attached constriant (for gear). void SetAttachedConstraint(Constraint2D* constraint); /// Return owner body. RigidBody2D* GetOwnerBody() const { return ownerBody_; } /// Return other body. RigidBody2D* GetOtherBody() const { return otherBody_; } /// Return collide connected. bool GetCollideConnected() const { return collideConnected_; } /// Return attached constraint (for gear). Constraint2D* GetAttachedConstraint() const { return attachedConstraint_; } /// Return Box2D joint. b2Joint* GetJoint() const { return joint_; } protected: /// Handle node being assigned. void OnNodeSet(Node* node) override; /// Handle scene being assigned. void OnSceneSet(Scene* scene) override; /// Return joint def. virtual b2JointDef* GetJointDef() { return nullptr; }; /// Recreate joint. void RecreateJoint(); /// Initialize joint def. void InitializeJointDef(b2JointDef* jointDef); /// Mark other body node ID dirty. void MarkOtherBodyNodeIDDirty() { otherBodyNodeIDDirty_ = true; } /// Physics world. WeakPtr<PhysicsWorld2D> physicsWorld_; /// Box2D joint. b2Joint* joint_{}; /// Owner body. WeakPtr<RigidBody2D> ownerBody_; /// Other body. WeakPtr<RigidBody2D> otherBody_; /// Other body node ID for serialization. unsigned otherBodyNodeID_{}; /// Collide connected flag. bool collideConnected_{}; /// Other body node ID dirty flag. bool otherBodyNodeIDDirty_{}; /// Attached constraint. WeakPtr<Constraint2D> attachedConstraint_; }; }
32.919643
113
0.711418
[ "object" ]
a2bf2373c9fc7e2a2a10ce4b28618c7e6e675d17
1,662
h
C
More/Polarimetry/Pulsar/PolnCalExtFreqIntegrate.h
rwharton/psrchive_dsn
9584862167154fa48db89b86151c4221ad4bb96b
[ "AFL-2.1" ]
null
null
null
More/Polarimetry/Pulsar/PolnCalExtFreqIntegrate.h
rwharton/psrchive_dsn
9584862167154fa48db89b86151c4221ad4bb96b
[ "AFL-2.1" ]
null
null
null
More/Polarimetry/Pulsar/PolnCalExtFreqIntegrate.h
rwharton/psrchive_dsn
9584862167154fa48db89b86151c4221ad4bb96b
[ "AFL-2.1" ]
1
2020-02-13T20:08:14.000Z
2020-02-13T20:08:14.000Z
//-*-C++-*- /*************************************************************************** * * Copyright (C) 2019 by Willem van Straten * Licensed under the Academic Free License version 2.1 * ***************************************************************************/ // psrchive/More/Polarimetry/Pulsar/PolnCalExtFreqIntegrate.h #ifndef __Pulsar_PolnCalExtFreqIntegrate_h #define __Pulsar_PolnCalExtFreqIntegrate_h #include "Pulsar/Integrate.h" #include "Pulsar/EvenlySpaced.h" #include "Pulsar/EvenlyWeighted.h" #include "Pulsar/PolnCalibratorExtension.h" namespace Pulsar { //! Integrates frequency channels in a polarization calibration extension class PolnCalExtFreqIntegrate : public Integrate<PolnCalibratorExtension> { public: //! Default constructor PolnCalExtFreqIntegrate (); //! The frequency integration operation void transform (PolnCalibratorExtension*); //! Policy for producing evenly spaced frequency channel ranges class EvenlySpaced; //! Policy for producing evenly distributed frequency channel ranges class EvenlyWeighted; }; class PolnCalExtFreqIntegrate::EvenlySpaced : public Integrate<PolnCalibratorExtension>::EvenlySpaced { unsigned get_size (const PolnCalibratorExtension* sub) { return sub->get_nchan(); } }; class PolnCalExtFreqIntegrate::EvenlyWeighted : public Integrate<PolnCalibratorExtension>::EvenlyWeighted { unsigned get_size (const PolnCalibratorExtension* sub) { return sub->get_nchan(); } double get_weight (const PolnCalibratorExtension* sub, unsigned ichan) { return sub->get_weight (ichan); } }; } #endif
27.245902
77
0.679904
[ "transform" ]
a2c06ed9735082317449ade7c02de7b8647246ac
2,401
h
C
src/xtd.core/include/xtd/internal/__numeric_formatter.h
gammasoft71/xtd
09e589a9dd2cb292d1e54c9c4f803c2b3ad22102
[ "MIT" ]
251
2019-04-20T02:02:24.000Z
2022-03-31T09:52:08.000Z
src/xtd.core/include/xtd/internal/__numeric_formatter.h
gammasoft71/xtd
09e589a9dd2cb292d1e54c9c4f803c2b3ad22102
[ "MIT" ]
29
2021-01-07T12:52:12.000Z
2022-03-29T08:42:14.000Z
src/xtd.core/include/xtd/internal/__numeric_formatter.h
gammasoft71/xtd
09e589a9dd2cb292d1e54c9c4f803c2b3ad22102
[ "MIT" ]
27
2019-11-21T02:37:44.000Z
2022-03-30T22:59:14.000Z
/// @file /// @brief Contains __numeric_formatter method. #pragma once /// @cond #ifndef __XTD_CORE_INTERNAL__ #error "Do not include this file: Internal use only" #endif /// @endcond #include "__binary_formatter.h" #include "__fixed_point_formatter.h" #include "__format_exception.h" #include "__sprintf.h" /// @cond template<typename char_t, typename value_t> inline std::basic_string<char_t> __numeric_formatter(const std::basic_string<char_t>& fmt, value_t value, const std::locale& loc) { std::basic_string<char_t> format = fmt; if (format.empty()) format = {'G'}; std::vector<char_t> possible_formats {'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'n', 'N', 'o', 'O', 'p', 'P', 'x', 'X'}; if (format.size() > 3 || std::find(possible_formats.begin(), possible_formats.end(), format[0]) == possible_formats.end() || (format.size() >= 2 && !std::isdigit(format[1])) || (format.size() == 3 && !std::isdigit(format[2]))) __format_exception("Custom format not yet implemented"); int precision = 0; if (format[0] == 'b' || format[0] == 'B' || format[0] == 'd' || format[0] == 'D' || format[0] == 'o' || format[0] == 'O' || format[0] == 'x' || format[0] == 'X') { try { for (auto c : format.substr(1)) if (!std::isdigit(c) && c != ' ' && c != '+' && c != '-') __format_exception("Invalid format expression"); if (format.size() > 1) precision = std::stoi(format.substr(1)); } catch(...) { __format_exception("Invalid format expression"); } if ((format[0] == 'd' || format[0] == 'D') && precision > 0 && value < 0) precision += 1; if ((format[0] == 'd' || format[0] == 'D') && precision < 0 && value < 0) precision -= 1; } std::basic_string<char_t> fmt_str({'%', '0', '*', 'l', 'l'}); switch (format[0]) { case 'b': case 'B': return __binary_formatter<char_t>(value, precision); case 'd': case 'D': case 'G': return __sprintf((fmt_str + char_t(std::is_unsigned<value_t>::value ? 'u' : 'd')).c_str(), precision, static_cast<long long>(value)); case 'o': case 'O': return __sprintf((fmt_str + char_t('o')).c_str(), precision, static_cast<long long>(value)); case 'x': case 'X': return __sprintf((fmt_str + format[0]).c_str(), precision, static_cast<long long>(value)); default: return __fixed_point_formatter(format, static_cast<long double>(value), loc); } } /// @endcond
46.173077
228
0.601833
[ "vector" ]
a2c71a5ec077688b9ed2c0ac1cc47e4e1f9d3d53
3,755
h
C
blades/xbmc/xbmc/storage/MediaManager.h
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
4
2016-04-26T03:43:54.000Z
2016-11-17T08:09:04.000Z
blades/xbmc/xbmc/storage/MediaManager.h
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
blades/xbmc/xbmc/storage/MediaManager.h
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
3
2016-04-26T03:43:55.000Z
2020-11-06T11:02:08.000Z
#pragma once /* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * 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; either version 2, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "MediaSource.h" // for VECSOURCES #include <map> #include "utils/Job.h" #include "IStorageProvider.h" #include "threads/CriticalSection.h" #define TRAY_OPEN 16 #define TRAY_CLOSED_NO_MEDIA 64 #define TRAY_CLOSED_MEDIA_PRESENT 96 #define DRIVE_OPEN 0 // Open... #define DRIVE_NOT_READY 1 // Opening.. Closing... #define DRIVE_READY 2 #define DRIVE_CLOSED_NO_MEDIA 3 // CLOSED...but no media in drive #define DRIVE_CLOSED_MEDIA_PRESENT 4 // Will be send once when the drive just have closed #define DRIVE_NONE 5 // system doesn't have an optical drive class CNetworkLocation { public: CNetworkLocation() { id = 0; }; int id; std::string path; }; class CMediaManager : public IStorageEventsCallback, public IJobCallback { public: CMediaManager(); void Initialize(); void Stop(); bool LoadSources(); bool SaveSources(); void GetLocalDrives(VECSOURCES &localDrives, bool includeQ = true); void GetRemovableDrives(VECSOURCES &removableDrives); void GetNetworkLocations(VECSOURCES &locations, bool autolocations = true); bool AddNetworkLocation(const std::string &path); bool HasLocation(const std::string& path) const; bool RemoveLocation(const std::string& path); bool SetLocationPath(const std::string& oldPath, const std::string& newPath); void AddAutoSource(const CMediaSource &share, bool bAutorun=false); void RemoveAutoSource(const CMediaSource &share); bool IsDiscInDrive(const std::string& devicePath=""); bool IsAudio(const std::string& devicePath=""); bool HasOpticalDrive(); std::string TranslateDevicePath(const std::string& devicePath, bool bReturnAsDevice=false); DWORD GetDriveStatus(const std::string& devicePath=""); #ifdef HAS_DVD_DRIVE MEDIA_DETECT::CCdInfo* GetCdInfo(const std::string& devicePath=""); bool RemoveCdInfo(const std::string& devicePath=""); std::string GetDiskLabel(const std::string& devicePath=""); std::string GetDiskUniqueId(const std::string& devicePath=""); #endif std::string GetDiscPath(); void SetHasOpticalDrive(bool bstatus); bool Eject(const std::string& mountpath); void EjectTray( const bool bEject=true, const char cDriveLetter='\0' ); void CloseTray(const char cDriveLetter='\0'); void ToggleTray(const char cDriveLetter='\0'); void ProcessEvents(); std::vector<std::string> GetDiskUsage(); virtual void OnStorageAdded(const std::string &label, const std::string &path); virtual void OnStorageSafelyRemoved(const std::string &label); virtual void OnStorageUnsafelyRemoved(const std::string &label); virtual void OnJobComplete(unsigned int jobID, bool success, CJob *job) { } protected: std::vector<CNetworkLocation> m_locations; CCriticalSection m_muAutoSource, m_CritSecStorageProvider; #ifdef HAS_DVD_DRIVE std::map<std::string,MEDIA_DETECT::CCdInfo*> m_mapCdInfo; #endif bool m_bhasoptical; std::string m_strFirstAvailDrive; private: IStorageProvider *m_platformStorage; }; extern class CMediaManager g_mediaManager;
33.230088
93
0.745672
[ "vector" ]
a2c8bb17cb7de2698ddc60b01f14d95d5739af78
3,766
h
C
thirdparty/cgal/CGAL-4.13/include/CGAL/Boolean_set_operations_2/Gps_merge.h
st4ll1/dust3d
c1de02f7ddcfdacc730cc96740f8073f87e7818c
[ "MIT" ]
null
null
null
thirdparty/cgal/CGAL-4.13/include/CGAL/Boolean_set_operations_2/Gps_merge.h
st4ll1/dust3d
c1de02f7ddcfdacc730cc96740f8073f87e7818c
[ "MIT" ]
null
null
null
thirdparty/cgal/CGAL-4.13/include/CGAL/Boolean_set_operations_2/Gps_merge.h
st4ll1/dust3d
c1de02f7ddcfdacc730cc96740f8073f87e7818c
[ "MIT" ]
null
null
null
// Copyright (c) 2005 Tel-Aviv University (Israel). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // 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. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // SPDX-License-Identifier: GPL-3.0+ // // Author(s) : Baruch Zukerman <baruchzu@post.tau.ac.il> #ifndef CGAL_GPS_MERGE_H #define CGAL_GPS_MERGE_H #include <CGAL/license/Boolean_set_operations_2.h> #include <CGAL/Boolean_set_operations_2/Gps_agg_op.h> #include <CGAL/Boolean_set_operations_2/Gps_bfs_join_visitor.h> #include <CGAL/Boolean_set_operations_2/Gps_bfs_xor_visitor.h> #include <CGAL/Boolean_set_operations_2/Gps_bfs_intersection_visitor.h> #include <vector> namespace CGAL { /*! \file Gps_merge.h \brief This file contains classes that are responsible for merging two sets of polygons in the divide-and-conquer algorithm. The file contains 3 mergers: Join_merge, Intersection_merge and Xor_merge. Join_merge is used when we want to merge the two sets, Intersection_merge is used for intersection, and Xor_merge is used for symmetric difference. */ //! Base_merge /*! Base_merge is the base class for all merger classes. All merges used BFS algorithm with a different visitor when discovering a new face. */ template <class Arrangement_, class Visitor_> class Base_merge { typedef Arrangement_ Arrangement_2; typedef Visitor_ Visitor; typedef typename Arrangement_2::Vertex_handle Vertex_handle; typedef std::pair<Arrangement_2 *, std::vector<Vertex_handle> *> Arr_entry; public: void operator()(unsigned int i, unsigned int j, unsigned int jump, std::vector<Arr_entry>& arr_vec) { if(i==j) return; const typename Arrangement_2::Geometry_traits_2 * tr = arr_vec[i].first->geometry_traits(); Arrangement_2 *res = new Arrangement_2(tr); std::vector<Vertex_handle> *verts = new std::vector<Vertex_handle>; Gps_agg_op<Arrangement_2, Visitor> agg_op(*res, *verts, *(res->traits_adaptor())); agg_op.sweep_arrangements(i, j, jump, arr_vec); for(unsigned int count=i; count<=j; count+=jump) { delete (arr_vec[count].first); delete (arr_vec[count].second); } arr_vec[i].first = res; arr_vec[i].second = verts; } }; //! Join_merge /*! Join_merge is used to join two sets of polygons together in the D&C algorithm. It is a base merge with a visitor that joins faces. */ template <class Arrangement_> class Join_merge : public Base_merge<Arrangement_, Gps_bfs_join_visitor<Arrangement_> > {}; //! Intersection_merge /*! Intersection_merge is used to merge two sets of polygons creating their intersection. */ template <class Arrangement_> class Intersection_merge : public Base_merge<Arrangement_, Gps_bfs_intersection_visitor<Arrangement_> > {}; //! Xor_merge /*! Xor_merge is used to merge two sets of polygons creating their symmetric difference. */ template <class Arrangement_> class Xor_merge : public Base_merge<Arrangement_, Gps_bfs_xor_visitor<Arrangement_> > { }; } //namespace CGAL #endif
31.123967
79
0.695964
[ "vector" ]
a2c8f980d9e36cbcb8331d94f414619e31ea559e
3,401
h
C
tensorflow/core/kernels/conv_ops_gpu.h
smrutiranjans/tensorflow
d8e8b872eae63188c75046d5bb068e03a81b3f85
[ "Apache-2.0" ]
7
2016-04-24T19:06:10.000Z
2018-10-03T16:33:51.000Z
tensorflow/core/kernels/conv_ops_gpu.h
smrutiranjans/tensorflow
d8e8b872eae63188c75046d5bb068e03a81b3f85
[ "Apache-2.0" ]
1
2016-10-19T02:43:04.000Z
2016-10-31T14:53:06.000Z
tensorflow/core/kernels/conv_ops_gpu.h
smrutiranjans/tensorflow
d8e8b872eae63188c75046d5bb068e03a81b3f85
[ "Apache-2.0" ]
8
2016-10-23T00:50:02.000Z
2019-04-21T11:11:57.000Z
/* Copyright 2015 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. ==============================================================================*/ #ifndef TENSORFLOW_CORE_KERNELS_CONV_OPS_GPU_H_ #define TENSORFLOW_CORE_KERNELS_CONV_OPS_GPU_H_ #if GOOGLE_CUDA #include "tensorflow/core/platform/stream_executor.h" namespace tensorflow { // TODO(zhengxq): move this to gpu_util.h. The use of such wrappers is wide // spread. template <typename T> perftools::gputools::DeviceMemory<T> AsDeviceMemory(const T* cuda_memory, uint64 size) { perftools::gputools::DeviceMemoryBase wrapped(const_cast<T*>(cuda_memory), size * sizeof(T)); perftools::gputools::DeviceMemory<T> typed(wrapped); return typed; } // Get the Cudnn workspace limit from the environment variable, which is in MB. // Return the workspace memory limit in bytes. If no value is set, return the // default value. int64 GetCudnnWorkspaceLimit(const string& envvar_in_mb, int64 default_value_in_bytes); // A class to provide scratch-space allocator for Stream-Executor Cudnn // callback. TensorFlow is responsible for releasing the temporary buffers after // the kernel finishes. class CudnnScratchAllocator : public perftools::gputools::ScratchAllocator { public: virtual ~CudnnScratchAllocator() {} CudnnScratchAllocator(int64 memory_limit, OpKernelContext* context) : memory_limit_(memory_limit), context_(context) {} virtual int64 GetMemoryLimitInBytes( perftools::gputools::Stream* stream) override { return memory_limit_; } virtual perftools::gputools::port::StatusOr< perftools::gputools::DeviceMemory<uint8>> AllocateBytes(perftools::gputools::Stream* stream, int64 byte_size) override { Tensor temporary_memory; AllocationAttributes allocation_attr; allocation_attr.no_retry_on_failure = true; Status allocation_status(context_->allocate_temp( DT_UINT8, TensorShape({byte_size}), &temporary_memory, AllocatorAttributes(), allocation_attr)); if (!allocation_status.ok()) { return perftools::gputools::port::StatusOr< perftools::gputools::DeviceMemory<uint8>>( AsDeviceMemory<uint8>(nullptr, 0)); } // Hold the reference of the allocated tensors until the end of the // allocator. allocated_tensors_.push_back(temporary_memory); return perftools::gputools::port::StatusOr< perftools::gputools::DeviceMemory<uint8>>( AsDeviceMemory(temporary_memory.flat<uint8>().data(), temporary_memory.flat<uint8>().size())); } private: int64 memory_limit_; OpKernelContext* context_; std::vector<Tensor> allocated_tensors_; }; } // namespace tensorflow #endif // GOOGLE_CUDA #endif // TENSORFLOW_CORE_KERNELS_CONV_OPS_GPU_H_
38.213483
80
0.709203
[ "vector" ]
a2cfedcd9ccff905d8be2abed22ecbde7da71c39
2,358
h
C
LargeBarrelAnalysis/UniversalFileLoader.h
kdulski/j-pet-framework-examples
ab2592a2c6cf8f901f5732f8878b750b9a7b6a49
[ "Apache-2.0" ]
2
2017-12-12T16:51:06.000Z
2021-11-04T08:01:34.000Z
LargeBarrelAnalysis/UniversalFileLoader.h
kdulski/j-pet-framework-examples
ab2592a2c6cf8f901f5732f8878b750b9a7b6a49
[ "Apache-2.0" ]
89
2016-07-23T22:12:09.000Z
2022-01-19T13:21:29.000Z
LargeBarrelAnalysis/UniversalFileLoader.h
kdulski/j-pet-framework-examples
ab2592a2c6cf8f901f5732f8878b750b9a7b6a49
[ "Apache-2.0" ]
34
2016-06-18T17:47:35.000Z
2021-04-27T12:18:00.000Z
/** * @copyright Copyright 2018 The J-PET Framework Authors. 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 find a copy of the License in the LICENCE file. * * 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 UNIVERSALFILELOADER_H #define UNIVERSALFILELOADER_H /** * @file UniversalFileLoader.h * @brief Tools for loading any ASCII file with cnfiguration parameters * * Set of tools allowing readout of set of configuration parameters form ASCII file * that is in standard format of Layer-Slot-Side-Threshold * Contains of structure of records that has to be initialized by user, * and methods of reading and validating constatns. */ #include <map> #include <string> #include "JPetPM/JPetPM.h" /** * POD structure, allowed values for fields (-1 corresponds to not set) * Layer: 1-3 * Slot: 1-96 * Side: JPetPM::SideA or JPetPM::SideB * Threshold nubmer: 1-4 */ struct ConfRecord { int layer; int slot; JPetPM::Side side; int thresholdNumber; std::vector<double> parameters; }; class UniversalFileLoader { public: typedef std::map<unsigned int, std::vector<double>> TOMBChToParameter; typedef std::map<std::tuple<int, int, JPetPM::Side, int>, int> TOMBChMap; static double getConfigurationParameter(const TOMBChToParameter& confParameters, const unsigned int channel); static TOMBChToParameter loadConfigurationParameters(const std::string& confFile, const TOMBChMap& tombMap); static TOMBChToParameter generateConfigurationParameters(const std::vector<ConfRecord>& confRecords, const TOMBChMap& tombMap); static std::vector<ConfRecord> readConfigurationParametersFromFile(const std::string& confFile); static bool fillConfRecord(const std::string& input, ConfRecord& outRecord); static bool areConfRecordsValid(const std::vector<ConfRecord>& records); private: UniversalFileLoader(const UniversalFileLoader&); void operator=(const UniversalFileLoader&); }; #endif /* !UNIVERSALFILELOADER_H */
37.428571
130
0.763783
[ "vector" ]
a2d2699aec799e8fe7c2b7a9d65f7b7e4f3e3e8d
3,082
h
C
Ligne_transitique_MONTRAC/V-Rep/programming/v_repExtUrdf/urdfdialog.h
keke02/Fast-reconfiguration-of-robotic-production-systems
44ffe14b8a4a4798b559eede9b3766acb55f294e
[ "CC0-1.0" ]
null
null
null
Ligne_transitique_MONTRAC/V-Rep/programming/v_repExtUrdf/urdfdialog.h
keke02/Fast-reconfiguration-of-robotic-production-systems
44ffe14b8a4a4798b559eede9b3766acb55f294e
[ "CC0-1.0" ]
null
null
null
Ligne_transitique_MONTRAC/V-Rep/programming/v_repExtUrdf/urdfdialog.h
keke02/Fast-reconfiguration-of-robotic-production-systems
44ffe14b8a4a4798b559eede9b3766acb55f294e
[ "CC0-1.0" ]
null
null
null
// This file is part of the URDF PLUGIN for V-REP // // Copyright 2006-2015 Coppelia Robotics GmbH. All rights reserved. // marc@coppeliarobotics.com // www.coppeliarobotics.com // // A big thanks to Ignacio Tartavull and Martin Pecka for their precious help! // // The URDF PLUGIN is licensed under the terms of GNU GPL: // // ------------------------------------------------------------------- // The URDF PLUGIN 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. // // THE URDF PLUGIN IS DISTRIBUTED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED // WARRANTY. THE USER WILL USE IT AT HIS/HER OWN RISK. THE ORIGINAL // AUTHORS AND COPPELIA ROBOTICS GMBH WILL NOT BE LIABLE FOR DATA LOSS, // DAMAGES, LOSS OF PROFITS OR ANY OTHER KIND OF LOSS WHILE USING OR // MISUSING THIS SOFTWARE. // // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with the URDF PLUGIN. If not, see <http://www.gnu.org/licenses/>. // ------------------------------------------------------------------- // // This file was automatically created for V-REP release V3.2.3 rev4 on December 21st 2015 // The URDF plugin is courtesy of Ignacio Tartavull and Martin Pecka. #ifndef URDFDIALOG_H #define URDFDIALOG_H #include <QDialog> struct SSimulationThreadCommand { int cmdId; std::vector<bool> boolParams; std::vector<int> intParams; std::vector<float> floatParams; std::vector<std::string> stringParams; }; enum { MAKE_VISIBLE_CMD=0, IMPORT_CMD, WARNING_MSG_CMD, }; namespace Ui { class CUrdfDialog; } class CUrdfDialog : public QDialog { Q_OBJECT public: explicit CUrdfDialog(QWidget *parent = 0); ~CUrdfDialog(); void refresh(); void makeVisible(bool visible); bool getVisible(); int dialogMenuItemHandle; void reject(); void addCommand(SSimulationThreadCommand cmd); void handleCommands(); void setSimulationStopped(bool stopped); private: std::vector<SSimulationThreadCommand> _simulThreadCommands; static bool hideCollisionLinks; static bool hideJoints; static bool convexDecompose; static bool showConvexDecompositionDlg; static bool createVisualIfNone; static bool centerModel; static bool prepareModel; static bool noSelfCollision; static bool positionCtrl; static bool simulationStopped; private slots: void on_qqImport_clicked(); void on_qqCollisionLinksHidden_clicked(); void on_qqJointsHidden_clicked(); void on_qqConvexDecompose_clicked(); void on_qqConvexDecomposeDlg_clicked(); void on_qqCreateVisualLinks_clicked(); void on_qqCenterModel_clicked(); void on_qqModelDefinition_clicked(); void on_qqAlternateMasks_clicked(); void on_qqPositionCtrl_clicked(); private: Ui::CUrdfDialog *ui; }; #endif // URDFDIALOG_H
26.118644
91
0.695328
[ "vector" ]
a2d28fde9738d67bd3d27bedef66517d8cf7db78
7,818
h
C
libraries/density/obdme_io.h
nd-nuclear-theory/shell
7458fbd10416f6e1550a3d669cd2a10fc9c49e0c
[ "MIT" ]
5
2019-11-15T01:09:24.000Z
2021-02-02T20:23:34.000Z
libraries/density/obdme_io.h
nd-nuclear-theory/shell
7458fbd10416f6e1550a3d669cd2a10fc9c49e0c
[ "MIT" ]
8
2019-06-03T19:53:54.000Z
2021-06-14T00:40:04.000Z
libraries/density/obdme_io.h
nd-nuclear-theory/shell
7458fbd10416f6e1550a3d669cd2a10fc9c49e0c
[ "MIT" ]
null
null
null
/************************************************************//** @file obdme_io.h Defines I/O classes for one-body density matrix element access. Language: C++11 Patrick J. Fasano University of Notre Dame + 11/22/16 (pjf): Created, based on radial_io. + 1/11/17 (pjf): Implemented MFDn v15 OBDME input. - InOBDMEStreamMulti parses info files at construction time. - The same reader can parse multiple data files. - Quantum numbers stored in data files are currently ignored. + 10/16/17 (pjf): - Define reader with g0 and Tz0. - TODO: check these values against those stored in data files. + 07/25/17 (pjf): - Add support for version 1600 OBDMEs from postprocessor. - Reorganize class structure so that multi-file OBDME formats (v1405/v1500) and single-file formats (v1600) share a common storage scheme. - Store all OBDMEs for a single data file. + 04/03/19 (pjf): - Use mcutils::GetLine for input. - Modify reading from version 1520 OBDME files (formerly known as 1600). - Convert to Rose convention on input, for consistency with other one-body operators. + 05/09/19 (pjf): Use std::size_t for basis indices and sizes. + 05/28/19 (pjf): + Rename K->j0, max_K->j0_max, and min_K->j0_min. + Deprecate max_K() and min_K() accessors. + Modify access specifications and provide accessors for matrices and sectors as a function of j0. + Fix indexing problems for j0_min != 0. + 08/17/19 (pjf): Fix conversion to Rose convention. ****************************************************************/ #ifndef OBDME_IO_H_ #define OBDME_IO_H_ #include <cstdlib> #include <iostream> #include <fstream> #include <string> #include "eigen3/Eigen/Core" #include "basis/operator.h" #include "basis/nlj_orbital.h" namespace shell { /** * Base class for unified one-body density matrix element retrieval */ class InOBDMEStream { public: InOBDMEStream() = default; void GetMultipole( int j0, basis::OrbitalSectorsLJPN& sectors, basis::OperatorBlocks<double>& matrices ) const; int j0_min() const { return j0_min_; } int j0_max() const { return j0_max_; } int g0() const { return g0_; } int Tz0() const { return Tz0_; } DEPRECATED("use j0_min() instead") inline int min_K() const { return j0_min_; } DEPRECATED("use j0_max() instead") inline int max_K() const { return j0_max_; } // indexing accessors const basis::OrbitalSpaceLJPN& orbital_space() const { return orbital_space_; } const basis::OrbitalSectorsLJPN& sectors(int j0) const { assert((j0 >= j0_min()) && (j0 <= j0_max())); return sectors_.at(j0-j0_min()); } const basis::OperatorBlocks<double>& matrices(int j0) const { assert((j0 >= j0_min()) && (j0 <= j0_max())); return matrices_.at(j0-j0_min()); } protected: InOBDMEStream( const basis::OrbitalSpaceLJPN& orbital_space, int g0 = 0, int Tz0 = 0 ) : orbital_space_(orbital_space), g0_(g0), Tz0_(Tz0) {}; // allocate and zero indexing and matrices void InitStorage(); // indexing information basis::OrbitalSpaceLJPN orbital_space_; int g0_, Tz0_; int j0_min_, j0_max_; // indexing accessors basis::OrbitalSectorsLJPN& sectors(int j0) { assert((j0 >= j0_min()) && (j0 <= j0_max())); return sectors_.at(j0-j0_min()); } basis::OperatorBlocks<double>& matrices(int j0) { assert((j0 >= j0_min()) && (j0 <= j0_max())); return matrices_.at(j0-j0_min()); } private: // matrix element storage std::vector<basis::OrbitalSectorsLJPN> sectors_; std::vector<basis::OperatorBlocks<double>> matrices_; }; /** * Class for reading old-style, multi-file one-body density matrix elements */ class InOBDMEStreamMulti : public InOBDMEStream { public: /** * Default constructor -- provided since required for certain * purposes by STL container classes (e.g., std::vector::resize) */ InOBDMEStreamMulti() = default; InOBDMEStreamMulti( const std::string& info_filename, const std::string& data_filename, const basis::OrbitalSpaceLJPN& orbital_space, int g0 = 0, int Tz0 = 0 ); // Construct a reader by parsing an info file. // destructor ~InOBDMEStreamMulti() { if (info_stream_ptr_) delete info_stream_ptr_; } // info file data structure struct InfoLine { basis::FullOrbitalLabels bra_labels; basis::FullOrbitalLabels ket_labels; int multipole; InfoLine(basis::FullOrbitalLabels bra, basis::FullOrbitalLabels ket, int mp) : bra_labels(bra), ket_labels(ket), multipole(mp) {} }; // accessors const std::vector<InfoLine>& obdme_info() const { return obdme_info_; } private: // read info header void ReadInfoHeader(); void ReadInfoHeader1405(); void ReadInfoHeader1500(); // read info void ReadInfo(); void ReadInfo1405(); void ReadInfo1500(); // read data header void ReadDataHeader(std::ifstream& data_stream, int& data_line_count) const; // void ReadDataHeader1405(std::ifstream& data_stream, int& data_line_count) const; // void ReadDataHeader1500(std::ifstream& data_stream, int& data_line_count) const; // read data void ReadData(); // filename std::string info_filename_; std::string data_filename_; // info file stream std::ifstream& info_stream() const {return *info_stream_ptr_;} // alias for convenience std::ifstream* info_stream_ptr_; int line_count_; // info file header int version_number_; std::size_t num_proton_obdme_; std::size_t num_neutron_obdme_; // info container std::vector<InfoLine> obdme_info_; }; /** * Class for reading new-style, single-file one-body density matrix elements */ class InOBDMEStreamSingle : public InOBDMEStream { public: /** * Default constructor -- provided since required for certain * purposes by STL container classes (e.g., std::vector::resize) */ InOBDMEStreamSingle() = default; InOBDMEStreamSingle( const std::string& filename, const basis::OrbitalSpaceLJPN& orbital_space ); // Construct a reader by parsing an info file. // accessors int Z_bra() const { return Z_bra_; } int N_bra() const { return N_bra_; } HalfInt J_bra() const { return HalfInt(TwiceJ_bra_, 2); } HalfInt M_bra() const { return HalfInt(TwiceM_bra_, 2); } HalfInt Tz_bra() const { return HalfInt(Z_bra_-N_bra_, 2); } int g_bra() const { return g_bra_; } int n_bra() const { return n_bra_; } double T_bra() const { return T_bra_; } double E_bra() const { return E_bra_; } int Z_ket() const { return Z_ket_; } int N_ket() const { return N_ket_; } HalfInt J_ket() const { return HalfInt(TwiceJ_ket_, 2); } HalfInt M_ket() const { return HalfInt(TwiceM_ket_, 2); } HalfInt Tz_ket() const { return HalfInt(Z_ket_-N_ket_, 2); } int g_ket() const { return g_ket_; } int n_ket() const { return n_ket_; } double T_ket() const { return T_ket_; } double E_ket() const { return E_ket_; } // destructor ~InOBDMEStreamSingle() { if (stream_ptr_) delete stream_ptr_; } private: // read info header void ReadHeader(); void ReadHeader1520(); // read data void ReadData(); void ReadData1520(); // filename std::string filename_; // file stream std::ifstream& stream() const {return *stream_ptr_;} // alias for convenience std::ifstream* stream_ptr_; int line_count_; // file header int version_number_; int Z_bra_, N_bra_, seq_bra_, TwiceJ_bra_, TwiceM_bra_, g_bra_, n_bra_; float T_bra_, E_bra_; int Z_ket_, N_ket_, seq_ket_, TwiceJ_ket_, TwiceM_ket_, g_ket_, n_ket_; float T_ket_, E_ket_; std::size_t num_proton_obdme_; std::size_t num_neutron_obdme_; basis::OrbitalPNList orbital_list_; }; }; // namespace shell #endif // RADIAL_IO_H_
28.429091
90
0.67626
[ "vector" ]
a2dbb80b09a9fc716a52b8ebaf1357c85d2ab65e
6,333
h
C
targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_bank_internal.h
pradeep-gr/mbed-os5-onsemi
576d096f2d9933c39b8a220f486e9756d89173f2
[ "Apache-2.0" ]
22
2019-05-03T03:39:09.000Z
2022-02-26T17:14:15.000Z
targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_bank_internal.h
pradeep-gr/mbed-os5-onsemi
576d096f2d9933c39b8a220f486e9756d89173f2
[ "Apache-2.0" ]
28
2020-05-10T02:00:25.000Z
2021-12-20T07:27:34.000Z
targets/TARGET_NORDIC/TARGET_NRF5/TARGET_SDK11/libraries/bootloader_dfu/dfu_bank_internal.h
pradeep-gr/mbed-os5-onsemi
576d096f2d9933c39b8a220f486e9756d89173f2
[ "Apache-2.0" ]
11
2020-02-05T07:35:39.000Z
2021-08-19T08:20:53.000Z
/* * Copyright (c) 2014 Nordic Semiconductor ASA * 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, except as embedded into a Nordic Semiconductor ASA * integrated circuit in a product or a software update for such product, 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 Nordic Semiconductor ASA nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary or object form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * 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 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. * */ /**@file * * @defgroup dfu_bank_internal Device Firmware Update internal header for bank handling in DFU. * @{ * * @brief Device Firmware Update Bank handling module interface. * * @details This header is intended for shared definition and functions between single and dual bank * implementations used for DFU support. It is not supposed to be used for external access * to the DFU module. * */ #ifndef DFU_BANK_INTERNAL_H__ #define DFU_BANK_INTERNAL_H__ #include <dfu_types.h> /**@brief States of the DFU state machine. */ typedef enum { DFU_STATE_INIT_ERROR, /**< State for: dfu_init(...) error. */ DFU_STATE_IDLE, /**< State for: idle. */ DFU_STATE_PREPARING, /**< State for: preparing, indicates that the flash is being erased and no data packets can be processed. */ DFU_STATE_RDY, /**< State for: ready. */ DFU_STATE_RX_INIT_PKT, /**< State for: receiving initialization packet. */ DFU_STATE_RX_DATA_PKT, /**< State for: receiving data packet. */ DFU_STATE_VALIDATE, /**< State for: validate. */ DFU_STATE_WAIT_4_ACTIVATE /**< State for: waiting for dfu_image_activate(). */ } dfu_state_t; #define APP_TIMER_PRESCALER 0 /**< Value of the RTC1 PRESCALER register. */ #define DFU_TIMEOUT_INTERVAL APP_TIMER_TICKS(120000, APP_TIMER_PRESCALER) /**< DFU timeout interval in units of timer ticks. */ #define IS_UPDATING_SD(START_PKT) ((START_PKT).dfu_update_mode & DFU_UPDATE_SD) /**< Macro for determining if a SoftDevice update is ongoing. */ #define IS_UPDATING_BL(START_PKT) ((START_PKT).dfu_update_mode & DFU_UPDATE_BL) /**< Macro for determining if a Bootloader update is ongoing. */ #define IS_UPDATING_APP(START_PKT) ((START_PKT).dfu_update_mode & DFU_UPDATE_APP) /**< Macro for determining if a Application update is ongoing. */ #define IMAGE_WRITE_IN_PROGRESS() (m_data_received > 0) /**< Macro for determining if an image write is in progress. */ #define IS_WORD_SIZED(SIZE) ((SIZE & (sizeof(uint32_t) - 1)) == 0) /**< Macro for checking that the provided is word sized. */ /**@cond NO_DOXYGEN */ static uint32_t m_data_received; /**< Amount of received data. */ /**@endcond */ /**@brief Type definition of function used for preparing of the bank before receiving of a * software image. * * @param[in] image_size Size of software image being received. */ typedef void (*dfu_bank_prepare_t)(uint32_t image_size); /**@brief Type definition of function used for handling clear complete of the bank before * receiving of a software image. */ typedef void (*dfu_bank_cleared_t)(void); /**@brief Type definition of function used for activating of the software image received. * * @return NRF_SUCCESS If the image has been successfully activated any other NRF_ERROR code in * case of a failure. */ typedef uint32_t (*dfu_bank_activate_t)(void); /**@brief Structure for holding of function pointers for needed prepare and activate procedure for * the requested update procedure. */ typedef struct { dfu_bank_prepare_t prepare; /**< Function pointer to the prepare function called on start of update procedure. */ dfu_bank_cleared_t cleared; /**< Function pointer to the cleared function called after prepare function completes. */ dfu_bank_activate_t activate; /**< Function pointer to the activate function called on finalizing the update procedure. */ } dfu_bank_func_t; #endif // DFU_BANK_INTERNAL_H__ /** @} */
55.069565
192
0.64235
[ "object" ]
a2dd28cc6605148b6097bd44c89302dd782872ae
6,569
h
C
ui/base/dragdrop/os_exchange_data_provider_win.h
JoKaWare/WTL-DUI
89fd6f4ed7e6a4ce85f9af29c40de0d9a85ca8b2
[ "BSD-3-Clause" ]
19
2015-03-30T09:49:58.000Z
2020-01-17T20:05:12.000Z
ui/base/dragdrop/os_exchange_data_provider_win.h
jjzhang166/WTL-DUI
89fd6f4ed7e6a4ce85f9af29c40de0d9a85ca8b2
[ "BSD-3-Clause" ]
1
2015-12-31T06:08:27.000Z
2015-12-31T06:08:27.000Z
ui/base/dragdrop/os_exchange_data_provider_win.h
jjzhang166/WTL-DUI
89fd6f4ed7e6a4ce85f9af29c40de0d9a85ca8b2
[ "BSD-3-Clause" ]
11
2015-06-01T06:18:03.000Z
2020-05-10T07:18:53.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_WIN_H_ #define UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_WIN_H_ #pragma once #include <objidl.h> #include <shlobj.h> #include <string> #include "base/win/scoped_comptr.h" #include "ui/base/dragdrop/os_exchange_data.h" #include "ui/base/ui_export.h" namespace ui { class DataObjectImpl : public DownloadFileObserver, public IDataObject, public IAsyncOperation { public: class Observer { public: virtual void OnWaitForData() = 0; virtual void OnDataObjectDisposed() = 0; protected: virtual ~Observer() { } }; DataObjectImpl(); // Accessors. void set_observer(Observer* observer) { observer_ = observer; } // Number of known formats. size_t size() const { return contents_.size(); } // DownloadFileObserver implementation: virtual void OnDownloadCompleted(const FilePath& file_path); virtual void OnDownloadAborted(); // IDataObject implementation: HRESULT __stdcall GetData(FORMATETC* format_etc, STGMEDIUM* medium); HRESULT __stdcall GetDataHere(FORMATETC* format_etc, STGMEDIUM* medium); HRESULT __stdcall QueryGetData(FORMATETC* format_etc); HRESULT __stdcall GetCanonicalFormatEtc( FORMATETC* format_etc, FORMATETC* result); HRESULT __stdcall SetData( FORMATETC* format_etc, STGMEDIUM* medium, BOOL should_release); HRESULT __stdcall EnumFormatEtc( DWORD direction, IEnumFORMATETC** enumerator); HRESULT __stdcall DAdvise(FORMATETC* format_etc, DWORD advf, IAdviseSink* sink, DWORD* connection); HRESULT __stdcall DUnadvise(DWORD connection); HRESULT __stdcall EnumDAdvise(IEnumSTATDATA** enumerator); // IAsyncOperation implementation: HRESULT __stdcall EndOperation( HRESULT result, IBindCtx* reserved, DWORD effects); HRESULT __stdcall GetAsyncMode(BOOL* is_op_async); HRESULT __stdcall InOperation(BOOL* in_async_op); HRESULT __stdcall SetAsyncMode(BOOL do_op_async); HRESULT __stdcall StartOperation(IBindCtx* reserved); // IUnknown implementation: HRESULT __stdcall QueryInterface(const IID& iid, void** object); ULONG __stdcall AddRef(); ULONG __stdcall Release(); private: // FormatEtcEnumerator only likes us for our StoredDataMap typedef. friend class FormatEtcEnumerator; friend class OSExchangeDataProviderWin; virtual ~DataObjectImpl(); void StopDownloads(); // Removes from contents_ the first data that matches |format|. void RemoveData(const FORMATETC& format); // Our internal representation of stored data & type info. struct StoredDataInfo { FORMATETC format_etc; STGMEDIUM* medium; bool owns_medium; bool in_delay_rendering; scoped_refptr<DownloadFileProvider> downloader; StoredDataInfo(CLIPFORMAT cf, STGMEDIUM* medium) : medium(medium), owns_medium(true), in_delay_rendering(false) { format_etc.cfFormat = cf; format_etc.dwAspect = DVASPECT_CONTENT; format_etc.lindex = -1; format_etc.ptd = NULL; format_etc.tymed = medium ? medium->tymed : TYMED_HGLOBAL; } StoredDataInfo(FORMATETC* format_etc, STGMEDIUM* medium) : format_etc(*format_etc), medium(medium), owns_medium(true), in_delay_rendering(false) { } ~StoredDataInfo() { if (owns_medium) { ReleaseStgMedium(medium); delete medium; } if (downloader.get()) downloader->Stop(); } }; typedef std::vector<StoredDataInfo*> StoredData; StoredData contents_; base::win::ScopedComPtr<IDataObject> source_object_; bool is_aborting_; bool in_async_mode_; bool async_operation_started_; Observer* observer_; }; class UI_EXPORT OSExchangeDataProviderWin : public OSExchangeData::Provider { public: // Returns true if source has plain text that is a valid url. static bool HasPlainTextURL(IDataObject* source); // Returns true if source has plain text that is a valid URL and sets url to // that url. // static bool GetPlainTextURL(IDataObject* source, GURL* url); static DataObjectImpl* GetDataObjectImpl(const OSExchangeData& data); static IDataObject* GetIDataObject(const OSExchangeData& data); static IAsyncOperation* GetIAsyncOperation(const OSExchangeData& data); explicit OSExchangeDataProviderWin(IDataObject* source); OSExchangeDataProviderWin(); virtual ~OSExchangeDataProviderWin(); IDataObject* data_object() const { return data_.get(); } IAsyncOperation* async_operation() const { return data_.get(); } // OSExchangeData::Provider methods. virtual void SetString(const string16& data); // virtual void SetURL(const GURL& url, const string16& title); virtual void SetFilename(const FilePath& path); virtual void SetFilenames( const std::vector<OSExchangeData::FileInfo>& filenames) { NOTREACHED(); } virtual void SetPickledData(OSExchangeData::CustomFormat format, const Pickle& data); virtual void SetFileContents(const FilePath& filename, const std::string& file_contents); // virtual void SetHtml(const string16& html, const GURL& base_url); virtual bool GetString(string16* data) const; // virtual bool GetURLAndTitle(GURL* url, string16* title) const; virtual bool GetFilename(FilePath* path) const; virtual bool GetFilenames( std::vector<OSExchangeData::FileInfo>* filenames) const { NOTREACHED(); return false; } virtual bool GetPickledData(OSExchangeData::CustomFormat format, Pickle* data) const; virtual bool GetFileContents(FilePath* filename, std::string* file_contents) const; // virtual bool GetHtml(string16* html, GURL* base_url) const; virtual bool HasString() const; virtual bool HasURL() const; virtual bool HasFile() const; virtual bool HasFileContents() const; virtual bool HasHtml() const; virtual bool HasCustomFormat(OSExchangeData::CustomFormat format) const; virtual void SetDownloadFileInfo( const OSExchangeData::DownloadFileInfo& download_info); private: scoped_refptr<DataObjectImpl> data_; base::win::ScopedComPtr<IDataObject> source_object_; DISALLOW_COPY_AND_ASSIGN(OSExchangeDataProviderWin); }; } // namespace ui #endif // UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_WIN_H_
33.345178
78
0.724616
[ "object", "vector" ]
a2df1846df81e06c7dccd6f2e5529869eb1c0356
30,801
h
C
src/jac_eqs.h
vicrucann/Kmat-virtual
2bf4557b4369e1b24b1af8043dd7eed56c8a77ba
[ "BSD-3-Clause" ]
6
2016-10-18T02:17:55.000Z
2021-12-30T07:32:16.000Z
src/jac_eqs.h
vicrucann/Kmat-virtual
2bf4557b4369e1b24b1af8043dd7eed56c8a77ba
[ "BSD-3-Clause" ]
null
null
null
src/jac_eqs.h
vicrucann/Kmat-virtual
2bf4557b4369e1b24b1af8043dd7eed56c8a77ba
[ "BSD-3-Clause" ]
1
2017-04-01T22:56:08.000Z
2017-04-01T22:56:08.000Z
/* Jacobian formulas Copyright (C) 2014 Victoria Rudakova <vicrucann@gmail.com> 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, either version 3 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, see <http://www.gnu.org/licenses/>. */ #ifndef JAC_EQS_H #define JAC_EQS_H #include <math.h> #include <stdio.h> template <typename T> T Power(T base, T pow){return std::pow(base, pow);} template <typename T> T Sqrt(T exp){return std::sqrt(exp);} // jacobian formulas for H^{-1} template <typename T> void jac_inv_equations(const vector<T> &P, const matrix<T> &s, T u, T v, T &dEdh1, T &dEdh2, T &dEdh3, T &dEdh4, T &dEdh5, T &dEdh6, T &dEdh7, T &dEdh8, T &dEdh9) { T h1 = P[0], h2 = P[1], h3 = P[2]; T h4 = P[3], h5 = P[4], h6 = P[5]; T h7 = P[6], h8 = P[7], h9 = P[8]; T a = s(0,2), b = s(1,2), f = s(2,2); dEdh1 = (2*(-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3 + a*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) + ((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(-((h2 + a*h8)*(h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)) - (h2 + a*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8)) + (2*h1 + 2*a*h7)*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))* (h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/Power<T>(-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)* (h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) +(h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))* (h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)),2))*(-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))* (h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/(-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)* (h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) +(h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))* (h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u) + 2*(-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3 + a*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) + ((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(-((h2 + a*h8)*(h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)) - (h2 + a*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8)) + (2*h1 + 2*a*h7)*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))* (h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/Power<T>(-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)* (h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))* (h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)),2) - ((-h2 - a*h8)*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))))* (-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v))/ (2.*Sqrt<T>(Power<T>(-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u,2) + Power<T>(-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v,2))); dEdh2 = (2*(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))* ((h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(2*h2 + 2*a*h8) - (h1 + a*h7)*(h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8) - (h1 + a*h7)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8)) )*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ Power<T>(-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)),2) - ((2*h2 + 2*a*h8)*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))))* (-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u) + 2*(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))* ((h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(2*h2 + 2*a*h8) - (h1 + a*h7)*(h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8) - (h1 + a*h7)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8)) )*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ Power<T>(-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)),2) - ((-h1 - a*h7)*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))))* (-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v))/ (2.*Sqrt<T>(Power<T>(-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u,2) + Power<T>(-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v,2))); dEdh3 = ((-2*(h1 + a*h7)*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))* (-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))) - (2*(h1 + a*h7)*(-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))* (-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))))/ (2.*Sqrt<T>(Power<T>(-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u,2) + Power<T>(-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v,2))); dEdh4 = (2*(-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h6 + b*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) + ((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))* (-((h5 + b*h8)*(h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)) - (h5 + b*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8)) + (2*h4 + 2*b*h7)*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ Power<T>(-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)),2))* (-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u) + 2*(-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h6 + b*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) + ((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))* (-((h5 + b*h8)*(h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)) - (h5 + b*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8)) + (2*h4 + 2*b*h7)*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ Power<T>(-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)),2) - ((-h5 - b*h8)*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))))* (-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v))/ (2.*Sqrt<T>(Power<T>(-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u,2) + Power<T>(-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v,2))); dEdh5 = (2*(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))* ((h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(2*h5 + 2*b*h8) - (h4 + b*h7)*(h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8) - (h4 + b*h7)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8)) )*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ Power<T>(-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)),2) - ((2*h5 + 2*b*h8)*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))))* (-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u) + 2*(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))* ((h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(2*h5 + 2*b*h8) - (h4 + b*h7)*(h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8) - (h4 + b*h7)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8)) )*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ Power<T>(-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)),2) - ((-h4 - b*h7)*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))))* (-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v))/ (2.*Sqrt<T>(Power<T>(-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u,2) + Power<T>(-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v,2))); dEdh6 = ((-2*(h4 + b*h7)*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))* (-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))) - (2*(h4 + b*h7)*(-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))* (-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))))/ (2.*Sqrt<T>(Power<T>(-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u,2) + Power<T>(-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v,2))); dEdh7 = (2*(-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(a*h3 + b*h6 + f*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) + ((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))* (-((a*h2 + b*h5 + f*h8)*(h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)) - (a*h2 + b*h5 + f*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8)) + (2*a*h1 + 2*b*h4 + 2*f*h7)*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))* (h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ Power<T>(-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)),2))* (-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u) + 2*(-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(a*h3 + b*h6 + f*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) + ((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))* (-((a*h2 + b*h5 + f*h8)*(h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)) - (a*h2 + b*h5 + f*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8)) + (2*a*h1 + 2*b*h4 + 2*f*h7)*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))* (h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ Power<T>(-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)),2) - ((-(a*h2) - b*h5 - f*h8)*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))))* (-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v))/ (2.*Sqrt<T>(Power<T>(-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u,2) + Power<T>(-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v,2))); dEdh8 = (2*(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))* ((h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(2*a*h2 + 2*b*h5 + 2*f*h8) - (a*h1 + b*h4 + f*h7)*(h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8) - (a*h1 + b*h4 + f*h7)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8)))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ Power<T>(-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)),2) - ((2*a*h2 + 2*b*h5 + 2*f*h8)*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))))* (-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u) + 2*(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))* ((h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(2*a*h2 + 2*b*h5 + 2*f*h8) - (a*h1 + b*h4 + f*h7)*(h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8) - (a*h1 + b*h4 + f*h7)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8)))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ Power<T>(-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)),2) - ((-(a*h1) - b*h4 - f*h7)*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))))* (-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v))/ (2.*Sqrt<T>(Power<T>(-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u,2) + Power<T>(-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v,2))); dEdh9 = ((-2*(a*h1 + b*h4 + f*h7)*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))* (-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))) - (2*(a*h1 + b*h4 + f*h7)*(-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))* (-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))))/ (2.*Sqrt<T>(Power<T>(-(((h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - u,2) + Power<T>(-(((-(h1*(h2 + a*h8)) - h4*(h5 + b*h8) - h7*(a*h2 + b*h5 + f*h8))*(h3*(h1 + a*h7) + h6*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h9))/ (-((h2*(h1 + a*h7) + h5*(h4 + b*h7) + (a*h1 + b*h4 + f*h7)*h8)*(h1*(h2 + a*h8) + h4*(h5 + b*h8) + h7*(a*h2 + b*h5 + f*h8))) + (h1*(h1 + a*h7) + h4*(h4 + b*h7) + h7*(a*h1 + b*h4 + f*h7))*(h2*(h2 + a*h8) + h5*(h5 + b*h8) + h8*(a*h2 + b*h5 + f*h8)))) - v,2))); } #endif
106.210345
154
0.401967
[ "vector" ]
313e8ed2c9959cd202cdbff89f1c9ae2ae9e9798
48,415
c
C
source/blender/blenkernel/intern/material.c
wycivil08/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
30
2015-01-29T14:06:05.000Z
2022-01-10T07:47:29.000Z
source/blender/blenkernel/intern/material.c
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
1
2017-02-20T20:57:48.000Z
2018-12-19T23:44:38.000Z
source/blender/blenkernel/intern/material.c
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
15
2015-04-23T02:38:36.000Z
2021-03-01T20:09:39.000Z
/* * $Id: material.c 40940 2011-10-11 23:08:17Z campbellbarton $ * * ***** BEGIN GPL LICENSE BLOCK ***** * * 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; 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. * All rights reserved. * * The Original Code is: all of this file. * * Contributor(s): none yet. * * ***** END GPL LICENSE BLOCK ***** */ /** \file blender/blenkernel/intern/material.c * \ingroup bke */ #include <string.h> #include <math.h> #include <stddef.h> #include "MEM_guardedalloc.h" #include "DNA_curve_types.h" #include "DNA_material_types.h" #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" #include "DNA_customdata_types.h" #include "DNA_ID.h" #include "DNA_meta_types.h" #include "DNA_node_types.h" #include "DNA_object_types.h" #include "DNA_scene_types.h" #include "BLI_math.h" #include "BLI_listbase.h" #include "BLI_utildefines.h" #include "BKE_animsys.h" #include "BKE_displist.h" #include "BKE_global.h" #include "BKE_icons.h" #include "BKE_image.h" #include "BKE_library.h" #include "BKE_main.h" #include "BKE_material.h" #include "BKE_mesh.h" #include "BKE_node.h" #include "BKE_curve.h" #include "GPU_material.h" /* used in UI and render */ Material defmaterial; /* called on startup, creator.c */ void init_def_material(void) { init_material(&defmaterial); } /* not material itself */ void free_material(Material *ma) { MTex *mtex; int a; for(a=0; a<MAX_MTEX; a++) { mtex= ma->mtex[a]; if(mtex && mtex->tex) mtex->tex->id.us--; if(mtex) MEM_freeN(mtex); } if(ma->ramp_col) MEM_freeN(ma->ramp_col); if(ma->ramp_spec) MEM_freeN(ma->ramp_spec); BKE_free_animdata((ID *)ma); if(ma->preview) BKE_previewimg_free(&ma->preview); BKE_icon_delete((struct ID*)ma); ma->id.icon_id = 0; /* is no lib link block, but material extension */ if(ma->nodetree) { ntreeFreeTree(ma->nodetree); MEM_freeN(ma->nodetree); } if(ma->gpumaterial.first) GPU_material_free(ma); } void init_material(Material *ma) { ma->r= ma->g= ma->b= ma->ref= 0.8; ma->specr= ma->specg= ma->specb= 1.0; ma->mirr= ma->mirg= ma->mirb= 1.0; ma->spectra= 1.0; ma->amb= 1.0; ma->alpha= 1.0; ma->spec= ma->hasize= 0.5; ma->har= 50; ma->starc= ma->ringc= 4; ma->linec= 12; ma->flarec= 1; ma->flaresize= ma->subsize= 1.0; ma->flareboost= 1; ma->seed2= 6; ma->friction= 0.5; ma->refrac= 4.0; ma->roughness= 0.5; ma->param[0]= 0.5; ma->param[1]= 0.1; ma->param[2]= 0.5; ma->param[3]= 0.1; ma->rms= 0.1; ma->darkness= 1.0; ma->strand_sta= ma->strand_end= 1.0f; ma->ang= 1.0; ma->ray_depth= 2; ma->ray_depth_tra= 2; ma->fresnel_mir= 0.0; ma->fresnel_tra= 0.0; ma->fresnel_tra_i= 1.25; ma->fresnel_mir_i= 1.25; ma->tx_limit= 0.0; ma->tx_falloff= 1.0; ma->shad_alpha= 1.0f; ma->gloss_mir = ma->gloss_tra= 1.0; ma->samp_gloss_mir = ma->samp_gloss_tra= 18; ma->adapt_thresh_mir = ma->adapt_thresh_tra = 0.005; ma->dist_mir = 0.0; ma->fadeto_mir = MA_RAYMIR_FADETOSKY; ma->rampfac_col= 1.0; ma->rampfac_spec= 1.0; ma->pr_lamp= 3; /* two lamps, is bits */ ma->pr_type= MA_SPHERE; ma->sss_radius[0]= 1.0f; ma->sss_radius[1]= 1.0f; ma->sss_radius[2]= 1.0f; ma->sss_col[0]= 1.0f; ma->sss_col[1]= 1.0f; ma->sss_col[2]= 1.0f; ma->sss_error= 0.05f; ma->sss_scale= 0.1f; ma->sss_ior= 1.3f; ma->sss_colfac= 1.0f; ma->sss_texfac= 0.0f; ma->sss_front= 1.0f; ma->sss_back= 1.0f; ma->vol.density = 1.0f; ma->vol.emission = 0.0f; ma->vol.scattering = 1.0f; ma->vol.reflection = 1.0f; ma->vol.transmission_col[0] = ma->vol.transmission_col[1] = ma->vol.transmission_col[2] = 1.0f; ma->vol.reflection_col[0] = ma->vol.reflection_col[1] = ma->vol.reflection_col[2] = 1.0f; ma->vol.emission_col[0] = ma->vol.emission_col[1] = ma->vol.emission_col[2] = 1.0f; ma->vol.density_scale = 1.0f; ma->vol.depth_cutoff = 0.01f; ma->vol.stepsize_type = MA_VOL_STEP_RANDOMIZED; ma->vol.stepsize = 0.2f; ma->vol.shade_type = MA_VOL_SHADE_SHADED; ma->vol.shadeflag |= MA_VOL_PRECACHESHADING; ma->vol.precache_resolution = 50; ma->vol.ms_spread = 0.2f; ma->vol.ms_diff = 1.f; ma->vol.ms_intensity = 1.f; ma->game.flag = GEMAT_BACKCULL; ma->game.alpha_blend=0; ma->game.face_orientation=0; ma->mode= MA_TRACEBLE|MA_SHADBUF|MA_SHADOW|MA_RAYBIAS|MA_TANGENT_STR|MA_ZTRANSP; ma->shade_flag= MA_APPROX_OCCLUSION; ma->preview = NULL; } Material *add_material(const char *name) { Material *ma; ma= alloc_libblock(&G.main->mat, ID_MA, name); init_material(ma); return ma; } /* XXX keep synced with next function */ Material *copy_material(Material *ma) { Material *man; int a; man= copy_libblock(ma); id_lib_extern((ID *)man->group); for(a=0; a<MAX_MTEX; a++) { if(ma->mtex[a]) { man->mtex[a]= MEM_mallocN(sizeof(MTex), "copymaterial"); memcpy(man->mtex[a], ma->mtex[a], sizeof(MTex)); id_us_plus((ID *)man->mtex[a]->tex); } } if(ma->ramp_col) man->ramp_col= MEM_dupallocN(ma->ramp_col); if(ma->ramp_spec) man->ramp_spec= MEM_dupallocN(ma->ramp_spec); if (ma->preview) man->preview = BKE_previewimg_copy(ma->preview); if(ma->nodetree) { man->nodetree= ntreeCopyTree(ma->nodetree); /* 0 == full new tree */ } man->gpumaterial.first= man->gpumaterial.last= NULL; return man; } /* XXX (see above) material copy without adding to main dbase */ Material *localize_material(Material *ma) { Material *man; int a; man= copy_libblock(ma); BLI_remlink(&G.main->mat, man); /* no increment for texture ID users, in previewrender.c it prevents decrement */ for(a=0; a<MAX_MTEX; a++) { if(ma->mtex[a]) { man->mtex[a]= MEM_mallocN(sizeof(MTex), "copymaterial"); memcpy(man->mtex[a], ma->mtex[a], sizeof(MTex)); } } if(ma->ramp_col) man->ramp_col= MEM_dupallocN(ma->ramp_col); if(ma->ramp_spec) man->ramp_spec= MEM_dupallocN(ma->ramp_spec); man->preview = NULL; if(ma->nodetree) man->nodetree= ntreeLocalize(ma->nodetree); man->gpumaterial.first= man->gpumaterial.last= NULL; return man; } static void extern_local_material(Material *ma) { int i; for(i=0; i < MAX_MTEX; i++) { if(ma->mtex[i]) id_lib_extern((ID *)ma->mtex[i]->tex); } } void make_local_material(Material *ma) { Main *bmain= G.main; Object *ob; Mesh *me; Curve *cu; MetaBall *mb; Material *man; int a, local=0, lib=0; /* - only lib users: do nothing * - only local users: set flag * - mixed: make copy */ if(ma->id.lib==NULL) return; if(ma->id.us==1) { ma->id.lib= NULL; ma->id.flag= LIB_LOCAL; new_id(&bmain->mat, (ID *)ma, NULL); extern_local_material(ma); return; } /* test objects */ ob= bmain->object.first; while(ob) { if(ob->mat) { for(a=0; a<ob->totcol; a++) { if(ob->mat[a]==ma) { if(ob->id.lib) lib= 1; else local= 1; } } } ob= ob->id.next; } /* test meshes */ me= bmain->mesh.first; while(me) { if(me->mat) { for(a=0; a<me->totcol; a++) { if(me->mat[a]==ma) { if(me->id.lib) lib= 1; else local= 1; } } } me= me->id.next; } /* test curves */ cu= bmain->curve.first; while(cu) { if(cu->mat) { for(a=0; a<cu->totcol; a++) { if(cu->mat[a]==ma) { if(cu->id.lib) lib= 1; else local= 1; } } } cu= cu->id.next; } /* test mballs */ mb= bmain->mball.first; while(mb) { if(mb->mat) { for(a=0; a<mb->totcol; a++) { if(mb->mat[a]==ma) { if(mb->id.lib) lib= 1; else local= 1; } } } mb= mb->id.next; } if(local && lib==0) { ma->id.lib= NULL; ma->id.flag= LIB_LOCAL; new_id(&bmain->mat, (ID *)ma, NULL); extern_local_material(ma); } else if(local && lib) { man= copy_material(ma); man->id.us= 0; /* do objects */ ob= bmain->object.first; while(ob) { if(ob->mat) { for(a=0; a<ob->totcol; a++) { if(ob->mat[a]==ma) { if(ob->id.lib==NULL) { ob->mat[a]= man; man->id.us++; ma->id.us--; } } } } ob= ob->id.next; } /* do meshes */ me= bmain->mesh.first; while(me) { if(me->mat) { for(a=0; a<me->totcol; a++) { if(me->mat[a]==ma) { if(me->id.lib==NULL) { me->mat[a]= man; man->id.us++; ma->id.us--; } } } } me= me->id.next; } /* do curves */ cu= bmain->curve.first; while(cu) { if(cu->mat) { for(a=0; a<cu->totcol; a++) { if(cu->mat[a]==ma) { if(cu->id.lib==NULL) { cu->mat[a]= man; man->id.us++; ma->id.us--; } } } } cu= cu->id.next; } /* do mballs */ mb= bmain->mball.first; while(mb) { if(mb->mat) { for(a=0; a<mb->totcol; a++) { if(mb->mat[a]==ma) { if(mb->id.lib==NULL) { mb->mat[a]= man; man->id.us++; ma->id.us--; } } } } mb= mb->id.next; } } } /* for curve, mball, mesh types */ void extern_local_matarar(struct Material **matar, short totcol) { short i; for(i= 0; i < totcol; i++) { id_lib_extern((ID *)matar[i]); } } Material ***give_matarar(Object *ob) { Mesh *me; Curve *cu; MetaBall *mb; if(ob->type==OB_MESH) { me= ob->data; return &(me->mat); } else if ELEM3(ob->type, OB_CURVE, OB_FONT, OB_SURF) { cu= ob->data; return &(cu->mat); } else if(ob->type==OB_MBALL) { mb= ob->data; return &(mb->mat); } return NULL; } short *give_totcolp(Object *ob) { Mesh *me; Curve *cu; MetaBall *mb; if(ob->type==OB_MESH) { me= ob->data; return &(me->totcol); } else if ELEM3(ob->type, OB_CURVE, OB_FONT, OB_SURF) { cu= ob->data; return &(cu->totcol); } else if(ob->type==OB_MBALL) { mb= ob->data; return &(mb->totcol); } return NULL; } /* same as above but for ID's */ Material ***give_matarar_id(ID *id) { switch(GS(id->name)) { case ID_ME: return &(((Mesh *)id)->mat); break; case ID_CU: return &(((Curve *)id)->mat); break; case ID_MB: return &(((MetaBall *)id)->mat); break; } return NULL; } short *give_totcolp_id(ID *id) { switch(GS(id->name)) { case ID_ME: return &(((Mesh *)id)->totcol); break; case ID_CU: return &(((Curve *)id)->totcol); break; case ID_MB: return &(((MetaBall *)id)->totcol); break; } return NULL; } static void data_delete_material_index_id(ID *id, short index) { switch(GS(id->name)) { case ID_ME: mesh_delete_material_index((Mesh *)id, index); break; case ID_CU: curve_delete_material_index((Curve *)id, index); break; case ID_MB: /* meta-elems dont have materials atm */ break; } } void material_append_id(ID *id, Material *ma) { Material ***matar; if((matar= give_matarar_id(id))) { short *totcol= give_totcolp_id(id); Material **mat= MEM_callocN(sizeof(void *) * ((*totcol) + 1), "newmatar"); if(*totcol) memcpy(mat, *matar, sizeof(void *) * (*totcol)); if(*matar) MEM_freeN(*matar); *matar= mat; (*matar)[(*totcol)++]= ma; id_us_plus((ID *)ma); test_object_materials(id); } } Material *material_pop_id(ID *id, int index_i, int remove_material_slot) { short index= (short)index_i; Material *ret= NULL; Material ***matar; if((matar= give_matarar_id(id))) { short *totcol= give_totcolp_id(id); if(index >= 0 && index < (*totcol)) { ret= (*matar)[index]; id_us_min((ID *)ret); if (remove_material_slot) { if(*totcol <= 1) { *totcol= 0; MEM_freeN(*matar); *matar= NULL; } else { Material **mat; if(index + 1 != (*totcol)) memmove((*matar)+index, (*matar)+(index+1), sizeof(void *) * ((*totcol) - (index + 1))); (*totcol)--; mat= MEM_callocN(sizeof(void *) * (*totcol), "newmatar"); memcpy(mat, *matar, sizeof(void *) * (*totcol)); MEM_freeN(*matar); *matar= mat; test_object_materials(id); } /* decrease mat_nr index */ data_delete_material_index_id(id, index); } /* don't remove material slot, only clear it*/ else (*matar)[index]= NULL; } } return ret; } Material *give_current_material(Object *ob, short act) { Material ***matarar, *ma; short *totcolp; if(ob==NULL) return NULL; /* if object cannot have material, totcolp==NULL */ totcolp= give_totcolp(ob); if(totcolp==NULL || ob->totcol==0) return NULL; if(act<0) { printf("no!\n"); } if(act>ob->totcol) act= ob->totcol; else if(act<=0) act= 1; if(ob->matbits && ob->matbits[act-1]) { /* in object */ ma= ob->mat[act-1]; } else { /* in data */ /* check for inconsistency */ if(*totcolp < ob->totcol) ob->totcol= *totcolp; if(act>ob->totcol) act= ob->totcol; matarar= give_matarar(ob); if(matarar && *matarar) ma= (*matarar)[act-1]; else ma= NULL; } return ma; } ID *material_from(Object *ob, short act) { if(ob==NULL) return NULL; if(ob->totcol==0) return ob->data; if(act==0) act= 1; if(ob->matbits[act-1]) return (ID *)ob; else return ob->data; } Material *give_node_material(Material *ma) { if(ma && ma->use_nodes && ma->nodetree) { bNode *node= nodeGetActiveID(ma->nodetree, ID_MA); if(node) return (Material *)node->id; } return NULL; } /* GS reads the memory pointed at in a specific ordering. There are, * however two definitions for it. I have jotted them down here, both, * but I think the first one is actually used. The thing is that * big-endian systems might read this the wrong way round. OTOH, we * constructed the IDs that are read out with this macro explicitly as * well. I expect we'll sort it out soon... */ /* from blendef: */ #define GS(a) (*((short *)(a))) /* from misc_util: flip the bytes from x */ /* #define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1]) */ void resize_object_material(Object *ob, const short totcol) { Material **newmatar; char *newmatbits; if(totcol==0) { if(ob->totcol) { MEM_freeN(ob->mat); MEM_freeN(ob->matbits); ob->mat= NULL; ob->matbits= NULL; } } else if(ob->totcol<totcol) { newmatar= MEM_callocN(sizeof(void *)*totcol, "newmatar"); newmatbits= MEM_callocN(sizeof(char)*totcol, "newmatbits"); if(ob->totcol) { memcpy(newmatar, ob->mat, sizeof(void *)*ob->totcol); memcpy(newmatbits, ob->matbits, sizeof(char)*ob->totcol); MEM_freeN(ob->mat); MEM_freeN(ob->matbits); } ob->mat= newmatar; ob->matbits= newmatbits; } ob->totcol= totcol; if(ob->totcol && ob->actcol==0) ob->actcol= 1; if(ob->actcol>ob->totcol) ob->actcol= ob->totcol; } void test_object_materials(ID *id) { /* make the ob mat-array same size as 'ob->data' mat-array */ Object *ob; short *totcol; if(id==NULL || (totcol=give_totcolp_id(id))==NULL) { return; } for(ob= G.main->object.first; ob; ob= ob->id.next) { if(ob->data==id) { resize_object_material(ob, *totcol); } } } void assign_material_id(ID *id, Material *ma, short act) { Material *mao, **matar, ***matarar; short *totcolp; if(act>MAXMAT) return; if(act<1) act= 1; /* prevent crashing when using accidentally */ BLI_assert(id->lib == NULL); if(id->lib) return; /* test arraylens */ totcolp= give_totcolp_id(id); matarar= give_matarar_id(id); if(totcolp==NULL || matarar==NULL) return; if(act > *totcolp) { matar= MEM_callocN(sizeof(void *)*act, "matarray1"); if(*totcolp) { memcpy(matar, *matarar, sizeof(void *)*(*totcolp)); MEM_freeN(*matarar); } *matarar= matar; *totcolp= act; } /* in data */ mao= (*matarar)[act-1]; if(mao) mao->id.us--; (*matarar)[act-1]= ma; if(ma) id_us_plus((ID *)ma); test_object_materials(id); } void assign_material(Object *ob, Material *ma, short act) { Material *mao, **matar, ***matarar; char *matbits; short *totcolp; if(act>MAXMAT) return; if(act<1) act= 1; /* prevent crashing when using accidentally */ BLI_assert(ob->id.lib == NULL); if(ob->id.lib) return; /* test arraylens */ totcolp= give_totcolp(ob); matarar= give_matarar(ob); if(totcolp==NULL || matarar==NULL) return; if(act > *totcolp) { matar= MEM_callocN(sizeof(void *)*act, "matarray1"); if(*totcolp) { memcpy(matar, *matarar, sizeof(void *)*(*totcolp)); MEM_freeN(*matarar); } *matarar= matar; *totcolp= act; } if(act > ob->totcol) { matar= MEM_callocN(sizeof(void *)*act, "matarray2"); matbits= MEM_callocN(sizeof(char)*act, "matbits1"); if( ob->totcol) { memcpy(matar, ob->mat, sizeof(void *)*( ob->totcol )); memcpy(matbits, ob->matbits, sizeof(char)*(*totcolp)); MEM_freeN(ob->mat); MEM_freeN(ob->matbits); } ob->mat= matar; ob->matbits= matbits; ob->totcol= act; /* copy object/mesh linking, or assign based on userpref */ if(ob->actcol) ob->matbits[act-1]= ob->matbits[ob->actcol-1]; else ob->matbits[act-1]= (U.flag & USER_MAT_ON_OB)? 1: 0; } /* do it */ if(ob->matbits[act-1]) { /* in object */ mao= ob->mat[act-1]; if(mao) mao->id.us--; ob->mat[act-1]= ma; } else { /* in data */ mao= (*matarar)[act-1]; if(mao) mao->id.us--; (*matarar)[act-1]= ma; } if(ma) id_us_plus((ID *)ma); test_object_materials(ob->data); } /* XXX - this calls many more update calls per object then are needed, could be optimized */ void assign_matarar(struct Object *ob, struct Material ***matar, short totcol) { int actcol_orig= ob->actcol; short i; while(object_remove_material_slot(ob)) {}; /* now we have the right number of slots */ for(i=0; i<totcol; i++) assign_material(ob, (*matar)[i], i+1); if(actcol_orig > ob->totcol) actcol_orig= ob->totcol; ob->actcol= actcol_orig; } short find_material_index(Object *ob, Material *ma) { Material ***matarar; short a, *totcolp; if(ma==NULL) return 0; totcolp= give_totcolp(ob); matarar= give_matarar(ob); if(totcolp==NULL || matarar==NULL) return 0; for(a=0; a<*totcolp; a++) if((*matarar)[a]==ma) break; if(a<*totcolp) return a+1; return 0; } int object_add_material_slot(Object *ob) { if(ob==NULL) return FALSE; if(ob->totcol>=MAXMAT) return FALSE; assign_material(ob, NULL, ob->totcol+1); ob->actcol= ob->totcol; return TRUE; } static void do_init_render_material(Material *ma, int r_mode, float *amb) { MTex *mtex; int a, needuv=0, needtang=0; if(ma->flarec==0) ma->flarec= 1; /* add all texcoflags from mtex, texco and mapto were cleared in advance */ for(a=0; a<MAX_MTEX; a++) { /* separate tex switching */ if(ma->septex & (1<<a)) continue; mtex= ma->mtex[a]; if(mtex && mtex->tex && (mtex->tex->type | (mtex->tex->use_nodes && mtex->tex->nodetree) )) { ma->texco |= mtex->texco; ma->mapto |= mtex->mapto; /* always get derivatives for these textures */ if ELEM3(mtex->tex->type, TEX_IMAGE, TEX_PLUGIN, TEX_ENVMAP) ma->texco |= TEXCO_OSA; else if(mtex->texflag & (MTEX_COMPAT_BUMP|MTEX_3TAP_BUMP|MTEX_5TAP_BUMP)) ma->texco |= TEXCO_OSA; if(ma->texco & (TEXCO_ORCO|TEXCO_REFL|TEXCO_NORM|TEXCO_STRAND|TEXCO_STRESS)) needuv= 1; else if(ma->texco & (TEXCO_GLOB|TEXCO_UV|TEXCO_OBJECT|TEXCO_SPEED)) needuv= 1; else if(ma->texco & (TEXCO_LAVECTOR|TEXCO_VIEW|TEXCO_STICKY)) needuv= 1; if((ma->mapto & MAP_NORM) && (mtex->normapspace == MTEX_NSPACE_TANGENT)) needtang= 1; } } if(needtang) ma->mode |= MA_NORMAP_TANG; else ma->mode &= ~MA_NORMAP_TANG; if(ma->mode & (MA_VERTEXCOL|MA_VERTEXCOLP|MA_FACETEXTURE)) { needuv= 1; if(r_mode & R_OSA) ma->texco |= TEXCO_OSA; /* for texfaces */ } if(needuv) ma->texco |= NEED_UV; /* since the raytracer doesnt recalc O structs for each ray, we have to preset them all */ if(r_mode & R_RAYTRACE) { if((ma->mode & (MA_RAYMIRROR|MA_SHADOW_TRA)) || ((ma->mode & MA_TRANSP) && (ma->mode & MA_RAYTRANSP))) { ma->texco |= NEED_UV|TEXCO_ORCO|TEXCO_REFL|TEXCO_NORM; if(r_mode & R_OSA) ma->texco |= TEXCO_OSA; } } if(amb) { ma->ambr= ma->amb*amb[0]; ma->ambg= ma->amb*amb[1]; ma->ambb= ma->amb*amb[2]; } /* will become or-ed result of all node modes */ ma->mode_l= ma->mode; ma->mode_l &= ~MA_SHLESS; if(ma->strand_surfnor > 0.0f) ma->mode_l |= MA_STR_SURFDIFF; /* parses the geom+tex nodes */ if(ma->nodetree && ma->use_nodes) ntreeShaderGetTexcoMode(ma->nodetree, r_mode, &ma->texco, &ma->mode_l); } static void init_render_nodetree(bNodeTree *ntree, Material *basemat, int r_mode, float *amb) { bNode *node; for(node=ntree->nodes.first; node; node= node->next) { if(node->id) { if(GS(node->id->name)==ID_MA) { Material *ma= (Material *)node->id; if(ma!=basemat) { do_init_render_material(ma, r_mode, amb); basemat->texco |= ma->texco; basemat->mode_l |= ma->mode_l & ~(MA_TRANSP|MA_ZTRANSP|MA_RAYTRANSP); } } else if(node->type==NODE_GROUP) init_render_nodetree((bNodeTree *)node->id, basemat, r_mode, amb); } } } void init_render_material(Material *mat, int r_mode, float *amb) { do_init_render_material(mat, r_mode, amb); if(mat->nodetree && mat->use_nodes) { init_render_nodetree(mat->nodetree, mat, r_mode, amb); if (!mat->nodetree->execdata) mat->nodetree->execdata = ntreeShaderBeginExecTree(mat->nodetree, 1); } } void init_render_materials(Main *bmain, int r_mode, float *amb) { Material *ma; /* clear these flags before going over materials, to make sure they * are cleared only once, otherwise node materials contained in other * node materials can go wrong */ for(ma= bmain->mat.first; ma; ma= ma->id.next) { if(ma->id.us) { ma->texco= 0; ma->mapto= 0; } } /* two steps, first initialize, then or the flags for layers */ for(ma= bmain->mat.first; ma; ma= ma->id.next) { /* is_used flag comes back in convertblender.c */ ma->flag &= ~MA_IS_USED; if(ma->id.us) init_render_material(ma, r_mode, amb); } do_init_render_material(&defmaterial, r_mode, amb); } /* only needed for nodes now */ void end_render_material(Material *mat) { if(mat && mat->nodetree && mat->use_nodes) { if (mat->nodetree->execdata) ntreeShaderEndExecTree(mat->nodetree->execdata, 1); } } void end_render_materials(Main *bmain) { Material *ma; for(ma= bmain->mat.first; ma; ma= ma->id.next) if(ma->id.us) end_render_material(ma); } static int material_in_nodetree(bNodeTree *ntree, Material *mat) { bNode *node; for(node=ntree->nodes.first; node; node= node->next) { if(node->id && GS(node->id->name)==ID_MA) { if(node->id==(ID*)mat) return 1; } else if(node->type==NODE_GROUP) if(material_in_nodetree((bNodeTree*)node->id, mat)) return 1; } return 0; } int material_in_material(Material *parmat, Material *mat) { if(parmat==mat) return 1; else if(parmat->nodetree && parmat->use_nodes) return material_in_nodetree(parmat->nodetree, mat); else return 0; } /* ****************** */ static char colname_array[125][20]= { "Black","DarkRed","HalfRed","Red","Red", "DarkGreen","DarkOlive","Brown","Chocolate","OrangeRed", "HalfGreen","GreenOlive","DryOlive","Goldenrod","DarkOrange", "LightGreen","Chartreuse","YellowGreen","Yellow","Gold", "Green","LawnGreen","GreenYellow","LightOlive","Yellow", "DarkBlue","DarkPurple","HotPink","VioletPink","RedPink", "SlateGray","DarkGrey","PalePurple","IndianRed","Tomato", "SeaGreen","PaleGreen","GreenKhaki","LightBrown","LightSalmon", "SpringGreen","PaleGreen","MediumOlive","YellowBrown","LightGold", "LightGreen","LightGreen","LightGreen","GreenYellow","PaleYellow", "HalfBlue","DarkSky","HalfMagenta","VioletRed","DeepPink", "SteelBlue","SkyBlue","Orchid","LightHotPink","HotPink", "SeaGreen","SlateGray","MediumGrey","Burlywood","LightPink", "SpringGreen","Aquamarine","PaleGreen","Khaki","PaleOrange", "SpringGreen","SeaGreen","PaleGreen","PaleWhite","YellowWhite", "LightBlue","Purple","MediumOrchid","Magenta","Magenta", "RoyalBlue","SlateBlue","MediumOrchid","Orchid","Magenta", "DeepSkyBlue","LightSteelBlue","LightSkyBlue","Violet","LightPink", "Cyan","DarkTurquoise","SkyBlue","Grey","Snow", "Mint","Mint","Aquamarine","MintCream","Ivory", "Blue","Blue","DarkMagenta","DarkOrchid","Magenta", "SkyBlue","RoyalBlue","LightSlateBlue","MediumOrchid","Magenta", "DodgerBlue","SteelBlue","MediumPurple","PalePurple","Plum", "DeepSkyBlue","PaleBlue","LightSkyBlue","PalePurple","Thistle", "Cyan","ColdBlue","PaleTurquoise","GhostWhite","White" }; void automatname(Material *ma) { int nr, r, g, b; float ref; if(ma==NULL) return; if(ma->mode & MA_SHLESS) ref= 1.0; else ref= ma->ref; r= (int)(4.99f*(ref*ma->r)); g= (int)(4.99f*(ref*ma->g)); b= (int)(4.99f*(ref*ma->b)); nr= r + 5*g + 25*b; if(nr>124) nr= 124; new_id(&G.main->mat, (ID *)ma, colname_array[nr]); } int object_remove_material_slot(Object *ob) { Material *mao, ***matarar; Object *obt; short *totcolp; short a, actcol; if (ob==NULL || ob->totcol==0) { return FALSE; } /* this should never happen and used to crash */ if (ob->actcol <= 0) { printf("%s: invalid material index %d, report a bug!\n", __func__, ob->actcol); BLI_assert(0); return FALSE; } /* take a mesh/curve/mball as starting point, remove 1 index, * AND with all objects that share the ob->data * * after that check indices in mesh/curve/mball!!! */ totcolp= give_totcolp(ob); matarar= give_matarar(ob); if(*matarar==NULL) return FALSE; /* we delete the actcol */ mao= (*matarar)[ob->actcol-1]; if(mao) mao->id.us--; for(a=ob->actcol; a<ob->totcol; a++) (*matarar)[a-1]= (*matarar)[a]; (*totcolp)--; if(*totcolp==0) { MEM_freeN(*matarar); *matarar= NULL; } actcol= ob->actcol; obt= G.main->object.first; while(obt) { if(obt->data==ob->data) { /* WATCH IT: do not use actcol from ob or from obt (can become zero) */ mao= obt->mat[actcol-1]; if(mao) mao->id.us--; for(a=actcol; a<obt->totcol; a++) { obt->mat[a-1]= obt->mat[a]; obt->matbits[a-1]= obt->matbits[a]; } obt->totcol--; if(obt->actcol > obt->totcol) obt->actcol= obt->totcol; if(obt->totcol==0) { MEM_freeN(obt->mat); MEM_freeN(obt->matbits); obt->mat= NULL; obt->matbits= NULL; } } obt= obt->id.next; } /* check indices from mesh */ if (ELEM4(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT)) { data_delete_material_index_id((ID *)ob->data, actcol-1); freedisplist(&ob->disp); } return TRUE; } /* r g b = current value, col = new value, fac==0 is no change */ /* if g==NULL, it only does r channel */ void ramp_blend(int type, float *r, float *g, float *b, float fac, const float col[3]) { float tmp, facm= 1.0f-fac; switch (type) { case MA_RAMP_BLEND: *r = facm*(*r) + fac*col[0]; if(g) { *g = facm*(*g) + fac*col[1]; *b = facm*(*b) + fac*col[2]; } break; case MA_RAMP_ADD: *r += fac*col[0]; if(g) { *g += fac*col[1]; *b += fac*col[2]; } break; case MA_RAMP_MULT: *r *= (facm + fac*col[0]); if(g) { *g *= (facm + fac*col[1]); *b *= (facm + fac*col[2]); } break; case MA_RAMP_SCREEN: *r = 1.0f - (facm + fac*(1.0f - col[0])) * (1.0f - *r); if(g) { *g = 1.0f - (facm + fac*(1.0f - col[1])) * (1.0f - *g); *b = 1.0f - (facm + fac*(1.0f - col[2])) * (1.0f - *b); } break; case MA_RAMP_OVERLAY: if(*r < 0.5f) *r *= (facm + 2.0f*fac*col[0]); else *r = 1.0f - (facm + 2.0f*fac*(1.0f - col[0])) * (1.0f - *r); if(g) { if(*g < 0.5f) *g *= (facm + 2.0f*fac*col[1]); else *g = 1.0f - (facm + 2.0f*fac*(1.0f - col[1])) * (1.0f - *g); if(*b < 0.5f) *b *= (facm + 2.0f*fac*col[2]); else *b = 1.0f - (facm + 2.0f*fac*(1.0f - col[2])) * (1.0f - *b); } break; case MA_RAMP_SUB: *r -= fac*col[0]; if(g) { *g -= fac*col[1]; *b -= fac*col[2]; } break; case MA_RAMP_DIV: if(col[0]!=0.0f) *r = facm*(*r) + fac*(*r)/col[0]; if(g) { if(col[1]!=0.0f) *g = facm*(*g) + fac*(*g)/col[1]; if(col[2]!=0.0f) *b = facm*(*b) + fac*(*b)/col[2]; } break; case MA_RAMP_DIFF: *r = facm*(*r) + fac*fabsf(*r-col[0]); if(g) { *g = facm*(*g) + fac*fabsf(*g-col[1]); *b = facm*(*b) + fac*fabsf(*b-col[2]); } break; case MA_RAMP_DARK: tmp=col[0]+((1-col[0])*facm); if(tmp < *r) *r= tmp; if(g) { tmp=col[1]+((1-col[1])*facm); if(tmp < *g) *g= tmp; tmp=col[2]+((1-col[2])*facm); if(tmp < *b) *b= tmp; } break; case MA_RAMP_LIGHT: tmp= fac*col[0]; if(tmp > *r) *r= tmp; if(g) { tmp= fac*col[1]; if(tmp > *g) *g= tmp; tmp= fac*col[2]; if(tmp > *b) *b= tmp; } break; case MA_RAMP_DODGE: if(*r !=0.0f){ tmp = 1.0f - fac*col[0]; if(tmp <= 0.0f) *r = 1.0f; else if ((tmp = (*r) / tmp)> 1.0f) *r = 1.0f; else *r = tmp; } if(g) { if(*g !=0.0f){ tmp = 1.0f - fac*col[1]; if(tmp <= 0.0f ) *g = 1.0f; else if ((tmp = (*g) / tmp) > 1.0f ) *g = 1.0f; else *g = tmp; } if(*b !=0.0f){ tmp = 1.0f - fac*col[2]; if(tmp <= 0.0f) *b = 1.0f; else if ((tmp = (*b) / tmp) > 1.0f ) *b = 1.0f; else *b = tmp; } } break; case MA_RAMP_BURN: tmp = facm + fac*col[0]; if(tmp <= 0.0f) *r = 0.0f; else if (( tmp = (1.0f - (1.0f - (*r)) / tmp )) < 0.0f) *r = 0.0f; else if (tmp > 1.0f) *r=1.0f; else *r = tmp; if(g) { tmp = facm + fac*col[1]; if(tmp <= 0.0f) *g = 0.0f; else if (( tmp = (1.0f - (1.0f - (*g)) / tmp )) < 0.0f ) *g = 0.0f; else if(tmp >1.0f) *g=1.0f; else *g = tmp; tmp = facm + fac*col[2]; if(tmp <= 0.0f) *b = 0.0f; else if (( tmp = (1.0f - (1.0f - (*b)) / tmp )) < 0.0f ) *b = 0.0f; else if(tmp >1.0f) *b= 1.0f; else *b = tmp; } break; case MA_RAMP_HUE: if(g){ float rH,rS,rV; float colH,colS,colV; float tmpr,tmpg,tmpb; rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV); if(colS!=0 ){ rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV); hsv_to_rgb( colH , rS, rV, &tmpr, &tmpg, &tmpb); *r = facm*(*r) + fac*tmpr; *g = facm*(*g) + fac*tmpg; *b = facm*(*b) + fac*tmpb; } } break; case MA_RAMP_SAT: if(g){ float rH,rS,rV; float colH,colS,colV; rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV); if(rS!=0){ rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV); hsv_to_rgb( rH, (facm*rS +fac*colS), rV, r, g, b); } } break; case MA_RAMP_VAL: if(g){ float rH,rS,rV; float colH,colS,colV; rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV); rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV); hsv_to_rgb( rH, rS, (facm*rV +fac*colV), r, g, b); } break; case MA_RAMP_COLOR: if(g){ float rH,rS,rV; float colH,colS,colV; float tmpr,tmpg,tmpb; rgb_to_hsv(col[0],col[1],col[2],&colH,&colS,&colV); if(colS!=0){ rgb_to_hsv(*r,*g,*b,&rH,&rS,&rV); hsv_to_rgb( colH, colS, rV, &tmpr, &tmpg, &tmpb); *r = facm*(*r) + fac*tmpr; *g = facm*(*g) + fac*tmpg; *b = facm*(*b) + fac*tmpb; } } break; case MA_RAMP_SOFT: if (g){ float scr, scg, scb; /* first calculate non-fac based Screen mix */ scr = 1.0f - (1.0f - col[0]) * (1.0f - *r); scg = 1.0f - (1.0f - col[1]) * (1.0f - *g); scb = 1.0f - (1.0f - col[2]) * (1.0f - *b); *r = facm*(*r) + fac*(((1.0f - *r) * col[0] * (*r)) + (*r * scr)); *g = facm*(*g) + fac*(((1.0f - *g) * col[1] * (*g)) + (*g * scg)); *b = facm*(*b) + fac*(((1.0f - *b) * col[2] * (*b)) + (*b * scb)); } break; case MA_RAMP_LINEAR: if (col[0] > 0.5f) *r = *r + fac*(2.0f*(col[0]-0.5f)); else *r = *r + fac*(2.0f*(col[0]) - 1.0f); if (g){ if (col[1] > 0.5f) *g = *g + fac*(2.0f*(col[1]-0.5f)); else *g = *g + fac*(2.0f*(col[1]) -1.0f); if (col[2] > 0.5f) *b = *b + fac*(2.0f*(col[2]-0.5f)); else *b = *b + fac*(2.0f*(col[2]) - 1.0f); } break; } } /* copy/paste buffer, if we had a propper py api that would be better */ static Material matcopybuf; static short matcopied= 0; void clear_matcopybuf(void) { memset(&matcopybuf, 0, sizeof(Material)); matcopied= 0; } void free_matcopybuf(void) { int a; for(a=0; a<MAX_MTEX; a++) { if(matcopybuf.mtex[a]) { MEM_freeN(matcopybuf.mtex[a]); matcopybuf.mtex[a]= NULL; } } if(matcopybuf.ramp_col) MEM_freeN(matcopybuf.ramp_col); if(matcopybuf.ramp_spec) MEM_freeN(matcopybuf.ramp_spec); matcopybuf.ramp_col= NULL; matcopybuf.ramp_spec= NULL; if(matcopybuf.nodetree) { ntreeFreeTree(matcopybuf.nodetree); MEM_freeN(matcopybuf.nodetree); matcopybuf.nodetree= NULL; } matcopied= 0; } void copy_matcopybuf(Material *ma) { int a; MTex *mtex; if(matcopied) free_matcopybuf(); memcpy(&matcopybuf, ma, sizeof(Material)); if(matcopybuf.ramp_col) matcopybuf.ramp_col= MEM_dupallocN(matcopybuf.ramp_col); if(matcopybuf.ramp_spec) matcopybuf.ramp_spec= MEM_dupallocN(matcopybuf.ramp_spec); for(a=0; a<MAX_MTEX; a++) { mtex= matcopybuf.mtex[a]; if(mtex) { matcopybuf.mtex[a]= MEM_dupallocN(mtex); } } matcopybuf.nodetree= ntreeCopyTree(ma->nodetree); matcopybuf.preview= NULL; matcopybuf.gpumaterial.first= matcopybuf.gpumaterial.last= NULL; matcopied= 1; } void paste_matcopybuf(Material *ma) { int a; MTex *mtex; ID id; if(matcopied==0) return; /* free current mat */ if(ma->ramp_col) MEM_freeN(ma->ramp_col); if(ma->ramp_spec) MEM_freeN(ma->ramp_spec); for(a=0; a<MAX_MTEX; a++) { mtex= ma->mtex[a]; if(mtex && mtex->tex) mtex->tex->id.us--; if(mtex) MEM_freeN(mtex); } if(ma->nodetree) { ntreeFreeTree(ma->nodetree); MEM_freeN(ma->nodetree); } GPU_material_free(ma); id= (ma->id); memcpy(ma, &matcopybuf, sizeof(Material)); (ma->id)= id; if(matcopybuf.ramp_col) ma->ramp_col= MEM_dupallocN(matcopybuf.ramp_col); if(matcopybuf.ramp_spec) ma->ramp_spec= MEM_dupallocN(matcopybuf.ramp_spec); for(a=0; a<MAX_MTEX; a++) { mtex= ma->mtex[a]; if(mtex) { ma->mtex[a]= MEM_dupallocN(mtex); if(mtex->tex) id_us_plus((ID *)mtex->tex); } } ma->nodetree= ntreeCopyTree(matcopybuf.nodetree); } /*********************** texface to material convert functions **********************/ /* encode all the TF information into a single int */ static int encode_tfaceflag(MTFace *tf, int convertall) { /* calculate the flag */ int flag = tf->mode; /* options that change the material offline render */ if (!convertall) { flag &= ~TF_OBCOL; } /* clean flags that are not being converted */ flag &= ~TF_TEX; flag &= ~TF_SHAREDVERT; flag &= ~TF_SHAREDCOL; flag &= ~TF_CONVERTED; /* light tface flag is ignored in GLSL mode */ flag &= ~TF_LIGHT; /* 15 is how big the flag can be - hardcoded here and in decode_tfaceflag() */ flag |= tf->transp << 15; /* increase 1 so flag 0 is different than no flag yet */ return flag + 1; } /* set the material options based in the tface flag */ static void decode_tfaceflag(Material *ma, int flag, int convertall) { int alphablend; GameSettings *game= &ma->game; /* flag is shifted in 1 to make 0 != no flag yet (see encode_tfaceflag) */ flag -= 1; alphablend = flag >> 15; //encoded in the encode_tfaceflag function (*game).flag = 0; /* General Material Options */ if ((flag & TF_DYNAMIC)==0) (*game).flag |= GEMAT_NOPHYSICS; /* Material Offline Rendering Properties */ if (convertall) { if (flag & TF_OBCOL) ma->shade_flag |= MA_OBCOLOR; } /* Special Face Properties */ if ((flag & TF_TWOSIDE)==0) (*game).flag |= GEMAT_BACKCULL; if (flag & TF_INVISIBLE)(*game).flag |= GEMAT_INVISIBLE; if (flag & TF_BMFONT) (*game).flag |= GEMAT_TEXT; /* Face Orientation */ if (flag & TF_BILLBOARD) (*game).face_orientation |= GEMAT_HALO; else if (flag & TF_BILLBOARD2) (*game).face_orientation |= GEMAT_BILLBOARD; else if (flag & TF_SHADOW) (*game).face_orientation |= GEMAT_SHADOW; /* Alpha Blend */ if (flag & TF_ALPHASORT && ELEM(alphablend, TF_ALPHA, TF_ADD)) (*game).alpha_blend = GEMAT_ALPHA_SORT; else if (alphablend & TF_ALPHA) (*game).alpha_blend = GEMAT_ALPHA; else if (alphablend & TF_ADD) (*game).alpha_blend = GEMAT_ADD; else if (alphablend & TF_CLIP) (*game).alpha_blend = GEMAT_CLIP; } /* boolean check to see if the mesh needs a material */ static int check_tfaceneedmaterial(int flag) { // check if the flags we have are not deprecated != than default material options // also if only flags are visible and collision see if all objects using this mesh have this option in physics /* flag is shifted in 1 to make 0 != no flag yet (see encode_tfaceflag) */ flag -=1; // deprecated flags flag &= ~TF_OBCOL; flag &= ~TF_SHAREDVERT; flag &= ~TF_SHAREDCOL; /* light tface flag is ignored in GLSL mode */ flag &= ~TF_LIGHT; // automatic detected if tex image has alpha flag &= ~(TF_ALPHA << 15); // automatic detected if using texture flag &= ~TF_TEX; // settings for the default NoMaterial if (flag == TF_DYNAMIC) return 0; else return 1; } /* return number of digits of an integer */ // XXX to be optmized or replaced by an equivalent blender internal function static int integer_getdigits(int number) { int i=0; if (number == 0) return 1; while (number != 0){ number = (int)(number/10); i++; } return i; } static void calculate_tface_materialname(char *matname, char *newname, int flag) { // if flag has only light and collision and material matches those values // you can do strcpy(name, mat_name); // otherwise do: int digits = integer_getdigits(flag); /* clamp the old name, remove the MA prefix and add the .TF.flag suffix e.g. matname = "MALoooooooooooooongName"; newname = "Loooooooooooooon.TF.2" */ sprintf(newname, "%.*s.TF.%0*d", MAX_ID_NAME-(digits+5), matname, digits, flag); } /* returns -1 if no match */ static short mesh_getmaterialnumber(Mesh *me, Material *ma) { short a; for (a=0; a<me->totcol; a++) { if (me->mat[a] == ma) { return a; } } return -1; } /* append material */ static short mesh_addmaterial(Mesh *me, Material *ma) { material_append_id(&me->id, NULL); me->mat[me->totcol-1]= ma; id_us_plus(&ma->id); return me->totcol-1; } static void set_facetexture_flags(Material *ma, Image *image) { if(image) { ma->mode |= MA_FACETEXTURE; /* we could check if the texture has alpha, but then more meshes sharing the same * material may need it. Let's make it simple. */ if(BKE_image_has_alpha(image)) ma->mode |= MA_FACETEXTURE_ALPHA; } } /* returns material number */ static short convert_tfacenomaterial(Main *main, Mesh *me, MTFace *tf, int flag) { Material *ma; char idname[MAX_ID_NAME]; short mat_nr= -1; /* new material, the name uses the flag*/ sprintf(idname, "MAMaterial.TF.%0*d", integer_getdigits(flag), flag); if ((ma= BLI_findstring(&main->mat, idname+2, offsetof(ID, name)+2))) { mat_nr= mesh_getmaterialnumber(me, ma); /* assign the material to the mesh */ if(mat_nr == -1) mat_nr= mesh_addmaterial(me, ma); /* if needed set "Face Textures [Alpha]" Material options */ set_facetexture_flags(ma, tf->tpage); } /* create a new material */ else { ma= add_material(idname+2); if(ma){ printf("TexFace Convert: Material \"%s\" created.\n", idname+2); mat_nr= mesh_addmaterial(me, ma); /* if needed set "Face Textures [Alpha]" Material options */ set_facetexture_flags(ma, tf->tpage); decode_tfaceflag(ma, flag, 1); // the final decoding will happen after, outside the main loop // for now store the flag into the material and change light/tex/collision // store the flag as a negative number ma->game.flag = -flag; id_us_min((ID *)ma); } else printf("Error: Unable to create Material \"%s\" for Mesh \"%s\".", idname+2, me->id.name+2); } /* set as converted, no need to go bad to this face */ tf->mode |= TF_CONVERTED; return mat_nr; } /* Function to fully convert materials */ static void convert_tfacematerial(Main *main, Material *ma) { Mesh *me; Material *mat_new; MFace *mf; MTFace *tf; int flag, index; int a; short mat_nr; CustomDataLayer *cdl; char idname[MAX_ID_NAME]; for(me=main->mesh.first; me; me=me->id.next){ /* check if this mesh uses this material */ for(a=0;a<me->totcol;a++) if(me->mat[a] == ma) break; /* no material found */ if (a == me->totcol) continue; /* get the active tface layer */ index= CustomData_get_active_layer_index(&me->fdata, CD_MTFACE); cdl= (index == -1)? NULL: &me->fdata.layers[index]; if (!cdl) continue; /* loop over all the faces and stop at the ones that use the material*/ for(a=0, mf=me->mface; a<me->totface; a++, mf++) { if(me->mat[mf->mat_nr] != ma) continue; /* texface data for this face */ tf = ((MTFace*)cdl->data) + a; flag = encode_tfaceflag(tf, 1); /* the name of the new material */ calculate_tface_materialname(ma->id.name, (char *)&idname, flag); if ((mat_new= BLI_findstring(&main->mat, idname+2, offsetof(ID, name)+2))) { /* material already existent, see if the mesh has it */ mat_nr = mesh_getmaterialnumber(me, mat_new); /* material is not in the mesh, add it */ if(mat_nr == -1) mat_nr= mesh_addmaterial(me, mat_new); } /* create a new material */ else { mat_new=copy_material(ma); if(mat_new){ /* rename the material*/ strcpy(mat_new->id.name, idname); id_us_min((ID *)mat_new); mat_nr= mesh_addmaterial(me, mat_new); decode_tfaceflag(mat_new, flag, 1); } else { printf("Error: Unable to create Material \"%s\" for Mesh \"%s.", idname+2, me->id.name+2); mat_nr = mf->mat_nr; continue; } } /* if the material has a texture but no texture channel * set "Face Textures [Alpha]" Material options * actually we need to run it always, because of old behavior * of using face texture if any texture channel was present (multitex) */ //if((!mat_new->mtex[0]) && (!mat_new->mtex[0]->tex)) set_facetexture_flags(mat_new, tf->tpage); /* set the material number to the face*/ mf->mat_nr = mat_nr; } /* remove material from mesh */ for(a=0;a<me->totcol;) if(me->mat[a] == ma) material_pop_id(&me->id, a, 1);else a++; } } #define MAT_BGE_DISPUTED -99999 int do_version_tface(Main *main, int fileload) { Mesh *me; Material *ma; MFace *mf; MTFace *tf; CustomDataLayer *cdl; int a; int flag; int index; /* sometimes mesh has no materials but will need a new one. In those * cases we need to ignore the mf->mat_nr and only look at the face * mode because it can be zero as uninitialized or the 1st created material */ int nomaterialslots; /* alert to user to check the console */ int nowarning = 1; /* mark all the materials to conversion with a flag * if there is tface create a complete flag for that storing in flag * if there is tface and flag > 0: creates a new flag based on this face * if flags are different set flag to -1 */ /* 1st part: marking mesh materials to update */ for(me=main->mesh.first; me; me=me->id.next){ if (me->id.lib) continue; /* get the active tface layer */ index= CustomData_get_active_layer_index(&me->fdata, CD_MTFACE); cdl= (index == -1)? NULL: &me->fdata.layers[index]; if (!cdl) continue; nomaterialslots = (me->totcol==0?1:0); /* loop over all the faces*/ for(a=0, mf=me->mface; a<me->totface; a++, mf++) { /* texface data for this face */ tf = ((MTFace*)cdl->data) + a; /* conversion should happen only once */ if (fileload) tf->mode &= ~TF_CONVERTED; else { if((tf->mode & TF_CONVERTED)) continue; else tf->mode |= TF_CONVERTED; } /* no material slots */ if(nomaterialslots) { flag = encode_tfaceflag(tf, 1); /* create/find a new material and assign to the face */ if (check_tfaceneedmaterial(flag)) { mf->mat_nr= convert_tfacenomaterial(main, me, tf, flag); } /* else mark them as no-material to be reverted to 0 later */ else { mf->mat_nr = -1; } } else if(mf->mat_nr < me->totcol) { ma= me->mat[mf->mat_nr]; /* no material create one if necessary */ if(!ma) { /* find a new material and assign to the face */ flag = encode_tfaceflag(tf, 1); /* create/find a new material and assign to the face */ if (check_tfaceneedmaterial(flag)) mf->mat_nr= convert_tfacenomaterial(main, me, tf, flag); continue; } /* we can't read from this if it comes from a library, * at doversion time: direct_link might not have happened on it, * so ma->mtex is not pointing to valid memory yet. * later we could, but it's better not */ else if(ma->id.lib) continue; /* material already marked as disputed */ else if(ma->game.flag == MAT_BGE_DISPUTED) continue; /* found a material */ else { flag = encode_tfaceflag(tf, ((fileload)?0:1)); /* first time changing this material */ if (ma->game.flag == 0) ma->game.flag= -flag; /* mark material as disputed */ else if (ma->game.flag != -flag) { ma->game.flag = MAT_BGE_DISPUTED; continue; } /* material ok so far */ else { ma->game.flag = -flag; /* some people uses multitexture with TexFace by creating a texture * channel which not neccessarly the tf->tpage image. But the game engine * was enabling it. Now it's required to set "Face Texture [Alpha] in the * material settings. */ if(!fileload) set_facetexture_flags(ma, tf->tpage); } } } else continue; } /* if we didn't have material slot and now we do, we need to * make sure the materials are correct */ if(nomaterialslots) { if (me->totcol>0) { for(a=0, mf=me->mface; a<me->totface; a++, mf++) { if (mf->mat_nr == -1) { /* texface data for this face */ tf = ((MTFace*)cdl->data) + a; mf->mat_nr= convert_tfacenomaterial(main, me, tf, encode_tfaceflag(tf, 1)); } } } else { for(a=0, mf=me->mface; a<me->totface; a++, mf++) { mf->mat_nr=0; } } } } /* 2nd part - conversion */ /* skip library files */ /* we shouldn't loop through the materials created in the loop. make the loop stop at its original length) */ for (ma= main->mat.first, a=0; ma; ma= ma->id.next, a++) { if (ma->id.lib) continue; /* disputed material */ if (ma->game.flag == MAT_BGE_DISPUTED) { ma->game.flag = 0; if (fileload) { printf("Warning: material \"%s\" skipped - to convert old game texface to material go to the Help menu.\n", ma->id.name+2); nowarning = 0; } else convert_tfacematerial(main, ma); continue; } /* no conflicts in this material - 90% of cases * convert from tface system to material */ else if (ma->game.flag < 0) { decode_tfaceflag(ma, -(ma->game.flag), 1); /* material is good make sure all faces using * this material are set to converted */ if (fileload) { for(me=main->mesh.first; me; me=me->id.next){ /* check if this mesh uses this material */ for(a=0;a<me->totcol;a++) if(me->mat[a] == ma) break; /* no material found */ if (a == me->totcol) continue; /* get the active tface layer */ index= CustomData_get_active_layer_index(&me->fdata, CD_MTFACE); cdl= (index == -1)? NULL: &me->fdata.layers[index]; if (!cdl) continue; /* loop over all the faces and stop at the ones that use the material*/ for (a=0, mf=me->mface; a<me->totface; a++, mf++) { if (me->mat[mf->mat_nr] == ma) { /* texface data for this face */ tf = ((MTFace*)cdl->data) + a; tf->mode |= TF_CONVERTED; } } } } } /* material is not used by faces with texface * set the default flag - do it only once */ else if (fileload) ma->game.flag = GEMAT_BACKCULL; } return nowarning; }
24.063121
127
0.614479
[ "mesh", "render", "object" ]
3143902d72ad978daced223ee9b41eea6b71af65
20,278
c
C
src/pcre2demo.c
GerHobbelt/pcre
7638ef29378a6e5f70e03eac73cba8968d5caac3
[ "BSD-3-Clause" ]
null
null
null
src/pcre2demo.c
GerHobbelt/pcre
7638ef29378a6e5f70e03eac73cba8968d5caac3
[ "BSD-3-Clause" ]
null
null
null
src/pcre2demo.c
GerHobbelt/pcre
7638ef29378a6e5f70e03eac73cba8968d5caac3
[ "BSD-3-Clause" ]
null
null
null
/************************************************* * PCRE2 DEMONSTRATION PROGRAM * *************************************************/ /* This is a demonstration program to illustrate a straightforward way of using the PCRE2 regular expression library from a C program. See the pcre2sample documentation for a short discussion ("man pcre2sample" if you have the PCRE2 man pages installed). PCRE2 is a revised API for the library, and is incompatible with the original PCRE API. There are actually three libraries, each supporting a different code unit width. This demonstration program uses the 8-bit library. The default is to process each code unit as a separate character, but if the pattern begins with "(*UTF)", both it and the subject are treated as UTF-8 strings, where characters may occupy multiple code units. In Unix-like environments, if PCRE2 is installed in your standard system libraries, you should be able to compile this program using this command: cc -Wall pcre2demo.c -lpcre2-8 -o pcre2demo If PCRE2 is not installed in a standard place, it is likely to be installed with support for the pkg-config mechanism. If you have pkg-config, you can compile this program using this command: cc -Wall pcre2demo.c `pkg-config --cflags --libs libpcre2-8` -o pcre2demo If you do not have pkg-config, you may have to use something like this: cc -Wall pcre2demo.c -I/usr/local/include -L/usr/local/lib \ -R/usr/local/lib -lpcre2-8 -o pcre2demo Replace "/usr/local/include" and "/usr/local/lib" with wherever the include and library files for PCRE2 are installed on your system. Only some operating systems (Solaris is one) use the -R option. Building under Windows: If you want to statically link this program against a non-dll .a file, you must define PCRE2_STATIC before including pcre2.h, so in this environment, uncomment the following line. */ /* #define PCRE2_STATIC */ /* The PCRE2_CODE_UNIT_WIDTH macro must be defined before including pcre2.h. For a program that uses only one code unit width, setting it to 8, 16, or 32 makes it possible to use generic function names such as pcre2_compile(). Note that just changing 8 to 16 (for example) is not sufficient to convert this program to process 16-bit characters. Even in a fully 16-bit environment, where string-handling functions such as strcmp() and printf() work with 16-bit characters, the code for handling the table of named substrings will still need to be modified. */ #define PCRE2_CODE_UNIT_WIDTH 8 #include <stdio.h> #include <string.h> #include <pcre2.h> /************************************************************************** * Here is the program. The API includes the concept of "contexts" for * * setting up unusual interface requirements for compiling and matching, * * such as custom memory managers and non-standard newline definitions. * * This program does not do any of this, so it makes no use of contexts, * * always passing NULL where a context could be given. * **************************************************************************/ #if defined(BUILD_MONOLITHIC) #define main(cnt, arr) pcre2_demo_main(cnt, arr) #endif int main(int argc, const char** argv) { pcre2_code *re; PCRE2_SPTR pattern; /* PCRE2_SPTR is a pointer to unsigned code units of */ PCRE2_SPTR subject; /* the appropriate width (in this case, 8 bits). */ PCRE2_SPTR name_table = 0; int crlf_is_newline; int errornumber; int find_all; int i; int rc; int utf8; uint32_t option_bits; uint32_t namecount; uint32_t name_entry_size; uint32_t newline; PCRE2_SIZE erroroffset; PCRE2_SIZE *ovector; PCRE2_SIZE subject_length; pcre2_match_data *match_data; /************************************************************************** * First, sort out the command line. There is only one possible option at * * the moment, "-g" to request repeated matching to find all occurrences, * * like Perl's /g option. We set the variable find_all to a non-zero value * * if the -g option is present. * **************************************************************************/ find_all = 0; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-g") == 0) find_all = 1; else if (argv[i][0] == '-') { printf("Unrecognised option %s\n", argv[i]); return 1; } else break; } /* After the options, we require exactly two arguments, which are the pattern, and the subject string. */ if (argc - i != 2) { printf("Exactly two arguments required: a regex and a subject string\n"); return 1; } /* Pattern and subject are char arguments, so they can be straightforwardly cast to PCRE2_SPTR because we are working in 8-bit code units. The subject length is cast to PCRE2_SIZE for completeness, though PCRE2_SIZE is in fact defined to be size_t. */ pattern = (PCRE2_SPTR)argv[i]; subject = (PCRE2_SPTR)argv[i+1]; subject_length = (PCRE2_SIZE)strlen((char *)subject); /************************************************************************* * Now we are going to compile the regular expression pattern, and handle * * any errors that are detected. * *************************************************************************/ re = pcre2_compile( pattern, /* the pattern */ PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */ 0, /* default options */ &errornumber, /* for error number */ &erroroffset, /* for error offset */ NULL); /* use default compile context */ /* Compilation failed: print the error message and exit. */ if (re == NULL) { PCRE2_UCHAR buffer[256]; pcre2_get_error_message(errornumber, buffer, sizeof(buffer)); printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset, buffer); return 1; } /************************************************************************* * If the compilation succeeded, we call PCRE2 again, in order to do a * * pattern match against the subject string. This does just ONE match. If * * further matching is needed, it will be done below. Before running the * * match we must set up a match_data block for holding the result. Using * * pcre2_match_data_create_from_pattern() ensures that the block is * * exactly the right size for the number of capturing parentheses in the * * pattern. If you need to know the actual size of a match_data block as * * a number of bytes, you can find it like this: * * * * PCRE2_SIZE match_data_size = pcre2_get_match_data_size(match_data); * *************************************************************************/ match_data = pcre2_match_data_create_from_pattern(re, NULL); /* Now run the match. */ rc = pcre2_match( re, /* the compiled pattern */ subject, /* the subject string */ subject_length, /* the length of the subject */ 0, /* start at offset 0 in the subject */ 0, /* default options */ match_data, /* block for storing the result */ NULL); /* use default match context */ /* Matching failed: handle error cases */ if (rc < 0) { switch(rc) { case PCRE2_ERROR_NOMATCH: printf("No match\n"); break; /* Handle other special cases if you like */ default: printf("Matching error %d\n", rc); break; } pcre2_match_data_free(match_data); /* Release memory used for the match */ pcre2_code_free(re); /* data and the compiled pattern. */ return 1; } /* Match succeeded. Get a pointer to the output vector, where string offsets are stored. */ ovector = pcre2_get_ovector_pointer(match_data); printf("Match succeeded at offset %d\n", (int)ovector[0]); /************************************************************************* * We have found the first match within the subject string. If the output * * vector wasn't big enough, say so. Then output any substrings that were * * captured. * *************************************************************************/ /* The output vector wasn't big enough. This should not happen, because we used pcre2_match_data_create_from_pattern() above. */ if (rc == 0) printf("ovector was not big enough for all the captured substrings\n"); /* Since release 10.38 PCRE2 has locked out the use of \K in lookaround assertions. However, there is an option to re-enable the old behaviour. If that is set, it is possible to run patterns such as /(?=.\K)/ that use \K in an assertion to set the start of a match later than its end. In this demonstration program, we show how to detect this case, but it shouldn't arise because the option is never set. */ if (ovector[0] > ovector[1]) { printf("\\K was used in an assertion to set the match start after its end.\n" "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]), (char *)(subject + ovector[1])); printf("Run abandoned\n"); pcre2_match_data_free(match_data); pcre2_code_free(re); return 1; } /* Show substrings stored in the output vector by number. Obviously, in a real application you might want to do things other than print them. */ for (i = 0; i < rc; i++) { PCRE2_SPTR substring_start = subject + ovector[2*i]; PCRE2_SIZE substring_length = ovector[2*i+1] - ovector[2*i]; printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start); } /************************************************************************** * That concludes the basic part of this demonstration program. We have * * compiled a pattern, and performed a single match. The code that follows * * shows first how to access named substrings, and then how to code for * * repeated matches on the same subject. * **************************************************************************/ /* See if there are any named substrings, and if so, show them by name. First we have to extract the count of named parentheses from the pattern. */ (void)pcre2_pattern_info( re, /* the compiled pattern */ PCRE2_INFO_NAMECOUNT, /* get the number of named substrings */ &namecount); /* where to put the answer */ if (namecount == 0) printf("No named substrings\n"); else { PCRE2_SPTR tabptr; printf("Named substrings\n"); /* Before we can access the substrings, we must extract the table for translating names to numbers, and the size of each entry in the table. */ (void)pcre2_pattern_info( re, /* the compiled pattern */ PCRE2_INFO_NAMETABLE, /* address of the table */ &name_table); /* where to put the answer */ (void)pcre2_pattern_info( re, /* the compiled pattern */ PCRE2_INFO_NAMEENTRYSIZE, /* size of each entry in the table */ &name_entry_size); /* where to put the answer */ /* Now we can scan the table and, for each entry, print the number, the name, and the substring itself. In the 8-bit library the number is held in two bytes, most significant first. */ tabptr = name_table; for (i = 0; i < namecount; i++) { int n = (tabptr[0] << 8) | tabptr[1]; printf("(%d) %*s: %.*s\n", n, name_entry_size - 3, tabptr + 2, (int)(ovector[2*n+1] - ovector[2*n]), subject + ovector[2*n]); tabptr += name_entry_size; } } /************************************************************************* * If the "-g" option was given on the command line, we want to continue * * to search for additional matches in the subject string, in a similar * * way to the /g option in Perl. This turns out to be trickier than you * * might think because of the possibility of matching an empty string. * * What happens is as follows: * * * * If the previous match was NOT for an empty string, we can just start * * the next match at the end of the previous one. * * * * If the previous match WAS for an empty string, we can't do that, as it * * would lead to an infinite loop. Instead, a call of pcre2_match() is * * made with the PCRE2_NOTEMPTY_ATSTART and PCRE2_ANCHORED flags set. The * * first of these tells PCRE2 that an empty string at the start of the * * subject is not a valid match; other possibilities must be tried. The * * second flag restricts PCRE2 to one match attempt at the initial string * * position. If this match succeeds, an alternative to the empty string * * match has been found, and we can print it and proceed round the loop, * * advancing by the length of whatever was found. If this match does not * * succeed, we still stay in the loop, advancing by just one character. * * In UTF-8 mode, which can be set by (*UTF) in the pattern, this may be * * more than one byte. * * * * However, there is a complication concerned with newlines. When the * * newline convention is such that CRLF is a valid newline, we must * * advance by two characters rather than one. The newline convention can * * be set in the regex by (*CR), etc.; if not, we must find the default. * *************************************************************************/ if (!find_all) /* Check for -g */ { pcre2_match_data_free(match_data); /* Release the memory that was used */ pcre2_code_free(re); /* for the match data and the pattern. */ return 0; /* Exit the program. */ } /* Before running the loop, check for UTF-8 and whether CRLF is a valid newline sequence. First, find the options with which the regex was compiled and extract the UTF state. */ (void)pcre2_pattern_info(re, PCRE2_INFO_ALLOPTIONS, &option_bits); utf8 = (option_bits & PCRE2_UTF) != 0; /* Now find the newline convention and see whether CRLF is a valid newline sequence. */ (void)pcre2_pattern_info(re, PCRE2_INFO_NEWLINE, &newline); crlf_is_newline = newline == PCRE2_NEWLINE_ANY || newline == PCRE2_NEWLINE_CRLF || newline == PCRE2_NEWLINE_ANYCRLF; /* Loop for second and subsequent matches */ for (;;) { uint32_t options = 0; /* Normally no options */ PCRE2_SIZE start_offset = ovector[1]; /* Start at end of previous match */ /* If the previous match was for an empty string, we are finished if we are at the end of the subject. Otherwise, arrange to run another match at the same point to see if a non-empty match can be found. */ if (ovector[0] == ovector[1]) { if (ovector[0] == subject_length) break; options = PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED; } /* If the previous match was not an empty string, there is one tricky case to consider. If a pattern contains \K within a lookbehind assertion at the start, the end of the matched string can be at the offset where the match started. Without special action, this leads to a loop that keeps on matching the same substring. We must detect this case and arrange to move the start on by one character. The pcre2_get_startchar() function returns the starting offset that was passed to pcre2_match(). */ else { PCRE2_SIZE startchar = pcre2_get_startchar(match_data); if (start_offset <= startchar) { if (startchar >= subject_length) break; /* Reached end of subject. */ start_offset = startchar + 1; /* Advance by one character. */ if (utf8) /* If UTF-8, it may be more */ { /* than one code unit. */ for (; start_offset < subject_length; start_offset++) if ((subject[start_offset] & 0xc0) != 0x80) break; } } } /* Run the next matching operation */ rc = pcre2_match( re, /* the compiled pattern */ subject, /* the subject string */ subject_length, /* the length of the subject */ start_offset, /* starting offset in the subject */ options, /* options */ match_data, /* block for storing the result */ NULL); /* use default match context */ /* This time, a result of NOMATCH isn't an error. If the value in "options" is zero, it just means we have found all possible matches, so the loop ends. Otherwise, it means we have failed to find a non-empty-string match at a point where there was a previous empty-string match. In this case, we do what Perl does: advance the matching position by one character, and continue. We do this by setting the "end of previous match" offset, because that is picked up at the top of the loop as the point at which to start again. There are two complications: (a) When CRLF is a valid newline sequence, and the current position is just before it, advance by an extra byte. (b) Otherwise we must ensure that we skip an entire UTF character if we are in UTF mode. */ if (rc == PCRE2_ERROR_NOMATCH) { if (options == 0) break; /* All matches found */ ovector[1] = start_offset + 1; /* Advance one code unit */ if (crlf_is_newline && /* If CRLF is a newline & */ start_offset < subject_length - 1 && /* we are at CRLF, */ subject[start_offset] == '\r' && subject[start_offset + 1] == '\n') ovector[1] += 1; /* Advance by one more. */ else if (utf8) /* Otherwise, ensure we */ { /* advance a whole UTF-8 */ while (ovector[1] < subject_length) /* character. */ { if ((subject[ovector[1]] & 0xc0) != 0x80) break; ovector[1] += 1; } } continue; /* Go round the loop again */ } /* Other matching errors are not recoverable. */ if (rc < 0) { printf("Matching error %d\n", rc); pcre2_match_data_free(match_data); pcre2_code_free(re); return 1; } /* Match succeeded */ printf("\nMatch succeeded again at offset %d\n", (int)ovector[0]); /* The match succeeded, but the output vector wasn't big enough. This should not happen. */ if (rc == 0) printf("ovector was not big enough for all the captured substrings\n"); /* We must guard against patterns such as /(?=.\K)/ that use \K in an assertion to set the start of a match later than its end. In this demonstration program, we just detect this case and give up. */ if (ovector[0] > ovector[1]) { printf("\\K was used in an assertion to set the match start after its end.\n" "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]), (char *)(subject + ovector[1])); printf("Run abandoned\n"); pcre2_match_data_free(match_data); pcre2_code_free(re); return 1; } /* As before, show substrings stored in the output vector by number, and then also any named substrings. */ for (i = 0; i < rc; i++) { PCRE2_SPTR substring_start = subject + ovector[2*i]; size_t substring_length = ovector[2*i+1] - ovector[2*i]; printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start); } if (namecount == 0) printf("No named substrings\n"); else { PCRE2_SPTR tabptr = name_table; printf("Named substrings\n"); for (i = 0; i < namecount; i++) { int n = (tabptr[0] << 8) | tabptr[1]; printf("(%d) %*s: %.*s\n", n, name_entry_size - 3, tabptr + 2, (int)(ovector[2*n+1] - ovector[2*n]), subject + ovector[2*n]); tabptr += name_entry_size; } } } /* End of loop to find second and subsequent matches */ printf("\n"); pcre2_match_data_free(match_data); pcre2_code_free(re); return 0; } /* End of pcre2demo.c */
40.234127
81
0.608591
[ "vector" ]
31443cfc2d89175977fad0fc22729ce494c4e92b
2,528
h
C
src/mafGUI/mafOperationWidget.h
tartarini/MAF3
f9614d36591754544b23e3a670980799254dfd2c
[ "Apache-2.0" ]
1
2021-05-10T19:01:48.000Z
2021-05-10T19:01:48.000Z
src/mafGUI/mafOperationWidget.h
examyes/MAF3
f9614d36591754544b23e3a670980799254dfd2c
[ "Apache-2.0" ]
null
null
null
src/mafGUI/mafOperationWidget.h
examyes/MAF3
f9614d36591754544b23e3a670980799254dfd2c
[ "Apache-2.0" ]
1
2018-02-06T03:51:57.000Z
2018-02-06T03:51:57.000Z
/* * mafOperationWidget.h * mafGUI * * Created by Paolo Quadrani on 08/02/11. * Copyright 2011 SCS-B3C. All rights reserved. * * See Licence at: http://tiny.cc/QXJ4D * */ #ifndef MAFOPERATIONWIDGET_H #define MAFOPERATIONWIDGET_H // Includes list #include "mafGUIDefinitions.h" #include <QWidget> // forward declarations class mafImporterWidget; namespace Ui { class mafOperationWidget; } // Class forwarding list class mafObjectBase; /// Base panel on which will be shown all MAF operation. /** Class name: mafOperationWidget This class is the base panel for oll the MAF operations. This widget create the Ok/Cancel buttons to manage the start and stop operation execution. When a new operation has started, the mafOperationWidget is created and get the pointer to the mafOperation (algorithmic code) and to the UI loaded. It then connect the widgets contained into the UI with the slots presents inside the mafOperation and initialize the widgets with the operation's properties. When the operation is dismissed (with Ok or Cancel) it emits the signal operationDismissed to notify the mafGUIManager that the operation execution is terminated and the GUI of the main window has to be updated. */ class mafOperationWidget : public QWidget { Q_OBJECT Q_PROPERTY(QString operationName READ operationName WRITE setOperationName) public: /// Object constructor. mafOperationWidget(QWidget *parent = 0); /// Object destructor. ~mafOperationWidget(); /// Assign the current operation void setOperation(mafCore::mafObjectBase *op); /// Assign the operation's name associated to the menu label. void setOperationName(QString name); /// Return the operation name. QString operationName() const; /// Assign the operation's GUI void setOperationGUI(QWidget *gui); Q_SIGNALS: /// Signal to alert the observet that the operation GUI has been dismissed. void operationDismissed(); public Q_SLOTS: /// Execute the operation void execute(); /// Cancel the operation. void cancel(); protected: /// Method called when the user update the Application's locale. void changeEvent(QEvent *e); private: Ui::mafOperationWidget *ui; ///< Pointer to the associated UI file mafCore::mafObjectBase *m_Operation; ///< Pointer to the current running operation. QWidget *m_OperationGUI; ///< GUI associated to m_Operation. mafImporterWidget *m_ImporterWidget; }; #endif // MAFOPERATIONWIDGET_H
30.095238
161
0.735364
[ "object" ]
3145bca00e6079630ceb4af7222a02bea5b024e4
2,477
h
C
mcrouter/lib/routes/AllMajorityRoute.h
alynx282/mcrouter
b16af1a119eee775b051d323cb885b73fdf75757
[ "MIT" ]
null
null
null
mcrouter/lib/routes/AllMajorityRoute.h
alynx282/mcrouter
b16af1a119eee775b051d323cb885b73fdf75757
[ "MIT" ]
null
null
null
mcrouter/lib/routes/AllMajorityRoute.h
alynx282/mcrouter
b16af1a119eee775b051d323cb885b73fdf75757
[ "MIT" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <memory> #include <string> #include <vector> #include <folly/fibers/AddTasks.h> #include "mcrouter/lib/McResUtil.h" #include "mcrouter/lib/Reply.h" #include "mcrouter/lib/RouteHandleTraverser.h" #include "mcrouter/lib/mc/msg.h" namespace facebook { namespace memcache { /** * Sends the same request to all child route handles. * Collects replies until some result appears (half + 1) times * (or all results if that never happens). * Responds with one of the replies with the most common result. * Ties are broken using Reply::reduce(). */ template <class RouteHandleIf> class AllMajorityRoute { public: static std::string routeName() { return "all-majority"; } template <class Request> bool traverse( const Request& req, const RouteHandleTraverser<RouteHandleIf>& t) const { return t(children_, req); } explicit AllMajorityRoute(std::vector<std::shared_ptr<RouteHandleIf>> rh) : children_(std::move(rh)) { assert(!children_.empty()); } template <class Request> ReplyT<Request> route(const Request& req) const { using Reply = ReplyT<Request>; std::vector<std::function<Reply()>> funcs; funcs.reserve(children_.size()); auto reqCopy = std::make_shared<Request>(req); for (auto& rh : children_) { funcs.push_back([reqCopy, rh]() { return rh->route(*reqCopy); }); } std::array<size_t, static_cast<size_t>(mc_nres)> counts; counts.fill(0); size_t majorityCount = 0; Reply majorityReply = createReply(DefaultReply, req); auto taskIt = folly::fibers::addTasks(funcs.begin(), funcs.end()); taskIt.reserve(children_.size() / 2 + 1); while (taskIt.hasNext() && majorityCount < children_.size() / 2 + 1) { auto reply = taskIt.awaitNext(); auto result = static_cast<size_t>(*reply.result_ref()); ++counts[result]; if ((counts[result] == majorityCount && worseThan(*reply.result_ref(), *majorityReply.result_ref())) || (counts[result] > majorityCount)) { majorityReply = std::move(reply); majorityCount = counts[result]; } } return majorityReply; } private: const std::vector<std::shared_ptr<RouteHandleIf>> children_; }; } // namespace memcache } // namespace facebook
27.831461
75
0.673799
[ "vector" ]
314bf365ce51f32b210438e96e6e34aa07f438fb
15,826
c
C
yahoo/libyahoo2_partial.c
fioresoft/NO5
0acb1fdf191e3aa1e6f082ae996c1bf2a545e6c4
[ "MIT" ]
6
2017-06-01T01:28:11.000Z
2022-01-06T13:24:42.000Z
yahoo/libyahoo2_partial.c
fioresoft/NO5
0acb1fdf191e3aa1e6f082ae996c1bf2a545e6c4
[ "MIT" ]
null
null
null
yahoo/libyahoo2_partial.c
fioresoft/NO5
0acb1fdf191e3aa1e6f082ae996c1bf2a545e6c4
[ "MIT" ]
2
2021-07-05T01:17:23.000Z
2022-01-06T13:24:44.000Z
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <ctype.h> #include "yahoolib2_partial.h" #include "md5.h" #include "sha.h" #include "yahoo_util.h" // only for FREE #include "yahoo_fn.h" #define snprintf _snprintf extern char *yahoo_crypt(char *key, char *salt); static char base64digits[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789._"; static void to_y64(unsigned char *out, const unsigned char *in, int inlen) /* raw bytes in quasi-big-endian order to base 64 string (NUL-terminated) */ { for (; inlen >= 3; inlen -= 3) { *out++ = base64digits[in[0] >> 2]; *out++ = base64digits[((in[0]<<4) & 0x30) | (in[1]>>4)]; *out++ = base64digits[((in[1]<<2) & 0x3c) | (in[2]>>6)]; *out++ = base64digits[in[2] & 0x3f]; in += 3; } if (inlen > 0) { unsigned char fragment; *out++ = base64digits[in[0] >> 2]; fragment = (in[0] << 4) & 0x30; if (inlen > 1) fragment |= in[1] >> 4; *out++ = base64digits[fragment]; *out++ = (inlen < 2) ? '-' : base64digits[(in[1] << 2) & 0x3c]; *out++ = '-'; } *out = '\0'; } // libyahoo2 name: //static void yahoo_process_auth_pre_0x0b(struct yahoo_input_data *yid, // const char *seed, const char *sn) // result6 and result96 must be at least 25 characters long // user is yd->user // pw is yd->pw void GetYahooStringsPreVer11(const char *seed,const char *sn, char *user,char *pw,unsigned char *result6,unsigned char *result96) { /* So, Yahoo has stopped supporting its older clients in India, and * undoubtedly will soon do so in the rest of the world. * * The new clients use this authentication method. I warn you in * advance, it's bizzare, convoluted, inordinately complicated. * It's also no more secure than crypt() was. The only purpose this * scheme could serve is to prevent third part clients from connecting * to their servers. * * Sorry, Yahoo. */ md5_byte_t result[16]; md5_state_t ctx; char *crypt_result; unsigned char *password_hash = malloc(25); unsigned char *crypt_hash = malloc(25); unsigned char *hash_string_p = malloc(50 + strlen(sn)); unsigned char *hash_string_c = malloc(50 + strlen(sn)); char checksum; int sv; //unsigned char *result6 = malloc(25); //unsigned char *result96 = malloc(25); sv = seed[15]; sv = (sv % 8) % 5; md5_init(&ctx); md5_append(&ctx, (md5_byte_t *)pw, strlen(pw)); md5_finish(&ctx, result); to_y64(password_hash, result, 16); md5_init(&ctx); crypt_result = yahoo_crypt(pw, "$1$_2S43d5f$"); md5_append(&ctx, (md5_byte_t *)crypt_result, strlen(crypt_result)); md5_finish(&ctx, result); to_y64(crypt_hash, result, 16); free(crypt_result); switch (sv) { case 0: checksum = seed[seed[7] % 16]; snprintf((char *)hash_string_p, strlen(sn) + 50, "%c%s%s%s", checksum, password_hash, user, seed); snprintf((char *)hash_string_c, strlen(sn) + 50, "%c%s%s%s", checksum, crypt_hash, user, seed); break; case 1: checksum = seed[seed[9] % 16]; snprintf((char *)hash_string_p, strlen(sn) + 50, "%c%s%s%s", checksum, user, seed, password_hash); snprintf((char *)hash_string_c, strlen(sn) + 50, "%c%s%s%s", checksum, user, seed, crypt_hash); break; case 2: checksum = seed[seed[15] % 16]; snprintf((char *)hash_string_p, strlen(sn) + 50, "%c%s%s%s", checksum, seed, password_hash, user); snprintf((char *)hash_string_c, strlen(sn) + 50, "%c%s%s%s", checksum, seed, crypt_hash, user); break; case 3: checksum = seed[seed[1] % 16]; snprintf((char *)hash_string_p, strlen(sn) + 50, "%c%s%s%s", checksum, user, password_hash, seed); snprintf((char *)hash_string_c, strlen(sn) + 50, "%c%s%s%s", checksum, user, crypt_hash, seed); break; case 4: checksum = seed[seed[3] % 16]; snprintf((char *)hash_string_p, strlen(sn) + 50, "%c%s%s%s", checksum, password_hash, seed, user); snprintf((char *)hash_string_c, strlen(sn) + 50, "%c%s%s%s", checksum, crypt_hash, seed, user); break; } md5_init(&ctx); md5_append(&ctx, (md5_byte_t *)hash_string_p, strlen((char *)hash_string_p)); md5_finish(&ctx, result); to_y64(result6, result, 16); md5_init(&ctx); md5_append(&ctx, (md5_byte_t *)hash_string_c, strlen((char *)hash_string_c)); md5_finish(&ctx, result); to_y64(result96, result, 16); //FREE(result6); //FREE(result96); FREE(password_hash); FREE(crypt_hash); FREE(hash_string_p); FREE(hash_string_c); } /* * New auth protocol cracked by Cerulean Studios and sent in to Gaim */ //static void yahoo_process_auth_0x0b(struct yahoo_input_data *yid, const char *seed, const char *sn) // resp_6 and resp_96 must be 100 chars void GetYahooStringsVer11(const char *seed,const char *sn, char *pw,char *res6,char *res96) { //struct yahoo_packet *pack = NULL; //struct yahoo_data *yd = yid->yd; md5_byte_t result[16]; md5_state_t ctx; SHA_CTX ctx1; SHA_CTX ctx2; char *alphabet1 = "FBZDWAGHrJTLMNOPpRSKUVEXYChImkwQ"; char *alphabet2 = "F0E1D2C3B4A59687abcdefghijklmnop"; char *challenge_lookup = "qzec2tb3um1olpar8whx4dfgijknsvy5"; char *operand_lookup = "+|&%/*^-"; char *delimit_lookup = ",;"; unsigned char *password_hash = malloc(25); unsigned char *crypt_hash = malloc(25); char *crypt_result = NULL; unsigned char pass_hash_xor1[64]; unsigned char pass_hash_xor2[64]; unsigned char crypt_hash_xor1[64]; unsigned char crypt_hash_xor2[64]; unsigned char chal[7]; char resp_6[100]; char resp_96[100]; unsigned char digest1[20]; unsigned char digest2[20]; unsigned char magic_key_char[4]; const unsigned char *magic_ptr; unsigned int magic[64]; unsigned int magic_work=0; char comparison_src[20]; int x, j, i; int cnt = 0; int magic_cnt = 0; int magic_len; int depth =0, table =0; memset(&pass_hash_xor1, 0, 64); memset(&pass_hash_xor2, 0, 64); memset(&crypt_hash_xor1, 0, 64); memset(&crypt_hash_xor2, 0, 64); memset(&digest1, 0, 20); memset(&digest2, 0, 20); memset(&magic, 0, 64); memset(&resp_6, 0, 100); memset(&resp_96, 0, 100); memset(&magic_key_char, 0, 4); /* * Magic: Phase 1. Generate what seems to be a 30 * byte value (could change if base64 * ends up differently? I don't remember and I'm * tired, so use a 64 byte buffer. */ magic_ptr = (unsigned char *)seed; while (*magic_ptr != (int)NULL) { char *loc; /* Ignore parentheses. */ if (*magic_ptr == '(' || *magic_ptr == ')') { magic_ptr++; continue; } /* Characters and digits verify against the challenge lookup. */ if (isalpha(*magic_ptr) || isdigit(*magic_ptr)) { loc = strchr(challenge_lookup, *magic_ptr); if (!loc) { /* This isn't good */ continue; } /* Get offset into lookup table and lsh 3. */ magic_work = loc - challenge_lookup; magic_work <<= 3; magic_ptr++; continue; } else { unsigned int local_store; loc = strchr(operand_lookup, *magic_ptr); if (!loc) { /* Also not good. */ continue; } local_store = loc - operand_lookup; /* Oops; how did this happen? */ if (magic_cnt >= 64) break; magic[magic_cnt++] = magic_work | local_store; magic_ptr++; continue; } } magic_len = magic_cnt; magic_cnt = 0; /* Magic: Phase 2. Take generated magic value and * sprinkle fairy dust on the values. */ for (magic_cnt = magic_len-2; magic_cnt >= 0; magic_cnt--) { unsigned char byte1; unsigned char byte2; /* Bad. Abort. */ if (magic_cnt >= magic_len) { //WARNING(("magic_cnt(%d) magic_len(%d)", magic_cnt, magic_len)) break; } byte1 = magic[magic_cnt]; byte2 = magic[magic_cnt+1]; byte1 *= 0xcd; byte1 ^= byte2; magic[magic_cnt+1] = byte1; } /* Magic: Phase 3. This computes 20 bytes. The first 4 bytes are used as our magic * key (and may be changed later); the next 16 bytes are an MD5 sum of the magic key * plus 3 bytes. The 3 bytes are found by looping, and they represent the offsets * into particular functions we'll later call to potentially alter the magic key. * * %-) */ magic_cnt = 1; x = 0; do { unsigned int bl = 0; unsigned int cl = magic[magic_cnt++]; if (magic_cnt >= magic_len) break; if (cl > 0x7F) { if (cl < 0xe0) bl = cl = (cl & 0x1f) << 6; else { bl = magic[magic_cnt++]; cl = (cl & 0x0f) << 6; bl = ((bl & 0x3f) + cl) << 6; } cl = magic[magic_cnt++]; bl = (cl & 0x3f) + bl; } else bl = cl; comparison_src[x++] = (bl & 0xff00) >> 8; comparison_src[x++] = bl & 0xff; } while (x < 20); /* Dump magic key into a char for SHA1 action. */ for(x = 0; x < 4; x++) magic_key_char[x] = comparison_src[x]; /* Compute values for recursive function table! */ memcpy( chal, magic_key_char, 4 ); x = 1; for( i = 0; i < 0xFFFF && x; i++ ) { for( j = 0; j < 5 && x; j++ ) { chal[4] = i; chal[5] = i >> 8; chal[6] = j; md5_init( &ctx ); md5_append( &ctx, chal, 7 ); md5_finish( &ctx, result ); if( memcmp( comparison_src + 4, result, 16 ) == 0 ) { depth = i; table = j; x = 0; } } } /* Transform magic_key_char using transform table */ x = magic_key_char[3] << 24 | magic_key_char[2] << 16 | magic_key_char[1] << 8 | magic_key_char[0]; x = yahoo_xfrm( table, depth, x ); x = yahoo_xfrm( table, depth, x ); magic_key_char[0] = x & 0xFF; magic_key_char[1] = x >> 8 & 0xFF; magic_key_char[2] = x >> 16 & 0xFF; magic_key_char[3] = x >> 24 & 0xFF; /* Get password and crypt hashes as per usual. */ md5_init(&ctx); md5_append(&ctx, (md5_byte_t *)pw, strlen(pw)); md5_finish(&ctx, result); to_y64(password_hash, result, 16); md5_init(&ctx); crypt_result = yahoo_crypt(pw, "$1$_2S43d5f$"); md5_append(&ctx, (md5_byte_t *)crypt_result, strlen(crypt_result)); md5_finish(&ctx, result); to_y64(crypt_hash, result, 16); /* Our first authentication response is based off * of the password hash. */ for (x = 0; x < (int)strlen((char *)password_hash); x++) pass_hash_xor1[cnt++] = password_hash[x] ^ 0x36; if (cnt < 64) memset(&(pass_hash_xor1[cnt]), 0x36, 64-cnt); cnt = 0; for (x = 0; x < (int)strlen((char *)password_hash); x++) pass_hash_xor2[cnt++] = password_hash[x] ^ 0x5c; if (cnt < 64) memset(&(pass_hash_xor2[cnt]), 0x5c, 64-cnt); shaInit(&ctx1); shaInit(&ctx2); /* The first context gets the password hash XORed * with 0x36 plus a magic value * which we previously extrapolated from our * challenge. */ shaUpdate(&ctx1, pass_hash_xor1, 64); if (j >= 3) ctx1.sizeLo = 0x1ff; shaUpdate(&ctx1, magic_key_char, 4); shaFinal(&ctx1, digest1); /* The second context gets the password hash XORed * with 0x5c plus the SHA-1 digest * of the first context. */ shaUpdate(&ctx2, pass_hash_xor2, 64); shaUpdate(&ctx2, digest1, 20); shaFinal(&ctx2, digest2); /* Now that we have digest2, use it to fetch * characters from an alphabet to construct * our first authentication response. */ for (x = 0; x < 20; x += 2) { unsigned int val = 0; unsigned int lookup = 0; char byte[6]; memset(&byte, 0, 6); /* First two bytes of digest stuffed * together. */ val = digest2[x]; val <<= 8; val += digest2[x+1]; lookup = (val >> 0x0b); lookup &= 0x1f; if (lookup >= strlen(alphabet1)) break; sprintf(byte, "%c", alphabet1[lookup]); strcat(resp_6, byte); strcat(resp_6, "="); lookup = (val >> 0x06); lookup &= 0x1f; if (lookup >= strlen(alphabet2)) break; sprintf(byte, "%c", alphabet2[lookup]); strcat(resp_6, byte); lookup = (val >> 0x01); lookup &= 0x1f; if (lookup >= strlen(alphabet2)) break; sprintf(byte, "%c", alphabet2[lookup]); strcat(resp_6, byte); lookup = (val & 0x01); if (lookup >= strlen(delimit_lookup)) break; sprintf(byte, "%c", delimit_lookup[lookup]); strcat(resp_6, byte); } /* Our second authentication response is based off * of the crypto hash. */ cnt = 0; memset(&digest1, 0, 20); memset(&digest2, 0, 20); for (x = 0; x < (int)strlen((char *)crypt_hash); x++) crypt_hash_xor1[cnt++] = crypt_hash[x] ^ 0x36; if (cnt < 64) memset(&(crypt_hash_xor1[cnt]), 0x36, 64-cnt); cnt = 0; for (x = 0; x < (int)strlen((char *)crypt_hash); x++) crypt_hash_xor2[cnt++] = crypt_hash[x] ^ 0x5c; if (cnt < 64) memset(&(crypt_hash_xor2[cnt]), 0x5c, 64-cnt); shaInit(&ctx1); shaInit(&ctx2); /* The first context gets the password hash XORed * with 0x36 plus a magic value * which we previously extrapolated from our * challenge. */ shaUpdate(&ctx1, crypt_hash_xor1, 64); if (j >= 3) ctx1.sizeLo = 0x1ff; shaUpdate(&ctx1, magic_key_char, 4); shaFinal(&ctx1, digest1); /* The second context gets the password hash XORed * with 0x5c plus the SHA-1 digest * of the first context. */ shaUpdate(&ctx2, crypt_hash_xor2, 64); shaUpdate(&ctx2, digest1, 20); shaFinal(&ctx2, digest2); /* Now that we have digest2, use it to fetch * characters from an alphabet to construct * our first authentication response. */ for (x = 0; x < 20; x += 2) { unsigned int val = 0; unsigned int lookup = 0; char byte[6]; memset(&byte, 0, 6); /* First two bytes of digest stuffed * together. */ val = digest2[x]; val <<= 8; val += digest2[x+1]; lookup = (val >> 0x0b); lookup &= 0x1f; if (lookup >= strlen(alphabet1)) break; sprintf(byte, "%c", alphabet1[lookup]); strcat(resp_96, byte); strcat(resp_96, "="); lookup = (val >> 0x06); lookup &= 0x1f; if (lookup >= strlen(alphabet2)) break; sprintf(byte, "%c", alphabet2[lookup]); strcat(resp_96, byte); lookup = (val >> 0x01); lookup &= 0x1f; if (lookup >= strlen(alphabet2)) break; sprintf(byte, "%c", alphabet2[lookup]); strcat(resp_96, byte); lookup = (val & 0x01); if (lookup >= strlen(delimit_lookup)) break; sprintf(byte, "%c", delimit_lookup[lookup]); strcat(resp_96, byte); } /* pack = yahoo_packet_new(YAHOO_SERVICE_AUTHRESP, yd->initial_status, yd->session_id); yahoo_packet_hash(pack, 0, sn); yahoo_packet_hash(pack, 6, resp_6); yahoo_packet_hash(pack, 96, resp_96); yahoo_packet_hash(pack, 1, sn); yahoo_send_packet(yid, pack, 0); yahoo_packet_free(pack); */ memcpy(res6,&resp_6[0],sizeof(resp_6)/sizeof(resp_6[0])); memcpy(res96,&resp_96[0],sizeof(resp_6)/sizeof(resp_96[0])); free(password_hash); free(crypt_hash); } /* static void yahoo_process_auth(struct yahoo_input_data *yid, struct yahoo_packet *pkt) { char *seed = NULL; char *sn = NULL; YList *l = pkt->hash; int m = 0; while (l) { struct yahoo_pair *pair = l->data; if (pair->key == 94) seed = pair->value; if (pair->key == 1) sn = pair->value; if (pair->key == 13) m = atoi(pair->value); l = l->next; } if (!seed) return; switch (m) { case 0: yahoo_process_auth_pre_0x0b(yid, seed, sn); break; case 1: yahoo_process_auth_0x0b(yid, seed, sn); break; default: // call error WARNING(("unknown auth type %d", m)); yahoo_process_auth_0x0b(yid, seed, sn); break; } } */
25.691558
102
0.607608
[ "transform" ]
3150839569f593603c5986a22e08f2d44f6657dd
4,787
h
C
libQGLViewer-2.2.6-1/QGLViewer/VRender/Exporter.h
szmurlor/fiver
083251420eb934d860c99dcf1eb07ae5b8ba7e8c
[ "Apache-2.0" ]
null
null
null
libQGLViewer-2.2.6-1/QGLViewer/VRender/Exporter.h
szmurlor/fiver
083251420eb934d860c99dcf1eb07ae5b8ba7e8c
[ "Apache-2.0" ]
null
null
null
libQGLViewer-2.2.6-1/QGLViewer/VRender/Exporter.h
szmurlor/fiver
083251420eb934d860c99dcf1eb07ae5b8ba7e8c
[ "Apache-2.0" ]
null
null
null
/* This file is part of the VRender library. Copyright (C) 2005 Cyril Soler (Cyril.Soler@imag.fr) Version 1.0.0, released on June 27, 2005. http://artis.imag.fr/Members/Cyril.Soler/VRender VRender 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. VRender 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 VRender; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /**************************************************************************** Copyright (C) 2002-2006 Gilles Debunne (Gilles.Debunne@imag.fr) This file is part of the QGLViewer library. Version 2.2.6-1, released on July 4, 2007. http://artis.imag.fr/Members/Gilles.Debunne/QGLViewer libQGLViewer 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. libQGLViewer 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 libQGLViewer; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *****************************************************************************/ #ifndef _VRENDER_EXPORTER_H #define _VRENDER_EXPORTER_H // Set of classes for exporting in various formats, like EPS, XFig3.2, SVG. #include "Primitive.h" namespace vrender { class VRenderParams ; class Exporter { public: Exporter() ; virtual ~Exporter() {}; virtual void exportToFile(const char *filename,const std::vector<PtrPrimitive>&,VRenderParams&) ; void setBoundingBox(float xmin,float ymin,float xmax,float ymax) ; void setClearColor(float r,float g,float b) ; void setClearBackground(bool b) ; void setBlackAndWhite(bool b) ; protected: virtual void spewPoint(const Point *,FILE *) = 0 ; virtual void spewSegment(const Segment *,FILE *) = 0 ; virtual void spewPolygone(const Polygone *,FILE *) = 0 ; virtual void writeHeader(FILE *) const = 0 ; virtual void writeFooter(FILE *) const = 0 ; float _clearR,_clearG,_clearB ; float _pointSize ; float _lineWidth ; GLfloat _xmin,_xmax,_ymin,_ymax,_zmin,_zmax ; bool _clearBG,_blackAndWhite ; }; // Exports to encapsulated postscript. class EPSExporter: public Exporter { public: EPSExporter() ; virtual ~EPSExporter() {}; protected: virtual void spewPoint(const Point *,FILE *) ; virtual void spewSegment(const Segment *,FILE *) ; virtual void spewPolygone(const Polygone *,FILE *) ; virtual void writeHeader(FILE *) const ; virtual void writeFooter(FILE *) const ; private: void setColor(FILE *,float,float,float) ; static const double EPS_GOURAUD_THRESHOLD ; static const char *GOURAUD_TRIANGLE_EPS[] ; static const char *CREATOR ; static float last_r ; static float last_g ; static float last_b ; }; // Exports to postscript. The only difference is the filename extension and // the showpage at the end. class PSExporter: public EPSExporter { public: virtual ~PSExporter() {}; protected: virtual void writeFooter(FILE *) const ; }; class FIGExporter: public Exporter { public: FIGExporter() ; virtual ~FIGExporter() {}; protected: virtual void spewPoint(const Point *,FILE *) ; virtual void spewSegment(const Segment *,FILE *) ; virtual void spewPolygone(const Polygone *,FILE *) ; virtual void writeHeader(FILE *) const ; virtual void writeFooter(FILE *) const ; private: mutable int _sizeX ; mutable int _sizeY ; mutable int _depth ; int FigCoordX(double) const ; int FigCoordY(double) const ; int FigGrayScaleIndex(float red, float green, float blue) const ; }; #ifdef A_FAIRE class SVGExporter: public Exporter { protected: virtual void spewPoint(const Point *,FILE *) ; virtual void spewSegment(const Segment *,FILE *) ; virtual void spewPolygone(const Polygone *,FILE *) ; virtual void writeHeader(FILE *) const ; virtual void writeFooter(FILE *) const ; }; #endif } #endif
29.012121
100
0.703572
[ "vector" ]
315945b8a61ce10148744004f29ac9d881650402
1,782
h
C
sourceCode/application/ui/project/dialog_exportresult.h
lp-rep/stackprof-1
62d9cb96ad7dcdaa26b6383559f542cadc1c7af2
[ "CECILL-B" ]
2
2022-02-27T20:08:04.000Z
2022-03-03T13:45:40.000Z
sourceCode/application/ui/project/dialog_exportresult.h
lp-rep/stackprof-1
62d9cb96ad7dcdaa26b6383559f542cadc1c7af2
[ "CECILL-B" ]
1
2021-06-07T17:09:04.000Z
2021-06-11T11:48:23.000Z
sourceCode/application/ui/project/dialog_exportresult.h
lp-rep/stackprof-1
62d9cb96ad7dcdaa26b6383559f542cadc1c7af2
[ "CECILL-B" ]
1
2021-06-03T21:06:55.000Z
2021-06-03T21:06:55.000Z
#ifndef DIALOG_EXPORTRESULT_H #define DIALOG_EXPORTRESULT_H #include <QDialog> #include "../../logic/model/core/exportResult.h" namespace Ui { class Dialog_exportResult; } class Dialog_exportResult : public QDialog { Q_OBJECT public: explicit Dialog_exportResult(QWidget *parent = nullptr); //void setExportSettings(const S_ExportSettings& sExportSettings); void setCurrentBoxId(int currentBoxId); void setSomeFlaggedProfilExist(bool bSomeFlaggedProfilExist_anyBoxes, bool bSomeFlaggedProfilExistForCurrentBoxId); //void setCurrentBoxId(int currentBoxId); //S_ExportSettings getExportSettings(); ~Dialog_exportResult(); public slots: void slot_radioButton_json_toggled(bool bChecked); void slot_radioButton_ascii_toggled(bool bChecked); void slot_radioButton_allBoxes_toggled(bool bChecked); void slot_radioButton_onlyCurrentBox_toggled(bool bChecked); void slot_checkBox_includeProfilesCurvesData_stateChanged(int iCheckState); void slot_selectOutputFileAndExport(); void slot_checkBox_setLinRegResultAsEmpty_stateChanged(int iCheckState); void slot_checkBox_setProfileCurveDataAsEmpty_stateChanged(int iCheckState); signals: void signal_project_exportResult(S_ExportSettings sExportSettings); private: void setExportSettings(const S_ExportSettings& sExportSettings); void updateEnableWidgetState_aboutSomeFlaggedProfilExistStates(); private: Ui::Dialog_exportResult *ui; S_ExportSettings _sExportSettings; bool _bSomeFlaggedProfilExist_anyBoxes; bool _bSomeFlaggedProfilExistForCurrentBoxId; //bool _bUiSetLogicFields_forsetProfileCurveDataAsEmpty; bool _bUiSetLogicFields_forsetAsEmpty; }; #endif // DIALOG_EXPORTRESULT_H
27.415385
80
0.795174
[ "model" ]
315abf310d56ae9dfc171f354ca3e97a779fe56e
5,584
h
C
g_src/ViewBase.h
yolonir/df-build
18db73fc61309f444d5d68ced73882365ff865a0
[ "FTL", "Unlicense" ]
21
2015-02-01T21:01:57.000Z
2021-08-15T11:01:58.000Z
g_src/ViewBase.h
yolonir/df-build
18db73fc61309f444d5d68ced73882365ff865a0
[ "FTL", "Unlicense" ]
3
2017-03-22T17:32:43.000Z
2018-08-21T15:55:07.000Z
g_src/ViewBase.h
yolonir/df-build
18db73fc61309f444d5d68ced73882365ff865a0
[ "FTL", "Unlicense" ]
6
2015-10-12T07:19:11.000Z
2019-03-28T15:15:36.000Z
#ifndef VIEWBASE_H #define VIEWBASE_H #include <set> #include <map> #include <string> #include "keybindings.h" #include "graphics.h" enum InterfaceBreakdownTypes { INTERFACE_BREAKDOWN_NONE, INTERFACE_BREAKDOWN_QUIT, INTERFACE_BREAKDOWN_STOPSCREEN, INTERFACE_BREAKDOWN_TOFIRST, INTERFACE_BREAKDOWNNUM }; class viewscreenst { public: viewscreenst *child; viewscreenst *parent; char breakdownlevel; char option_key_pressed; virtual void feed(std::set<InterfaceKey> &events){} virtual void logic(){} virtual void render(){} virtual void resize(int w, int h){} virtual void help(); virtual char movies_okay(){return 1;} virtual char is_option_screen(){return 0;} virtual char is_save_screen(){return 0;} viewscreenst() { child=0; parent=0; breakdownlevel=INTERFACE_BREAKDOWN_NONE; option_key_pressed=0; } virtual ~viewscreenst(){} virtual bool key_conflict(InterfaceKey test_key); }; namespace widgets { using namespace std; template <typename T> class menu { typedef map<int,pair<string, T> > dict; dict lines; int selection; int last_displayheight; bool bleached; map<int, pair<int,int> > colors; // Given 'total' lines, with 'sel' selected, and 'space' to draw in, // returns the first line that should be drawn. int first_line(int total, int sel, int space) { // There is no doubt some clever math to do this, but I'm tired and don't care. for (int start = 0;; start += space / 2) { if (start + space/2 >= sel) return start; if (start + space >= total) return start; } } pair<string,T> mp(string s, T t) { return make_pair(s,t); } // Scrolls N lines up/down; positive = down void scroll(int n) { typename dict::iterator it = lines.find(selection); for (int i = 0; i < abs(n); i++) { if (n < 0 && it == lines.begin()) { // We've hit the top if (i) break; else { it = --(lines.end()); break; } } if (n < 0) --it; else ++it; // Scroll one line if (it == lines.end()) { // We've hit the bottom if (i) { --it; break; } else { it = lines.begin(); break; } } // If we hit neither the top nor bottom, loop. } selection = it->first; } public: menu() { clear(); } int size() { return lines.size(); } // Adds a line just past the last taken position void add(string text, T token) { if (!lines.size()) { lines[0] = mp(text,token); } else { typename dict::iterator it = --(lines.end()); lines[it->first + 1] = mp(text,token); } } // (Re)sets the text of the given line void set(int line, string text, T token) { lines[line] = mp(text,token); } // Set the color of a line void set_color(int line, int fg, int bg) { colors[line] = make_pair(fg,bg); } // Handles (page) up/down void feed(std::set<InterfaceKey> &input) { if (!lines.size()) return; if (input.count(INTERFACEKEY_STANDARDSCROLL_UP)) scroll(-1); if (input.count(INTERFACEKEY_STANDARDSCROLL_DOWN)) scroll(1); if (input.count(INTERFACEKEY_STANDARDSCROLL_PAGEUP)) scroll(-(last_displayheight / 2)); if (input.count(INTERFACEKEY_STANDARDSCROLL_PAGEDOWN)) scroll(last_displayheight / 2); } void render(int x1, int x2, int y1, int y2) { gps.erasescreen_rect(x1,x2,y1,y2); int h = y2 - y1 + 1, w = x2 - x1 + 1, x = x1, y = y1; last_displayheight = h; if (!lines.size()) return; int total = (--lines.end())->first + 1; int first = first_line(total, selection, h); typename dict::iterator it = lines.lower_bound(first); for (; it != lines.end() && it->first - first < h; ++it) { gps.locate(it->first - first + y, x); map<int,pair<int,int> >::iterator color = colors.find(it->first - first); int fg = 7, bg = 0; if (color != colors.end()) { fg = color->second.first; bg = color->second.second; } gps.changecolor(fg, bg, it->first == selection && !bleached); gps.addst(it->second.first.substr(0, w)); } } // Read out the current selection T get_selection() { return lines[selection].second; } int get_pos() { return selection; } // Set the position by line void set_pos(int pos) { if (pos < size()) selection = pos; } // Delete the currently selected line void del_selection() { typename dict::iterator it = lines.find(selection); typename dict::iterator newsel = it; ++newsel; if (newsel == lines.end()) { newsel = it; --newsel; } lines.erase(it); if (lines.size()) selection = newsel->first; } // If true, don't draw a highlight void bleach(bool b) { bleached = b; } // Reset the menu void clear() { selection = 0; lines.clear(); last_displayheight = 10; bleached = false; colors.clear(); } }; class textbox { string text; bool keep; public: textbox() { textbox("", false); } textbox(string initializer, bool keep) { this->keep = keep; text = initializer; } string get_text() { return text; } // Only cares about INTERFACEKEY_STRING events void feed(std::set<InterfaceKey> &input); void render(int x1, int x2, int y1, int y2); }; } #endif
28.20202
100
0.582199
[ "render" ]
315b3962a4969f6579a63dbab0a908c5a4828a75
584
h
C
TouTiaoApp/XiaoShiPin/View/TTXiaoShiPinDetailCell.h
SoftBoys/TouTiaoApp
90383997d5e0929fcb0bbd9fc0351807433b7c62
[ "MIT" ]
3
2018-08-08T11:44:47.000Z
2022-02-24T03:42:00.000Z
TouTiaoApp/XiaoShiPin/View/TTXiaoShiPinDetailCell.h
SoftBoys/TouTiaoApp
90383997d5e0929fcb0bbd9fc0351807433b7c62
[ "MIT" ]
null
null
null
TouTiaoApp/XiaoShiPin/View/TTXiaoShiPinDetailCell.h
SoftBoys/TouTiaoApp
90383997d5e0929fcb0bbd9fc0351807433b7c62
[ "MIT" ]
2
2018-10-12T06:47:10.000Z
2019-12-13T05:54:15.000Z
// // TTXiaoShiPinDetailCell.h // TouTiaoApp // // Created by gjw on 2018/8/10. // Copyright © 2018年 guojunwei. All rights reserved. // #import <UIKit/UIKit.h> static NSInteger kXiaoShiPinContainerViewTag = 10000; @class TTXiaoShiPinListModel, TTXiaoShiPinDetailCell; @protocol TTXiaoShiPinDetailCell <NSObject> @optional - (void)closeXiaoShiPinCell:(TTXiaoShiPinDetailCell *)cell; @end @interface TTXiaoShiPinDetailCell : UICollectionViewCell @property (nonatomic, strong) TTXiaoShiPinListModel *model; @property (nonatomic, weak) id<TTXiaoShiPinDetailCell> delegate; @end
23.36
64
0.787671
[ "model" ]
316049fcfb0e79fb34f1b4575dc17e78bdcdd8d4
1,890
h
C
Library/Tools/include/nova/Tools/Utilities/File_Utilities.h
OrionQuest/Nova
473a4df24191097c6542c3ec935b3d1bdd2cf13a
[ "Apache-2.0" ]
23
2018-08-24T01:40:56.000Z
2021-01-14T06:58:44.000Z
Library/Tools/include/nova/Tools/Utilities/File_Utilities.h
SoldierDown/Nova
d2da3ee316687316d5a858cd2b95605c483859db
[ "Apache-2.0" ]
2
2017-07-04T11:25:17.000Z
2020-10-10T12:31:01.000Z
Library/Tools/include/nova/Tools/Utilities/File_Utilities.h
SoldierDown/Nova
d2da3ee316687316d5a858cd2b95605c483859db
[ "Apache-2.0" ]
7
2017-07-02T01:10:05.000Z
2020-01-29T17:59:31.000Z
//!##################################################################### //! \file File_Utilities.h //!##################################################################### // Class File_Utilities //###################################################################### #ifndef __File_Utilities__ #define __File_Utilities__ #define BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #undef BOOST_NO_CXX11_SCOPED_ENUMS #include <nova/Tools/Read_Write/Utilities/Read_Write.h> #include <fstream> #include <iostream> namespace Nova{ namespace File_Utilities { std::string Get_Working_Directory(); bool Create_Directory(const std::string& directory); bool File_Exists(const std::string& filename,const bool use_absolute_path=true); std::istream* Safe_Open_Input(const std::string& filename,bool binary=true); std::ostream* Safe_Open_Output(const std::string& filename,bool binary=true); template<class T> inline void Read_From_File(const std::string& filename,T& object) { std::istream* input=Safe_Open_Input(filename); Read_Write<T>::Read(*input,object); delete input; } FILE* Temporary_File(); template<class T> inline void Write_To_File(const std::string& filename,const T& object) { std::ostream* output=Safe_Open_Output(filename); Read_Write<T>::Write(*output,object); delete output; } template<class T> inline void Write_To_Text_File(const std::string& filename,const T& object) { std::ostream* output=Safe_Open_Output(filename,false); *output<<object; delete output; } template<class T> inline void Read_From_Text_File(const std::string& filename,T& object) { std::istream* input=Safe_Open_Input(filename,false); *input>>object; delete input; } } } #endif
32.586207
97
0.628042
[ "object" ]
3160e5418887dce27c30022dc2182d04469a36f2
7,501
h
C
libs/containers/include/mrpt/containers/ts_hash_map.h
SupraBitKid/mrpt
f0647dba071864bf5d83a28a3653126537f6a407
[ "BSD-3-Clause" ]
null
null
null
libs/containers/include/mrpt/containers/ts_hash_map.h
SupraBitKid/mrpt
f0647dba071864bf5d83a28a3653126537f6a407
[ "BSD-3-Clause" ]
null
null
null
libs/containers/include/mrpt/containers/ts_hash_map.h
SupraBitKid/mrpt
f0647dba071864bf5d83a28a3653126537f6a407
[ "BSD-3-Clause" ]
null
null
null
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2021, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #pragma once #include <mrpt/core/common.h> // remove MSVC warnings #include <mrpt/core/integer_select.h> #include <array> #include <stdexcept> #include <string_view> namespace mrpt::containers { template <typename KEY, typename VALUE> struct ts_map_entry { bool used{false}; KEY first; VALUE second; ts_map_entry() = default; }; /** hash function used by ts_hash_map. Uses dbj2 method */ void reduced_hash(const std::string_view& value, uint8_t& hash); void reduced_hash(const std::string_view& value, uint16_t& hash); void reduced_hash(const std::string_view& value, uint32_t& hash); void reduced_hash(const std::string_view& value, uint64_t& hash); /** A thread-safe (ts) container which minimally emulates a std::map<>'s [] and * find() methods but which is implemented as a linear vector indexed by a hash * of KEY. * Any custom hash function can be implemented, we don't rely by default on * C++11 std::hash<> due to its limitation in some implementations. * * This implementation is much more efficient than std::map<> when the most * common operation is accessing elements * by KEY with find() or [], and is also thread-safe if different threads * create entries with different hash values. * * The default underlying non-associative container is a "memory-aligned * std::vector<>", but it can be changed to a * standard vector<> or to a deque<> (to avoid memory reallocations) by * changing the template parameter \a VECTOR_T. * * \note Defined in #include <mrpt/containers/ts_hash_map.h> * \ingroup mrpt_containers_grp */ template < typename KEY, typename VALUE, unsigned int NUM_BYTES_HASH_TABLE = 1, unsigned int NUM_HAS_TABLE_COLLISIONS_ALLOWED = 5, typename VECTOR_T = std::array< std::array<ts_map_entry<KEY, VALUE>, NUM_HAS_TABLE_COLLISIONS_ALLOWED>, 1u << (8 * NUM_BYTES_HASH_TABLE)>> class ts_hash_map { public: /** @name Types @{ */ using self_t = ts_hash_map< KEY, VALUE, NUM_BYTES_HASH_TABLE, NUM_HAS_TABLE_COLLISIONS_ALLOWED, VECTOR_T>; using key_type = KEY; using value_type = ts_map_entry<KEY, VALUE>; using vec_t = VECTOR_T; struct iterator; struct const_iterator { public: const_iterator() : m_vec(nullptr), m_parent(nullptr) {} const_iterator( const VECTOR_T& vec, const self_t& parent, int idx_outer, int idx_inner) : m_vec(const_cast<VECTOR_T*>(&vec)), m_parent(const_cast<self_t*>(&parent)), m_idx_outer(idx_outer), m_idx_inner(idx_inner) { } const_iterator(const const_iterator& o) { *this = o; } const_iterator& operator=(const const_iterator& o) { m_vec = o.m_vec; m_idx_outer = o.m_idx_outer; m_idx_inner = o.m_idx_inner; return *this; } bool operator==(const const_iterator& o) const { return m_vec == o.m_vec && m_idx_outer == o.m_idx_outer && m_idx_inner == o.m_idx_inner; } bool operator!=(const const_iterator& o) const { return !(*this == o); } const value_type& operator*() const { return (*m_vec)[m_idx_outer][m_idx_inner]; } const value_type* operator->() const { return &(*m_vec)[m_idx_outer][m_idx_inner]; } inline const_iterator operator++(int) { /* Post: it++ */ const_iterator aux = *this; ++(*this); return aux; } inline const_iterator& operator++() { /* pre: ++it */ incr(); return *this; } protected: VECTOR_T* m_vec; self_t* m_parent; int m_idx_outer{0}, m_idx_inner{0}; void incr() { // This loop ends with the first used entry in the nested arrays, or // an iterator pointing to "end()". do { if (++m_idx_inner >= static_cast<int>(NUM_HAS_TABLE_COLLISIONS_ALLOWED)) { m_idx_inner = 0; m_idx_outer++; } } while (m_idx_outer < static_cast<int>(m_parent->m_vec.size()) && !(*m_vec)[m_idx_outer][m_idx_inner].used); } }; struct iterator : public const_iterator { public: iterator() : const_iterator() {} iterator(VECTOR_T& vec, self_t& parent, int idx_outer, int idx_inner) : const_iterator(vec, parent, idx_outer, idx_inner) { } value_type& operator*() { return (*const_iterator::m_vec)[const_iterator::m_idx_outer] [const_iterator::m_idx_inner]; } value_type* operator->() { return &(*const_iterator::m_vec)[const_iterator::m_idx_outer] [const_iterator::m_idx_inner]; } inline iterator operator++(int) { /* Post: it++ */ iterator aux = *this; ++(*this); return aux; } inline iterator& operator++() { /* pre: ++it */ const_iterator::incr(); return *this; } }; /** @} */ private: /** The actual container */ vec_t m_vec; /** Number of elements accessed with write access so far */ size_t m_size{0}; public: /** @name Constructors, read/write access and other operations @{ */ //!< Default constructor */ ts_hash_map() = default; /** Clear the contents of this container */ void clear() { m_size = 0; for (size_t oi = 0; oi < m_vec.size(); oi++) for (size_t ii = 0; ii < NUM_HAS_TABLE_COLLISIONS_ALLOWED; ii++) m_vec[oi][ii] = value_type(); } bool empty() const { return m_size == 0; } /** noexcept version of operator[], returns nullptr upon failure */ VALUE* find_or_alloc(const KEY& key) noexcept { typename mrpt::uint_select_by_bytecount<NUM_BYTES_HASH_TABLE>::type hash; reduced_hash(key, hash); std::array<ts_map_entry<KEY, VALUE>, NUM_HAS_TABLE_COLLISIONS_ALLOWED>& match_arr = m_vec[hash]; for (unsigned int i = 0; i < NUM_HAS_TABLE_COLLISIONS_ALLOWED; i++) { if (!match_arr[i].used) { m_size++; match_arr[i].used = true; match_arr[i].first = key; return &match_arr[i].second; } if (match_arr[i].first == key) return &match_arr[i].second; } return nullptr; } /** Write/read via [i] operator, that creates an element if it didn't exist * already. */ VALUE& operator[](const KEY& key) { VALUE* v = find_or_alloc(key); if (!v) throw std::runtime_error("ts_hash_map: too many hash collisions!"); return *v; } const_iterator find(const KEY& key) const { typename mrpt::uint_select_by_bytecount<NUM_BYTES_HASH_TABLE>::type hash; reduced_hash(key, hash); const std::array< ts_map_entry<KEY, VALUE>, NUM_HAS_TABLE_COLLISIONS_ALLOWED>& match_arr = m_vec[hash]; for (unsigned int i = 0; i < NUM_HAS_TABLE_COLLISIONS_ALLOWED; i++) { if (match_arr[i].used && match_arr[i].first == key) return const_iterator(m_vec, *this, hash, i); } return this->end(); } const_iterator begin() const { const_iterator it(m_vec, *this, 0, -1); ++it; return it; } const_iterator end() const { return const_iterator(m_vec, *this, m_vec.size(), 0); } iterator begin() { iterator it(m_vec, *this, 0, -1); ++it; return it; } iterator end() { return iterator(m_vec, *this, m_vec.size(), 0); } /** @} */ }; // end class ts_hash_map } // namespace mrpt::containers
28.520913
80
0.645247
[ "vector" ]
3161221178e52205143f7842605fa4f5ecc77bf9
713
h
C
skeleton.h
MarcoLG/openglSandBox
ed796ac19a4bd9af505965f1c1ec4852ba416df3
[ "MIT" ]
null
null
null
skeleton.h
MarcoLG/openglSandBox
ed796ac19a4bd9af505965f1c1ec4852ba416df3
[ "MIT" ]
null
null
null
skeleton.h
MarcoLG/openglSandBox
ed796ac19a4bd9af505965f1c1ec4852ba416df3
[ "MIT" ]
null
null
null
#ifndef SKELETON_H #define SKELETON_H #include <vector> #include <string> #include <GLFW/glfw3.h> #include <glm/glm.hpp> class Node; class Skeleton { // Access specifier public: Skeleton(); ~Skeleton(); void setShaders(std::string vfile,std::string ffile); void loadMesh(); void draw(); void printSkeleton(Node* n=NULL); void skeletonMesh(Node* n=NULL); void skeletonVBO(); std::string vertShaderFilename; std::string fragShaderFilename; std::vector<glm::vec3> vertices; std::vector<glm::vec3> colors; GLuint programID; GLuint MatrixID; GLuint ModelMatrixID; GLuint VertexArrayID; GLuint vertexbuffer; GLuint colorbuffer; glm::mat4 ModelMatrix; Node* root; }; #endif
13.711538
54
0.71669
[ "vector" ]
316375838d41c149c5b1ea9d6dc9ca451dff5ec2
1,013
h
C
module_morse/morse.h
aehoppe/BombSquad
81444baa6683af8ffe7cbefb06d3e3cd9466ba14
[ "MIT" ]
5
2018-11-19T01:30:59.000Z
2020-08-28T14:18:56.000Z
module_morse/morse.h
aehoppe/BombSquad
81444baa6683af8ffe7cbefb06d3e3cd9466ba14
[ "MIT" ]
null
null
null
module_morse/morse.h
aehoppe/BombSquad
81444baa6683af8ffe7cbefb06d3e3cd9466ba14
[ "MIT" ]
1
2020-03-04T19:31:54.000Z
2020-03-04T19:31:54.000Z
void disp_mhz(uint16_t reading); void dispSeconds(uint16_t seconds); void doMorse(char* morse_str); void dispNumber(uint16_t number); const char morse_table[15][32] = { "... .... . .-.. .-..", //shell ".... .- .-.. .-.. ...", //halls "... .-.. .. -.-. -.-", //slick "- .-. .. -.-. -.-", //trick "-... --- -..- . ...", //boxes ".-.. . .- -.- ...", //leaks "... - .-. --- -... .", //strobe "-... .. ... - .-. ---", //bistro "..-. .-.. .. -.-. -.-", //flick "-... --- -- -... ...", //bombs "-... .-. . .- -.-", //break "-... .-. .. -.-. -.-", //brick "... - . .- -.-", //steak "... - .. -. --.", //sting "...- . -.-. - --- .-." //vector }; const uint16_t freq_table[15] = { 3505, //shell 3515, //halls 3522, //slick 3532, //trick 3535, //boxes 3542, //leaks 3545, //strobe 3552, //bistro 3555, //flick 3565, //bombs 3572, //break 3575, //brick 3582, //steak 3592, //sting 3595 //vector };
23.022727
37
0.3692
[ "vector" ]
3166fe3063a8889b64e3531e8028217474c49b57
12,518
h
C
EBookDroid/jni/djvu/GException.h
hk0792/UsefulClass
d840880d67e16de257d1e22060d71bb79091ce94
[ "Apache-2.0" ]
112
2015-01-23T03:36:47.000Z
2021-09-29T03:31:17.000Z
EBookDroid/jni/djvu/GException.h
hk0792/UsefulClass
d840880d67e16de257d1e22060d71bb79091ce94
[ "Apache-2.0" ]
null
null
null
EBookDroid/jni/djvu/GException.h
hk0792/UsefulClass
d840880d67e16de257d1e22060d71bb79091ce94
[ "Apache-2.0" ]
66
2015-03-28T15:24:16.000Z
2020-04-07T08:59:05.000Z
//C- -*- C++ -*- //C- ------------------------------------------------------------------- //C- DjVuLibre-3.5 //C- Copyright (c) 2002 Leon Bottou and Yann Le Cun. //C- Copyright (c) 2001 AT&T //C- //C- This software is subject to, and may be distributed under, the //C- GNU General Public License, either Version 2 of the license, //C- or (at your option) any later version. The license should have //C- accompanied the software or you may obtain a copy of the license //C- from the Free Software Foundation at http://www.fsf.org . //C- //C- This program is distributed in the hope that it will be useful, //C- but WITHOUT ANY WARRANTY; without even the implied warranty of //C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //C- GNU General Public License for more details. //C- //C- DjVuLibre-3.5 is derived from the DjVu(r) Reference Library from //C- Lizardtech Software. Lizardtech Software has authorized us to //C- replace the original DjVu(r) Reference Library notice by the following //C- text (see doc/lizard2002.djvu and doc/lizardtech2007.djvu): //C- //C- ------------------------------------------------------------------ //C- | DjVu (r) Reference Library (v. 3.5) //C- | Copyright (c) 1999-2001 LizardTech, Inc. All Rights Reserved. //C- | The DjVu Reference Library is protected by U.S. Pat. No. //C- | 6,058,214 and patents pending. //C- | //C- | This software is subject to, and may be distributed under, the //C- | GNU General Public License, either Version 2 of the license, //C- | or (at your option) any later version. The license should have //C- | accompanied the software or you may obtain a copy of the license //C- | from the Free Software Foundation at http://www.fsf.org . //C- | //C- | The computer code originally released by LizardTech under this //C- | license and unmodified by other parties is deemed "the LIZARDTECH //C- | ORIGINAL CODE." Subject to any third party intellectual property //C- | claims, LizardTech grants recipient a worldwide, royalty-free, //C- | non-exclusive license to make, use, sell, or otherwise dispose of //C- | the LIZARDTECH ORIGINAL CODE or of programs derived from the //C- | LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU //C- | General Public License. This grant only confers the right to //C- | infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to //C- | the extent such infringement is reasonably necessary to enable //C- | recipient to make, have made, practice, sell, or otherwise dispose //C- | of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to //C- | any greater extent that may be necessary to utilize further //C- | modifications or combinations. //C- | //C- | The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY //C- | OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED //C- | TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF //C- | MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. //C- +------------------------------------------------------------------ #ifndef _GEXCEPTION_H_ #define _GEXCEPTION_H_ #ifdef HAVE_CONFIG_H # include "config.h" #endif #if NEED_GNUG_PRAGMAS # pragma interface #endif #ifndef no_return #ifdef __GNUC__ #define no_return __attribute__ ((noreturn)) #else #define no_return #endif #endif /** @name GException.h Files #"GException.h"# and #"GException.cpp"# define a portable exception scheme used through the DjVu Reference Library. This scheme can use native C++ exceptions or an exception emulation based on #longjmp#/#setjmp#. A particular model can be forced a compile time by defining option #CPP_SUPPORTS_EXCEPTIONS# or #USE_EXCEPTION_EMULATION#. This emulation code was motivated because many compilers did not properly support exceptions as mandated by the C++ standard documents. This emulation is now considered obsolete because (a) it is not able to call the proper destructors when an exception occurs, and (b) it is not thread safe. Although all modern C++ compiler handle exception decently, the exception handling intrinsics are not always thread safe. Therefore we urge programmers to {\em only} use exceptions to signal error conditions that force the library to discontinue execution. There are four macros for handling exceptions. Macros #G_TRY#, #G_CATCH# and #G_ENDCATCH# are used to define an exception catching block. Exceptions can be thrown at all times using macro #G_THROW(cause)#. An exception can be re-thrown from a catch block using macro #G_RETHROW#. Example: \begin{verbatim} G_TRY { // program lines which may result in a call to THROW() G_THROW("message"); } G_CATCH(ex) { // Variable ex refers to a GException object. ex.perror(); // You can rethrow the exception to an outer exception handler. G_RETHROW; } G_ENDCATCH; \end{verbatim} @memo Portable exceptions. @author L\'eon Bottou <leonb@research.att.com> -- initial implementation.\\ Andrei Erofeev <eaf@geocities.com> -- fixed message memory allocation. */ //@{ #include "DjVuGlobal.h" // Check if compiler supports native exceptions #ifdef HAVE_CONFIG_H # if HAVE_EXCEPTIONS # define CPP_SUPPORTS_EXCEPTIONS # endif #else # if defined(_MSC_VER) # define CPP_SUPPORTS_EXCEPTIONS # endif # if defined(__MWERKS__) # define CPP_SUPPORTS_EXCEPTIONS # endif # if defined(__EXCEPTIONS) # define CPP_SUPPORTS_EXCEPTIONS # endif #endif // Decide which exception model to use #ifndef CPP_SUPPORTS_EXCEPTIONS # ifndef USE_EXCEPTION_EMULATION # define USE_EXCEPTION_EMULATION # endif #endif #ifdef USE_EXCEPTION_EMULATION # include <setjmp.h> #endif #ifdef HAVE_NAMESPACES namespace DJVU { # ifdef NOT_DEFINED // Just to fool emacs c++ mode } # endif #endif /** Exception class. The library always uses macros #G_TRY#, #G_THROW#, #G_CATCH# and #G_ENDCATCH# for throwing and catching exceptions (see \Ref{GException.h}). These macros only deal with exceptions of type #GException#. */ class DJVUAPI GException { public: enum source_type { GINTERNAL=0, GEXTERNAL, GAPPLICATION, GOTHER }; /** Constructs a GException. This constructor is usually called by macro #G_THROW#. Argument #cause# is a plain text error message. As a convention, string #ByteStream::EndOfFile# is used when reaching an unexpected end-of-file condition and string #DataPool::Stop# is used when the user interrupts the execution. The remaining arguments are usually provided by the predefined macros #__FILE__#, #__LINE__#, and (G++ and EGCS only) #__PRETTY_FUNCTION__#. */ GException (const char *cause, const char *file=0, int line=0, const char *func=0, const source_type source=GINTERNAL); /** Copy Constructor. */ GException (const GException & exc); /** Null Constructor. */ GException (); /** Destructor. */ virtual ~GException(void); /** Copy Operator. */ GException & operator=(const GException & exc); /** Prints an error message on stderr. This function no longer takes a message parameter because some instances used a i18n message id and other instances used a literal string. */ void perror(void) const; /** Returns the string describing the cause of the exception. The returned pointer is never null. Exception handlers should not rely on the value of the string #cause#. As a convention however, string #ByteStream::EndOfFile# is used when reaching an unexpected end-of-file condition and string #DataPool::Stop# is used when the user interrupts the execution. These strings can be tested by the exception handlers, with #cmp_cause#. Similar conventional strings may be defined in the future. They all will be small strings with only uppercase characters. */ const char* get_cause(void) const; /** Compares the cause with the specified string, ignoring anything after the first tab. */ int cmp_cause(const char s2[]) const; /** Compares the cause with the specified string, ignoring anything after the first tab. */ static int cmp_cause(const char s1[],const char s2[]); /** Returns the function name from which the exception was thrown. A null pointer is returned if no function name is available. */ const char* get_function(void) const { return func; } /** Returns the file name from which the exception was thrown. A null pointer is returned if no file name is available. */ const char* get_file(void) const { return file; } /** Returns the exception source */ source_type get_source(void) const { return source; } /** Returns the line number from which the exception was thrown. A zero is returned if no line number is available. */ int get_line(void) const { return line; }; // Magic cause string static const char * const outofmemory; private: const char *cause; const char *file; const char *func; int line; source_type source; }; //@} #undef G_TRY #undef G_CATCH #undef G_CATCH_ALL #undef G_ENDCATCH #undef G_RETHROW #undef G_THROW #undef G_THROW_TYPE #undef G_THROW_INTERNAL #undef G_THROW_EXTERNAL #undef G_THROW_APPLICATION #undef G_THROW_OTHER #ifndef USE_EXCEPTION_EMULATION // Compiler supports ANSI C++ exceptions. // Defined exception macros accordingly. class DJVUAPI GExceptionHandler { public: #ifndef NO_LIBGCC_HOOKS static void exthrow(const GException &) no_return; #else static void exthrow(const GException ) no_return; #endif /* NO_LIBGCC_HOOKS */ static void rethrow(void) no_return; }; #define G_TRY try #define G_CATCH(n) catch(const GException &n) { #define G_CATCH_ALL catch(...) { #define G_ENDCATCH } #define G_RETHROW GExceptionHandler::rethrow() #define G_EMTHROW(ex) GExceptionHandler::exthrow(ex) #ifdef __GNUG__ #define G_THROW_TYPE(msg,xtype) GExceptionHandler::exthrow \ (GException(msg, __FILE__, __LINE__, __PRETTY_FUNCTION__, xtype)) #else #define G_THROW_TYPE(msg,xtype) GExceptionHandler::exthrow \ (GException(msg, __FILE__, __LINE__,0, xtype)) #endif #else // USE_EXCEPTION_EMULATION // Compiler does not support ANSI C++ exceptions. // Emulate with setjmp/longjmp. class DJVUAPI GExceptionHandler { public: jmp_buf jump; GExceptionHandler *next; GException current; public: static GExceptionHandler *head; static void emthrow(const GException &) no_return; public: GExceptionHandler() { next = head; }; ~GExceptionHandler() { head = next; }; }; #define G_TRY do { GExceptionHandler __exh; \ if (!setjmp(__exh.jump)) \ { GExceptionHandler::head = &__exh; #define G_CATCH_ALL } else { GExceptionHandler::head = __exh.next; #define G_CATCH(n) G_CATCH_ALL const GException& n = __exh.current; #define G_ENDCATCH } } while(0) #define G_RETHROW GExceptionHandler::emthrow(__exh.current) #ifdef __GNUG__ #define G_THROW_TYPE(msg,xtype) GExceptionHandler::emthrow \ (GException(msg, __FILE__, __LINE__, __PRETTY_FUNCTION__, xtype)) #define G_EMTHROW(ex) GExceptionHandler::emthrow(ex) #else #define G_THROW_TYPE(m,xtype) GExceptionHandler::emthrow \ (GException(m, __FILE__, __LINE__,0, xtype)) #define G_EMTHROW(ex) GExceptionHandler::emthrow(ex) #endif #endif // !CPP_SUPPORTS_EXCEPTIONS inline void G_EXTHROW(const GException &ex, const char *msg=0,const char *file=0,int line=0, const char *func=0, const GException::source_type source=GException::GINTERNAL) { G_EMTHROW( (msg||file||line||func)? GException(msg?msg:ex.get_cause(), file?file:ex.get_file(), line?line:ex.get_line(), func?func:ex.get_function(), source) :ex); } inline void G_EXTHROW(const char msg[], const char *file=0,int line=0,const char *func=0, const GException::source_type source=GException::GINTERNAL ) { G_EMTHROW(GException(msg,file,line,func,source)); } #define G_THROW(msg) G_THROW_TYPE(msg,GException::GINTERNAL) #define G_THROW_INTERNAL(msg) G_THROW_TYPE(msg,GException::GINTERNAL) #define G_THROW_EXTERNAL(msg) G_THROW_TYPE(msg,GException::GEXTERNAL) #define G_THROW_APPLICATION(msg) G_THROW_TYPE(msg,GException::GAPPLICATION) #define G_THROW_OTHER(msg) G_THROW_TYPE(msg,GException::GOTHER) // -------------- THE END #ifdef HAVE_NAMESPACES } # ifndef NOT_USING_DJVU_NAMESPACE using namespace DJVU; # endif #endif #endif
34.96648
85
0.710816
[ "object", "model" ]
3168b17213ff0216874b2136f685a4e8723ddb87
26,690
h
C
GCodeInterpreter/canon.h
parhansson/KMotionX
9e827917572fee477fe7971f67709c4c2ee4f97a
[ "BSD-3-Clause" ]
17
2015-01-04T19:58:54.000Z
2020-12-15T07:01:14.000Z
GCodeInterpreter/canon.h
parhansson/KMotionX
9e827917572fee477fe7971f67709c4c2ee4f97a
[ "BSD-3-Clause" ]
6
2015-12-10T21:24:01.000Z
2020-02-27T23:35:24.000Z
GCodeInterpreter/canon.h
parhansson/KMotionX
9e827917572fee477fe7971f67709c4c2ee4f97a
[ "BSD-3-Clause" ]
16
2015-02-07T23:42:53.000Z
2022-01-22T06:09:43.000Z
#ifndef CANON_HH #define CANON_HH #include <stdio.h> // FILE extern char Output[2560]; extern char ErrorOutput[2560]; extern int ErrorFileLineNumber; extern int line_number; /* canon.hh This is the header file that all applications that use the canonical commands for three- to six-axis machining should include. Three mutually orthogonal (in a right-handed system) X, Y, and Z axes are always present. In addition, there may be zero to three rotational axes: A (parallel to the X-axis), B (parallel to the Y-axis), and C (parallel to the Z-axis). In the functions that use rotational axes, the axis value is that of a wrapped linear axis, in degrees. It is assumed in these activities that the spindle tip is always at some location called the 'current location,' and the controller always knows where that is. It is also assumed that there is always a 'selected plane' which must be the XY-plane, the YZ-plane, or the ZX-plane of the machine. */ /* Modification history: 7-Jan-2004 FMP added the NO_AA, NO_BB and NO_CC flags to simplify building of the ABC interpreter by default and allow overriding to build interpreters that exclude one or more rotary axes. */ /* The RS274NGC compiler references canon.hh, and here we switch on the symbols AA, BB and CC to declare the position structures. The EMC uses AA, BB and CC, and thus by default will get these. In the rs274ngc_new directory, the Makefile defines the NO_AA, etc. compile flags to force the exclusion of some axes. Note that these interpreters won't work with the EMC. */ #ifndef NO_AA #define AA #endif #ifndef NO_BB #define BB #endif #ifndef NO_CC #define CC #endif typedef int CANON_PLANE; #define CANON_PLANE_XY 1 #define CANON_PLANE_YZ 2 #define CANON_PLANE_XZ 3 typedef int CANON_UNITS; #define CANON_UNITS_INCHES 1 #define CANON_UNITS_MM 2 #define CANON_UNITS_CM 3 typedef int CANON_MOTION_MODE; #define CANON_EXACT_STOP 1 #define CANON_EXACT_PATH 2 #define CANON_CONTINUOUS 3 typedef int CANON_SPINDLE_MODE; #define CANON_SPINDLE_NORMAL 1 #define CANON_SPINDLE_CSS 2 typedef int CANON_SPEED_FEED_MODE; #define CANON_SYNCHED 1 #define CANON_INDEPENDENT 2 typedef int CANON_DIRECTION; #define CANON_STOPPED 1 #define CANON_CLOCKWISE 2 #define CANON_COUNTERCLOCKWISE 3 typedef int CANON_FEED_REFERENCE; #define CANON_WORKPIECE 1 #define CANON_XYZ 2 typedef int CANON_SIDE; #define CANON_SIDE_RIGHT 1 #define CANON_SIDE_LEFT 2 #define CANON_SIDE_OFF 3 typedef int CANON_AXIS; #define CANON_AXIS_X 1 #define CANON_AXIS_Y 2 #define CANON_AXIS_Z 3 #define CANON_AXIS_A 4 #define CANON_AXIS_B 5 #define CANON_AXIS_C 6 #define CANON_AXIS_U 7 #define CANON_AXIS_V 8 /* Currently using the typedefs above rather than the enums below typedef enum {CANON_PLANE_XY, CANON_PLANE_YZ, CANON_PLANE_XZ} CANON_PLANE; typedef enum {CANON_UNITS_INCHES, CANON_UNITS_MM, CANON_UNITS_CM} CANON_UNITS; typedef enum {CANON_EXACT_STOP, CANON_EXACT_PATH, CANON_CONTINUOUS} CANON_MOTION_MODE; typedef enum {CANON_SYNCHED, CANON_INDEPENDENT} CANON_SPEED_FEED_MODE; typedef enum {CANON_STOPPED, CANON_CLOCKWISE, CANON_COUNTERCLOCKWISE} CANON_DIRECTION; typedef enum {CANON_WORKPIECE, CANON_XYZ} CANON_FEED_REFERENCE; typedef enum {CANON_SIDE_RIGHT, CANON_SIDE_LEFT, CANON_SIDE_OFF} CANON_SIDE; typedef enum {CANON_AXIS_X, CANON_AXIS_Y, CANON_AXIS_Z, CANON_AXIS_A, CANON_AXIS_B, CANON_AXIS_C} CANON_AXIS; */ struct CANON_VECTOR { CANON_VECTOR() { } CANON_VECTOR(double _x, double _y, double _z) { x = _x; y = _y; z = _z; } double x, y, z; }; struct CANON_POSITION { CANON_POSITION() { } CANON_POSITION( double _x, double _y, double _z, double _a, double _b, double _c, double _u, double _v) { x = _x; y = _y; z = _z; a = _a; b = _b; c = _c; u = _u; v = _v; } double x, y, z, a, b, c, u, v; }; /* Tools are numbered 1..CANON_TOOL_MAX, with tool 0 meaning no tool. */ #define CANON_TOOL_MAX 128 // max size of carousel handled #define CANON_TOOL_ENTRY_LEN 256 // how long each file line can be struct CANON_TOOL_TABLE { int slot; int id; double length; double diameter; double xoffset; double yoffset; char Comment[256]; char ToolImage[MAX_PATH]; }; /* Initialization */ /* reads world model data into the canonical interface */ extern void SET_CANON_DEVICE(int *device); /* reads world model data into the canonical interface */ extern void INIT_CANON(); /* Representation */ extern void SET_ORIGIN_OFFSETS(double x, double y, double z, double a, double b, double c, double u, double v); /* Offset the origin to the point with absolute coordinates x, y, z, a, b, and c. Values of x, y, z, a, b, and c are real numbers. The units are whatever length units are being used at the time this command is given. */ extern void USE_LENGTH_UNITS(CANON_UNITS u); /* Use the specified units for length. Conceptually, the units must be either inches or millimeters. */ extern void SELECT_PLANE(CANON_PLANE pl); /* Use the plane designated by selected_plane as the selected plane. Conceptually, the selected_plane must be the XY-plane, the XZ-plane, or the YZ-plane. */ /* Free Space Motion */ extern void SET_TRAVERSE_RATE(double rate); /* Set the traverse rate that will be used when the spindle traverses. It is expected that no cutting will occur while a traverse move is being made. */ extern void STRAIGHT_TRAVERSE(double x, double y, double z, double a_position, double b_position, double c_position, double u_position, double v_position); /* Move at traverse rate so that at any time during the move, all axes have covered the same proportion of their required motion. The final XYZ position is given by x, y, and z. If there is an a-axis, its final position is given by a_position, and similarly for the b-axis and c-axis. A more positive value of a rotational axis is in the counterclockwise direction. Clockwise or counterclockwise is from the point of view of the workpiece. If the workpiece is fastened to a turntable, the turntable will turn clockwise (from the point of view of the machinist or anyone else not moving with respect to the machining center) in order to make the tool move counterclockwise from the point of view of the workpiece. */ /* Machining Attributes */ extern void SET_FEED_RATE(double rate); /* SET_FEED_RATE sets the feed rate that will be used when the spindle is told to move at the currently set feed rate. The rate is either: 1. the rate of motion of the tool tip in the workpiece coordinate system, which is used when the feed_reference mode is "CANON_WORKPIECE", or 2. the rate of motion of the tool tip in the XYZ axis system, ignoring motion of other axes, which is used when the feed_reference mode is "CANON_XYZ". The units of the rate are: 1. If the feed_reference mode is CANON_WORKPIECE: length units (inches or millimeters according to the setting of CANON_UNITS) per minute along the programmed path as seen by the workpiece. 2. If the feed_reference mode is CANON_XYZ: A. For motion including one rotational axis only: degrees per minute. B. For motion including two rotational axes only: degrees per minute In this case, the rate applies to the axis with the larger angle to cover, and the second rotational axis rotates so that it has always completed the same proportion of its required motion as has the rotational axis to which the feed rate applies. C. For motion involving one or more of the XYZ axes (with or without simultaneous rotational axis motion): length units (inches or millimeters according to the setting of CANON_UNITS) per minute along the programmed XYZ path. */ extern void SET_FEED_REFERENCE(CANON_FEED_REFERENCE reference); /* This sets the feed_reference mode to either CANON_WORKPIECE or CANON_XYZ. The CANON_WORKPIECE mode is more natural and general, since the rate at which the tool passes through the material must be controlled for safe and effective machining. For machines with more than the three standard XYZ axes, however, computing the feed rate may be time-consuming because the trajectories that result from motion in four or more axes may be complex. Computation of path lengths when only XYZ motion is considered is quite simple for the two standard motion types (straight lines and helical arcs). Some programming languages (rs274kt, in particular) use CANON_XYZ mode. In these languages, the task of dealing with the rate at which the tool tip passes through material is pushed back on the NC-program generator, where the computation of path lengths is (almost always in 1995) an off-line activity where speed of calculation is not critical. In CANON_WORKPIECE mode, some motions cannot be carried out as fast as the programmed feed rate would require because axis motions tend to cancel each other. For example, an arc in the YZ-plane can exactly cancel a rotation around the A-axis, so that the location of the tool tip with respect to the workpiece does not change at all during the motion; in this case, the motion should take no time, which is impossible at any finite rate of axis motion. In such cases, the axes should be moved as fast as possible consistent with accurate machining. It would be possible to omit the SET_FEED_REFERENCE command from the canonical commands and operate always in one mode or the other, letting the interpreter issue SET_FEED_RATE commands, if necessary to compensate if the NC language being interpreted used the other mode. This would create two disadvantages when the feed_reference mode assumed by the canonical commands differed from that assumed by the NC language being interpreted: 1. The output code could have a lot of SET_FEED_RATE commands not found in the input code; this is a relatively minor consideration. 2. If the interpreter reads a program in language which uses the CANON_XYZ mode and writes canonical commands in the CANON_WORKPIECE mode, both the interpreter and the executor of the output canonical commands would have to perform a lot of complex calculations. With the SET_FEED_REFERENCE command available, both do only simple calculations for the same motions. */ extern void SET_MOTION_CONTROL_MODE(CANON_MOTION_MODE mode); /* This sets the motion control mode to one of: CANON_EXACT_STOP, CANON_EXACT_PATH, or CANON_CONTINUOUS. */ extern void SET_SPINDLE_MODE(CANON_SPINDLE_MODE mode); /* This sets the spindle mode to one of: CANON_SPINDLE_NORMAL or CANON_SPINDLE_CSS. */ extern void SET_CUTTER_RADIUS_COMPENSATION(double radius); /* Set the radius to use when performing cutter radius compensation. */ extern void START_CUTTER_RADIUS_COMPENSATION(int direction); /* Conceptually, the direction must be left (meaning the cutter stays to the left of the programmed path) or right. */ extern void STOP_CUTTER_RADIUS_COMPENSATION(); /* Do not apply cutter radius compensation when executing spindle translation commands. */ extern void START_SPEED_FEED_SYNCH(); extern void STOP_SPEED_FEED_SYNCH(); /* Machining Functions */ extern void ARC_FEED(double first_end, double second_end, double first_axis, double second_axis, int rotation, double axis_end_point, double a_position, double b_position, double c_position, double u_position, double v_position, int ID=0); /* Move in a helical arc from the current location at the existing feed rate. The axis of the helix is parallel to the x, y, or z axis, according to which one is perpendicular to the selected plane. The helical arc may degenerate to a circular arc if there is no motion parallel to the axis of the helix. 1. If the selected plane is the xy-plane: A. first_end is the x-coordinate of the end of the arc. B. second_end is the y-coordinate of the end of the arc. C. first_axis is the x-coordinate of the axis (center) of the arc. D. second_axis is the y-coordinate of the axis. E. axis_end_point is the z-coordinate of the end of the arc. 2. If the selected plane is the yz-plane: A. first_end is the y-coordinate of the end of the arc. B. second_end is the z-coordinate of the end of the arc. C. first_axis is the y-coordinate of the axis (center) of the arc. D. second_axis is the z-coordinate of the axis. E. axis_end_point is the x-coordinate of the end of the arc. 3. If the selected plane is the zx-plane: A. first_end is the z-coordinate of the end of the arc. B. second_end is the x-coordinate of the end of the arc. C. first_axis is the z-coordinate of the axis (center) of the arc. D. second_axis is the x-coordinate of the axis. E. axis_end_point is the y-coordinate of the end of the arc. If rotation is positive, the arc is traversed counterclockwise as viewed from the positive end of the coordinate axis perpendicular to the currently selected plane. If rotation is negative, the arc is traversed clockwise. If rotation is 0, first_end and second_end must be the same as the corresponding coordinates of the current point and no arc is made (but there may be translation parallel to the axis perpendicular to the selected plane and motion along the rotational axes). If rotation is 1, more than 0 but not more than 360 degrees of arc should be made. In general, if rotation is n, the amount of rotation in the arc should be more than ([n-1] x 360) but not more than (n x 360). The radius of the helix is determined by the distance from the current location to the axis of helix or by the distance from the end location to the axis of the helix. It is recommended that the executing system verify that the two radii are the same (within some tolerance) at the beginning of executing this function. While the XYZ motion is going on, move the rotational axes so that they have always covered the same proportion of their total motion as a point moving along the arc has of its total motion. */ extern void STRAIGHT_FEED(double x, double y, double z, double a_position, double b_position, double c_position, double u_position, double v_position, int ID=0); /* Move at existing feed rate so that at any time during the move, all axes have covered the same proportion of their required motion. The meanings of the parameters is the same as for STRAIGHT_TRAVERSE.*/ extern void STRAIGHT_PROBE(double x, double y, double z, double a_position, double b_position, double c_position, double u_position, double v_position); /* Perform a probing operation. This is a temporary addition to the canonical machining functions and its semantics are not defined. When the operation is finished, all axes should be back where they started. */ extern void STOP(); /* stop motion after current feed */ extern void DWELL(double seconds); /* freeze x,y,z for a time */ /* Spindle Functions */ extern void SPINDLE_RETRACT_TRAVERSE(); /* Retract the spindle at traverse rate to the fully retracted position. */ extern void START_SPINDLE_CLOCKWISE(); /* Turn the spindle clockwise at the currently set speed rate. If the spindle is already turning that way, this command has no effect. */ extern void START_SPINDLE_COUNTERCLOCKWISE(); /* Turn the spindle counterclockwise at the currently set speed rate. If the spindle is already turning that way, this command has no effect. */ extern void SET_SPINDLE_SPEED(double r); /* Set the spindle speed that will be used when the spindle is turning. This is usually given in rpm and refers to the rate of spindle rotation. If the spindle is already turning and is at a different speed, change to the speed given with this command. */ extern void STOP_SPINDLE_TURNING(); /* Stop the spindle from turning. If the spindle is already stopped, this command may be given, but it will have no effect. */ extern void SPINDLE_RETRACT(); extern void ORIENT_SPINDLE(double orientation, CANON_DIRECTION direction); extern void LOCK_SPINDLE_Z(); extern void USE_SPINDLE_FORCE(); extern void USE_NO_SPINDLE_FORCE(); /* Tool Functions */ extern void USE_TOOL_LENGTH_OFFSET(double length, double xoffset, double yoffset); extern void CHANGE_TOOL(int slot); /* slot is slot number */ /* It is assumed that each cutting tool in the machine is assigned to a slot (intended to correspond to a slot number in a tool carousel). This command results in the tool currently in the spindle (if any) being returned to its slot, and the tool from the slot designated by slot_number (if any) being inserted in the spindle. If there is no tool in the slot designated by the slot argument, there will be no tool in the spindle after this command is executed and no error condition will result in the controller. Similarly, if there is no tool in the spindle when this command is given, no tool will be returned to the carousel and no error condition will result in the controller, whether or not a tool was previously selected in the program. It is expected that when the machine tool controller is initialized, the designated slot for a tool already in the spindle will be established. This may be done in any manner deemed fit, including (for, example) recording that information in a persistent, crash-proof location so it is always available from the last time the machine was run, or having the operator enter it. It is expected that the machine tool controller will remember that information as long as it is not re-initialized; in particular, it will be remembered between programs. For the purposes of this command, the tool includes the tool holder. For machines which can carry out a select_tool command separately from a change_tool command, the select_tool command must have been given before the change_tool command, and the value of slot must be the slot number of the selected tool. */ extern void SELECT_TOOL(int i); /* i is slot number */ /* Miscellaneous Functions */ extern void CLAMP_AXIS(CANON_AXIS axis); extern int M100(int mcode); /* User M code */ /* Clamp the given axis. If the machining center does not have a clamp for that axis, this command should result in an error condition in the controller. An attempt to move an axis while it is clamped should result in an error condition in the controller. */ extern void COMMENT(char *s); /* This function has no physical effect. If commands are being printed or logged, the comment command is printed or logged, including the string which is the value of comment_text. This serves to allow formal comments at specific locations in programs or command files. */ extern void DISABLE_FEED_OVERRIDE(); extern void ENABLE_FEED_OVERRIDE(); extern void DISABLE_SPEED_OVERRIDE(); extern void ENABLE_SPEED_OVERRIDE(); extern void FLOOD_OFF(); /* Turn flood coolant off. */ extern void FLOOD_ON(); /* Turn flood coolant on. */ extern void MESSAGE(char *s); extern void MIST_OFF(); /* Turn mist coolant off. */ extern void MIST_ON(); /* Turn mist coolant on. */ extern void PALLET_SHUTTLE(); /* If the machining center has a pallet shuttle mechanism (a mechanism which switches the position of two pallets), this command should cause that switch to be made. If either or both of the pallets are missing, this will not result in an error condition in the controller. If the machining center does not have a pallet shuttle, this command should result in an error condition in the controller. */ extern void TURN_PROBE_OFF(); extern void TURN_PROBE_ON(); extern void UNCLAMP_AXIS(CANON_AXIS axis); /* Unclamp the given axis. If the machining center does not have a clamp for that axis, this command should result in an error condition in the controller. */ /* NURB Functions */ extern void NURB_KNOT_VECTOR(); /* double knot values, -1.0 signals done */ extern void NURB_CONTROL_POINT(int i, double x, double y, double z, double w); extern void NURB_FEED(double sStart, double sEnd); /* Program Functions */ extern void OPTIONAL_PROGRAM_STOP(); /* If the machining center has an optional stop switch, and it is on when this command is read from a program, stop executing the program at this point, but be prepared to resume with the next line of the program. If the machining center does not have an optional stop switch, or commands are being executed with a stop after each one already (such as when the interpreter is being used with keyboard input), this command has no effect. */ extern void PROGRAM_END(int MCode); /* If a program is being read, stop executing the program and be prepared to accept a new program or to be shut down. */ extern void PROGRAM_STOP(); /* If this command is read from a program, stop executing the program at this point, but be prepared to resume with the next line of the program. If commands are being executed with a stop after each one already (such as when the interpreter is being used with keyboard input), this command has no effect. */ /*************************************************************************/ /* Canonical "Give me information" functions for the interpreter to call In general, returned values are valid only if any canonical do it commands that may have been called for have been executed to completion. If a function returns a valid value regardless of execution, that is noted in the comments below. */ /* The interpreter is not using this function // Returns the system angular unit factor, in units / degree extern double GET_EXTERNAL_ANGLE_UNIT_FACTOR(); */ // Returns the system feed rate extern double GET_EXTERNAL_FEED_RATE(); // Returns the system value for flood coolant, zero = off, non-zero = on extern int GET_EXTERNAL_FLOOD(); /* The interpreter is not using this function // Returns the system length unit factor, in units / mm extern double GET_EXTERNAL_LENGTH_UNIT_FACTOR(); */ // Returns the system length unit type CANON_UNITS GET_EXTERNAL_LENGTH_UNIT_TYPE(); // Returns the system value for mist coolant, zero = off, non-zero = on extern int GET_EXTERNAL_MIST(); // Returns the current motion control mode extern CANON_MOTION_MODE GET_EXTERNAL_MOTION_CONTROL_MODE(); // Returns the current spindle mode extern CANON_SPINDLE_MODE GET_EXTERNAL_SPINDLE_MODE(); /* The interpreter is not using these six GET_EXTERNAL_ORIGIN functions // returns the current a-axis origin offset extern double GET_EXTERNAL_ORIGIN_A(); // returns the current b-axis origin offset extern double GET_EXTERNAL_ORIGIN_B(); // returns the current c-axis origin offset extern double GET_EXTERNAL_ORIGIN_C(); // returns the current x-axis origin offset extern double GET_EXTERNAL_ORIGIN_X(); // returns the current y-axis origin offset extern double GET_EXTERNAL_ORIGIN_Y(); // returns the current z-axis origin offset extern double GET_EXTERNAL_ORIGIN_Z(); */ // returns nothing but copies the name of the parameter file into // the filename array, stopping at max_size if the name is longer // An empty string may be placed in filename. extern void GET_EXTERNAL_PARAMETER_FILE_NAME(char *filename, int max_size); // returns the currently active plane extern CANON_PLANE GET_EXTERNAL_PLANE(); // returns the current a-axis position extern double GET_EXTERNAL_POSITION_A(); // returns the current b-axis position extern double GET_EXTERNAL_POSITION_B(); // returns the current c-axis position extern double GET_EXTERNAL_POSITION_C(); // returns the current u-axis position extern double GET_EXTERNAL_POSITION_U(); // returns the current v-axis position extern double GET_EXTERNAL_POSITION_V(); // returns the current x-axis position extern double GET_EXTERNAL_POSITION_X(); // returns the current y-axis position extern double GET_EXTERNAL_POSITION_Y(); // returns the current z-axis position extern double GET_EXTERNAL_POSITION_Z(); // Returns the machine A-axis position at the last probe trip. extern double GET_EXTERNAL_PROBE_POSITION_A(); // Returns the machine B-axis position at the last probe trip. extern double GET_EXTERNAL_PROBE_POSITION_B(); // Returns the machine C-axis position at the last probe trip. extern double GET_EXTERNAL_PROBE_POSITION_C(); // Returns the machine U-axis position at the last probe trip. extern double GET_EXTERNAL_PROBE_POSITION_U(); // Returns the machine V-axis position at the last probe trip. extern double GET_EXTERNAL_PROBE_POSITION_V(); // Returns the machine X-axis position at the last probe trip. extern double GET_EXTERNAL_PROBE_POSITION_X(); // Returns the machine Y-axis position at the last probe trip. extern double GET_EXTERNAL_PROBE_POSITION_Y(); // Returns the machine Z-axis position at the last probe trip. extern double GET_EXTERNAL_PROBE_POSITION_Z(); // Returns the value for any analog non-contact probing. extern double GET_EXTERNAL_PROBE_VALUE(); // Returns zero if queue is not empty, non-zero if the queue is empty // This always returns a valid value extern int GET_EXTERNAL_QUEUE_EMPTY(); // Returns the system value for spindle speed in rpm extern double GET_EXTERNAL_SPEED(); // Returns the system value for direction of spindle turning extern CANON_DIRECTION GET_EXTERNAL_SPINDLE(); // returns current tool length offset extern double GET_EXTERNAL_TOOL_LENGTH_OFFSET(); // Returns number of slots in carousel extern int GET_EXTERNAL_TOOL_MAX(); // Returns the system value for the carousel slot in which the tool // currently in the spindle belongs. Return value zero means there is no // tool in the spindle. extern int GET_EXTERNAL_TOOL_SLOT(); // Returns the CANON_TOOL_TABLE structure associated with the tool // in the given pocket extern CANON_TOOL_TABLE GET_EXTERNAL_TOOL_TABLE(int pocket); // Returns the system traverse rate extern double GET_EXTERNAL_TRAVERSE_RATE(); extern FILE *_outfile; /* where to print, set in main */ extern CANON_TOOL_TABLE _tools[]; /* in canon.cc */ extern int _tool_max; /* in canon.cc */ extern char _parameter_file_name[]; /* in canon.cc */ #define PARAMETER_FILE_NAME_LENGTH 100 extern int CHECK_INIT_ON_EXE(); extern int CHECK_PREVIOUS_STOP(double mx, double my, int log); #endif /* ifndef CANON_HH */
36.214383
122
0.754777
[ "model" ]
316ae491036e99b60a0bb4ba5ffc27f23ac98375
4,596
h
C
src/client.h
The-Compiler/herbstluftwm
a4f13aa299a760841ee204ddb180944bad6ceb2d
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/client.h
The-Compiler/herbstluftwm
a4f13aa299a760841ee204ddb180944bad6ceb2d
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/client.h
The-Compiler/herbstluftwm
a4f13aa299a760841ee204ddb180944bad6ceb2d
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#ifndef __CLIENTLIST_H_ #define __CLIENTLIST_H_ #include <X11/X.h> #include <X11/Xlib.h> #include "attribute_.h" #include "object.h" #include "regexstr.h" #include "types.h" #include "x11-types.h" class Decoration; class DecTriple; class Ewmh; class Slice; class HSTag; class Monitor; class Settings; class Theme; class ClientManager; class Client : public Object { public: Client(Window w, bool visible_already, ClientManager& cm); ~Client() override; Window window_; std::unique_ptr<Decoration> dec; // pimpl Rectangle last_size_; // last size excluding the window border Rectangle float_size_ = {0, 0, 100, 100}; // floating size without the window border HSTag* tag_ = {}; Slice* slice = {}; bool ewmhfullscreen_ = false; // ewmh fullscreen state bool neverfocus_ = false; // do not give the focus via XSetInputFocus bool visible_; bool dragged_ = false; // if this client is dragged currently int ignore_unmaps_ = 0; // Ignore one unmap for each reparenting // action, because reparenting creates an unmap // notify event // for size hints float mina_ = 0; float maxa_ = 0; int basew_ = 0; int baseh_ = 0; int incw_ = 0; int inch_ = 0; int maxw_ = 0; int maxh_ = 0; int minw_ = 0; int minh_ = 0; // for other modules Signal_<HSTag*> needsRelayout; // attributes: Attribute_<bool> urgent_; Attribute_<bool> floating_; Attribute_<bool> fullscreen_; Attribute_<std::string> title_; // or also called window title; this is never NULL DynAttribute_<std::string> tag_str_; Attribute_<std::string> window_id_str; Attribute_<RegexStr> keyMask_; // regex for key bindings that are active on this window Attribute_<RegexStr> keysInactive_; // regex for key bindings that are inactive on this window Attribute_<int> pid_; Attribute_<int> pgid_; Attribute_<bool> pseudotile_; // only move client but don't resize (if possible) Attribute_<bool> ewmhrequests_; // accept ewmh-requests for this client Attribute_<bool> ewmhnotify_; // send ewmh-notifications for this client Attribute_<bool> sizehints_floating_; // respect size hints regarding this client in floating mode Attribute_<bool> sizehints_tiling_; // respect size hints regarding this client in tiling mode DynAttribute_<std::string> window_class_; DynAttribute_<std::string> window_instance_; public: void init_from_X(); void make_full_client(); void listen_for_events(); // setter and getter for attributes HSTag* tag() { return tag_; } void setTag(HSTag* tag); Window x11Window() const { return window_; } Window decorationWindow(); friend void mouse_function_resize(XMotionEvent* me); // other member functions void window_focus(); void window_unfocus(); static void window_unfocus_last(); void fuzzy_fix_initial_position(); Rectangle outer_floating_rect(); void setup_border(bool focused); void resize_tiling(Rectangle rect, bool isFocused, bool minimalDecoration); void resize_floating(Monitor* m, bool isFocused); void resize_fullscreen(Rectangle m, bool isFocused); bool is_client_floated(); void set_urgent(bool state); void update_wm_hints(); void update_title(); void raise(); void send_configure(); bool applysizehints(int *w, int *h); bool applysizehints_xy(int *x, int *y, int *w, int *h); void updatesizehints(); void set_visible(bool visible_); void set_urgent_force(bool state); void requestClose(); //! ask the client to close void clear_properties(); bool ignore_unmapnotify(); void updateEwmhState(); private: std::string getWindowClass(); std::string getWindowInstance(); std::string triggerRelayoutMonitor(); void requestRedraw(); friend Decoration; ClientManager& manager; Theme& theme; Settings& settings; Ewmh& ewmh; std::string tagName(); const DecTriple& getDecTriple(); }; void reset_client_colors(); Client* get_client_from_window(Window window); Client* get_current_client(); Client* get_client(const char* str); Window get_window(const std::string& str); int close_command(Input input, Output output); // sets a client property, depending on argv[0] int client_set_property_command(int argc, char** argv); bool is_window_class_ignored(char* window_class); bool is_window_ignored(Window win); #endif
29.844156
103
0.68886
[ "object" ]
316ae87c2cb0cc009d560e6f03fe112e99379a5f
4,277
h
C
release/src-rt-6.x.4708/router/mysql/storage/innodb_plugin/include/ut0vec.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
278
2015-11-03T03:01:20.000Z
2022-01-20T18:21:05.000Z
release/src-rt-6.x.4708/router/mysql/storage/innodb_plugin/include/ut0vec.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
374
2015-11-03T12:37:22.000Z
2021-12-17T14:18:08.000Z
release/src-rt-6.x.4708/router/mysql/storage/innodb_plugin/include/ut0vec.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
96
2015-11-22T07:47:26.000Z
2022-01-20T19:52:19.000Z
/***************************************************************************** Copyright (c) 2006, 2009, Innobase Oy. All Rights Reserved. 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ /*******************************************************************//** @file include/ut0vec.h A vector of pointers to data items Created 4/6/2006 Osku Salerma ************************************************************************/ #ifndef IB_VECTOR_H #define IB_VECTOR_H #include "univ.i" #include "mem0mem.h" /** An automatically resizing vector data type. */ typedef struct ib_vector_struct ib_vector_t; /* An automatically resizing vector datatype with the following properties: -Contains void* items. -The items are owned by the caller. -All memory allocation is done through a heap owned by the caller, who is responsible for freeing it when done with the vector. -When the vector is resized, the old memory area is left allocated since it uses the same heap as the new memory area, so this is best used for relatively small or short-lived uses. */ /****************************************************************//** Create a new vector with the given initial size. @return vector */ UNIV_INTERN ib_vector_t* ib_vector_create( /*=============*/ mem_heap_t* heap, /*!< in: heap */ ulint size); /*!< in: initial size */ /****************************************************************//** Push a new element to the vector, increasing its size if necessary. */ UNIV_INTERN void ib_vector_push( /*===========*/ ib_vector_t* vec, /*!< in: vector */ void* elem); /*!< in: data element */ /****************************************************************//** Get the number of elements in the vector. @return number of elements in vector */ UNIV_INLINE ulint ib_vector_size( /*===========*/ const ib_vector_t* vec); /*!< in: vector */ /****************************************************************//** Test whether a vector is empty or not. @return TRUE if empty */ UNIV_INLINE ibool ib_vector_is_empty( /*===============*/ const ib_vector_t* vec); /*!< in: vector */ /****************************************************************//** Get the n'th element. @return n'th element */ UNIV_INLINE void* ib_vector_get( /*==========*/ ib_vector_t* vec, /*!< in: vector */ ulint n); /*!< in: element index to get */ /****************************************************************//** Get last element. The vector must not be empty. @return last element */ UNIV_INLINE void* ib_vector_get_last( /*===============*/ ib_vector_t* vec); /*!< in: vector */ /****************************************************************//** Set the n'th element. */ UNIV_INLINE void ib_vector_set( /*==========*/ ib_vector_t* vec, /*!< in/out: vector */ ulint n, /*!< in: element index to set */ void* elem); /*!< in: data element */ /****************************************************************//** Remove the last element from the vector. */ UNIV_INLINE void* ib_vector_pop( /*==========*/ ib_vector_t* vec); /*!< in: vector */ /****************************************************************//** Free the underlying heap of the vector. Note that vec is invalid after this call. */ UNIV_INLINE void ib_vector_free( /*===========*/ ib_vector_t* vec); /*!< in,own: vector */ /** An automatically resizing vector data type. */ struct ib_vector_struct { mem_heap_t* heap; /*!< heap */ void** data; /*!< data elements */ ulint used; /*!< number of elements currently used */ ulint total; /*!< number of elements allocated */ }; #ifndef UNIV_NONINL #include "ut0vec.ic" #endif #endif
29.496552
78
0.546879
[ "vector" ]
316f8b692d8e343d47d6e7c26af55929a57d10a6
1,939
h
C
src/GHOpenVR/GHOpenVRSkeletalAvatar.h
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
src/GHOpenVR/GHOpenVRSkeletalAvatar.h
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
src/GHOpenVR/GHOpenVRSkeletalAvatar.h
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
#pragma once #include "GHUtils/GHController.h" #include <openvr.h> #include "GHString/GHString.h" #include "GHInputState.h" class GHOpenVRAvatarDebugDraw; class GHTransform; class GHModel; class GHTransformNode; class GHStringIdFactory; class GHOpenVRSkeletalAvatar : public GHController { public: GHOpenVRSkeletalAvatar(GHModel& leftHandModel, GHModel& rightHandModel, const GHInputState& inputState, int gamepadIndex, const GHStringIdFactory& idFactory, const GHTransform& hmdOrigin, const char* gestureMapFilename); virtual ~GHOpenVRSkeletalAvatar(void); virtual void onActivate(void); virtual void onDeactivate(void); virtual void update(void); struct SkeletalData { SkeletalData(const GHInputStructs::Poseable& poseable, const GHStringIdFactory& idFactory) : mPoseable(poseable) , mIdFactory(idFactory) { } const GHInputStructs::Poseable& mPoseable; const GHStringIdFactory& mIdFactory; GHString mActionName; GHModel* mGHModel{ 0 }; vr::VRActionHandle_t mAction{ 0 }; vr::InputSkeletalActionData_t mSkeletalData; vr::InputPoseActionData_t mPoseData; uint32_t mNumBones{ 0 }; vr::BoneIndex_t* mBoneParentIndices{ 0 }; vr::VRBoneTransform_t* mReferenceTransforms{ 0 }; //Dynamic data vr::VRBoneTransform_t* mBoneTransforms{ 0 }; GHTransform* mWorldSpaceBoneTransforms{ 0 }; //Scratch memory for computing world transforms if necessary GHTransformNode** mTargetModelTransforms{ 0 }; GHOpenVRAvatarDebugDraw* mDebugDrawer{ 0 }; bool mInitializedSuccessfully{ false }; bool mIsInModelSpace{ false }; //true if mBoneTransforms are in model space, false if in bone space ~SkeletalData(void); bool initialize(const char* actionName, GHModel* ghModel); bool tryReinitialize(void); void update(void); }; private: SkeletalData mLeftHand; SkeletalData mRightHand; GHOpenVRAvatarDebugDraw* mDebugDrawer{ 0 }; const GHTransform& mHMDOrigin; };
28.940299
107
0.769469
[ "model" ]
31745a4d28b7c6d6832a9b92ac54ab132be35b57
5,704
h
C
aws-cpp-sdk-config/include/aws/config/model/EvaluationResultIdentifier.h
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2020-07-16T19:03:13.000Z
2020-07-16T19:03:13.000Z
aws-cpp-sdk-config/include/aws/config/model/EvaluationResultIdentifier.h
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
18
2018-05-15T16:41:07.000Z
2018-05-21T00:46:30.000Z
aws-cpp-sdk-config/include/aws/config/model/EvaluationResultIdentifier.h
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2021-10-01T15:29:44.000Z
2021-10-01T15:29:44.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/config/ConfigService_EXPORTS.h> #include <aws/config/model/EvaluationResultQualifier.h> #include <aws/core/utils/DateTime.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace ConfigService { namespace Model { /** * <p>Uniquely identifies an evaluation result.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/EvaluationResultIdentifier">AWS * API Reference</a></p> */ class AWS_CONFIGSERVICE_API EvaluationResultIdentifier { public: EvaluationResultIdentifier(); EvaluationResultIdentifier(const Aws::Utils::Json::JsonValue& jsonValue); EvaluationResultIdentifier& operator=(const Aws::Utils::Json::JsonValue& jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>Identifies an AWS Config rule used to evaluate an AWS resource, and provides * the type and ID of the evaluated resource.</p> */ inline const EvaluationResultQualifier& GetEvaluationResultQualifier() const{ return m_evaluationResultQualifier; } /** * <p>Identifies an AWS Config rule used to evaluate an AWS resource, and provides * the type and ID of the evaluated resource.</p> */ inline void SetEvaluationResultQualifier(const EvaluationResultQualifier& value) { m_evaluationResultQualifierHasBeenSet = true; m_evaluationResultQualifier = value; } /** * <p>Identifies an AWS Config rule used to evaluate an AWS resource, and provides * the type and ID of the evaluated resource.</p> */ inline void SetEvaluationResultQualifier(EvaluationResultQualifier&& value) { m_evaluationResultQualifierHasBeenSet = true; m_evaluationResultQualifier = std::move(value); } /** * <p>Identifies an AWS Config rule used to evaluate an AWS resource, and provides * the type and ID of the evaluated resource.</p> */ inline EvaluationResultIdentifier& WithEvaluationResultQualifier(const EvaluationResultQualifier& value) { SetEvaluationResultQualifier(value); return *this;} /** * <p>Identifies an AWS Config rule used to evaluate an AWS resource, and provides * the type and ID of the evaluated resource.</p> */ inline EvaluationResultIdentifier& WithEvaluationResultQualifier(EvaluationResultQualifier&& value) { SetEvaluationResultQualifier(std::move(value)); return *this;} /** * <p>The time of the event that triggered the evaluation of your AWS resources. * The time can indicate when AWS Config delivered a configuration item change * notification, or it can indicate when AWS Config delivered the configuration * snapshot, depending on which event triggered the evaluation.</p> */ inline const Aws::Utils::DateTime& GetOrderingTimestamp() const{ return m_orderingTimestamp; } /** * <p>The time of the event that triggered the evaluation of your AWS resources. * The time can indicate when AWS Config delivered a configuration item change * notification, or it can indicate when AWS Config delivered the configuration * snapshot, depending on which event triggered the evaluation.</p> */ inline void SetOrderingTimestamp(const Aws::Utils::DateTime& value) { m_orderingTimestampHasBeenSet = true; m_orderingTimestamp = value; } /** * <p>The time of the event that triggered the evaluation of your AWS resources. * The time can indicate when AWS Config delivered a configuration item change * notification, or it can indicate when AWS Config delivered the configuration * snapshot, depending on which event triggered the evaluation.</p> */ inline void SetOrderingTimestamp(Aws::Utils::DateTime&& value) { m_orderingTimestampHasBeenSet = true; m_orderingTimestamp = std::move(value); } /** * <p>The time of the event that triggered the evaluation of your AWS resources. * The time can indicate when AWS Config delivered a configuration item change * notification, or it can indicate when AWS Config delivered the configuration * snapshot, depending on which event triggered the evaluation.</p> */ inline EvaluationResultIdentifier& WithOrderingTimestamp(const Aws::Utils::DateTime& value) { SetOrderingTimestamp(value); return *this;} /** * <p>The time of the event that triggered the evaluation of your AWS resources. * The time can indicate when AWS Config delivered a configuration item change * notification, or it can indicate when AWS Config delivered the configuration * snapshot, depending on which event triggered the evaluation.</p> */ inline EvaluationResultIdentifier& WithOrderingTimestamp(Aws::Utils::DateTime&& value) { SetOrderingTimestamp(std::move(value)); return *this;} private: EvaluationResultQualifier m_evaluationResultQualifier; bool m_evaluationResultQualifierHasBeenSet; Aws::Utils::DateTime m_orderingTimestamp; bool m_orderingTimestampHasBeenSet; }; } // namespace Model } // namespace ConfigService } // namespace Aws
42.887218
177
0.737728
[ "model" ]
317d48f915cb4e0526a99293d8cc7ade9b53877a
908
h
C
test/e2e/test_master/skia/src/codec/SkJpegUtility.h
BlueCannonBall/cppparser
9ae5f0c21268be6696532cf5b90c0384d6eb4940
[ "MIT" ]
null
null
null
test/e2e/test_master/skia/src/codec/SkJpegUtility.h
BlueCannonBall/cppparser
9ae5f0c21268be6696532cf5b90c0384d6eb4940
[ "MIT" ]
null
null
null
test/e2e/test_master/skia/src/codec/SkJpegUtility.h
BlueCannonBall/cppparser
9ae5f0c21268be6696532cf5b90c0384d6eb4940
[ "MIT" ]
null
null
null
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkJpegUtility_codec_DEFINED # define SkJpegUtility_codec_DEFINED # include "include/core/SkStream.h" # include "src/codec/SkJpegPriv.h" # include <setjmp.h> // stdio is needed for jpeglib # include <stdio.h> extern "C" { # include "jpeglib.h" # include "jerror.h" } /* * Error handling function */ void skjpeg_err_exit(j_common_ptr cinfo); /* * Source handling struct for that allows libjpeg to use our stream object */ struct skjpeg_source_mgr : jpeg_source_mgr { skjpeg_source_mgr(SkStream* stream); SkStream* fStream; enum { // TODO (msarett): Experiment with different buffer sizes. // This size was chosen because it matches SkImageDecoder. kBufferSize = 1024 }; uint8_t fBuffer[kBufferSize]; }; #endif
24.540541
74
0.711454
[ "object" ]
318b3ab8f3de4dd76a68e59bbae9d26924c57468
92,087
c
C
generic/tkImgPNG.c
Acidburn0zzz/tk
05b3198bf31fec9ed2d6f89a2f15143a288edd9d
[ "TCL" ]
1
2021-02-02T04:55:58.000Z
2021-02-02T04:55:58.000Z
generic/tkImgPNG.c
Acidburn0zzz/tk
05b3198bf31fec9ed2d6f89a2f15143a288edd9d
[ "TCL" ]
null
null
null
generic/tkImgPNG.c
Acidburn0zzz/tk
05b3198bf31fec9ed2d6f89a2f15143a288edd9d
[ "TCL" ]
null
null
null
/* * tkImgPNG.c -- * * A Tk photo image file handler for PNG files. * * Copyright © 2006-2008 Muonics, Inc. * Copyright © 2008 Donal K. Fellows * * See the file "license.terms" for information on usage and redistribution of * this file, and for a DISCLAIMER OF ALL WARRANTIES. */ #include "tkInt.h" #define PNG_INT32(a,b,c,d) \ (((long)(a) << 24) | ((long)(b) << 16) | ((long)(c) << 8) | (long)(d)) #define PNG_BLOCK_SZ 1024 /* Process up to 1k at a time. */ #define PNG_MIN(a, b) (((a) < (b)) ? (a) : (b)) /* * Every PNG image starts with the following 8-byte signature. */ #define PNG_SIG_SZ 8 static const unsigned char pngSignature[] = { 137, 80, 78, 71, 13, 10, 26, 10 }; static const int startLine[8] = { 0, 0, 0, 4, 0, 2, 0, 1 }; /* * Chunk type flags. */ #define PNG_CF_ANCILLARY 0x20000000L /* Non-critical chunk (can ignore). */ #define PNG_CF_PRIVATE 0x00100000L /* Application-specific chunk. */ #define PNG_CF_RESERVED 0x00001000L /* Not used. */ #define PNG_CF_COPYSAFE 0x00000010L /* Opaque data safe for copying. */ /* * Chunk types, not all of which have support implemented. Note that there are * others in the official extension set which we will never support (as they * are officially deprecated). */ #define CHUNK_IDAT PNG_INT32('I','D','A','T') /* Pixel data. */ #define CHUNK_IEND PNG_INT32('I','E','N','D') /* End of Image. */ #define CHUNK_IHDR PNG_INT32('I','H','D','R') /* Header. */ #define CHUNK_PLTE PNG_INT32('P','L','T','E') /* Palette. */ #define CHUNK_bKGD PNG_INT32('b','K','G','D') /* Background Color */ #define CHUNK_cHRM PNG_INT32('c','H','R','M') /* Chroma values. */ #define CHUNK_gAMA PNG_INT32('g','A','M','A') /* Gamma. */ #define CHUNK_hIST PNG_INT32('h','I','S','T') /* Histogram. */ #define CHUNK_iCCP PNG_INT32('i','C','C','P') /* Color profile. */ #define CHUNK_iTXt PNG_INT32('i','T','X','t') /* Internationalized * text (comments, * etc.) */ #define CHUNK_oFFs PNG_INT32('o','F','F','s') /* Image offset. */ #define CHUNK_pCAL PNG_INT32('p','C','A','L') /* Pixel calibration * data. */ #define CHUNK_pHYs PNG_INT32('p','H','Y','s') /* Physical pixel * dimensions. */ #define CHUNK_sBIT PNG_INT32('s','B','I','T') /* Significant bits */ #define CHUNK_sCAL PNG_INT32('s','C','A','L') /* Physical scale. */ #define CHUNK_sPLT PNG_INT32('s','P','L','T') /* Suggested * palette. */ #define CHUNK_sRGB PNG_INT32('s','R','G','B') /* Standard RGB space * declaration. */ #define CHUNK_tEXt PNG_INT32('t','E','X','t') /* Plain Latin-1 * text. */ #define CHUNK_tIME PNG_INT32('t','I','M','E') /* Time stamp. */ #define CHUNK_tRNS PNG_INT32('t','R','N','S') /* Transparency. */ #define CHUNK_zTXt PNG_INT32('z','T','X','t') /* Compressed Latin-1 * text. */ /* * Color flags. */ #define PNG_COLOR_INDEXED 1 #define PNG_COLOR_USED 2 #define PNG_COLOR_ALPHA 4 /* * Actual color types. */ #define PNG_COLOR_GRAY 0 #define PNG_COLOR_RGB (PNG_COLOR_USED) #define PNG_COLOR_PLTE (PNG_COLOR_USED | PNG_COLOR_INDEXED) #define PNG_COLOR_GRAYALPHA (PNG_COLOR_GRAY | PNG_COLOR_ALPHA) #define PNG_COLOR_RGBA (PNG_COLOR_USED | PNG_COLOR_ALPHA) /* * Compression Methods. */ #define PNG_COMPRESS_DEFLATE 0 /* * Filter Methods. */ #define PNG_FILTMETH_STANDARD 0 /* * Interlacing Methods. */ #define PNG_INTERLACE_NONE 0 #define PNG_INTERLACE_ADAM7 1 /* * State information, used to store everything about the PNG image being * currently parsed or created. */ typedef struct { /* * PNG data source/destination channel/object/byte array. */ Tcl_Channel channel; /* Channel for from-file reads. */ Tcl_Obj *objDataPtr; unsigned char *strDataBuf; /* Raw source data for from-string reads. */ TkSizeT strDataLen; /* Length of source data. */ unsigned char *base64Data; /* base64 encoded string data. */ unsigned char base64Bits; /* Remaining bits from last base64 read. */ unsigned char base64State; /* Current state of base64 decoder. */ double alpha; /* Alpha from -format option. */ /* * Image header information. */ unsigned char bitDepth; /* Number of bits per pixel. */ unsigned char colorType; /* Grayscale, TrueColor, etc. */ unsigned char compression; /* Compression Mode (always zlib). */ unsigned char filter; /* Filter mode (0 - 3). */ unsigned char interlace; /* Type of interlacing (if any). */ unsigned char numChannels; /* Number of channels per pixel. */ unsigned char bytesPerPixel;/* Bytes per pixel in scan line. */ int bitScale; /* Scale factor for RGB/Gray depths < 8. */ int currentLine; /* Current line being unfiltered. */ unsigned char phase; /* Interlacing phase (0..6). */ Tk_PhotoImageBlock block; int blockLen; /* Number of bytes in Tk image pixels. */ /* * For containing data read from PLTE (palette) and tRNS (transparency) * chunks. */ int paletteLen; /* Number of PLTE entries (1..256). */ int useTRNS; /* Flag to indicate whether there was a * palette given. */ struct { unsigned char red; unsigned char green; unsigned char blue; unsigned char alpha; } palette[256]; /* Palette RGB/Transparency table. */ unsigned char transVal[6]; /* Fully-transparent RGB/Gray Value. */ /* * For compressing and decompressing IDAT chunks. */ Tcl_ZlibStream stream; /* Inflating or deflating stream; this one is * not bound to a Tcl command. */ Tcl_Obj *lastLineObj; /* Last line of pixels, for unfiltering. */ Tcl_Obj *thisLineObj; /* Current line of pixels to process. */ int lineSize; /* Number of bytes in a PNG line. */ int phaseSize; /* Number of bytes/line in current phase. */ } PNGImage; /* * Maximum size of various chunks. */ #define PNG_PLTE_MAXSZ 768 /* 3 bytes/RGB entry, 256 entries max */ #define PNG_TRNS_MAXSZ 256 /* 1-byte alpha, 256 entries max */ /* * Forward declarations of non-global functions defined in this file: */ static void ApplyAlpha(PNGImage *pngPtr); static int CheckColor(Tcl_Interp *interp, PNGImage *pngPtr); static inline int CheckCRC(Tcl_Interp *interp, PNGImage *pngPtr, unsigned long calculated); static void CleanupPNGImage(PNGImage *pngPtr); static int DecodeLine(Tcl_Interp *interp, PNGImage *pngPtr); static int DecodePNG(Tcl_Interp *interp, PNGImage *pngPtr, Tcl_Obj *fmtObj, Tk_PhotoHandle imageHandle, int destX, int destY); static int EncodePNG(Tcl_Interp *interp, Tk_PhotoImageBlock *blockPtr, PNGImage *pngPtr); static int FileMatchPNG(Tcl_Channel chan, const char *fileName, Tcl_Obj *fmtObj, int *widthPtr, int *heightPtr, Tcl_Interp *interp); static int FileReadPNG(Tcl_Interp *interp, Tcl_Channel chan, const char *fileName, Tcl_Obj *fmtObj, Tk_PhotoHandle imageHandle, int destX, int destY, int width, int height, int srcX, int srcY); static int FileWritePNG(Tcl_Interp *interp, const char *filename, Tcl_Obj *fmtObj, Tk_PhotoImageBlock *blockPtr); static int InitPNGImage(Tcl_Interp *interp, PNGImage *pngPtr, Tcl_Channel chan, Tcl_Obj *objPtr, int dir); static inline unsigned char Paeth(int a, int b, int c); static int ParseFormat(Tcl_Interp *interp, Tcl_Obj *fmtObj, PNGImage *pngPtr); static int ReadBase64(Tcl_Interp *interp, PNGImage *pngPtr, unsigned char *destPtr, size_t destSz, unsigned long *crcPtr); static int ReadByteArray(Tcl_Interp *interp, PNGImage *pngPtr, unsigned char *destPtr, size_t destSz, unsigned long *crcPtr); static int ReadData(Tcl_Interp *interp, PNGImage *pngPtr, unsigned char *destPtr, size_t destSz, unsigned long *crcPtr); static int ReadChunkHeader(Tcl_Interp *interp, PNGImage *pngPtr, size_t *sizePtr, unsigned long *typePtr, unsigned long *crcPtr); static int ReadIDAT(Tcl_Interp *interp, PNGImage *pngPtr, int chunkSz, unsigned long crc); static int ReadIHDR(Tcl_Interp *interp, PNGImage *pngPtr); static inline int ReadInt32(Tcl_Interp *interp, PNGImage *pngPtr, unsigned long *resultPtr, unsigned long *crcPtr); static int ReadPLTE(Tcl_Interp *interp, PNGImage *pngPtr, int chunkSz, unsigned long crc); static int ReadTRNS(Tcl_Interp *interp, PNGImage *pngPtr, int chunkSz, unsigned long crc); static int SkipChunk(Tcl_Interp *interp, PNGImage *pngPtr, int chunkSz, unsigned long crc); static int StringMatchPNG(Tcl_Obj *dataObj, Tcl_Obj *fmtObj, int *widthPtr, int *heightPtr, Tcl_Interp *interp); static int StringReadPNG(Tcl_Interp *interp, Tcl_Obj *dataObj, Tcl_Obj *fmtObj, Tk_PhotoHandle imageHandle, int destX, int destY, int width, int height, int srcX, int srcY); static int StringWritePNG(Tcl_Interp *interp, Tcl_Obj *fmtObj, Tk_PhotoImageBlock *blockPtr); static int UnfilterLine(Tcl_Interp *interp, PNGImage *pngPtr); static inline int WriteByte(Tcl_Interp *interp, PNGImage *pngPtr, unsigned char c, unsigned long *crcPtr); static inline int WriteChunk(Tcl_Interp *interp, PNGImage *pngPtr, unsigned long chunkType, const unsigned char *dataPtr, size_t dataSize); static int WriteData(Tcl_Interp *interp, PNGImage *pngPtr, const unsigned char *srcPtr, size_t srcSz, unsigned long *crcPtr); static int WriteExtraChunks(Tcl_Interp *interp, PNGImage *pngPtr); static int WriteIHDR(Tcl_Interp *interp, PNGImage *pngPtr, Tk_PhotoImageBlock *blockPtr); static int WriteIDAT(Tcl_Interp *interp, PNGImage *pngPtr, Tk_PhotoImageBlock *blockPtr); static inline int WriteInt32(Tcl_Interp *interp, PNGImage *pngPtr, unsigned long l, unsigned long *crcPtr); /* * The format record for the PNG file format: */ Tk_PhotoImageFormat tkImgFmtPNG = { "png", /* name */ FileMatchPNG, /* fileMatchProc */ StringMatchPNG, /* stringMatchProc */ FileReadPNG, /* fileReadProc */ StringReadPNG, /* stringReadProc */ FileWritePNG, /* fileWriteProc */ StringWritePNG, /* stringWriteProc */ NULL }; /* *---------------------------------------------------------------------- * * InitPNGImage -- * * This function is invoked by each of the Tk image handler procs * (MatchStringProc, etc.) to initialize state information used during * the course of encoding or decoding a PNG image. * * Results: * TCL_OK, or TCL_ERROR if initialization failed. * * Side effects: * The reference count of the -data Tcl_Obj*, if any, is incremented. * *---------------------------------------------------------------------- */ static int InitPNGImage( Tcl_Interp *interp, PNGImage *pngPtr, Tcl_Channel chan, Tcl_Obj *objPtr, int dir) { memset(pngPtr, 0, sizeof(PNGImage)); pngPtr->channel = chan; pngPtr->alpha = 1.0; /* * If decoding from a -data string object, increment its reference count * for the duration of the decode and get its length and byte array for * reading with ReadData(). */ if (objPtr) { Tcl_IncrRefCount(objPtr); pngPtr->objDataPtr = objPtr; pngPtr->strDataBuf = Tcl_GetByteArrayFromObj(objPtr, &pngPtr->strDataLen); } /* * Initialize the palette transparency table to fully opaque. */ memset(pngPtr->palette, 255, sizeof(pngPtr->palette)); /* * Initialize Zlib inflate/deflate stream. */ if (Tcl_ZlibStreamInit(NULL, dir, TCL_ZLIB_FORMAT_ZLIB, TCL_ZLIB_COMPRESS_DEFAULT, NULL, &pngPtr->stream) != TCL_OK) { if (interp) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "zlib initialization failed", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "ZLIB_INIT", NULL); } if (objPtr) { Tcl_DecrRefCount(objPtr); } return TCL_ERROR; } return TCL_OK; } /* *---------------------------------------------------------------------- * * CleanupPNGImage -- * * This function is invoked by each of the Tk image handler procs * (MatchStringProc, etc.) prior to returning to Tcl in order to clean up * any allocated memory and call other cleanup handlers such as zlib's * inflateEnd/deflateEnd. * * Results: * None. * * Side effects: * The reference count of the -data Tcl_Obj*, if any, is decremented. * Buffers are freed, streams are closed. The PNGImage should not be used * for any purpose without being reinitialized post-cleanup. * *---------------------------------------------------------------------- */ static void CleanupPNGImage( PNGImage *pngPtr) { /* * Don't need the object containing the -data value anymore. */ if (pngPtr->objDataPtr) { Tcl_DecrRefCount(pngPtr->objDataPtr); } /* * Discard pixel buffer. */ if (pngPtr->stream) { Tcl_ZlibStreamClose(pngPtr->stream); } if (pngPtr->block.pixelPtr) { ckfree(pngPtr->block.pixelPtr); } if (pngPtr->thisLineObj) { Tcl_DecrRefCount(pngPtr->thisLineObj); } if (pngPtr->lastLineObj) { Tcl_DecrRefCount(pngPtr->lastLineObj); } memset(pngPtr, 0, sizeof(PNGImage)); } /* *---------------------------------------------------------------------- * * ReadBase64 -- * * This function is invoked to read the specified number of bytes from * base-64 encoded image data. * * Note: It would be better if the Tk_PhotoImage stuff handled this by * creating a channel from the -data value, which would take care of * base64 decoding and made the data readable as if it were coming from a * file. * * Results: * TCL_OK, or TCL_ERROR if an I/O error occurs. * * Side effects: * The file position will change. The running CRC is updated if a pointer * to it is provided. * *---------------------------------------------------------------------- */ static int ReadBase64( Tcl_Interp *interp, PNGImage *pngPtr, unsigned char *destPtr, size_t destSz, unsigned long *crcPtr) { static const unsigned char from64[] = { 0x82, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x80, 0x80, 0x83, 0x80, 0x80, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x80, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x3e, 0x83, 0x83, 0x83, 0x3f, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x83, 0x83, 0x83, 0x81, 0x83, 0x83, 0x83, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83, 0x83 }; /* * Definitions for the base-64 decoder. */ #define PNG64_SPECIAL 0x80 /* Flag bit */ #define PNG64_SPACE 0x80 /* Whitespace */ #define PNG64_PAD 0x81 /* Padding */ #define PNG64_DONE 0x82 /* End of data */ #define PNG64_BAD 0x83 /* Ooooh, naughty! */ while (destSz && pngPtr->strDataLen) { unsigned char c = 0; unsigned char c64 = from64[*pngPtr->strDataBuf++]; pngPtr->strDataLen--; if (PNG64_SPACE == c64) { continue; } if (c64 & PNG64_SPECIAL) { c = (unsigned char) pngPtr->base64Bits; } else { switch (pngPtr->base64State++) { case 0: pngPtr->base64Bits = c64 << 2; continue; case 1: c = (unsigned char) (pngPtr->base64Bits | (c64 >> 4)); pngPtr->base64Bits = (c64 & 0xF) << 4; break; case 2: c = (unsigned char) (pngPtr->base64Bits | (c64 >> 2)); pngPtr->base64Bits = (c64 & 0x3) << 6; break; case 3: c = (unsigned char) (pngPtr->base64Bits | c64); pngPtr->base64State = 0; pngPtr->base64Bits = 0; break; } } if (crcPtr) { *crcPtr = Tcl_ZlibCRC32(*crcPtr, &c, 1); } if (destPtr) { *destPtr++ = c; } destSz--; if (c64 & PNG64_SPECIAL) { break; } } if (destSz) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "unexpected end of image data", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "EARLY_END", NULL); return TCL_ERROR; } return TCL_OK; } /* *---------------------------------------------------------------------- * * ReadByteArray -- * * This function is invoked to read the specified number of bytes from a * non-base64-encoded byte array provided via the -data option. * * Note: It would be better if the Tk_PhotoImage stuff handled this by * creating a channel from the -data value and made the data readable as * if it were coming from a file. * * Results: * TCL_OK, or TCL_ERROR if an I/O error occurs. * * Side effects: * The file position will change. The running CRC is updated if a pointer * to it is provided. * *---------------------------------------------------------------------- */ static int ReadByteArray( Tcl_Interp *interp, PNGImage *pngPtr, unsigned char *destPtr, size_t destSz, unsigned long *crcPtr) { /* * Check to make sure the number of requested bytes are available. */ if ((size_t)pngPtr->strDataLen < destSz) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "unexpected end of image data", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "EARLY_END", NULL); return TCL_ERROR; } while (destSz) { size_t blockSz = PNG_MIN(destSz, PNG_BLOCK_SZ); memcpy(destPtr, pngPtr->strDataBuf, blockSz); pngPtr->strDataBuf += blockSz; pngPtr->strDataLen -= blockSz; if (crcPtr) { *crcPtr = Tcl_ZlibCRC32(*crcPtr, destPtr, blockSz); } destPtr += blockSz; destSz -= blockSz; } return TCL_OK; } /* *---------------------------------------------------------------------- * * ReadData -- * * This function is invoked to read the specified number of bytes from * the image file or data. It is a wrapper around the choice of byte * array Tcl_Obj or Tcl_Channel which depends on whether the image data * is coming from a file or -data. * * Results: * TCL_OK, or TCL_ERROR if an I/O error occurs. * * Side effects: * The file position will change. The running CRC is updated if a pointer * to it is provided. * *---------------------------------------------------------------------- */ static int ReadData( Tcl_Interp *interp, PNGImage *pngPtr, unsigned char *destPtr, size_t destSz, unsigned long *crcPtr) { if (pngPtr->base64Data) { return ReadBase64(interp, pngPtr, destPtr, destSz, crcPtr); } else if (pngPtr->strDataBuf) { return ReadByteArray(interp, pngPtr, destPtr, destSz, crcPtr); } while (destSz) { TkSizeT blockSz = PNG_MIN(destSz, PNG_BLOCK_SZ); blockSz = Tcl_Read(pngPtr->channel, (char *)destPtr, blockSz); if (blockSz == TCL_IO_FAILURE) { /* TODO: failure info... */ Tcl_SetObjResult(interp, Tcl_ObjPrintf( "channel read failed: %s", Tcl_PosixError(interp))); return TCL_ERROR; } /* * Update CRC, pointer, and remaining count if anything was read. */ if (blockSz) { if (crcPtr) { *crcPtr = Tcl_ZlibCRC32(*crcPtr, destPtr, blockSz); } destPtr += blockSz; destSz -= blockSz; } /* * Check for EOF before all desired data was read. */ if (destSz && Tcl_Eof(pngPtr->channel)) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "unexpected end of file", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "EOF", NULL); return TCL_ERROR; } } return TCL_OK; } /* *---------------------------------------------------------------------- * * ReadInt32 -- * * This function is invoked to read a 32-bit integer in network byte * order from the image data and return the value in host byte order. * This is used, for example, to read the 32-bit CRC value for a chunk * stored in the image file for comparison with the calculated CRC value. * * Results: * TCL_OK, or TCL_ERROR if an I/O error occurs. * * Side effects: * The file position will change. The running CRC is updated if a pointer * to it is provided. * *---------------------------------------------------------------------- */ static inline int ReadInt32( Tcl_Interp *interp, PNGImage *pngPtr, unsigned long *resultPtr, unsigned long *crcPtr) { unsigned char p[4]; if (ReadData(interp, pngPtr, p, 4, crcPtr) == TCL_ERROR) { return TCL_ERROR; } *resultPtr = PNG_INT32(p[0], p[1], p[2], p[3]); return TCL_OK; } /* *---------------------------------------------------------------------- * * CheckCRC -- * * This function is reads the final 4-byte integer CRC from a chunk and * compares it to the running CRC calculated over the chunk type and data * fields. * * Results: * TCL_OK, or TCL_ERROR if an I/O error or CRC mismatch occurs. * * Side effects: * The file position will change. * *---------------------------------------------------------------------- */ static inline int CheckCRC( Tcl_Interp *interp, PNGImage *pngPtr, unsigned long calculated) { unsigned long chunked; /* * Read the CRC field at the end of the chunk. */ if (ReadInt32(interp, pngPtr, &chunked, NULL) == TCL_ERROR) { return TCL_ERROR; } /* * Compare the read CRC to what we calculate to make sure they match. */ if (calculated != chunked) { Tcl_SetObjResult(interp, Tcl_NewStringObj("CRC check failed", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "CRC", NULL); return TCL_ERROR; } return TCL_OK; } /* *---------------------------------------------------------------------- * * SkipChunk -- * * This function is used to skip a PNG chunk that is not used by this * implementation. Given the input stream has had the chunk length and * chunk type fields already read, this function will read the number of * bytes indicated by the chunk length, plus four for the CRC, and will * verify that CRC is correct for the skipped data. * * Results: * TCL_OK, or TCL_ERROR if an I/O error or CRC mismatch occurs. * * Side effects: * The file position will change. * *---------------------------------------------------------------------- */ static int SkipChunk( Tcl_Interp *interp, PNGImage *pngPtr, int chunkSz, unsigned long crc) { unsigned char buffer[PNG_BLOCK_SZ]; /* * Skip data in blocks until none is left. Read up to PNG_BLOCK_SZ bytes * at a time, rather than trusting the claimed chunk size, which may not * be trustworthy. */ while (chunkSz) { int blockSz = PNG_MIN(chunkSz, PNG_BLOCK_SZ); if (ReadData(interp, pngPtr, buffer, blockSz, &crc) == TCL_ERROR) { return TCL_ERROR; } chunkSz -= blockSz; } if (CheckCRC(interp, pngPtr, crc) == TCL_ERROR) { return TCL_ERROR; } return TCL_OK; } /* * 4.3. Summary of standard chunks * * This table summarizes some properties of the standard chunk types. * * Critical chunks (must appear in this order, except PLTE is optional): * * Name Multiple Ordering constraints OK? * * IHDR No Must be first * PLTE No Before IDAT * IDAT Yes Multiple IDATs must be consecutive * IEND No Must be last * * Ancillary chunks (need not appear in this order): * * Name Multiple Ordering constraints OK? * * cHRM No Before PLTE and IDAT * gAMA No Before PLTE and IDAT * iCCP No Before PLTE and IDAT * sBIT No Before PLTE and IDAT * sRGB No Before PLTE and IDAT * bKGD No After PLTE; before IDAT * hIST No After PLTE; before IDAT * tRNS No After PLTE; before IDAT * pHYs No Before IDAT * sPLT Yes Before IDAT * tIME No None * iTXt Yes None * tEXt Yes None * zTXt Yes None * * [From the PNG specification.] */ /* *---------------------------------------------------------------------- * * ReadChunkHeader -- * * This function is used at the start of each chunk to extract the * four-byte chunk length and four-byte chunk type fields. It will * continue reading until it finds a chunk type that is handled by this * implementation, checking the CRC of any chunks it skips. * * Results: * TCL_OK, or TCL_ERROR if an I/O error occurs or an unknown critical * chunk type is encountered. * * Side effects: * The file position will change. The running CRC is updated. * *---------------------------------------------------------------------- */ static int ReadChunkHeader( Tcl_Interp *interp, PNGImage *pngPtr, size_t *sizePtr, unsigned long *typePtr, unsigned long *crcPtr) { unsigned long chunkType = 0; int chunkSz = 0; unsigned long crc = 0; /* * Continue until finding a chunk type that is handled. */ while (!chunkType) { unsigned long temp; unsigned char pc[4]; int i; /* * Read the 4-byte length field for the chunk. The length field is not * included in the CRC calculation, so the running CRC must be reset * afterward. Limit chunk lengths to INT_MAX, to align with the * maximum size for Tcl_Read, Tcl_GetByteArrayFromObj, etc. */ if (ReadData(interp, pngPtr, pc, 4, NULL) == TCL_ERROR) { return TCL_ERROR; } temp = PNG_INT32(pc[0], pc[1], pc[2], pc[3]); if (temp > INT_MAX) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "chunk size is out of supported range on this architecture", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "OUTSIZE", NULL); return TCL_ERROR; } chunkSz = (int) temp; crc = Tcl_ZlibCRC32(0, NULL, 0); /* * Read the 4-byte chunk type. */ if (ReadData(interp, pngPtr, pc, 4, &crc) == TCL_ERROR) { return TCL_ERROR; } /* * Convert it to a host-order integer for simple comparison. */ chunkType = PNG_INT32(pc[0], pc[1], pc[2], pc[3]); /* * Check to see if this is a known/supported chunk type. Note that the * PNG specs require non-critical (i.e., ancillary) chunk types that * are not recognized to be ignored, rather than be treated as an * error. It does, however, recommend that an unknown critical chunk * type be treated as a failure. * * This switch/loop acts as a filter of sorts for undesired chunk * types. The chunk type should still be checked elsewhere for * determining it is in the correct order. */ switch (chunkType) { /* * These chunk types are required and/or supported. */ case CHUNK_IDAT: case CHUNK_IEND: case CHUNK_IHDR: case CHUNK_PLTE: case CHUNK_tRNS: break; /* * These chunk types are part of the standard, but are not used by * this implementation (at least not yet). Note that these are all * ancillary chunks (lowercase first letter). */ case CHUNK_bKGD: case CHUNK_cHRM: case CHUNK_gAMA: case CHUNK_hIST: case CHUNK_iCCP: case CHUNK_iTXt: case CHUNK_oFFs: case CHUNK_pCAL: case CHUNK_pHYs: case CHUNK_sBIT: case CHUNK_sCAL: case CHUNK_sPLT: case CHUNK_sRGB: case CHUNK_tEXt: case CHUNK_tIME: case CHUNK_zTXt: /* * TODO: might want to check order here. */ if (SkipChunk(interp, pngPtr, chunkSz, crc) == TCL_ERROR) { return TCL_ERROR; } chunkType = 0; break; default: /* * Unknown chunk type. If it's critical, we can't continue. */ if (!(chunkType & PNG_CF_ANCILLARY)) { if (chunkType & PNG_INT32(128,128,128,128)) { /* * No nice ASCII conversion; shouldn't happen either, but * we'll be doubly careful. */ Tcl_SetObjResult(interp, Tcl_NewStringObj( "encountered an unsupported critical chunk type", -1)); } else { char typeString[5]; typeString[0] = (char) ((chunkType >> 24) & 255); typeString[1] = (char) ((chunkType >> 16) & 255); typeString[2] = (char) ((chunkType >> 8) & 255); typeString[3] = (char) (chunkType & 255); typeString[4] = '\0'; Tcl_SetObjResult(interp, Tcl_ObjPrintf( "encountered an unsupported critical chunk type" " \"%s\"", typeString)); } Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "UNSUPPORTED_CRITICAL", NULL); return TCL_ERROR; } /* * Check to see if the chunk type has legal bytes. */ for (i=0 ; i<4 ; i++) { if ((pc[i] < 65) || (pc[i] > 122) || ((pc[i] > 90) && (pc[i] < 97))) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "invalid chunk type", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "INVALID_CHUNK", NULL); return TCL_ERROR; } } /* * It seems to be an otherwise legally labelled ancillary chunk * that we don't want, so skip it after at least checking its CRC. */ if (SkipChunk(interp, pngPtr, chunkSz, crc) == TCL_ERROR) { return TCL_ERROR; } chunkType = 0; } } /* * Found a known chunk type that's handled, albiet possibly not in the * right order. Send back the chunk type (for further checking or * handling), the chunk size and the current CRC for the rest of the * calculation. */ *typePtr = chunkType; *sizePtr = chunkSz; *crcPtr = crc; return TCL_OK; } /* *---------------------------------------------------------------------- * * CheckColor -- * * Do validation on color type, depth, and related information, and * calculates storage requirements and offsets based on image dimensions * and color. * * Results: * TCL_OK, or TCL_ERROR if color information is invalid or some other * failure occurs. * * Side effects: * None * *---------------------------------------------------------------------- */ static int CheckColor( Tcl_Interp *interp, PNGImage *pngPtr) { int offset; /* * Verify the color type is valid and the bit depth is allowed. */ switch (pngPtr->colorType) { case PNG_COLOR_GRAY: pngPtr->numChannels = 1; if ((1 != pngPtr->bitDepth) && (2 != pngPtr->bitDepth) && (4 != pngPtr->bitDepth) && (8 != pngPtr->bitDepth) && (16 != pngPtr->bitDepth)) { goto unsupportedDepth; } break; case PNG_COLOR_RGB: pngPtr->numChannels = 3; if ((8 != pngPtr->bitDepth) && (16 != pngPtr->bitDepth)) { goto unsupportedDepth; } break; case PNG_COLOR_PLTE: pngPtr->numChannels = 1; if ((1 != pngPtr->bitDepth) && (2 != pngPtr->bitDepth) && (4 != pngPtr->bitDepth) && (8 != pngPtr->bitDepth)) { goto unsupportedDepth; } break; case PNG_COLOR_GRAYALPHA: pngPtr->numChannels = 2; if ((8 != pngPtr->bitDepth) && (16 != pngPtr->bitDepth)) { goto unsupportedDepth; } break; case PNG_COLOR_RGBA: pngPtr->numChannels = 4; if ((8 != pngPtr->bitDepth) && (16 != pngPtr->bitDepth)) { unsupportedDepth: Tcl_SetObjResult(interp, Tcl_NewStringObj( "bit depth is not allowed for given color type", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_DEPTH", NULL); return TCL_ERROR; } break; default: Tcl_SetObjResult(interp, Tcl_ObjPrintf( "unknown color type field %d", pngPtr->colorType)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "UNKNOWN_COLOR", NULL); return TCL_ERROR; } /* * Set up the Tk photo block's pixel size and channel offsets. offset * array elements should already be 0 from the memset during InitPNGImage. */ offset = (pngPtr->bitDepth > 8) ? 2 : 1; if (pngPtr->colorType & PNG_COLOR_USED) { pngPtr->block.pixelSize = offset * 4; pngPtr->block.offset[1] = offset; pngPtr->block.offset[2] = offset * 2; pngPtr->block.offset[3] = offset * 3; } else { pngPtr->block.pixelSize = offset * 2; pngPtr->block.offset[3] = offset; } /* * Calculate the block pitch, which is the number of bytes per line in the * image, given image width and depth of color. Make sure that it it isn't * larger than Tk can handle. */ if (pngPtr->block.width > INT_MAX / pngPtr->block.pixelSize) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "image pitch is out of supported range on this architecture", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "PITCH", NULL); return TCL_ERROR; } pngPtr->block.pitch = pngPtr->block.pixelSize * pngPtr->block.width; /* * Calculate the total size of the image as represented to Tk given pitch * and image height. Make sure that it isn't larger than Tk can handle. */ if (pngPtr->block.height > INT_MAX / pngPtr->block.pitch) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "image total size is out of supported range on this architecture", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "SIZE", NULL); return TCL_ERROR; } pngPtr->blockLen = pngPtr->block.height * pngPtr->block.pitch; /* * Determine number of bytes per pixel in the source for later use. */ switch (pngPtr->colorType) { case PNG_COLOR_GRAY: pngPtr->bytesPerPixel = (pngPtr->bitDepth > 8) ? 2 : 1; break; case PNG_COLOR_RGB: pngPtr->bytesPerPixel = (pngPtr->bitDepth > 8) ? 6 : 3; break; case PNG_COLOR_PLTE: pngPtr->bytesPerPixel = 1; break; case PNG_COLOR_GRAYALPHA: pngPtr->bytesPerPixel = (pngPtr->bitDepth > 8) ? 4 : 2; break; case PNG_COLOR_RGBA: pngPtr->bytesPerPixel = (pngPtr->bitDepth > 8) ? 8 : 4; break; default: Tcl_SetObjResult(interp, Tcl_ObjPrintf( "unknown color type %d", pngPtr->colorType)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "UNKNOWN_COLOR", NULL); return TCL_ERROR; } /* * Calculate scale factor for bit depths less than 8, in order to adjust * them to a minimum of 8 bits per pixel in the Tk image. */ if (pngPtr->bitDepth < 8) { pngPtr->bitScale = 255 / (int)(pow(2, pngPtr->bitDepth) - 1); } else { pngPtr->bitScale = 1; } return TCL_OK; } /* *---------------------------------------------------------------------- * * ReadIHDR -- * * This function reads the PNG header from the beginning of a PNG file * and returns the dimensions of the image. * * Results: * The return value is 1 if file "f" appears to start with a valid PNG * header, 0 otherwise. If the header is valid, then *widthPtr and * *heightPtr are modified to hold the dimensions of the image. * * Side effects: * The access position in f advances. * *---------------------------------------------------------------------- */ static int ReadIHDR( Tcl_Interp *interp, PNGImage *pngPtr) { unsigned char sigBuf[PNG_SIG_SZ]; unsigned long chunkType; size_t chunkSz; unsigned long crc; unsigned long width, height; int mismatch; /* * Read the appropriate number of bytes for the PNG signature. */ if (ReadData(interp, pngPtr, sigBuf, PNG_SIG_SZ, NULL) == TCL_ERROR) { return TCL_ERROR; } /* * Compare the read bytes to the expected signature. */ mismatch = memcmp(sigBuf, pngSignature, PNG_SIG_SZ); /* * If reading from string, reset position and try base64 decode. */ if (mismatch && pngPtr->strDataBuf) { pngPtr->strDataBuf = Tcl_GetByteArrayFromObj(pngPtr->objDataPtr, &pngPtr->strDataLen); pngPtr->base64Data = pngPtr->strDataBuf; if (ReadData(interp, pngPtr, sigBuf, PNG_SIG_SZ, NULL) == TCL_ERROR) { return TCL_ERROR; } mismatch = memcmp(sigBuf, pngSignature, PNG_SIG_SZ); } if (mismatch) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "data stream does not have a PNG signature", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "NO_SIG", NULL); return TCL_ERROR; } if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType, &crc) == TCL_ERROR) { return TCL_ERROR; } /* * Read in the IHDR (header) chunk for width, height, etc. * * The first chunk in the file must be the IHDR (headr) chunk. */ if (chunkType != CHUNK_IHDR) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "expected IHDR chunk type", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "NO_IHDR", NULL); return TCL_ERROR; } if (chunkSz != 13) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "invalid IHDR chunk size", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_IHDR", NULL); return TCL_ERROR; } /* * Read and verify the image width and height to be sure Tk can handle its * dimensions. The PNG specification does not permit zero-width or * zero-height images. */ if (ReadInt32(interp, pngPtr, &width, &crc) == TCL_ERROR) { return TCL_ERROR; } if (ReadInt32(interp, pngPtr, &height, &crc) == TCL_ERROR) { return TCL_ERROR; } if (!width || !height || (width > INT_MAX) || (height > INT_MAX)) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "image dimensions are invalid or beyond architecture limits", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "DIMENSIONS", NULL); return TCL_ERROR; } /* * Set height and width for the Tk photo block. */ pngPtr->block.width = (int) width; pngPtr->block.height = (int) height; /* * Read and the Bit Depth and Color Type. */ if (ReadData(interp, pngPtr, &pngPtr->bitDepth, 1, &crc) == TCL_ERROR) { return TCL_ERROR; } if (ReadData(interp, pngPtr, &pngPtr->colorType, 1, &crc) == TCL_ERROR) { return TCL_ERROR; } /* * Verify that the color type is valid, the bit depth is allowed for the * color type, and calculate the number of channels and pixel depth (bits * per pixel * channels). Also set up offsets and sizes in the Tk photo * block for the pixel data. */ if (CheckColor(interp, pngPtr) == TCL_ERROR) { return TCL_ERROR; } /* * Only one compression method is currently defined by the standard. */ if (ReadData(interp, pngPtr, &pngPtr->compression, 1, &crc) == TCL_ERROR) { return TCL_ERROR; } if (pngPtr->compression != PNG_COMPRESS_DEFLATE) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "unknown compression method %d", pngPtr->compression)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_COMPRESS", NULL); return TCL_ERROR; } /* * Only one filter method is currently defined by the standard; the method * has five actual filter types associated with it. */ if (ReadData(interp, pngPtr, &pngPtr->filter, 1, &crc) == TCL_ERROR) { return TCL_ERROR; } if (pngPtr->filter != PNG_FILTMETH_STANDARD) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "unknown filter method %d", pngPtr->filter)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_FILTER", NULL); return TCL_ERROR; } if (ReadData(interp, pngPtr, &pngPtr->interlace, 1, &crc) == TCL_ERROR) { return TCL_ERROR; } switch (pngPtr->interlace) { case PNG_INTERLACE_NONE: case PNG_INTERLACE_ADAM7: break; default: Tcl_SetObjResult(interp, Tcl_ObjPrintf( "unknown interlace method %d", pngPtr->interlace)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_INTERLACE", NULL); return TCL_ERROR; } return CheckCRC(interp, pngPtr, crc); } /* *---------------------------------------------------------------------- * * ReadPLTE -- * * This function reads the PLTE (indexed color palette) chunk data from * the PNG file and populates the palette table in the PNGImage * structure. * * Results: * TCL_OK, or TCL_ERROR if an I/O error occurs or the PLTE chunk is * invalid. * * Side effects: * The access position in f advances. * *---------------------------------------------------------------------- */ static int ReadPLTE( Tcl_Interp *interp, PNGImage *pngPtr, int chunkSz, unsigned long crc) { unsigned char buffer[PNG_PLTE_MAXSZ]; int i, c; /* * This chunk is mandatory for color type 3 and forbidden for 2 and 6. */ switch (pngPtr->colorType) { case PNG_COLOR_GRAY: case PNG_COLOR_GRAYALPHA: Tcl_SetObjResult(interp, Tcl_NewStringObj( "PLTE chunk type forbidden for grayscale", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "PLTE_UNEXPECTED", NULL); return TCL_ERROR; default: break; } /* * The palette chunk contains from 1 to 256 palette entries. Each entry * consists of a 3-byte RGB value. It must therefore contain a non-zero * multiple of 3 bytes, up to 768. */ if (!chunkSz || (chunkSz > PNG_PLTE_MAXSZ) || (chunkSz % 3)) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "invalid palette chunk size", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_PLTE", NULL); return TCL_ERROR; } /* * Read the palette contents and stash them for later, possibly. */ if (ReadData(interp, pngPtr, buffer, chunkSz, &crc) == TCL_ERROR) { return TCL_ERROR; } if (CheckCRC(interp, pngPtr, crc) == TCL_ERROR) { return TCL_ERROR; } /* * Stash away the palette entries and entry count for later mapping each * pixel's palette index to its color. */ for (i=0, c=0 ; c<chunkSz ; i++) { pngPtr->palette[i].red = buffer[c++]; pngPtr->palette[i].green = buffer[c++]; pngPtr->palette[i].blue = buffer[c++]; } pngPtr->paletteLen = i; return TCL_OK; } /* *---------------------------------------------------------------------- * * ReadTRNS -- * * This function reads the tRNS (transparency) chunk data from the PNG * file and populates the alpha field of the palette table in the * PNGImage structure or the single color transparency, as appropriate * for the color type. * * Results: * TCL_OK, or TCL_ERROR if an I/O error occurs or the tRNS chunk is * invalid. * * Side effects: * The access position in f advances. * *---------------------------------------------------------------------- */ static int ReadTRNS( Tcl_Interp *interp, PNGImage *pngPtr, int chunkSz, unsigned long crc) { unsigned char buffer[PNG_TRNS_MAXSZ]; int i; if (pngPtr->colorType & PNG_COLOR_ALPHA) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "tRNS chunk not allowed color types with a full alpha channel", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "INVALID_TRNS", NULL); return TCL_ERROR; } /* * For indexed color, there is up to one single-byte transparency value * per palette entry (thus a max of 256). */ if (chunkSz > PNG_TRNS_MAXSZ) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "invalid tRNS chunk size", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_TRNS", NULL); return TCL_ERROR; } /* * Read in the raw transparency information. */ if (ReadData(interp, pngPtr, buffer, chunkSz, &crc) == TCL_ERROR) { return TCL_ERROR; } if (CheckCRC(interp, pngPtr, crc) == TCL_ERROR) { return TCL_ERROR; } switch (pngPtr->colorType) { case PNG_COLOR_GRAYALPHA: case PNG_COLOR_RGBA: break; case PNG_COLOR_PLTE: /* * The number of tRNS entries must be less than or equal to the number * of PLTE entries, and consists of a single-byte alpha level for the * corresponding PLTE entry. */ if (chunkSz > pngPtr->paletteLen) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "size of tRNS chunk is too large for the palette", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "TRNS_SIZE", NULL); return TCL_ERROR; } for (i=0 ; i<chunkSz ; i++) { pngPtr->palette[i].alpha = buffer[i]; } break; case PNG_COLOR_GRAY: /* * Grayscale uses a single 2-byte gray level, which we'll store in * palette index 0, since we're not using the palette. */ if (chunkSz != 2) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "invalid tRNS chunk size - must 2 bytes for grayscale", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_TRNS", NULL); return TCL_ERROR; } /* * According to the PNG specs, if the bit depth is less than 16, then * only the lower byte is used. */ if (16 == pngPtr->bitDepth) { pngPtr->transVal[0] = buffer[0]; pngPtr->transVal[1] = buffer[1]; } else { pngPtr->transVal[0] = buffer[1]; } pngPtr->useTRNS = 1; break; case PNG_COLOR_RGB: /* * TrueColor uses a single RRGGBB triplet. */ if (chunkSz != 6) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "invalid tRNS chunk size - must 6 bytes for RGB", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_TRNS", NULL); return TCL_ERROR; } /* * According to the PNG specs, if the bit depth is less than 16, then * only the lower byte is used. But the tRNS chunk still contains two * bytes per channel. */ if (16 == pngPtr->bitDepth) { memcpy(pngPtr->transVal, buffer, 6); } else { pngPtr->transVal[0] = buffer[1]; pngPtr->transVal[1] = buffer[3]; pngPtr->transVal[2] = buffer[5]; } pngPtr->useTRNS = 1; break; } return TCL_OK; } /* *---------------------------------------------------------------------- * * Paeth -- * * Utility function for applying the Paeth filter to a pixel. The Paeth * filter is a linear function of the pixel to be filtered and the pixels * to the left, above, and above-left of the pixel to be unfiltered. * * Results: * Result of the Paeth function for the left, above, and above-left * pixels. * * Side effects: * None * *---------------------------------------------------------------------- */ static inline unsigned char Paeth( int a, int b, int c) { int pa = abs(b - c); int pb = abs(a - c); int pc = abs(a + b - c - c); if ((pa <= pb) && (pa <= pc)) { return (unsigned char) a; } if (pb <= pc) { return (unsigned char) b; } return (unsigned char) c; } /* *---------------------------------------------------------------------- * * UnfilterLine -- * * Applies the filter algorithm specified in first byte of a line to the * line of pixels being read from a PNG image. * * PNG specifies four filter algorithms (Sub, Up, Average, and Paeth) * that combine a pixel's value with those of other pixels in the same * and/or previous lines. Filtering is intended to make an image more * compressible. * * Results: * TCL_OK, or TCL_ERROR if the filter type is not recognized. * * Side effects: * Pixel data in thisLineObj are modified. * *---------------------------------------------------------------------- */ static int UnfilterLine( Tcl_Interp *interp, PNGImage *pngPtr) { unsigned char *thisLine = Tcl_GetByteArrayFromObj(pngPtr->thisLineObj, (int *)NULL); unsigned char *lastLine = Tcl_GetByteArrayFromObj(pngPtr->lastLineObj, (int *)NULL); #define PNG_FILTER_NONE 0 #define PNG_FILTER_SUB 1 #define PNG_FILTER_UP 2 #define PNG_FILTER_AVG 3 #define PNG_FILTER_PAETH 4 switch (*thisLine) { case PNG_FILTER_NONE: /* Nothing to do */ break; case PNG_FILTER_SUB: { /* Sub(x) = Raw(x) - Raw(x-bpp) */ unsigned char *rawBpp = thisLine + 1; unsigned char *raw = rawBpp + pngPtr->bytesPerPixel; unsigned char *end = thisLine + pngPtr->phaseSize; while (raw < end) { *raw++ += *rawBpp++; } break; } case PNG_FILTER_UP: /* Up(x) = Raw(x) - Prior(x) */ if (pngPtr->currentLine > startLine[pngPtr->phase]) { unsigned char *prior = lastLine + 1; unsigned char *raw = thisLine + 1; unsigned char *end = thisLine + pngPtr->phaseSize; while (raw < end) { *raw++ += *prior++; } } break; case PNG_FILTER_AVG: /* Avg(x) = Raw(x) - floor((Raw(x-bpp)+Prior(x))/2) */ if (pngPtr->currentLine > startLine[pngPtr->phase]) { unsigned char *prior = lastLine + 1; unsigned char *rawBpp = thisLine + 1; unsigned char *raw = rawBpp; unsigned char *end = thisLine + pngPtr->phaseSize; unsigned char *end2 = raw + pngPtr->bytesPerPixel; while ((raw < end2) && (raw < end)) { *raw++ += *prior++ / 2; } while (raw < end) { *raw++ += (unsigned char) (((int) *rawBpp++ + (int) *prior++) / 2); } } else { unsigned char *rawBpp = thisLine + 1; unsigned char *raw = rawBpp + pngPtr->bytesPerPixel; unsigned char *end = thisLine + pngPtr->phaseSize; while (raw < end) { *raw++ += *rawBpp++ / 2; } } break; case PNG_FILTER_PAETH: /* Paeth(x) = Raw(x) - PaethPredictor(Raw(x-bpp), Prior(x), Prior(x-bpp)) */ if (pngPtr->currentLine > startLine[pngPtr->phase]) { unsigned char *priorBpp = lastLine + 1; unsigned char *prior = priorBpp; unsigned char *rawBpp = thisLine + 1; unsigned char *raw = rawBpp; unsigned char *end = thisLine + pngPtr->phaseSize; unsigned char *end2 = rawBpp + pngPtr->bytesPerPixel; while ((raw < end) && (raw < end2)) { *raw++ += *prior++; } while (raw < end) { *raw++ += Paeth(*rawBpp++, *prior++, *priorBpp++); } } else { unsigned char *rawBpp = thisLine + 1; unsigned char *raw = rawBpp + pngPtr->bytesPerPixel; unsigned char *end = thisLine + pngPtr->phaseSize; while (raw < end) { *raw++ += *rawBpp++; } } break; default: Tcl_SetObjResult(interp, Tcl_ObjPrintf( "invalid filter type %d", *thisLine)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_FILTER", NULL); return TCL_ERROR; } return TCL_OK; } /* *---------------------------------------------------------------------- * * DecodeLine -- * * Unfilters a line of pixels from the PNG source data and decodes the * data into the Tk_PhotoImageBlock for later copying into the Tk image. * * Results: * TCL_OK, or TCL_ERROR if the filter type is not recognized. * * Side effects: * Pixel data in thisLine and block are modified and state information * updated. * *---------------------------------------------------------------------- */ static int DecodeLine( Tcl_Interp *interp, PNGImage *pngPtr) { unsigned char *pixelPtr = pngPtr->block.pixelPtr; int colNum = 0; /* Current pixel column */ unsigned char chan = 0; /* Current channel (0..3) = (R, G, B, A) */ unsigned char readByte = 0; /* Current scan line byte */ int haveBits = 0; /* Number of bits remaining in current byte */ unsigned char pixBits = 0; /* Extracted bits for current channel */ int shifts = 0; /* Number of channels extracted from byte */ int offset = 0; /* Current offset into pixelPtr */ int colStep = 1; /* Column increment each pass */ int pixStep = 0; /* extra pixelPtr increment each pass */ unsigned char lastPixel[6]; unsigned char *p = Tcl_GetByteArrayFromObj(pngPtr->thisLineObj, (int *)NULL); p++; if (UnfilterLine(interp, pngPtr) == TCL_ERROR) { return TCL_ERROR; } if (pngPtr->currentLine >= pngPtr->block.height) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "PNG image data overflow")); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "DATA_OVERFLOW", NULL); return TCL_ERROR; } if (pngPtr->interlace) { switch (pngPtr->phase) { case 1: /* Phase 1: */ colStep = 8; /* 1 pixel per block of 8 per line */ break; /* Start at column 0 */ case 2: /* Phase 2: */ colStep = 8; /* 1 pixels per block of 8 per line */ colNum = 4; /* Start at column 4 */ break; case 3: /* Phase 3: */ colStep = 4; /* 2 pixels per block of 8 per line */ break; /* Start at column 0 */ case 4: /* Phase 4: */ colStep = 4; /* 2 pixels per block of 8 per line */ colNum = 2; /* Start at column 2 */ break; case 5: /* Phase 5: */ colStep = 2; /* 4 pixels per block of 8 per line */ break; /* Start at column 0 */ case 6: /* Phase 6: */ colStep = 2; /* 4 pixels per block of 8 per line */ colNum = 1; /* Start at column 1 */ break; /* Phase 7: */ /* 8 pixels per block of 8 per line */ /* Start at column 0 */ } } /* * Calculate offset into pixelPtr for the first pixel of the line. */ offset = pngPtr->currentLine * pngPtr->block.pitch; /* * Adjust up for the starting pixel of the line. */ offset += colNum * pngPtr->block.pixelSize; /* * Calculate the extra number of bytes to skip between columns. */ pixStep = (colStep - 1) * pngPtr->block.pixelSize; for ( ; colNum < pngPtr->block.width ; colNum += colStep) { if (haveBits < (pngPtr->bitDepth * pngPtr->numChannels)) { haveBits = 0; } for (chan = 0 ; chan < pngPtr->numChannels ; chan++) { if (!haveBits) { shifts = 0; readByte = *p++; haveBits += 8; } if (16 == pngPtr->bitDepth) { pngPtr->block.pixelPtr[offset++] = readByte; if (pngPtr->useTRNS) { lastPixel[chan * 2] = readByte; } readByte = *p++; if (pngPtr->useTRNS) { lastPixel[(chan * 2) + 1] = readByte; } pngPtr->block.pixelPtr[offset++] = readByte; haveBits = 0; continue; } switch (pngPtr->bitDepth) { case 1: pixBits = (unsigned char)((readByte >> (7-shifts)) & 0x01); break; case 2: pixBits = (unsigned char)((readByte >> (6-shifts*2)) & 0x03); break; case 4: pixBits = (unsigned char)((readByte >> (4-shifts*4)) & 0x0f); break; case 8: pixBits = readByte; break; } if (PNG_COLOR_PLTE == pngPtr->colorType) { pixelPtr[offset++] = pngPtr->palette[pixBits].red; pixelPtr[offset++] = pngPtr->palette[pixBits].green; pixelPtr[offset++] = pngPtr->palette[pixBits].blue; pixelPtr[offset++] = pngPtr->palette[pixBits].alpha; chan += 2; } else { pixelPtr[offset++] = (unsigned char) (pixBits * pngPtr->bitScale); if (pngPtr->useTRNS) { lastPixel[chan] = pixBits; } } haveBits -= pngPtr->bitDepth; shifts++; } /* * Apply boolean transparency via tRNS data if necessary (where * necessary means a tRNS chunk was provided and we're not using an * alpha channel or indexed alpha). */ if ((PNG_COLOR_PLTE != pngPtr->colorType) && !(pngPtr->colorType & PNG_COLOR_ALPHA)) { unsigned char alpha; if (pngPtr->useTRNS) { if (memcmp(lastPixel, pngPtr->transVal, pngPtr->bytesPerPixel) == 0) { alpha = 0x00; } else { alpha = 0xff; } } else { alpha = 0xff; } pixelPtr[offset++] = alpha; if (16 == pngPtr->bitDepth) { pixelPtr[offset++] = alpha; } } offset += pixStep; } if (pngPtr->interlace) { /* Skip lines */ switch (pngPtr->phase) { case 1: case 2: case 3: pngPtr->currentLine += 8; break; case 4: case 5: pngPtr->currentLine += 4; break; case 6: case 7: pngPtr->currentLine += 2; break; } /* * Start the next phase if there are no more lines to do. */ if (pngPtr->currentLine >= pngPtr->block.height) { unsigned long pixels = 0; while ((!pixels || (pngPtr->currentLine >= pngPtr->block.height)) && (pngPtr->phase < 7)) { pngPtr->phase++; switch (pngPtr->phase) { case 2: pixels = (pngPtr->block.width + 3) >> 3; pngPtr->currentLine = 0; break; case 3: pixels = (pngPtr->block.width + 3) >> 2; pngPtr->currentLine = 4; break; case 4: pixels = (pngPtr->block.width + 1) >> 2; pngPtr->currentLine = 0; break; case 5: pixels = (pngPtr->block.width + 1) >> 1; pngPtr->currentLine = 2; break; case 6: pixels = pngPtr->block.width >> 1; pngPtr->currentLine = 0; break; case 7: pngPtr->currentLine = 1; pixels = pngPtr->block.width; break; } } if (16 == pngPtr->bitDepth) { pngPtr->phaseSize = 1 + (pngPtr->numChannels * pixels * 2); } else { pngPtr->phaseSize = 1 + ((pngPtr->numChannels * pixels * pngPtr->bitDepth + 7) >> 3); } } } else { pngPtr->currentLine++; } return TCL_OK; } /* *---------------------------------------------------------------------- * * ReadIDAT -- * * This function reads the IDAT (pixel data) chunk from the PNG file to * build the image. It will continue reading until all IDAT chunks have * been processed or an error occurs. * * Results: * TCL_OK, or TCL_ERROR if an I/O error occurs or an IDAT chunk is * invalid. * * Side effects: * The access position in f advances. Memory may be allocated by zlib * through PNGZAlloc. * *---------------------------------------------------------------------- */ static int ReadIDAT( Tcl_Interp *interp, PNGImage *pngPtr, int chunkSz, unsigned long crc) { /* * Process IDAT contents until there is no more in this chunk. */ while (chunkSz && !Tcl_ZlibStreamEof(pngPtr->stream)) { TkSizeT len1, len2; /* * Read another block of input into the zlib stream if data remains. */ if (chunkSz) { Tcl_Obj *inputObj = NULL; int blockSz = PNG_MIN(chunkSz, PNG_BLOCK_SZ); unsigned char *inputPtr = NULL; /* * Check for end of zlib stream. */ if (Tcl_ZlibStreamEof(pngPtr->stream)) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "extra data after end of zlib stream", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "EXTRA_DATA", NULL); return TCL_ERROR; } inputObj = Tcl_NewObj(); Tcl_IncrRefCount(inputObj); inputPtr = Tcl_SetByteArrayLength(inputObj, blockSz); /* * Read the next bit of IDAT chunk data, up to read buffer size. */ if (ReadData(interp, pngPtr, inputPtr, blockSz, &crc) == TCL_ERROR) { Tcl_DecrRefCount(inputObj); return TCL_ERROR; } chunkSz -= blockSz; Tcl_ZlibStreamPut(pngPtr->stream, inputObj, TCL_ZLIB_NO_FLUSH); Tcl_DecrRefCount(inputObj); } /* * Inflate, processing each output buffer's worth as a line of pixels, * until we cannot fill the buffer any more. */ getNextLine: Tcl_GetByteArrayFromObj(pngPtr->thisLineObj, &len1); if (Tcl_ZlibStreamGet(pngPtr->stream, pngPtr->thisLineObj, pngPtr->phaseSize - len1) == TCL_ERROR) { return TCL_ERROR; } Tcl_GetByteArrayFromObj(pngPtr->thisLineObj, &len2); if (len2 == (TkSizeT)pngPtr->phaseSize) { if (pngPtr->phase > 7) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "extra data after final scan line of final phase", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "EXTRA_DATA", NULL); return TCL_ERROR; } if (DecodeLine(interp, pngPtr) == TCL_ERROR) { return TCL_ERROR; } /* * Swap the current/last lines so that we always have the last * line processed available, which is necessary for filtering. */ { Tcl_Obj *temp = pngPtr->lastLineObj; pngPtr->lastLineObj = pngPtr->thisLineObj; pngPtr->thisLineObj = temp; } Tcl_SetByteArrayLength(pngPtr->thisLineObj, 0); /* * Try to read another line of pixels out of the buffer * immediately, but don't allow write past end of block. */ if (pngPtr->currentLine < pngPtr->block.height) { goto getNextLine; } } /* * Got less than a whole buffer-load of pixels. Either we're going to * be getting more data from the next IDAT, or we've done what we can * here. */ } /* * Ensure that if we've got to the end of the compressed data, we've * also got to the end of the compressed stream. This sanity check is * enforced by most PNG readers. */ if (chunkSz != 0) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "compressed data after stream finalize in PNG data", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "EXTRA_DATA", NULL); return TCL_ERROR; } return CheckCRC(interp, pngPtr, crc); } /* *---------------------------------------------------------------------- * * ApplyAlpha -- * * Applies an overall alpha value to a complete image that has been read. * This alpha value is specified using the -format option to [image * create photo]. * * Results: * N/A * * Side effects: * The access position in f may change. * *---------------------------------------------------------------------- */ static void ApplyAlpha( PNGImage *pngPtr) { if (pngPtr->alpha != 1.0) { unsigned char *p = pngPtr->block.pixelPtr; unsigned char *endPtr = p + pngPtr->blockLen; int offset = pngPtr->block.offset[3]; p += offset; if (16 == pngPtr->bitDepth) { unsigned int channel; while (p < endPtr) { channel = (unsigned int) (((p[0] << 8) | p[1]) * pngPtr->alpha); *p++ = (unsigned char) (channel >> 8); *p++ = (unsigned char) (channel & 0xff); p += offset; } } else { while (p < endPtr) { p[0] = (unsigned char) (pngPtr->alpha * p[0]); p += 1 + offset; } } } } /* *---------------------------------------------------------------------- * * ParseFormat -- * * This function parses the -format string that can be specified to the * [image create photo] command to extract options for postprocessing of * loaded images. Currently, this just allows specifying and applying an * overall alpha value to the loaded image (for example, to make it * entirely 50% as transparent as the actual image file). * * Results: * TCL_OK, or TCL_ERROR if the format specification is invalid. * * Side effects: * None * *---------------------------------------------------------------------- */ static int ParseFormat( Tcl_Interp *interp, Tcl_Obj *fmtObj, PNGImage *pngPtr) { Tcl_Obj **objv = NULL; int objc = 0; static const char *const fmtOptions[] = { "-alpha", NULL }; enum fmtOptionsEnum { OPT_ALPHA }; /* * Extract elements of format specification as a list. */ if (fmtObj && Tcl_ListObjGetElements(interp, fmtObj, &objc, &objv) != TCL_OK) { return TCL_ERROR; } for (; objc>0 ; objc--, objv++) { int optIndex; /* * Ignore the "png" part of the format specification. */ if (!strcasecmp(Tcl_GetString(objv[0]), "png")) { continue; } if (Tcl_GetIndexFromObjStruct(interp, objv[0], fmtOptions, sizeof(char *), "option", 0, &optIndex) == TCL_ERROR) { return TCL_ERROR; } if (objc < 2) { Tcl_WrongNumArgs(interp, 1, objv, "value"); return TCL_ERROR; } objc--; objv++; switch ((enum fmtOptionsEnum) optIndex) { case OPT_ALPHA: if (Tcl_GetDoubleFromObj(interp, objv[0], &pngPtr->alpha) == TCL_ERROR) { return TCL_ERROR; } if ((pngPtr->alpha < 0.0) || (pngPtr->alpha > 1.0)) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "-alpha value must be between 0.0 and 1.0", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_ALPHA", NULL); return TCL_ERROR; } break; } } return TCL_OK; } /* *---------------------------------------------------------------------- * * DecodePNG -- * * This function handles the entirety of reading a PNG file (or data) * from the first byte to the last. * * Results: * TCL_OK, or TCL_ERROR if an I/O error occurs or any problems are * detected in the PNG file. * * Side effects: * The access position in f advances. Memory may be allocated and image * dimensions and contents may change. * *---------------------------------------------------------------------- */ static int DecodePNG( Tcl_Interp *interp, PNGImage *pngPtr, Tcl_Obj *fmtObj, Tk_PhotoHandle imageHandle, int destX, int destY) { unsigned long chunkType; size_t chunkSz; unsigned long crc; /* * Parse the PNG signature and IHDR (header) chunk. */ if (ReadIHDR(interp, pngPtr) == TCL_ERROR) { return TCL_ERROR; } /* * Extract alpha value from -format object, if specified. */ if (ParseFormat(interp, fmtObj, pngPtr) == TCL_ERROR) { return TCL_ERROR; } /* * The next chunk may either be a PLTE (Palette) chunk or the first of at * least one IDAT (data) chunks. It could also be one of a number of * ancillary chunks, but those are skipped for us by the switch in * ReadChunkHeader(). * * PLTE is mandatory for color type 3 and forbidden for 2 and 6 */ if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType, &crc) == TCL_ERROR) { return TCL_ERROR; } if (CHUNK_PLTE == chunkType) { /* * Finish parsing the PLTE chunk. */ if (ReadPLTE(interp, pngPtr, chunkSz, crc) == TCL_ERROR) { return TCL_ERROR; } /* * Begin the next chunk. */ if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType, &crc) == TCL_ERROR) { return TCL_ERROR; } } else if (PNG_COLOR_PLTE == pngPtr->colorType) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "PLTE chunk required for indexed color", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "NEED_PLTE", NULL); return TCL_ERROR; } /* * The next chunk may be a tRNS (palette transparency) chunk, depending on * the color type. It must come after the PLTE chunk and before the IDAT * chunk, but can be present if there is no PLTE chunk because it can be * used for Grayscale and TrueColor in lieu of an alpha channel. */ if (CHUNK_tRNS == chunkType) { /* * Finish parsing the tRNS chunk. */ if (ReadTRNS(interp, pngPtr, chunkSz, crc) == TCL_ERROR) { return TCL_ERROR; } /* * Begin the next chunk. */ if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType, &crc) == TCL_ERROR) { return TCL_ERROR; } } /* * Other ancillary chunk types could appear here, but for now we're only * interested in IDAT. The others should have been skipped. */ if (chunkType != CHUNK_IDAT) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "at least one IDAT chunk is required", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "NEED_IDAT", NULL); return TCL_ERROR; } /* * Expand the photo size (if not set by the user) to provide enough space * for the image being parsed. It does not matter if width or height wrap * to negative here: Tk will not shrink the image. */ if (Tk_PhotoExpand(interp, imageHandle, destX + pngPtr->block.width, destY + pngPtr->block.height) == TCL_ERROR) { return TCL_ERROR; } /* * A scan line consists of one byte for a filter type, plus the number of * bits per color sample times the number of color samples per pixel. */ if (pngPtr->block.width > ((INT_MAX - 1) / (pngPtr->numChannels * 2))) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "line size is out of supported range on this architecture", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "LINE_SIZE", NULL); return TCL_ERROR; } if (16 == pngPtr->bitDepth) { pngPtr->lineSize = 1 + (pngPtr->numChannels * pngPtr->block.width*2); } else { pngPtr->lineSize = 1 + ((pngPtr->numChannels * pngPtr->block.width) / (8 / pngPtr->bitDepth)); if (pngPtr->block.width % (8 / pngPtr->bitDepth)) { pngPtr->lineSize++; } } /* * Allocate space for decoding the scan lines. */ pngPtr->lastLineObj = Tcl_NewObj(); Tcl_IncrRefCount(pngPtr->lastLineObj); pngPtr->thisLineObj = Tcl_NewObj(); Tcl_IncrRefCount(pngPtr->thisLineObj); pngPtr->block.pixelPtr = (unsigned char *)attemptckalloc(pngPtr->blockLen); if (!pngPtr->block.pixelPtr) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "memory allocation failed", -1)); Tcl_SetErrorCode(interp, "TK", "MALLOC", NULL); return TCL_ERROR; } /* * Determine size of the first phase if interlaced. Phase size should * always be <= line size, so probably not necessary to check for * arithmetic overflow here: should be covered by line size check. */ if (pngPtr->interlace) { /* * Only one pixel per block of 8 per line in the first phase. */ unsigned int pixels = (pngPtr->block.width + 7) >> 3; pngPtr->phase = 1; if (16 == pngPtr->bitDepth) { pngPtr->phaseSize = 1 + pngPtr->numChannels*pixels*2; } else { pngPtr->phaseSize = 1 + ((pngPtr->numChannels*pixels*pngPtr->bitDepth + 7) >> 3); } } else { pngPtr->phaseSize = pngPtr->lineSize; } /* * All of the IDAT (data) chunks must be consecutive. */ while (CHUNK_IDAT == chunkType) { if (ReadIDAT(interp, pngPtr, chunkSz, crc) == TCL_ERROR) { return TCL_ERROR; } if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType, &crc) == TCL_ERROR) { return TCL_ERROR; } } /* * Ensure that we've got to the end of the compressed stream now that * there are no more IDAT segments. This sanity check is enforced by most * PNG readers. */ if (!Tcl_ZlibStreamEof(pngPtr->stream)) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "unfinalized data stream in PNG data", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "EXTRA_DATA", NULL); return TCL_ERROR; } /* * Now skip the remaining chunks which we're also not interested in. */ while (CHUNK_IEND != chunkType) { if (SkipChunk(interp, pngPtr, chunkSz, crc) == TCL_ERROR) { return TCL_ERROR; } if (ReadChunkHeader(interp, pngPtr, &chunkSz, &chunkType, &crc) == TCL_ERROR) { return TCL_ERROR; } } /* * Got the IEND (end of image) chunk. Do some final checks... */ if (chunkSz) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "IEND chunk contents must be empty", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_IEND", NULL); return TCL_ERROR; } /* * Check the CRC on the IEND chunk. */ if (CheckCRC(interp, pngPtr, crc) == TCL_ERROR) { return TCL_ERROR; } /* * TODO: verify that nothing else comes after the IEND chunk, or do we * really care? */ #if 0 if (ReadData(interp, pngPtr, &c, 1, NULL) != TCL_ERROR) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "extra data following IEND chunk", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "BAD_IEND", NULL); return TCL_ERROR; } #endif /* * Apply overall image alpha if specified. */ ApplyAlpha(pngPtr); /* * Copy the decoded image block into the Tk photo image. */ if (Tk_PhotoPutBlock(interp, imageHandle, &pngPtr->block, destX, destY, pngPtr->block.width, pngPtr->block.height, TK_PHOTO_COMPOSITE_SET) == TCL_ERROR) { return TCL_ERROR; } return TCL_OK; } /* *---------------------------------------------------------------------- * * FileMatchPNG -- * * This function is invoked by the photo image type to see if a file * contains image data in PNG format. * * Results: * The return value is 1 if the first characters in file f look like PNG * data, and 0 otherwise. * * Side effects: * The access position in f may change. * *---------------------------------------------------------------------- */ static int FileMatchPNG( Tcl_Channel chan, const char *fileName, Tcl_Obj *fmtObj, int *widthPtr, int *heightPtr, Tcl_Interp *interp) { PNGImage png; int match = 0; (void)fileName; (void)fmtObj; InitPNGImage(NULL, &png, chan, NULL, TCL_ZLIB_STREAM_INFLATE); if (ReadIHDR(interp, &png) == TCL_OK) { *widthPtr = png.block.width; *heightPtr = png.block.height; match = 1; } CleanupPNGImage(&png); return match; } /* *---------------------------------------------------------------------- * * FileReadPNG -- * * This function is called by the photo image type to read PNG format * data from a file and write it into a given photo image. * * Results: * A standard TCL completion code. If TCL_ERROR is returned then an error * message is left in the interp's result. * * Side effects: * The access position in file f is changed, and new data is added to the * image given by imageHandle. * *---------------------------------------------------------------------- */ static int FileReadPNG( Tcl_Interp *interp, Tcl_Channel chan, const char *fileName, Tcl_Obj *fmtObj, Tk_PhotoHandle imageHandle, int destX, int destY, int width, int height, int srcX, int srcY) { PNGImage png; int result = TCL_ERROR; (void)fileName; (void)width; (void)height; (void)srcX; (void)srcY; result = InitPNGImage(interp, &png, chan, NULL, TCL_ZLIB_STREAM_INFLATE); if (TCL_OK == result) { result = DecodePNG(interp, &png, fmtObj, imageHandle, destX, destY); } CleanupPNGImage(&png); return result; } /* *---------------------------------------------------------------------- * * StringMatchPNG -- * * This function is invoked by the photo image type to see if an object * contains image data in PNG format. * * Results: * The return value is 1 if the first characters in the data are like PNG * data, and 0 otherwise. * * Side effects: * The size of the image is placed in widthPre and heightPtr. * *---------------------------------------------------------------------- */ static int StringMatchPNG( Tcl_Obj *pObjData, Tcl_Obj *fmtObj, int *widthPtr, int *heightPtr, Tcl_Interp *interp) { PNGImage png; int match = 0; (void)fmtObj; InitPNGImage(NULL, &png, NULL, pObjData, TCL_ZLIB_STREAM_INFLATE); png.strDataBuf = Tcl_GetByteArrayFromObj(pObjData, &png.strDataLen); if (ReadIHDR(interp, &png) == TCL_OK) { *widthPtr = png.block.width; *heightPtr = png.block.height; match = 1; } CleanupPNGImage(&png); return match; } /* *---------------------------------------------------------------------- * * StringReadPNG -- * * This function is called by the photo image type to read PNG format * data from an object and give it to the photo image. * * Results: * A standard TCL completion code. If TCL_ERROR is returned then an error * message is left in the interp's result. * * Side effects: * New data is added to the image given by imageHandle. * *---------------------------------------------------------------------- */ static int StringReadPNG( Tcl_Interp *interp, Tcl_Obj *pObjData, Tcl_Obj *fmtObj, Tk_PhotoHandle imageHandle, int destX, int destY, int width, int height, int srcX, int srcY) { PNGImage png; int result = TCL_ERROR; (void)width; (void)height; (void)srcX; (void)srcY; result = InitPNGImage(interp, &png, NULL, pObjData, TCL_ZLIB_STREAM_INFLATE); if (TCL_OK == result) { result = DecodePNG(interp, &png, fmtObj, imageHandle, destX, destY); } CleanupPNGImage(&png); return result; } /* *---------------------------------------------------------------------- * * WriteData -- * * This function writes a bytes from a buffer out to the PNG image. * * Results: * TCL_OK, or TCL_ERROR if the write fails. * * Side effects: * File or buffer will be modified. * *---------------------------------------------------------------------- */ static int WriteData( Tcl_Interp *interp, PNGImage *pngPtr, const unsigned char *srcPtr, size_t srcSz, unsigned long *crcPtr) { if (!srcPtr || !srcSz) { return TCL_OK; } if (crcPtr) { *crcPtr = Tcl_ZlibCRC32(*crcPtr, srcPtr, srcSz); } /* * TODO: is Tcl_AppendObjToObj faster here? i.e., does Tcl join the * objects immediately or store them in a multi-object rep? */ if (pngPtr->objDataPtr) { TkSizeT objSz; unsigned char *destPtr; Tcl_GetByteArrayFromObj(pngPtr->objDataPtr, &objSz); if (objSz + srcSz > INT_MAX) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "image too large to store completely in byte array", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "TOO_LARGE", NULL); return TCL_ERROR; } destPtr = Tcl_SetByteArrayLength(pngPtr->objDataPtr, objSz + srcSz); if (!destPtr) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "memory allocation failed", -1)); Tcl_SetErrorCode(interp, "TK", "MALLOC", NULL); return TCL_ERROR; } memcpy(destPtr+objSz, srcPtr, srcSz); } else if (Tcl_Write(pngPtr->channel, (const char *) srcPtr, srcSz) == TCL_IO_FAILURE) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "write to channel failed: %s", Tcl_PosixError(interp))); return TCL_ERROR; } return TCL_OK; } static inline int WriteByte( Tcl_Interp *interp, PNGImage *pngPtr, unsigned char c, unsigned long *crcPtr) { return WriteData(interp, pngPtr, &c, 1, crcPtr); } /* *---------------------------------------------------------------------- * * WriteInt32 -- * * This function writes a 32-bit integer value out to the PNG image as * four bytes in network byte order. * * Results: * TCL_OK, or TCL_ERROR if the write fails. * * Side effects: * File or buffer will be modified. * *---------------------------------------------------------------------- */ static inline int WriteInt32( Tcl_Interp *interp, PNGImage *pngPtr, unsigned long l, unsigned long *crcPtr) { unsigned char pc[4]; pc[0] = (unsigned char) ((l & 0xff000000) >> 24); pc[1] = (unsigned char) ((l & 0x00ff0000) >> 16); pc[2] = (unsigned char) ((l & 0x0000ff00) >> 8); pc[3] = (unsigned char) ((l & 0x000000ff) >> 0); return WriteData(interp, pngPtr, pc, 4, crcPtr); } /* *---------------------------------------------------------------------- * * WriteChunk -- * * Writes a complete chunk to the PNG image, including chunk type, * length, contents, and CRC. * * Results: * TCL_OK, or TCL_ERROR if the write fails. * * Side effects: * None * *---------------------------------------------------------------------- */ static inline int WriteChunk( Tcl_Interp *interp, PNGImage *pngPtr, unsigned long chunkType, const unsigned char *dataPtr, size_t dataSize) { unsigned long crc = Tcl_ZlibCRC32(0, NULL, 0); int result = TCL_OK; /* * Write the length field for the chunk. */ result = WriteInt32(interp, pngPtr, dataSize, NULL); /* * Write the Chunk Type. */ if (TCL_OK == result) { result = WriteInt32(interp, pngPtr, chunkType, &crc); } /* * Write the contents (if any). */ if (TCL_OK == result) { result = WriteData(interp, pngPtr, dataPtr, dataSize, &crc); } /* * Write out the CRC at the end of the chunk. */ if (TCL_OK == result) { result = WriteInt32(interp, pngPtr, crc, NULL); } return result; } /* *---------------------------------------------------------------------- * * WriteIHDR -- * * This function writes the PNG header at the beginning of a PNG file, * which includes information such as dimensions and color type. * * Results: * TCL_OK, or TCL_ERROR if the write fails. * * Side effects: * File or buffer will be modified. * *---------------------------------------------------------------------- */ static int WriteIHDR( Tcl_Interp *interp, PNGImage *pngPtr, Tk_PhotoImageBlock *blockPtr) { unsigned long crc = Tcl_ZlibCRC32(0, NULL, 0); int result = TCL_OK; /* * The IHDR (header) chunk has a fixed size of 13 bytes. */ result = WriteInt32(interp, pngPtr, 13, NULL); /* * Write the IHDR Chunk Type. */ if (TCL_OK == result) { result = WriteInt32(interp, pngPtr, CHUNK_IHDR, &crc); } /* * Write the image width, height. */ if (TCL_OK == result) { result = WriteInt32(interp, pngPtr, (unsigned long) blockPtr->width, &crc); } if (TCL_OK == result) { result = WriteInt32(interp, pngPtr, (unsigned long) blockPtr->height, &crc); } /* * Write bit depth. Although the PNG format supports 16 bits per channel, * Tk supports only 8 in the internal representation, which blockPtr * points to. */ if (TCL_OK == result) { result = WriteByte(interp, pngPtr, 8, &crc); } /* * Write out the color type, previously determined. */ if (TCL_OK == result) { result = WriteByte(interp, pngPtr, pngPtr->colorType, &crc); } /* * Write compression method (only one method is defined). */ if (TCL_OK == result) { result = WriteByte(interp, pngPtr, PNG_COMPRESS_DEFLATE, &crc); } /* * Write filter method (only one method is defined). */ if (TCL_OK == result) { result = WriteByte(interp, pngPtr, PNG_FILTMETH_STANDARD, &crc); } /* * Write interlace method as not interlaced. * * TODO: support interlace through -format? */ if (TCL_OK == result) { result = WriteByte(interp, pngPtr, PNG_INTERLACE_NONE, &crc); } /* * Write out the CRC at the end of the chunk. */ if (TCL_OK == result) { result = WriteInt32(interp, pngPtr, crc, NULL); } return result; } /* *---------------------------------------------------------------------- * * WriteIDAT -- * * Writes the IDAT (data) chunk to the PNG image, containing the pixel * channel data. Currently, image lines are not filtered and writing * interlaced pixels is not supported. * * Results: * TCL_OK, or TCL_ERROR if the write fails. * * Side effects: * None * *---------------------------------------------------------------------- */ static int WriteIDAT( Tcl_Interp *interp, PNGImage *pngPtr, Tk_PhotoImageBlock *blockPtr) { int rowNum, flush = TCL_ZLIB_NO_FLUSH, result; Tcl_Obj *outputObj; unsigned char *outputBytes; TkSizeT outputSize; /* * Filter and compress each row one at a time. */ for (rowNum=0 ; rowNum < blockPtr->height ; rowNum++) { int colNum; unsigned char *srcPtr, *destPtr; srcPtr = blockPtr->pixelPtr + (rowNum * blockPtr->pitch); destPtr = Tcl_SetByteArrayLength(pngPtr->thisLineObj, pngPtr->lineSize); /* * TODO: use Paeth filtering. */ *destPtr++ = PNG_FILTER_NONE; /* * Copy each pixel into the destination buffer after the filter type * before filtering. */ for (colNum = 0 ; colNum < blockPtr->width ; colNum++) { /* * Copy red or gray channel. */ *destPtr++ = srcPtr[blockPtr->offset[0]]; /* * If not grayscale, copy the green and blue channels. */ if (pngPtr->colorType & PNG_COLOR_USED) { *destPtr++ = srcPtr[blockPtr->offset[1]]; *destPtr++ = srcPtr[blockPtr->offset[2]]; } /* * Copy the alpha channel, if used. */ if (pngPtr->colorType & PNG_COLOR_ALPHA) { *destPtr++ = srcPtr[blockPtr->offset[3]]; } /* * Point to the start of the next pixel. */ srcPtr += blockPtr->pixelSize; } /* * Compress the line of pixels into the destination. If this is the * last line, finalize the compressor at the same time. Note that this * can't be just a flush; that leads to a file that some PNG readers * choke on. [Bug 2984787] */ if (rowNum + 1 == blockPtr->height) { flush = TCL_ZLIB_FINALIZE; } if (Tcl_ZlibStreamPut(pngPtr->stream, pngPtr->thisLineObj, flush) != TCL_OK) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "deflate() returned error", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "DEFLATE", NULL); return TCL_ERROR; } /* * Swap line buffers to keep the last around for filtering next. */ { Tcl_Obj *temp = pngPtr->lastLineObj; pngPtr->lastLineObj = pngPtr->thisLineObj; pngPtr->thisLineObj = temp; } } /* * Now get the compressed data and write it as one big IDAT chunk. */ outputObj = Tcl_NewObj(); (void) Tcl_ZlibStreamGet(pngPtr->stream, outputObj, -1); outputBytes = Tcl_GetByteArrayFromObj(outputObj, &outputSize); result = WriteChunk(interp, pngPtr, CHUNK_IDAT, outputBytes, outputSize); Tcl_DecrRefCount(outputObj); return result; } /* *---------------------------------------------------------------------- * * WriteExtraChunks -- * * Writes an sBIT and a tEXt chunks to the PNG image, describing a bunch * of not very important metadata that many readers seem to need anyway. * * Results: * TCL_OK, or TCL_ERROR if the write fails. * * Side effects: * None * *---------------------------------------------------------------------- */ static int WriteExtraChunks( Tcl_Interp *interp, PNGImage *pngPtr) { static const unsigned char sBIT_contents[] = { 8, 8, 8, 8 }; int sBIT_length = 4; Tcl_DString buf; /* * Each byte of each channel is always significant; we always write RGBA * images with 8 bits per channel as that is what the photo image's basic * data model is. */ switch (pngPtr->colorType) { case PNG_COLOR_GRAY: sBIT_length = 1; break; case PNG_COLOR_GRAYALPHA: sBIT_length = 2; break; case PNG_COLOR_RGB: case PNG_COLOR_PLTE: sBIT_length = 3; break; case PNG_COLOR_RGBA: sBIT_length = 4; break; } if (WriteChunk(interp, pngPtr, CHUNK_sBIT, sBIT_contents, sBIT_length) != TCL_OK) { return TCL_ERROR; } /* * Say that it is Tk that made the PNG. Note that we *need* the NUL at the * end of "Software" to be transferred; do *not* change the length * parameter to -1 there! */ Tcl_DStringInit(&buf); Tcl_DStringAppend(&buf, "Software", 9); Tcl_DStringAppend(&buf, "Tk Toolkit v", -1); Tcl_DStringAppend(&buf, TK_PATCH_LEVEL, -1); if (WriteChunk(interp, pngPtr, CHUNK_tEXt, (unsigned char *) Tcl_DStringValue(&buf), Tcl_DStringLength(&buf)) != TCL_OK) { Tcl_DStringFree(&buf); return TCL_ERROR; } Tcl_DStringFree(&buf); return TCL_OK; } /* *---------------------------------------------------------------------- * * EncodePNG -- * * This function handles the entirety of writing a PNG file (or data) * from the first byte to the last. No effort is made to optimize the * image data for best compression. * * Results: * TCL_OK, or TCL_ERROR if an I/O or memory error occurs. * * Side effects: * None * *---------------------------------------------------------------------- */ static int EncodePNG( Tcl_Interp *interp, Tk_PhotoImageBlock *blockPtr, PNGImage *pngPtr) { int greenOffset, blueOffset, alphaOffset; /* * Determine appropriate color type based on color usage (e.g., only red * and maybe alpha channel = grayscale). * * TODO: Check whether this is doing any good; Tk might just be pushing * full RGBA data all the time through here, even though the actual image * doesn't need it... */ greenOffset = blockPtr->offset[1] - blockPtr->offset[0]; blueOffset = blockPtr->offset[2] - blockPtr->offset[0]; alphaOffset = blockPtr->offset[3]; if ((alphaOffset >= blockPtr->pixelSize) || (alphaOffset < 0)) { alphaOffset = 0; } else { alphaOffset -= blockPtr->offset[0]; } if ((greenOffset != 0) || (blueOffset != 0)) { if (alphaOffset) { pngPtr->colorType = PNG_COLOR_RGBA; pngPtr->bytesPerPixel = 4; } else { pngPtr->colorType = PNG_COLOR_RGB; pngPtr->bytesPerPixel = 3; } } else { if (alphaOffset) { pngPtr->colorType = PNG_COLOR_GRAYALPHA; pngPtr->bytesPerPixel = 2; } else { pngPtr->colorType = PNG_COLOR_GRAY; pngPtr->bytesPerPixel = 1; } } /* * Allocate buffers for lines for filtering and compressed data. */ pngPtr->lineSize = 1 + (pngPtr->bytesPerPixel * blockPtr->width); pngPtr->blockLen = pngPtr->lineSize * blockPtr->height; if ((blockPtr->width > (INT_MAX - 1) / (pngPtr->bytesPerPixel)) || (blockPtr->height > INT_MAX / pngPtr->lineSize)) { Tcl_SetObjResult(interp, Tcl_NewStringObj( "image is too large to encode pixel data", -1)); Tcl_SetErrorCode(interp, "TK", "IMAGE", "PNG", "TOO_LARGE", NULL); return TCL_ERROR; } pngPtr->lastLineObj = Tcl_NewObj(); Tcl_IncrRefCount(pngPtr->lastLineObj); pngPtr->thisLineObj = Tcl_NewObj(); Tcl_IncrRefCount(pngPtr->thisLineObj); /* * Write out the PNG Signature that all PNGs begin with. */ if (WriteData(interp, pngPtr, pngSignature, PNG_SIG_SZ, NULL) == TCL_ERROR) { return TCL_ERROR; } /* * Write out the IHDR (header) chunk containing image dimensions, color * type, etc. */ if (WriteIHDR(interp, pngPtr, blockPtr) == TCL_ERROR) { return TCL_ERROR; } /* * Write out the extra chunks containing metadata that is of interest to * other programs more than us. */ if (WriteExtraChunks(interp, pngPtr) == TCL_ERROR) { return TCL_ERROR; } /* * Write out the image pixels in the IDAT (data) chunk. */ if (WriteIDAT(interp, pngPtr, blockPtr) == TCL_ERROR) { return TCL_ERROR; } /* * Write out the IEND chunk that all PNGs end with. */ return WriteChunk(interp, pngPtr, CHUNK_IEND, NULL, 0); } /* *---------------------------------------------------------------------- * * FileWritePNG -- * * This function is called by the photo image type to write PNG format * data to a file. * * Results: * A standard TCL completion code. If TCL_ERROR is returned then an error * message is left in the interp's result. * * Side effects: * The specified file is overwritten. * *---------------------------------------------------------------------- */ static int FileWritePNG( Tcl_Interp *interp, const char *filename, Tcl_Obj *fmtObj, Tk_PhotoImageBlock *blockPtr) { Tcl_Channel chan; PNGImage png; int result = TCL_ERROR; (void)fmtObj; /* * Open a Tcl file channel where the image data will be stored. Tk ought * to take care of this, and just provide a channel, but it doesn't. */ chan = Tcl_OpenFileChannel(interp, filename, "w", 0644); if (!chan) { return TCL_ERROR; } /* * Initalize PNGImage instance for encoding. */ if (InitPNGImage(interp, &png, chan, NULL, TCL_ZLIB_STREAM_DEFLATE) == TCL_ERROR) { goto cleanup; } /* * Set the translation mode to binary so that CR and LF are not to the * platform's EOL sequence. */ if (Tcl_SetChannelOption(interp, chan, "-translation", "binary") != TCL_OK) { goto cleanup; } /* * Write the raw PNG data out to the file. */ result = EncodePNG(interp, blockPtr, &png); cleanup: Tcl_Close(interp, chan); CleanupPNGImage(&png); return result; } /* *---------------------------------------------------------------------- * * StringWritePNG -- * * This function is called by the photo image type to write PNG format * data to a Tcl object and return it in the result. * * Results: * A standard TCL completion code. If TCL_ERROR is returned then an error * message is left in the interp's result. * * Side effects: * None * *---------------------------------------------------------------------- */ static int StringWritePNG( Tcl_Interp *interp, Tcl_Obj *fmtObj, Tk_PhotoImageBlock *blockPtr) { Tcl_Obj *resultObj = Tcl_NewObj(); PNGImage png; int result = TCL_ERROR; (void)fmtObj; /* * Initalize PNGImage instance for encoding. */ if (InitPNGImage(interp, &png, NULL, resultObj, TCL_ZLIB_STREAM_DEFLATE) == TCL_ERROR) { goto cleanup; } /* * Write the raw PNG data into the prepared Tcl_Obj buffer. Set the result * back to the interpreter if successful. */ result = EncodePNG(interp, blockPtr, &png); if (TCL_OK == result) { Tcl_SetObjResult(interp, png.objDataPtr); } cleanup: CleanupPNGImage(&png); return result; } /* * Local Variables: * c-basic-offset: 4 * fill-column: 78 * End: */
25.737004
92
0.609065
[ "object", "model" ]