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
f54cc7c7354f9eb08707f687dc8b92551158911c
51,027
c
C
net/ipsec/pastore/regstore.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/ipsec/pastore/regstore.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/ipsec/pastore/regstore.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "precomp.h" LPWSTR gpszIpsecRegContainer = L"SOFTWARE\\Policies\\Microsoft\\Windows\\IPSec\\Policy\\Local"; DWORD OpenRegistryIPSECRootKey( LPWSTR pszServerName, LPWSTR pszIpsecRegRootContainer, HKEY * phRegistryKey ) { DWORD dwError = 0; dwError = RegOpenKeyExW( HKEY_LOCAL_MACHINE, (LPCWSTR) pszIpsecRegRootContainer, 0, KEY_ALL_ACCESS, phRegistryKey ); BAIL_ON_WIN32_ERROR(dwError); error: return(dwError); } DWORD ReadPolicyObjectFromRegistry( HKEY hRegistryKey, LPWSTR pszPolicyDN, LPWSTR pszIpsecRegRootContainer, PIPSEC_POLICY_OBJECT * ppIpsecPolicyObject ) { DWORD dwError = 0; PIPSEC_POLICY_OBJECT pIpsecPolicyObject = NULL; DWORD dwNumNFAObjectsReturned = 0; PIPSEC_NFA_OBJECT * ppIpsecNFAObjects = NULL; LPWSTR * ppszFilterReferences = NULL; DWORD dwNumFilterReferences = 0; LPWSTR * ppszNegPolReferences = NULL; DWORD dwNumNegPolReferences = 0; PIPSEC_FILTER_OBJECT * ppIpsecFilterObjects = NULL; DWORD dwNumFilterObjects = 0; PIPSEC_NEGPOL_OBJECT * ppIpsecNegPolObjects = NULL; DWORD dwNumNegPolObjects = 0; PIPSEC_ISAKMP_OBJECT * ppIpsecISAKMPObjects = NULL; DWORD dwNumISAKMPObjects = 0; dwError = UnMarshallRegistryPolicyObject( hRegistryKey, pszIpsecRegRootContainer, pszPolicyDN, REG_FULLY_QUALIFIED_NAME, &pIpsecPolicyObject ); BAIL_ON_WIN32_ERROR(dwError); dwError = ReadNFAObjectsFromRegistry( hRegistryKey, pszIpsecRegRootContainer, pIpsecPolicyObject->pszIpsecOwnersReference, pIpsecPolicyObject->ppszIpsecNFAReferences, pIpsecPolicyObject->NumberofRules, &ppIpsecNFAObjects, &dwNumNFAObjectsReturned, &ppszFilterReferences, &dwNumFilterReferences, &ppszNegPolReferences, &dwNumNegPolReferences ); BAIL_ON_WIN32_ERROR(dwError); dwError = ReadFilterObjectsFromRegistry( hRegistryKey, pszIpsecRegRootContainer, ppszFilterReferences, dwNumFilterReferences, &ppIpsecFilterObjects, &dwNumFilterObjects ); BAIL_ON_WIN32_ERROR(dwError); dwError = ReadNegPolObjectsFromRegistry( hRegistryKey, pszIpsecRegRootContainer, ppszNegPolReferences, dwNumNegPolReferences, &ppIpsecNegPolObjects, &dwNumNegPolObjects ); BAIL_ON_WIN32_ERROR(dwError); dwError = ReadISAKMPObjectsFromRegistry( hRegistryKey, pszIpsecRegRootContainer, &pIpsecPolicyObject->pszIpsecISAKMPReference, 1, &ppIpsecISAKMPObjects, &dwNumISAKMPObjects ); BAIL_ON_WIN32_ERROR(dwError); pIpsecPolicyObject->ppIpsecNFAObjects = ppIpsecNFAObjects; pIpsecPolicyObject->NumberofRulesReturned = dwNumNFAObjectsReturned; pIpsecPolicyObject->NumberofFilters = dwNumFilterObjects; pIpsecPolicyObject->ppIpsecFilterObjects = ppIpsecFilterObjects; pIpsecPolicyObject->ppIpsecNegPolObjects = ppIpsecNegPolObjects; pIpsecPolicyObject->NumberofNegPols = dwNumNegPolObjects; pIpsecPolicyObject->NumberofISAKMPs = dwNumISAKMPObjects; pIpsecPolicyObject->ppIpsecISAKMPObjects = ppIpsecISAKMPObjects; *ppIpsecPolicyObject = pIpsecPolicyObject; cleanup: if (ppszFilterReferences) { FreeFilterReferences( ppszFilterReferences, dwNumFilterReferences ); } if (ppszNegPolReferences) { FreeNegPolReferences( ppszNegPolReferences, dwNumNegPolReferences ); } return(dwError); error: if (pIpsecPolicyObject) { FreeIpsecPolicyObject( pIpsecPolicyObject ); } *ppIpsecPolicyObject = NULL; goto cleanup; } DWORD ReadNFAObjectsFromRegistry( HKEY hRegistryKey, LPWSTR pszIpsecRootContainer, LPWSTR pszIpsecOwnerReference, LPWSTR * ppszNFADNs, DWORD dwNumNfaObjects, PIPSEC_NFA_OBJECT ** pppIpsecNFAObjects, PDWORD pdwNumNfaObjects, LPWSTR ** pppszFilterReferences, PDWORD pdwNumFilterReferences, LPWSTR ** pppszNegPolReferences, PDWORD pdwNumNegPolReferences ) { DWORD dwError = 0; DWORD i = 0; PIPSEC_NFA_OBJECT pIpsecNFAObject = NULL; PIPSEC_NFA_OBJECT * ppIpsecNFAObjects = NULL; LPWSTR * ppszFilterReferences = NULL; LPWSTR * ppszNegPolReferences = NULL; LPWSTR pszFilterReference = NULL; LPWSTR pszNegPolReference = NULL; DWORD dwNumFilterReferences = 0; DWORD dwNumNegPolReferences = 0; BOOL bNewNegPolReference = TRUE; DWORD dwNumNFAObjectsReturned = 0; *pppszNegPolReferences = NULL; *pdwNumFilterReferences = 0; *pppszFilterReferences = NULL; *pdwNumNegPolReferences = 0; *pppIpsecNFAObjects = NULL; *pdwNumNfaObjects = 0; ppIpsecNFAObjects = (PIPSEC_NFA_OBJECT *)AllocPolMem( sizeof(PIPSEC_NFA_OBJECT)*dwNumNfaObjects ); if (!ppIpsecNFAObjects) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } ppszFilterReferences = (LPWSTR *)AllocPolMem( sizeof(LPWSTR)*dwNumNfaObjects ); if (!ppszFilterReferences) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } ppszNegPolReferences = (LPWSTR *)AllocPolMem( sizeof(LPWSTR)*dwNumNfaObjects ); if (!ppszNegPolReferences) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } for (i = 0; i < dwNumNfaObjects; i++) { dwError =UnMarshallRegistryNFAObject( hRegistryKey, pszIpsecRootContainer, *(ppszNFADNs + i), &pIpsecNFAObject, &pszFilterReference, &pszNegPolReference ); if (dwError == ERROR_SUCCESS) { *(ppIpsecNFAObjects + dwNumNFAObjectsReturned) = pIpsecNFAObject; if (pszFilterReference) { *(ppszFilterReferences + dwNumFilterReferences) = pszFilterReference; dwNumFilterReferences++; } if (pszNegPolReference) { bNewNegPolReference = !(IsStringInArray( ppszNegPolReferences, pszNegPolReference, dwNumNegPolReferences )); if (bNewNegPolReference) { *(ppszNegPolReferences + dwNumNegPolReferences) = pszNegPolReference; dwNumNegPolReferences++; } else { FreePolStr(pszNegPolReference); pszNegPolReference = NULL; } } dwNumNFAObjectsReturned++; } } if (dwNumNFAObjectsReturned == 0) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } *pppszFilterReferences = ppszFilterReferences; *pppszNegPolReferences = ppszNegPolReferences; *pppIpsecNFAObjects = ppIpsecNFAObjects; *pdwNumNfaObjects = dwNumNFAObjectsReturned; *pdwNumNegPolReferences = dwNumNegPolReferences; *pdwNumFilterReferences = dwNumFilterReferences; dwError = ERROR_SUCCESS; cleanup: return(dwError); error: if (ppszNegPolReferences) { FreeNegPolReferences( ppszNegPolReferences, dwNumNFAObjectsReturned ); } if (ppszFilterReferences) { FreeFilterReferences( ppszFilterReferences, dwNumNFAObjectsReturned ); } if (ppIpsecNFAObjects) { FreeIpsecNFAObjects( ppIpsecNFAObjects, dwNumNFAObjectsReturned ); } *pppszNegPolReferences = NULL; *pppszFilterReferences = NULL; *pppIpsecNFAObjects = NULL; *pdwNumNfaObjects = 0; *pdwNumNegPolReferences = 0; *pdwNumFilterReferences = 0; goto cleanup; } DWORD ReadFilterObjectsFromRegistry( HKEY hRegistryKey, LPWSTR pszIpsecRootContainer, LPWSTR * ppszFilterDNs, DWORD dwNumFilterObjects, PIPSEC_FILTER_OBJECT ** pppIpsecFilterObjects, PDWORD pdwNumFilterObjects ) { DWORD dwError = 0; DWORD i = 0; DWORD dwCount = 0; PIPSEC_FILTER_OBJECT pIpsecFilterObject = NULL; PIPSEC_FILTER_OBJECT * ppIpsecFilterObjects = NULL; DWORD dwNumFilterObjectsReturned = 0; *pppIpsecFilterObjects = NULL; *pdwNumFilterObjects = 0; ppIpsecFilterObjects = (PIPSEC_FILTER_OBJECT *)AllocPolMem( sizeof(PIPSEC_FILTER_OBJECT)*dwNumFilterObjects ); if (!ppIpsecFilterObjects) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } for (i = 0; i < dwNumFilterObjects; i++) { dwError =UnMarshallRegistryFilterObject( hRegistryKey, pszIpsecRootContainer, *(ppszFilterDNs + i), REG_FULLY_QUALIFIED_NAME, &pIpsecFilterObject ); if (dwError == ERROR_SUCCESS) { *(ppIpsecFilterObjects + dwNumFilterObjectsReturned) = pIpsecFilterObject; dwNumFilterObjectsReturned++; } } *pppIpsecFilterObjects = ppIpsecFilterObjects; *pdwNumFilterObjects = dwNumFilterObjectsReturned; dwError = ERROR_SUCCESS; return(dwError); error: if (ppIpsecFilterObjects) { FreeIpsecFilterObjects( ppIpsecFilterObjects, dwNumFilterObjectsReturned ); } *pppIpsecFilterObjects = NULL; *pdwNumFilterObjects = 0; return(dwError); } DWORD ReadNegPolObjectsFromRegistry( HKEY hRegistryKey, LPWSTR pszIpsecRootContainer, LPWSTR * ppszNegPolDNs, DWORD dwNumNegPolObjects, PIPSEC_NEGPOL_OBJECT ** pppIpsecNegPolObjects, PDWORD pdwNumNegPolObjects ) { DWORD dwError = 0; DWORD i = 0; DWORD dwCount = 0; PIPSEC_NEGPOL_OBJECT pIpsecNegPolObject = NULL; PIPSEC_NEGPOL_OBJECT * ppIpsecNegPolObjects = NULL; DWORD dwNumNegPolObjectsReturned = 0; *pppIpsecNegPolObjects = NULL; *pdwNumNegPolObjects = 0; ppIpsecNegPolObjects = (PIPSEC_NEGPOL_OBJECT *)AllocPolMem( sizeof(PIPSEC_NEGPOL_OBJECT)*dwNumNegPolObjects ); if (!ppIpsecNegPolObjects) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } for (i = 0; i < dwNumNegPolObjects; i++) { dwError =UnMarshallRegistryNegPolObject( hRegistryKey, pszIpsecRootContainer, *(ppszNegPolDNs + i), REG_FULLY_QUALIFIED_NAME, &pIpsecNegPolObject ); if (dwError == ERROR_SUCCESS) { *(ppIpsecNegPolObjects + dwNumNegPolObjectsReturned) = pIpsecNegPolObject; dwNumNegPolObjectsReturned++; } } if (dwNumNegPolObjectsReturned == 0) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } *pppIpsecNegPolObjects = ppIpsecNegPolObjects; *pdwNumNegPolObjects = dwNumNegPolObjectsReturned; dwError = ERROR_SUCCESS; return(dwError); error: if (ppIpsecNegPolObjects) { FreeIpsecNegPolObjects( ppIpsecNegPolObjects, dwNumNegPolObjectsReturned ); } *pppIpsecNegPolObjects = NULL; *pdwNumNegPolObjects = 0; return(dwError); } DWORD ReadISAKMPObjectsFromRegistry( HKEY hRegistryKey, LPWSTR pszIpsecRootContainer, LPWSTR * ppszISAKMPDNs, DWORD dwNumISAKMPObjects, PIPSEC_ISAKMP_OBJECT ** pppIpsecISAKMPObjects, PDWORD pdwNumISAKMPObjects ) { DWORD dwError = 0; DWORD i = 0; DWORD dwCount = 0; PIPSEC_ISAKMP_OBJECT pIpsecISAKMPObject = NULL; PIPSEC_ISAKMP_OBJECT * ppIpsecISAKMPObjects = NULL; DWORD dwNumISAKMPObjectsReturned = 0; *pppIpsecISAKMPObjects = NULL; *pdwNumISAKMPObjects = 0; ppIpsecISAKMPObjects = (PIPSEC_ISAKMP_OBJECT *)AllocPolMem( sizeof(PIPSEC_ISAKMP_OBJECT)*dwNumISAKMPObjects ); if (!ppIpsecISAKMPObjects) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } for (i = 0; i < dwNumISAKMPObjects; i++) { dwError =UnMarshallRegistryISAKMPObject( hRegistryKey, pszIpsecRootContainer, *(ppszISAKMPDNs + i), REG_FULLY_QUALIFIED_NAME, &pIpsecISAKMPObject ); if (dwError == ERROR_SUCCESS) { *(ppIpsecISAKMPObjects + dwNumISAKMPObjectsReturned) = pIpsecISAKMPObject; dwNumISAKMPObjectsReturned++; } } if (dwNumISAKMPObjectsReturned == 0) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } *pppIpsecISAKMPObjects = ppIpsecISAKMPObjects; *pdwNumISAKMPObjects = dwNumISAKMPObjectsReturned; dwError = ERROR_SUCCESS; return(dwError); error: if (ppIpsecISAKMPObjects) { FreeIpsecISAKMPObjects( ppIpsecISAKMPObjects, dwNumISAKMPObjectsReturned ); } *pppIpsecISAKMPObjects = NULL; *pdwNumISAKMPObjects = 0; return(dwError); } DWORD UnMarshallRegistryPolicyObject( HKEY hRegistryKey, LPWSTR pszIpsecRegRootContainer, LPWSTR pszIpsecPolicyDN, DWORD dwNameType, PIPSEC_POLICY_OBJECT * ppIpsecPolicyObject ) { PIPSEC_POLICY_OBJECT pIpsecPolicyObject = NULL; HKEY hRegKey = NULL; DWORD dwType = 0; DWORD dwSize = 0; DWORD dwIpsecDataType = 0; DWORD dwWhenChanged = 0; LPBYTE pBuffer = NULL; DWORD i = 0; DWORD dwCount = 0; DWORD dwError = 0; LPWSTR * ppszIpsecNFANames = NULL; LPWSTR pszIpsecNFAName = NULL; LPWSTR pszTemp = NULL; LPWSTR pszString = NULL; LPWSTR pszIpsecNFAReference = NULL; LPWSTR pszRelativeName = NULL; DWORD dwRootPathLen = 0; if (!pszIpsecPolicyDN || !*pszIpsecPolicyDN) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } if (dwNameType == REG_FULLY_QUALIFIED_NAME) { dwRootPathLen = wcslen(pszIpsecRegRootContainer); if (wcslen(pszIpsecPolicyDN) <= (dwRootPathLen+1)) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } pszRelativeName = pszIpsecPolicyDN + dwRootPathLen + 1; }else { pszRelativeName = pszIpsecPolicyDN; } dwError = RegOpenKeyExW( hRegistryKey, pszRelativeName, 0, KEY_ALL_ACCESS, &hRegKey ); BAIL_ON_WIN32_ERROR(dwError); pIpsecPolicyObject = (PIPSEC_POLICY_OBJECT)AllocPolMem( sizeof(IPSEC_POLICY_OBJECT) ); if (!pIpsecPolicyObject) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } /* dwError = RegstoreQueryValue( hRegKey, L"distinguishedName", REG_SZ, (LPBYTE *)&pIpsecPolicyObject->pszIpsecOwnersReference, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); */ pIpsecPolicyObject->pszIpsecOwnersReference = AllocPolStr( pszIpsecPolicyDN ); if (!pIpsecPolicyObject->pszIpsecOwnersReference) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } dwError = RegstoreQueryValue( hRegKey, L"ipsecName", REG_SZ, (LPBYTE *)&pIpsecPolicyObject->pszIpsecName, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"description", REG_SZ, (LPBYTE *)&pIpsecPolicyObject->pszDescription, &dwSize ); // BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecID", REG_SZ, (LPBYTE *)&pIpsecPolicyObject->pszIpsecID, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); dwType = REG_DWORD; dwSize = sizeof(DWORD); dwError = RegQueryValueExW( hRegKey, L"ipsecDataType", NULL, &dwType, (LPBYTE)&dwIpsecDataType, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); pIpsecPolicyObject->dwIpsecDataType = dwIpsecDataType; dwError = RegstoreQueryValue( hRegKey, L"ipsecData", REG_BINARY, &pIpsecPolicyObject->pIpsecData, &pIpsecPolicyObject->dwIpsecDataLen ); BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecISAKMPReference", REG_SZ, (LPBYTE *)&pIpsecPolicyObject->pszIpsecISAKMPReference, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecNFAReference", REG_MULTI_SZ, (LPBYTE *)&pszIpsecNFAReference, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); pszTemp = pszIpsecNFAReference; while (*pszTemp != L'\0') { pszTemp += wcslen(pszTemp) + 1; dwCount++; } ppszIpsecNFANames = (LPWSTR *)AllocPolMem( sizeof(LPWSTR)*dwCount ); if (!ppszIpsecNFANames) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } pszTemp = pszIpsecNFAReference; for (i = 0; i < dwCount; i++) { pszString = AllocPolStr(pszTemp); if (!pszString) { dwError = ERROR_OUTOFMEMORY; pIpsecPolicyObject->ppszIpsecNFAReferences = ppszIpsecNFANames; pIpsecPolicyObject->NumberofRules = i; BAIL_ON_WIN32_ERROR(dwError); } *(ppszIpsecNFANames + i) = pszString; pszTemp += wcslen(pszTemp) + 1; //for the null terminator; } if (pszIpsecNFAReference) { FreePolStr(pszIpsecNFAReference); } pIpsecPolicyObject->ppszIpsecNFAReferences = ppszIpsecNFANames; pIpsecPolicyObject->NumberofRules = dwCount; dwType = REG_DWORD; dwSize = sizeof(DWORD); dwError = RegQueryValueExW( hRegKey, L"whenChanged", NULL, &dwType, (LPBYTE)&dwWhenChanged, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); pIpsecPolicyObject->dwWhenChanged = dwWhenChanged; *ppIpsecPolicyObject = pIpsecPolicyObject; if (hRegKey) { RegCloseKey(hRegKey); } return(dwError); error: *ppIpsecPolicyObject = NULL; if (pszIpsecNFAReference) { FreePolStr(pszIpsecNFAReference); } if (pIpsecPolicyObject) { FreeIpsecPolicyObject(pIpsecPolicyObject); } if (hRegKey) { RegCloseKey(hRegKey); } return(dwError); } DWORD UnMarshallRegistryNFAObject( HKEY hRegistryKey, LPWSTR pszIpsecRegRootContainer, LPWSTR pszIpsecNFAReference, PIPSEC_NFA_OBJECT * ppIpsecNFAObject, LPWSTR * ppszFilterReference, LPWSTR * ppszNegPolReference ) { PIPSEC_NFA_OBJECT pIpsecNFAObject = NULL; HKEY hRegKey = NULL; DWORD dwType = 0; DWORD dwSize = 0; DWORD dwIpsecDataType = 0; DWORD dwWhenChanged = 0; LPBYTE pBuffer = NULL; DWORD i = 0; DWORD dwCount = 0; DWORD dwError = 0; LPWSTR pszTempFilterReference = NULL; LPWSTR pszTempNegPolReference = NULL; LPWSTR pszRelativeName = NULL; DWORD dwRootPathLen = 0; dwRootPathLen = wcslen(pszIpsecRegRootContainer); if (!pszIpsecNFAReference || !*pszIpsecNFAReference) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } if (wcslen(pszIpsecNFAReference) <= (dwRootPathLen+1)) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } pszRelativeName = pszIpsecNFAReference + dwRootPathLen + 1; dwError = RegOpenKeyExW( hRegistryKey, pszRelativeName, 0, KEY_ALL_ACCESS, &hRegKey ); BAIL_ON_WIN32_ERROR(dwError); pIpsecNFAObject = (PIPSEC_NFA_OBJECT)AllocPolMem( sizeof(IPSEC_NFA_OBJECT) ); if (!pIpsecNFAObject) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } /* dwError = RegstoreQueryValue( hRegKey, L"distinguishedName", REG_SZ, (LPBYTE *)&pIpsecNFAObject->pszDistinguishedName, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); */ pIpsecNFAObject->pszDistinguishedName = AllocPolStr( pszIpsecNFAReference ); if (!pIpsecNFAObject->pszDistinguishedName) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } // // Client does not always write the Name for an NFA // dwError = RegstoreQueryValue( hRegKey, L"ipsecName", REG_SZ, (LPBYTE *)&pIpsecNFAObject->pszIpsecName, &dwSize ); // BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"description", REG_SZ, (LPBYTE *)&pIpsecNFAObject->pszDescription, &dwSize ); // BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecID", REG_SZ, (LPBYTE *)&pIpsecNFAObject->pszIpsecID, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); dwType = REG_DWORD; dwSize = sizeof(DWORD); dwError = RegQueryValueExW( hRegKey, L"ipsecDataType", NULL, &dwType, (LPBYTE)&dwIpsecDataType, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); pIpsecNFAObject->dwIpsecDataType = dwIpsecDataType; // // unmarshall the ipsecData blob // dwError = RegstoreQueryValue( hRegKey, L"ipsecData", REG_BINARY, &pIpsecNFAObject->pIpsecData, &pIpsecNFAObject->dwIpsecDataLen ); BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecOwnersReference", REG_SZ, (LPBYTE *)&pIpsecNFAObject->pszIpsecOwnersReference, &dwSize ); // BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecNegotiationPolicyReference", REG_SZ, (LPBYTE *)&pIpsecNFAObject->pszIpsecNegPolReference, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecFilterReference", REG_SZ, (LPBYTE *)&pIpsecNFAObject->pszIpsecFilterReference, &dwSize ); // BAIL_ON_WIN32_ERROR(dwError); dwType = REG_DWORD; dwSize = sizeof(DWORD); dwError = RegQueryValueExW( hRegKey, L"whenChanged", NULL, &dwType, (LPBYTE)&dwWhenChanged, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); pIpsecNFAObject->dwWhenChanged = dwWhenChanged; if (pIpsecNFAObject->pszIpsecFilterReference && *(pIpsecNFAObject->pszIpsecFilterReference)) { pszTempFilterReference = AllocPolStr( pIpsecNFAObject->pszIpsecFilterReference ); if (!pszTempFilterReference) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } } pszTempNegPolReference = AllocPolStr( pIpsecNFAObject->pszIpsecNegPolReference ); if (!pszTempNegPolReference) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } *ppszFilterReference = pszTempFilterReference; *ppszNegPolReference = pszTempNegPolReference; *ppIpsecNFAObject = pIpsecNFAObject; cleanup: if (hRegKey) { RegCloseKey(hRegKey); } return(dwError); error: if (pIpsecNFAObject) { FreeIpsecNFAObject(pIpsecNFAObject); } if (pszTempFilterReference) { FreePolStr(pszTempFilterReference); } if (pszTempNegPolReference) { FreePolStr(pszTempNegPolReference); } *ppIpsecNFAObject = NULL; *ppszFilterReference = NULL; *ppszNegPolReference = NULL; goto cleanup; } DWORD UnMarshallRegistryFilterObject( HKEY hRegistryKey, LPWSTR pszIpsecRegRootContainer, LPWSTR pszIpsecFilterReference, DWORD dwNameType, PIPSEC_FILTER_OBJECT * ppIpsecFilterObject ) { PIPSEC_FILTER_OBJECT pIpsecFilterObject = NULL; HKEY hRegKey = NULL; DWORD dwType = 0; DWORD dwSize = 0; DWORD dwIpsecDataType = 0; DWORD dwWhenChanged = 0; LPBYTE pBuffer = NULL; DWORD dwCount = 0; DWORD i = 0; LPWSTR * ppszIpsecNFANames = NULL; LPWSTR pszString = NULL; LPWSTR pszIpsecNFAReference = NULL; LPWSTR pszTemp = NULL; DWORD dwError = 0; LPWSTR pszRelativeName = NULL; DWORD dwRootPathLen = 0; if (!pszIpsecFilterReference || !*pszIpsecFilterReference) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } if (dwNameType == REG_FULLY_QUALIFIED_NAME) { dwRootPathLen = wcslen(pszIpsecRegRootContainer); if (wcslen(pszIpsecFilterReference) <= (dwRootPathLen+1)) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } pszRelativeName = pszIpsecFilterReference + dwRootPathLen + 1; }else { pszRelativeName = pszIpsecFilterReference; } dwError = RegOpenKeyExW( hRegistryKey, pszRelativeName, 0, KEY_ALL_ACCESS, &hRegKey ); BAIL_ON_WIN32_ERROR(dwError); pIpsecFilterObject = (PIPSEC_FILTER_OBJECT)AllocPolMem( sizeof(IPSEC_FILTER_OBJECT) ); if (!pIpsecFilterObject) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } /* dwError = RegstoreQueryValue( hRegKey, L"distinguishedName", REG_SZ, (LPBYTE *)&pIpsecFilterObject->pszDistinguishedName, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); */ pIpsecFilterObject->pszDistinguishedName = AllocPolStr( pszIpsecFilterReference ); if (!pIpsecFilterObject->pszDistinguishedName) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } dwError = RegstoreQueryValue( hRegKey, L"description", REG_SZ, (LPBYTE *)&pIpsecFilterObject->pszDescription, &dwSize ); //BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecName", REG_SZ, (LPBYTE *)&pIpsecFilterObject->pszIpsecName, &dwSize ); //BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecID", REG_SZ, (LPBYTE *)&pIpsecFilterObject->pszIpsecID, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); dwType = REG_DWORD, dwSize = sizeof(DWORD); dwError = RegQueryValueExW( hRegKey, L"ipsecDataType", NULL, &dwType, (LPBYTE)&dwIpsecDataType, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); pIpsecFilterObject->dwIpsecDataType = dwIpsecDataType; // // unmarshall the ipsecData blob // dwError = RegstoreQueryValue( hRegKey, L"ipsecData", dwType, &pIpsecFilterObject->pIpsecData, &pIpsecFilterObject->dwIpsecDataLen ); BAIL_ON_WIN32_ERROR(dwError); // // Owner's reference // dwError = RegstoreQueryValue( hRegKey, L"ipsecOwnersReference", REG_MULTI_SZ, (LPBYTE *)&pszIpsecNFAReference, &dwSize ); //BAIL_ON_WIN32_ERROR(dwError); if (!dwError) { pszTemp = pszIpsecNFAReference; while (*pszTemp != L'\0') { pszTemp += wcslen(pszTemp) + 1; dwCount++; } ppszIpsecNFANames = (LPWSTR *)AllocPolMem( sizeof(LPWSTR)*dwCount ); if (!ppszIpsecNFANames) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } pszTemp = pszIpsecNFAReference; for (i = 0; i < dwCount; i++) { pszString = AllocPolStr(pszTemp); if (!pszString) { dwError = ERROR_OUTOFMEMORY; pIpsecFilterObject->ppszIpsecNFAReferences = ppszIpsecNFANames; pIpsecFilterObject->dwNFACount = i; if (pszIpsecNFAReference) { FreePolStr(pszIpsecNFAReference); } BAIL_ON_WIN32_ERROR(dwError); } *(ppszIpsecNFANames + i) = pszString; pszTemp += wcslen(pszTemp) + 1; //for the null terminator; } if (pszIpsecNFAReference) { FreePolStr(pszIpsecNFAReference); } pIpsecFilterObject->ppszIpsecNFAReferences = ppszIpsecNFANames; pIpsecFilterObject->dwNFACount = dwCount; } dwType = REG_DWORD; dwSize = sizeof(DWORD); dwError = RegQueryValueExW( hRegKey, L"whenChanged", NULL, &dwType, (LPBYTE)&dwWhenChanged, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); pIpsecFilterObject->dwWhenChanged = dwWhenChanged; *ppIpsecFilterObject = pIpsecFilterObject; cleanup: if (hRegKey) { RegCloseKey(hRegKey); } return(dwError); error: if (pIpsecFilterObject) { FreeIpsecFilterObject(pIpsecFilterObject); } *ppIpsecFilterObject = NULL; goto cleanup; } DWORD UnMarshallRegistryNegPolObject( HKEY hRegistryKey, LPWSTR pszIpsecRegRootContainer, LPWSTR pszIpsecNegPolReference, DWORD dwNameType, PIPSEC_NEGPOL_OBJECT * ppIpsecNegPolObject ) { PIPSEC_NEGPOL_OBJECT pIpsecNegPolObject = NULL; HKEY hRegKey = NULL; DWORD dwType = 0; DWORD dwSize = 0; DWORD dwIpsecDataType = 0; DWORD dwWhenChanged = 0; LPBYTE pBuffer = NULL; DWORD dwCount = 0; DWORD i = 0; LPWSTR * ppszIpsecNFANames = NULL; LPWSTR pszString = NULL; LPWSTR pszIpsecNFAReference = NULL; LPWSTR pszTemp = NULL; DWORD dwError = 0; LPWSTR pszRelativeName = NULL; DWORD dwRootPathLen = 0; if (!pszIpsecNegPolReference || !*pszIpsecNegPolReference) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } if (dwNameType == REG_FULLY_QUALIFIED_NAME) { dwRootPathLen = wcslen(pszIpsecRegRootContainer); if (wcslen(pszIpsecNegPolReference) <= (dwRootPathLen+1)) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } pszRelativeName = pszIpsecNegPolReference + dwRootPathLen + 1; }else { pszRelativeName = pszIpsecNegPolReference; } dwError = RegOpenKeyExW( hRegistryKey, pszRelativeName, 0, KEY_ALL_ACCESS, &hRegKey ); BAIL_ON_WIN32_ERROR(dwError); pIpsecNegPolObject = (PIPSEC_NEGPOL_OBJECT)AllocPolMem( sizeof(IPSEC_NEGPOL_OBJECT) ); if (!pIpsecNegPolObject) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } /* dwError = RegstoreQueryValue( hRegKey, L"distinguishedName", REG_SZ, (LPBYTE *)&pIpsecNegPolObject->pszDistinguishedName, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); */ pIpsecNegPolObject->pszDistinguishedName = AllocPolStr( pszIpsecNegPolReference ); if (!pIpsecNegPolObject->pszDistinguishedName) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } // // Names do not get written on an NegPol Object // dwError = RegstoreQueryValue( hRegKey, L"ipsecName", REG_SZ, (LPBYTE *)&pIpsecNegPolObject->pszIpsecName, &dwSize ); // BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"description", REG_SZ, (LPBYTE *)&pIpsecNegPolObject->pszDescription, &dwSize ); // BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecID", REG_SZ, (LPBYTE *)&pIpsecNegPolObject->pszIpsecID, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecNegotiationPolicyAction", REG_SZ, (LPBYTE *)&pIpsecNegPolObject->pszIpsecNegPolAction, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecNegotiationPolicyType", REG_SZ, (LPBYTE *)&pIpsecNegPolObject->pszIpsecNegPolType, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); dwType = REG_DWORD; dwSize = sizeof(DWORD); dwError = RegQueryValueExW( hRegKey, L"ipsecDataType", NULL, &dwType, (LPBYTE)&dwIpsecDataType, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); pIpsecNegPolObject->dwIpsecDataType = dwIpsecDataType; dwError = RegstoreQueryValue( hRegKey, L"ipsecData", REG_BINARY, &pIpsecNegPolObject->pIpsecData, &pIpsecNegPolObject->dwIpsecDataLen ); BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecOwnersReference", REG_MULTI_SZ, (LPBYTE *)&pszIpsecNFAReference, &dwSize ); // BAIL_ON_WIN32_ERROR(dwError); if (!dwError) { pszTemp = pszIpsecNFAReference; while (*pszTemp != L'\0') { pszTemp += wcslen(pszTemp) + 1; dwCount++; } ppszIpsecNFANames = (LPWSTR *)AllocPolMem( sizeof(LPWSTR)*dwCount ); if (!ppszIpsecNFANames) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } pszTemp = pszIpsecNFAReference; for (i = 0; i < dwCount; i++) { pszString = AllocPolStr(pszTemp); if (!pszString) { dwError = ERROR_OUTOFMEMORY; pIpsecNegPolObject->ppszIpsecNFAReferences = ppszIpsecNFANames; pIpsecNegPolObject->dwNFACount = i; if (pszIpsecNFAReference) { FreePolStr(pszIpsecNFAReference); } BAIL_ON_WIN32_ERROR(dwError); } *(ppszIpsecNFANames + i) = pszString; pszTemp += wcslen(pszTemp) + 1; //for the null terminator; } if (pszIpsecNFAReference) { FreePolStr(pszIpsecNFAReference); } pIpsecNegPolObject->ppszIpsecNFAReferences = ppszIpsecNFANames; pIpsecNegPolObject->dwNFACount = dwCount; } dwType = REG_DWORD; dwSize = sizeof(DWORD); dwError = RegQueryValueExW( hRegKey, L"whenChanged", NULL, &dwType, (LPBYTE)&dwWhenChanged, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); pIpsecNegPolObject->dwWhenChanged = dwWhenChanged; *ppIpsecNegPolObject = pIpsecNegPolObject; cleanup: if (hRegKey) { RegCloseKey(hRegKey); } return(dwError); error: if (pIpsecNegPolObject) { FreeIpsecNegPolObject(pIpsecNegPolObject); } *ppIpsecNegPolObject = NULL; goto cleanup; } DWORD UnMarshallRegistryISAKMPObject( HKEY hRegistryKey, LPWSTR pszIpsecRegRootContainer, LPWSTR pszIpsecISAKMPReference, DWORD dwNameType, PIPSEC_ISAKMP_OBJECT * ppIpsecISAKMPObject ) { PIPSEC_ISAKMP_OBJECT pIpsecISAKMPObject = NULL; HKEY hRegKey = NULL; DWORD dwType = 0; DWORD dwSize = 0; DWORD dwIpsecDataType = 0; DWORD dwWhenChanged = 0; LPBYTE pBuffer = NULL; DWORD dwCount = 0; DWORD i = 0; LPWSTR * ppszIpsecNFANames = NULL; LPWSTR pszString = NULL; LPWSTR pszIpsecNFAReference = NULL; LPWSTR pszTemp = NULL; DWORD dwError = 0; LPWSTR pszRelativeName = NULL; DWORD dwRootPathLen = 0; if (!pszIpsecISAKMPReference || !*pszIpsecISAKMPReference) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } if (dwNameType == REG_FULLY_QUALIFIED_NAME) { dwRootPathLen = wcslen(pszIpsecRegRootContainer); if (wcslen(pszIpsecISAKMPReference) <= (dwRootPathLen+1)) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } pszRelativeName = pszIpsecISAKMPReference + dwRootPathLen + 1; }else { pszRelativeName = pszIpsecISAKMPReference; } dwError = RegOpenKeyExW( hRegistryKey, pszRelativeName, 0, KEY_ALL_ACCESS, &hRegKey ); BAIL_ON_WIN32_ERROR(dwError); pIpsecISAKMPObject = (PIPSEC_ISAKMP_OBJECT)AllocPolMem( sizeof(IPSEC_ISAKMP_OBJECT) ); if (!pIpsecISAKMPObject) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } /* dwError = RegstoreQueryValue( hRegKey, L"distinguishedName", REG_SZ, (LPBYTE *)&pIpsecISAKMPObject->pszDistinguishedName, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); */ pIpsecISAKMPObject->pszDistinguishedName = AllocPolStr( pszIpsecISAKMPReference ); if (!pIpsecISAKMPObject->pszDistinguishedName) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } // // Names are not set for ISAKMP objects // dwError = RegstoreQueryValue( hRegKey, L"ipsecName", REG_SZ, (LPBYTE *)&pIpsecISAKMPObject->pszIpsecName, &dwSize ); // BAIL_ON_WIN32_ERROR(dwError); dwError = RegstoreQueryValue( hRegKey, L"ipsecID", REG_SZ, (LPBYTE *)&pIpsecISAKMPObject->pszIpsecID, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); dwType = REG_DWORD, dwSize = sizeof(DWORD); dwError = RegQueryValueExW( hRegKey, L"ipsecDataType", NULL, &dwType, (LPBYTE)&dwIpsecDataType, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); pIpsecISAKMPObject->dwIpsecDataType = dwIpsecDataType; // // unmarshall the ipsecData blob // dwError = RegstoreQueryValue( hRegKey, L"ipsecData", REG_BINARY, &pIpsecISAKMPObject->pIpsecData, &pIpsecISAKMPObject->dwIpsecDataLen ); BAIL_ON_WIN32_ERROR(dwError); // // ipsecOwnersReference not written // dwError = RegstoreQueryValue( hRegKey, L"ipsecOwnersReference", REG_MULTI_SZ, (LPBYTE *)&pszIpsecNFAReference, &dwSize ); // BAIL_ON_WIN32_ERROR(dwError); if (!dwError) { pszTemp = pszIpsecNFAReference; while (*pszTemp != L'\0') { pszTemp += wcslen(pszTemp) + 1; dwCount++; } ppszIpsecNFANames = (LPWSTR *)AllocPolMem( sizeof(LPWSTR)*dwCount ); if (!ppszIpsecNFANames) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } pszTemp = pszIpsecNFAReference; for (i = 0; i < dwCount; i++) { pszString = AllocPolStr(pszTemp); if (!pszString) { dwError = ERROR_OUTOFMEMORY; pIpsecISAKMPObject->ppszIpsecNFAReferences = ppszIpsecNFANames; pIpsecISAKMPObject->dwNFACount = i; if (pszIpsecNFAReference) { FreePolStr(pszIpsecNFAReference); } BAIL_ON_WIN32_ERROR(dwError); } *(ppszIpsecNFANames + i) = pszString; pszTemp += wcslen(pszTemp) + 1; //for the null terminator; } if (pszIpsecNFAReference) { FreePolStr(pszIpsecNFAReference); } pIpsecISAKMPObject->ppszIpsecNFAReferences = ppszIpsecNFANames; pIpsecISAKMPObject->dwNFACount = dwCount; } dwType = REG_DWORD; dwSize = sizeof(DWORD); dwError = RegQueryValueExW( hRegKey, L"whenChanged", NULL, &dwType, (LPBYTE)&dwWhenChanged, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); pIpsecISAKMPObject->dwWhenChanged = dwWhenChanged; *ppIpsecISAKMPObject = pIpsecISAKMPObject; cleanup: if (hRegKey) { RegCloseKey(hRegKey); } return(dwError); error: if (pIpsecISAKMPObject) { FreeIpsecISAKMPObject(pIpsecISAKMPObject); } *ppIpsecISAKMPObject = NULL; goto cleanup; } DWORD RegstoreQueryValue( HKEY hRegKey, LPWSTR pszValueName, DWORD dwType, LPBYTE * ppValueData, LPDWORD pdwSize ) { DWORD dwSize = 0; LPWSTR pszValueData = NULL; DWORD dwError = 0; LPBYTE pBuffer = NULL; LPWSTR pszBuf = NULL; dwError = RegQueryValueExW( hRegKey, pszValueName, NULL, &dwType, NULL, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); if (dwSize == 0) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } pBuffer = (LPBYTE)AllocPolMem(dwSize); if (!pBuffer) { dwError = ERROR_OUTOFMEMORY; BAIL_ON_WIN32_ERROR(dwError); } dwError = RegQueryValueExW( hRegKey, pszValueName, NULL, &dwType, pBuffer, &dwSize ); BAIL_ON_WIN32_ERROR(dwError); switch (dwType) { case REG_SZ: pszBuf = (LPWSTR) pBuffer; if (!pszBuf || !*pszBuf) { dwError = ERROR_INVALID_DATA; BAIL_ON_WIN32_ERROR(dwError); } break; default: break; } *ppValueData = pBuffer; *pdwSize = dwSize; return(dwError); error: if (pBuffer) { FreePolMem(pBuffer); } *ppValueData = NULL; *pdwSize = 0; return(dwError); } VOID FlushRegSaveKey( HKEY hRegistryKey ) { DWORD dwError = 0; WCHAR lpszName[MAX_PATH]; DWORD dwSize = 0; memset(lpszName, 0, sizeof(WCHAR)*MAX_PATH); dwSize = MAX_PATH; while((RegEnumKeyExW( hRegistryKey, 0, lpszName, &dwSize, NULL, NULL, NULL, NULL)) == ERROR_SUCCESS) { dwError = RegDeleteKeyW( hRegistryKey, lpszName ); if (dwError != ERROR_SUCCESS) { break; } memset(lpszName, 0, sizeof(WCHAR)*MAX_PATH); dwSize = MAX_PATH; } return; }
26.535101
99
0.516334
[ "object" ]
f567fc2bc383f9f27c42c224f1412e7217bc3f70
6,640
h
C
aws-cpp-sdk-inspector/include/aws/inspector/model/AgentFilter.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2019-10-10T20:58:44.000Z
2019-10-10T20:58:44.000Z
aws-cpp-sdk-inspector/include/aws/inspector/model/AgentFilter.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-inspector/include/aws/inspector/model/AgentFilter.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
/* * 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/inspector/Inspector_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/inspector/model/AgentHealth.h> #include <aws/inspector/model/AgentHealthCode.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace Inspector { namespace Model { /** * <p>Contains information about an Amazon Inspector agent. This data type is used * as a request parameter in the <a>ListAssessmentRunAgents</a> * action.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/AgentFilter">AWS * API Reference</a></p> */ class AWS_INSPECTOR_API AgentFilter { public: AgentFilter(); AgentFilter(Aws::Utils::Json::JsonView jsonValue); AgentFilter& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The current health state of the agent. Values can be set to <b>HEALTHY</b> or * <b>UNHEALTHY</b>.</p> */ inline const Aws::Vector<AgentHealth>& GetAgentHealths() const{ return m_agentHealths; } /** * <p>The current health state of the agent. Values can be set to <b>HEALTHY</b> or * <b>UNHEALTHY</b>.</p> */ inline bool AgentHealthsHasBeenSet() const { return m_agentHealthsHasBeenSet; } /** * <p>The current health state of the agent. Values can be set to <b>HEALTHY</b> or * <b>UNHEALTHY</b>.</p> */ inline void SetAgentHealths(const Aws::Vector<AgentHealth>& value) { m_agentHealthsHasBeenSet = true; m_agentHealths = value; } /** * <p>The current health state of the agent. Values can be set to <b>HEALTHY</b> or * <b>UNHEALTHY</b>.</p> */ inline void SetAgentHealths(Aws::Vector<AgentHealth>&& value) { m_agentHealthsHasBeenSet = true; m_agentHealths = std::move(value); } /** * <p>The current health state of the agent. Values can be set to <b>HEALTHY</b> or * <b>UNHEALTHY</b>.</p> */ inline AgentFilter& WithAgentHealths(const Aws::Vector<AgentHealth>& value) { SetAgentHealths(value); return *this;} /** * <p>The current health state of the agent. Values can be set to <b>HEALTHY</b> or * <b>UNHEALTHY</b>.</p> */ inline AgentFilter& WithAgentHealths(Aws::Vector<AgentHealth>&& value) { SetAgentHealths(std::move(value)); return *this;} /** * <p>The current health state of the agent. Values can be set to <b>HEALTHY</b> or * <b>UNHEALTHY</b>.</p> */ inline AgentFilter& AddAgentHealths(const AgentHealth& value) { m_agentHealthsHasBeenSet = true; m_agentHealths.push_back(value); return *this; } /** * <p>The current health state of the agent. Values can be set to <b>HEALTHY</b> or * <b>UNHEALTHY</b>.</p> */ inline AgentFilter& AddAgentHealths(AgentHealth&& value) { m_agentHealthsHasBeenSet = true; m_agentHealths.push_back(std::move(value)); return *this; } /** * <p>The detailed health state of the agent. Values can be set to <b>IDLE</b>, * <b>RUNNING</b>, <b>SHUTDOWN</b>, <b>UNHEALTHY</b>, <b>THROTTLED</b>, and * <b>UNKNOWN</b>. </p> */ inline const Aws::Vector<AgentHealthCode>& GetAgentHealthCodes() const{ return m_agentHealthCodes; } /** * <p>The detailed health state of the agent. Values can be set to <b>IDLE</b>, * <b>RUNNING</b>, <b>SHUTDOWN</b>, <b>UNHEALTHY</b>, <b>THROTTLED</b>, and * <b>UNKNOWN</b>. </p> */ inline bool AgentHealthCodesHasBeenSet() const { return m_agentHealthCodesHasBeenSet; } /** * <p>The detailed health state of the agent. Values can be set to <b>IDLE</b>, * <b>RUNNING</b>, <b>SHUTDOWN</b>, <b>UNHEALTHY</b>, <b>THROTTLED</b>, and * <b>UNKNOWN</b>. </p> */ inline void SetAgentHealthCodes(const Aws::Vector<AgentHealthCode>& value) { m_agentHealthCodesHasBeenSet = true; m_agentHealthCodes = value; } /** * <p>The detailed health state of the agent. Values can be set to <b>IDLE</b>, * <b>RUNNING</b>, <b>SHUTDOWN</b>, <b>UNHEALTHY</b>, <b>THROTTLED</b>, and * <b>UNKNOWN</b>. </p> */ inline void SetAgentHealthCodes(Aws::Vector<AgentHealthCode>&& value) { m_agentHealthCodesHasBeenSet = true; m_agentHealthCodes = std::move(value); } /** * <p>The detailed health state of the agent. Values can be set to <b>IDLE</b>, * <b>RUNNING</b>, <b>SHUTDOWN</b>, <b>UNHEALTHY</b>, <b>THROTTLED</b>, and * <b>UNKNOWN</b>. </p> */ inline AgentFilter& WithAgentHealthCodes(const Aws::Vector<AgentHealthCode>& value) { SetAgentHealthCodes(value); return *this;} /** * <p>The detailed health state of the agent. Values can be set to <b>IDLE</b>, * <b>RUNNING</b>, <b>SHUTDOWN</b>, <b>UNHEALTHY</b>, <b>THROTTLED</b>, and * <b>UNKNOWN</b>. </p> */ inline AgentFilter& WithAgentHealthCodes(Aws::Vector<AgentHealthCode>&& value) { SetAgentHealthCodes(std::move(value)); return *this;} /** * <p>The detailed health state of the agent. Values can be set to <b>IDLE</b>, * <b>RUNNING</b>, <b>SHUTDOWN</b>, <b>UNHEALTHY</b>, <b>THROTTLED</b>, and * <b>UNKNOWN</b>. </p> */ inline AgentFilter& AddAgentHealthCodes(const AgentHealthCode& value) { m_agentHealthCodesHasBeenSet = true; m_agentHealthCodes.push_back(value); return *this; } /** * <p>The detailed health state of the agent. Values can be set to <b>IDLE</b>, * <b>RUNNING</b>, <b>SHUTDOWN</b>, <b>UNHEALTHY</b>, <b>THROTTLED</b>, and * <b>UNKNOWN</b>. </p> */ inline AgentFilter& AddAgentHealthCodes(AgentHealthCode&& value) { m_agentHealthCodesHasBeenSet = true; m_agentHealthCodes.push_back(std::move(value)); return *this; } private: Aws::Vector<AgentHealth> m_agentHealths; bool m_agentHealthsHasBeenSet; Aws::Vector<AgentHealthCode> m_agentHealthCodes; bool m_agentHealthCodesHasBeenSet; }; } // namespace Model } // namespace Inspector } // namespace Aws
38.830409
171
0.661446
[ "vector", "model" ]
f56f3496e1023c1d56760deeba451a6093c5b764
941
h
C
SpaghettiDungeonGen/include/EntropyGrid.h
RedBreadcat/SpaghettiDungeonGenerator
1153dd8f26dfd835ca70c520e735f199f50ef858
[ "MIT" ]
39
2019-11-23T14:52:46.000Z
2022-01-04T08:57:04.000Z
SpaghettiDungeonGen/include/EntropyGrid.h
RedBreadcat/SpaghettiDungeonGenerator
1153dd8f26dfd835ca70c520e735f199f50ef858
[ "MIT" ]
null
null
null
SpaghettiDungeonGen/include/EntropyGrid.h
RedBreadcat/SpaghettiDungeonGenerator
1153dd8f26dfd835ca70c520e735f199f50ef858
[ "MIT" ]
5
2019-11-24T00:35:04.000Z
2019-12-09T11:08:16.000Z
#pragma once #include <boost/multi_array.hpp> #include <boost/heap/priority_queue.hpp> #include "Coord.h" #include "OutputTile.h" #include "Pattern.h" namespace WFC { class EntropyGrid { public: struct LowestEntropyResult { Coord position; float value; }; EntropyGrid(int width, int height); void Create(const boost::multi_array<OutputTile, 2>& output, const std::vector<Pattern>& patterns); void Collapse(Coord coord); LowestEntropyResult GetLowestEntropyPixel(); void ReduceEntropyNoUpdate(Coord pos, int amount); void CheckIfCoordShouldBeNewMinimum(Coord pos); private: boost::heap::priority_queue<LowestEntropyResult> min_entropy_tracker; boost::multi_array<float, 2> entropies_with_noise; int width; int height; std::vector<Coord> remaining_entropies_ordered; boost::multi_array<float, 2> noise; }; bool operator<(const EntropyGrid::LowestEntropyResult& lhs, const EntropyGrid::LowestEntropyResult& rhs); }
21.883721
105
0.776833
[ "vector" ]
91986f555320ce802006a0541b435539f3bb02e8
69,843
c
C
release/src/linux/linux/arch/ppc64/kernel/prom.c
ghsecuritylab/tomato_egg
50473a46347f4631eb4878a0f47955cc64c87293
[ "FSFAP" ]
278
2015-11-03T03:01:20.000Z
2022-01-20T18:21:05.000Z
release/src/linux/linux/arch/ppc64/kernel/prom.c
ghsecuritylab/tomato_egg
50473a46347f4631eb4878a0f47955cc64c87293
[ "FSFAP" ]
374
2015-11-03T12:37:22.000Z
2021-12-17T14:18:08.000Z
release/src/linux/linux/arch/ppc64/kernel/prom.c
ghsecuritylab/tomato_egg
50473a46347f4631eb4878a0f47955cc64c87293
[ "FSFAP" ]
96
2015-11-22T07:47:26.000Z
2022-01-20T19:52:19.000Z
/* - undefined for user space * * * Procedures for interfacing to Open Firmware. * * Paul Mackerras August 1996. * Copyright (C) 1996 Paul Mackerras. * * Adapted for 64bit PowerPC by Dave Engebretsen and Peter Bergner. * {engebret|bergner}@us.ibm.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. */ #if 0 #define DEBUG_YABOOT #endif #if 0 #define DEBUG_PROM #endif #include <stdarg.h> #include <linux/config.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/init.h> #include <linux/version.h> #include <linux/threads.h> #include <linux/spinlock.h> #include <linux/blk.h> #ifdef DEBUG_YABOOT #define call_yaboot(FUNC,...) \ do { \ if (FUNC) { \ struct prom_t *_prom = PTRRELOC(&prom); \ unsigned long prom_entry = _prom->entry;\ _prom->entry = (unsigned long)(FUNC); \ enter_prom(__VA_ARGS__); \ _prom->entry = prom_entry; \ } \ } while (0) #else #define call_yaboot(FUNC,...) do { ; } while (0) #endif #include <asm/init.h> #include <linux/types.h> #include <linux/pci.h> #include <asm/prom.h> #include <asm/rtas.h> #include <asm/lmb.h> #include <asm/abs_addr.h> #include <asm/page.h> #include <asm/processor.h> #include <asm/irq.h> #include <asm/io.h> #include <asm/smp.h> #include <asm/system.h> #include <asm/mmu.h> #include <asm/pgtable.h> #include <asm/bitops.h> #include <asm/naca.h> #include <asm/pci.h> #include "open_pic.h" #include <asm/bootinfo.h> #include <asm/ppcdebug.h> #ifdef CONFIG_FB #include <asm/linux_logo.h> #endif extern char _end[]; /* * prom_init() is called very early on, before the kernel text * and data have been mapped to KERNELBASE. At this point the code * is running at whatever address it has been loaded at, so * references to extern and static variables must be relocated * explicitly. The procedure reloc_offset() returns the address * we're currently running at minus the address we were linked at. * (Note that strings count as static variables.) * * Because OF may have mapped I/O devices into the area starting at * KERNELBASE, particularly on CHRP machines, we can't safely call * OF once the kernel has been mapped to KERNELBASE. Therefore all * OF calls should be done within prom_init(), and prom_init() * and all routines called within it must be careful to relocate * references as necessary. * * Note that the bss is cleared *after* prom_init runs, so we have * to make sure that any static or extern variables it accesses * are put in the data segment. */ #define PROM_BUG() do { \ prom_print(RELOC("kernel BUG at ")); \ prom_print(RELOC(__FILE__)); \ prom_print(RELOC(":")); \ prom_print_hex(__LINE__); \ prom_print(RELOC("!\n")); \ __asm__ __volatile__(".long " BUG_ILLEGAL_INSTR); \ } while (0) struct pci_reg_property { struct pci_address addr; u32 size_hi; u32 size_lo; }; struct isa_reg_property { u32 space; u32 address; u32 size; }; struct pci_intr_map { struct pci_address addr; u32 dunno; phandle int_ctrler; u32 intr; }; typedef unsigned long interpret_func(struct device_node *, unsigned long, int, int); #if 0 static interpret_func interpret_pci_props; #endif static unsigned long interpret_pci_props(struct device_node *, unsigned long, int, int); static interpret_func interpret_isa_props; static interpret_func interpret_root_props; #ifndef FB_MAX /* avoid pulling in all of the fb stuff */ #define FB_MAX 8 #endif struct prom_t prom = { 0, /* entry */ 0, /* chosen */ 0, /* cpu */ 0, /* stdout */ 0, /* disp_node */ {0,0,0,{0},NULL}, /* args */ 0, /* version */ 32, /* encode_phys_size */ 0 /* bi_rec pointer */ #ifdef DEBUG_YABOOT ,NULL /* yaboot */ #endif }; char *prom_display_paths[FB_MAX] __initdata = { 0, }; unsigned int prom_num_displays = 0; char *of_stdout_device = 0; extern struct rtas_t rtas; extern unsigned long klimit; extern struct lmb lmb; #ifdef CONFIG_MSCHUNKS extern struct msChunks msChunks; #endif /* CONFIG_MSCHUNKS */ #define MAX_PHB 16 * 3 // 16 Towers * 3 PHBs/tower struct _of_tce_table of_tce_table[MAX_PHB + 1] = {{0, 0, 0}}; char *bootpath = 0; char *bootdevice = 0; #define MAX_CPU_THREADS 2 struct device_node *allnodes = 0; static unsigned long call_prom(const char *service, int nargs, int nret, ...); static void prom_exit(void); static unsigned long copy_device_tree(unsigned long); static unsigned long inspect_node(phandle, struct device_node *, unsigned long, unsigned long, struct device_node ***); static unsigned long finish_node(struct device_node *, unsigned long, interpret_func *, int, int); static unsigned long finish_node_interrupts(struct device_node *, unsigned long); static unsigned long check_display(unsigned long); static int prom_next_node(phandle *); static struct bi_record * prom_bi_rec_verify(struct bi_record *); static unsigned long prom_bi_rec_reserve(unsigned long); static struct device_node *find_phandle(phandle); #ifdef CONFIG_MSCHUNKS static unsigned long prom_initialize_mschunks(unsigned long); #ifdef DEBUG_PROM void prom_dump_mschunks_mapping(void); #endif /* DEBUG_PROM */ #endif /* CONFIG_MSCHUNKS */ #ifdef DEBUG_PROM void prom_dump_lmb(void); #endif extern unsigned long reloc_offset(void); extern void enter_prom(void *dummy,...); void cacheable_memzero(void *, unsigned int); #ifndef CONFIG_CMDLINE #define CONFIG_CMDLINE "" #endif char cmd_line[512] = CONFIG_CMDLINE; unsigned long dev_tree_size; #ifdef CONFIG_HMT struct { unsigned int pir; unsigned int threadid; } hmt_thread_data[NR_CPUS] = {0}; #endif /* CONFIG_HMT */ char testString[] = "LINUX\n"; /* This is the one and *ONLY* place where we actually call open * firmware from, since we need to make sure we're running in 32b * mode when we do. We switch back to 64b mode upon return. */ static unsigned long __init call_prom(const char *service, int nargs, int nret, ...) { int i; unsigned long offset = reloc_offset(); struct prom_t *_prom = PTRRELOC(&prom); va_list list; _prom->args.service = (u32)LONG_LSW(service); _prom->args.nargs = nargs; _prom->args.nret = nret; _prom->args.rets = (prom_arg_t *)&(_prom->args.args[nargs]); va_start(list, nret); for (i=0; i < nargs ;i++) _prom->args.args[i] = (prom_arg_t)LONG_LSW(va_arg(list, unsigned long)); va_end(list); for (i=0; i < nret ;i++) _prom->args.rets[i] = 0; enter_prom(&_prom->args); return (unsigned long)((nret > 0) ? _prom->args.rets[0] : 0); } static void __init prom_exit() { unsigned long offset = reloc_offset(); call_prom(RELOC("exit"), 0, 0); for (;;) /* should never get here */ ; } void __init prom_enter(void) { unsigned long offset = reloc_offset(); call_prom(RELOC("enter"), 0, 0); } void __init prom_print(const char *msg) { const char *p, *q; unsigned long offset = reloc_offset(); struct prom_t *_prom = PTRRELOC(&prom); if (_prom->stdout == 0) return; for (p = msg; *p != 0; p = q) { for (q = p; *q != 0 && *q != '\n'; ++q) ; if (q > p) call_prom(RELOC("write"), 3, 1, _prom->stdout, p, q - p); if (*q != 0) { ++q; call_prom(RELOC("write"), 3, 1, _prom->stdout, RELOC("\r\n"), 2); } } } void prom_print_hex(unsigned long val) { int i, nibbles = sizeof(val)*2; char buf[sizeof(val)*2+1]; for (i = nibbles-1; i >= 0; i--) { buf[i] = (val & 0xf) + '0'; if (buf[i] > '9') buf[i] += ('a'-'0'-10); val >>= 4; } buf[nibbles] = '\0'; prom_print(buf); } void prom_print_nl(void) { unsigned long offset = reloc_offset(); prom_print(RELOC("\n")); } static unsigned long prom_initialize_naca(unsigned long mem) { phandle node; char type[64]; unsigned long num_cpus = 0; unsigned long offset = reloc_offset(); struct prom_t *_prom = PTRRELOC(&prom); struct naca_struct *_naca = RELOC(naca); struct systemcfg *_systemcfg = RELOC(systemcfg); /* NOTE: _naca->debug_switch is already initialized. */ #ifdef DEBUG_PROM prom_print(RELOC("prom_initialize_naca: start...\n")); #endif _naca->pftSize = 0; /* ilog2 of htab size. computed below. */ for (node = 0; prom_next_node(&node); ) { type[0] = 0; call_prom(RELOC("getprop"), 4, 1, node, RELOC("device_type"), type, sizeof(type)); if (!strcmp(type, RELOC("cpu"))) { num_cpus += 1; /* We're assuming *all* of the CPUs have the same * d-cache and i-cache sizes... -Peter */ if ( num_cpus == 1 ) { u32 size, lsize, sets; call_prom(RELOC("getprop"), 4, 1, node, RELOC("d-cache-size"), &size, sizeof(size)); call_prom(RELOC("getprop"), 4, 1, node, RELOC("d-cache-line-size"), &lsize, sizeof(lsize)); _systemcfg->dCacheL1Size = size; _systemcfg->dCacheL1LineSize = lsize; _naca->dCacheL1LogLineSize = __ilog2(lsize); _naca->dCacheL1LinesPerPage = PAGE_SIZE/lsize; call_prom(RELOC("getprop"), 4, 1, node, RELOC("i-cache-size"), &size, sizeof(size)); call_prom(RELOC("getprop"), 4, 1, node, RELOC("i-cache-line-size"), &lsize, sizeof(lsize)); _systemcfg->iCacheL1Size = size; _systemcfg->iCacheL1LineSize = lsize; _naca->iCacheL1LogLineSize = __ilog2(lsize); _naca->iCacheL1LinesPerPage = PAGE_SIZE/lsize; if (_systemcfg->platform == PLATFORM_PSERIES_LPAR) { u32 pft_size[2]; call_prom(RELOC("getprop"), 4, 1, node, RELOC("ibm,pft-size"), &pft_size, sizeof(pft_size)); /* pft_size[0] is the NUMA CEC cookie */ _naca->pftSize = pft_size[1]; } } } else if (!strcmp(type, RELOC("serial"))) { phandle isa, pci; struct isa_reg_property reg; union pci_range ranges; type[0] = 0; call_prom(RELOC("getprop"), 4, 1, node, RELOC("ibm,aix-loc"), type, sizeof(type)); if (strcmp(type, RELOC("S1"))) continue; call_prom(RELOC("getprop"), 4, 1, node, RELOC("reg"), &reg, sizeof(reg)); isa = call_prom(RELOC("parent"), 1, 1, node); if (!isa) PROM_BUG(); pci = call_prom(RELOC("parent"), 1, 1, isa); if (!pci) PROM_BUG(); call_prom(RELOC("getprop"), 4, 1, pci, RELOC("ranges"), &ranges, sizeof(ranges)); if ( _prom->encode_phys_size == 32 ) _naca->serialPortAddr = ranges.pci32.phys+reg.address; else { _naca->serialPortAddr = ((((unsigned long)ranges.pci64.phys_hi) << 32) | (ranges.pci64.phys_lo)) + reg.address; } } } _naca->interrupt_controller = IC_INVALID; for (node = 0; prom_next_node(&node); ) { type[0] = 0; call_prom(RELOC("getprop"), 4, 1, node, RELOC("name"), type, sizeof(type)); if (strcmp(type, RELOC("interrupt-controller"))) { continue; } call_prom(RELOC("getprop"), 4, 1, node, RELOC("compatible"), type, sizeof(type)); if (strstr(type, RELOC("open-pic"))) { _naca->interrupt_controller = IC_OPEN_PIC; } else if (strstr(type, RELOC("ppc-xicp"))) { _naca->interrupt_controller = IC_PPC_XIC; } else { prom_print(RELOC("prom: failed to recognize interrupt-controller\n")); } break; } if (_naca->interrupt_controller == IC_INVALID) { prom_print(RELOC("prom: failed to find interrupt-controller\n")); PROM_BUG(); } /* We gotta have at least 1 cpu... */ if ( (_systemcfg->processorCount = num_cpus) < 1 ) PROM_BUG(); _systemcfg->physicalMemorySize = lmb_phys_mem_size(); if (_systemcfg->platform == PLATFORM_PSERIES) { unsigned long rnd_mem_size, pteg_count; /* round mem_size up to next power of 2 */ rnd_mem_size = 1UL << __ilog2(_systemcfg->physicalMemorySize); if (rnd_mem_size < _systemcfg->physicalMemorySize) rnd_mem_size <<= 1; /* # pages / 2 */ pteg_count = (rnd_mem_size >> (12 + 1)); _naca->pftSize = __ilog2(pteg_count << 7); } if (_naca->pftSize == 0) { prom_print(RELOC("prom: failed to compute pftSize!\n")); PROM_BUG(); } /* * Hardcode to GP size. I am not sure where to get this info * in general, as there does not appear to be a slb-size OF * entry. At least in Condor and earlier. DRENG */ _naca->slb_size = 64; /* Add an eye catcher and the systemcfg layout version number */ strcpy(_systemcfg->eye_catcher, RELOC("SYSTEMCFG:PPC64")); _systemcfg->version.major = SYSTEMCFG_MAJOR; _systemcfg->version.minor = SYSTEMCFG_MINOR; _systemcfg->processor = _get_PVR(); #ifdef DEBUG_PROM prom_print(RELOC("systemcfg->processorCount = 0x")); prom_print_hex(_systemcfg->processorCount); prom_print_nl(); prom_print(RELOC("systemcfg->physicalMemorySize = 0x")); prom_print_hex(_systemcfg->physicalMemorySize); prom_print_nl(); prom_print(RELOC("naca->pftSize = 0x")); prom_print_hex(_naca->pftSize); prom_print_nl(); prom_print(RELOC("systemcfg->dCacheL1LineSize = 0x")); prom_print_hex(_systemcfg->dCacheL1LineSize); prom_print_nl(); prom_print(RELOC("systemcfg->iCacheL1LineSize = 0x")); prom_print_hex(_systemcfg->iCacheL1LineSize); prom_print_nl(); prom_print(RELOC("naca->serialPortAddr = 0x")); prom_print_hex(_naca->serialPortAddr); prom_print_nl(); prom_print(RELOC("naca->interrupt_controller = 0x")); prom_print_hex(_naca->interrupt_controller); prom_print_nl(); prom_print(RELOC("systemcfg->platform = 0x")); prom_print_hex(_systemcfg->platform); prom_print_nl(); prom_print(RELOC("prom_initialize_naca: end...\n")); #endif return mem; } static unsigned long __init prom_initialize_lmb(unsigned long mem) { phandle node; char type[64]; unsigned long i, offset = reloc_offset(); struct prom_t *_prom = PTRRELOC(&prom); union lmb_reg_property reg; unsigned long lmb_base, lmb_size; unsigned long num_regs, bytes_per_reg = (_prom->encode_phys_size*2)/8; #ifdef CONFIG_MSCHUNKS unsigned long max_addr = 0; #if 1 /* Fix me: 630 3G-4G IO hack here... -Peter (PPPBBB) */ unsigned long io_base = 3UL<<30; unsigned long io_size = 1UL<<30; unsigned long have_630 = 1; /* assume we have a 630 */ #else unsigned long io_base = <real io base here>; unsigned long io_size = <real io size here>; #endif #endif /* CONFIG_MSCHUNKS */ lmb_init(); for (node = 0; prom_next_node(&node); ) { type[0] = 0; call_prom(RELOC("getprop"), 4, 1, node, RELOC("device_type"), type, sizeof(type)); if (strcmp(type, RELOC("memory"))) continue; num_regs = call_prom(RELOC("getprop"), 4, 1, node, RELOC("reg"), &reg, sizeof(reg)) / bytes_per_reg; for (i=0; i < num_regs ;i++) { if (_prom->encode_phys_size == 32) { lmb_base = reg.addr32[i].address; lmb_size = reg.addr32[i].size; } else { lmb_base = reg.addr64[i].address; lmb_size = reg.addr64[i].size; } #ifdef CONFIG_MSCHUNKS if ( lmb_addrs_overlap(lmb_base,lmb_size, io_base,io_size) ) { /* If we really have dram here, then we don't * have a 630! -Peter */ have_630 = 0; } #endif /* CONFIG_MSCHUNKS */ if ( lmb_add(lmb_base, lmb_size) < 0 ) prom_print(RELOC("Too many LMB's, discarding this one...\n")); #ifdef CONFIG_MSCHUNKS else if ( max_addr < (lmb_base+lmb_size-1) ) max_addr = lmb_base+lmb_size-1; #endif /* CONFIG_MSCHUNKS */ } } #ifdef CONFIG_MSCHUNKS if ( have_630 && lmb_addrs_overlap(0,max_addr,io_base,io_size) ) lmb_add_io(io_base, io_size); #endif /* CONFIG_MSCHUNKS */ lmb_analyze(); #ifdef DEBUG_PROM prom_dump_lmb(); #endif /* DEBUG_PROM */ #ifdef CONFIG_MSCHUNKS mem = prom_initialize_mschunks(mem); #ifdef DEBUG_PROM prom_dump_mschunks_mapping(); #endif /* DEBUG_PROM */ #endif /* CONFIG_MSCHUNKS */ return mem; } static void __init prom_instantiate_rtas(void) { unsigned long offset = reloc_offset(); struct prom_t *_prom = PTRRELOC(&prom); struct rtas_t *_rtas = PTRRELOC(&rtas); struct naca_struct *_naca = RELOC(naca); struct systemcfg *_systemcfg = RELOC(systemcfg); ihandle prom_rtas; u32 getprop_rval; #ifdef DEBUG_PROM prom_print(RELOC("prom_instantiate_rtas: start...\n")); #endif prom_rtas = (ihandle)call_prom(RELOC("finddevice"), 1, 1, RELOC("/rtas")); if (prom_rtas != (ihandle) -1) { char hypertas_funcs[1024]; int rc; if ((rc = call_prom(RELOC("getprop"), 4, 1, prom_rtas, RELOC("ibm,hypertas-functions"), hypertas_funcs, sizeof(hypertas_funcs))) > 0) { _systemcfg->platform = PLATFORM_PSERIES_LPAR; } call_prom(RELOC("getprop"), 4, 1, prom_rtas, RELOC("rtas-size"), &getprop_rval, sizeof(getprop_rval)); _rtas->size = getprop_rval; prom_print(RELOC("instantiating rtas")); if (_rtas->size != 0) { unsigned long rtas_region = RTAS_INSTANTIATE_MAX; /* Grab some space within the first RTAS_INSTANTIATE_MAX bytes * of physical memory (or within the RMO region) because RTAS * runs in 32-bit mode and relocate off. */ if ( _systemcfg->platform == PLATFORM_PSERIES_LPAR ) { struct lmb *_lmb = PTRRELOC(&lmb); rtas_region = min(_lmb->rmo_size, RTAS_INSTANTIATE_MAX); } _rtas->base = lmb_alloc_base(_rtas->size, PAGE_SIZE, rtas_region); prom_print(RELOC(" at 0x")); prom_print_hex(_rtas->base); prom_rtas = (ihandle)call_prom(RELOC("open"), 1, 1, RELOC("/rtas")); prom_print(RELOC("...")); if ((long)call_prom(RELOC("call-method"), 3, 2, RELOC("instantiate-rtas"), prom_rtas, _rtas->base) >= 0) { _rtas->entry = (long)_prom->args.rets[1]; } } if (_rtas->entry <= 0) { prom_print(RELOC(" failed\n")); } else { prom_print(RELOC(" done\n")); } #ifdef DEBUG_PROM prom_print(RELOC("rtas->base = 0x")); prom_print_hex(_rtas->base); prom_print_nl(); prom_print(RELOC("rtas->entry = 0x")); prom_print_hex(_rtas->entry); prom_print_nl(); prom_print(RELOC("rtas->size = 0x")); prom_print_hex(_rtas->size); prom_print_nl(); #endif } #ifdef DEBUG_PROM prom_print(RELOC("prom_instantiate_rtas: end...\n")); #endif } unsigned long prom_strtoul(const char *cp) { unsigned long result = 0,value; while (*cp) { value = *cp-'0'; result = result*10 + value; cp++; } return result; } #ifdef CONFIG_MSCHUNKS static unsigned long prom_initialize_mschunks(unsigned long mem) { unsigned long offset = reloc_offset(); struct lmb *_lmb = PTRRELOC(&lmb); struct msChunks *_msChunks = PTRRELOC(&msChunks); unsigned long i, pchunk = 0; unsigned long addr_range = _lmb->memory.size + _lmb->memory.iosize; unsigned long chunk_size = _lmb->memory.lcd_size; mem = msChunks_alloc(mem, addr_range / chunk_size, chunk_size); /* First create phys -> abs mapping for memory/dram */ for (i=0; i < _lmb->memory.cnt ;i++) { unsigned long base = _lmb->memory.region[i].base; unsigned long size = _lmb->memory.region[i].size; unsigned long achunk = addr_to_chunk(base); unsigned long end_achunk = addr_to_chunk(base+size); if(_lmb->memory.region[i].type != LMB_MEMORY_AREA) continue; _lmb->memory.region[i].physbase = chunk_to_addr(pchunk); for (; achunk < end_achunk ;) { PTRRELOC(_msChunks->abs)[pchunk++] = achunk++; } } #ifdef CONFIG_MSCHUNKS /* Now create phys -> abs mapping for IO */ for (i=0; i < _lmb->memory.cnt ;i++) { unsigned long base = _lmb->memory.region[i].base; unsigned long size = _lmb->memory.region[i].size; unsigned long achunk = addr_to_chunk(base); unsigned long end_achunk = addr_to_chunk(base+size); if(_lmb->memory.region[i].type != LMB_IO_AREA) continue; _lmb->memory.region[i].physbase = chunk_to_addr(pchunk); for (; achunk < end_achunk ;) { PTRRELOC(_msChunks->abs)[pchunk++] = achunk++; } } #endif /* CONFIG_MSCHUNKS */ return mem; } #ifdef DEBUG_PROM void prom_dump_mschunks_mapping(void) { unsigned long offset = reloc_offset(); struct msChunks *_msChunks = PTRRELOC(&msChunks); unsigned long chunk; prom_print(RELOC("\nprom_dump_mschunks_mapping:\n")); prom_print(RELOC(" msChunks.num_chunks = 0x")); prom_print_hex(_msChunks->num_chunks); prom_print_nl(); prom_print(RELOC(" msChunks.chunk_size = 0x")); prom_print_hex(_msChunks->chunk_size); prom_print_nl(); prom_print(RELOC(" msChunks.chunk_shift = 0x")); prom_print_hex(_msChunks->chunk_shift); prom_print_nl(); prom_print(RELOC(" msChunks.chunk_mask = 0x")); prom_print_hex(_msChunks->chunk_mask); prom_print_nl(); prom_print(RELOC(" msChunks.abs = 0x")); prom_print_hex(_msChunks->abs); prom_print_nl(); prom_print(RELOC(" msChunks mapping:\n")); for(chunk=0; chunk < _msChunks->num_chunks ;chunk++) { prom_print(RELOC(" phys 0x")); prom_print_hex(chunk); prom_print(RELOC(" -> abs 0x")); prom_print_hex(PTRRELOC(_msChunks->abs)[chunk]); prom_print_nl(); } } #endif /* DEBUG_PROM */ #endif /* CONFIG_MSCHUNKS */ #ifdef DEBUG_PROM void prom_dump_lmb(void) { unsigned long i; unsigned long offset = reloc_offset(); struct lmb *_lmb = PTRRELOC(&lmb); prom_print(RELOC("\nprom_dump_lmb:\n")); prom_print(RELOC(" memory.cnt = 0x")); prom_print_hex(_lmb->memory.cnt); prom_print_nl(); prom_print(RELOC(" memory.size = 0x")); prom_print_hex(_lmb->memory.size); prom_print_nl(); prom_print(RELOC(" memory.lcd_size = 0x")); prom_print_hex(_lmb->memory.lcd_size); prom_print_nl(); for (i=0; i < _lmb->memory.cnt ;i++) { prom_print(RELOC(" memory.region[0x")); prom_print_hex(i); prom_print(RELOC("].base = 0x")); prom_print_hex(_lmb->memory.region[i].base); prom_print_nl(); prom_print(RELOC(" .physbase = 0x")); prom_print_hex(_lmb->memory.region[i].physbase); prom_print_nl(); prom_print(RELOC(" .size = 0x")); prom_print_hex(_lmb->memory.region[i].size); prom_print_nl(); prom_print(RELOC(" .type = 0x")); prom_print_hex(_lmb->memory.region[i].type); prom_print_nl(); } prom_print_nl(); prom_print(RELOC(" reserved.cnt = 0x")); prom_print_hex(_lmb->reserved.cnt); prom_print_nl(); prom_print(RELOC(" reserved.size = 0x")); prom_print_hex(_lmb->reserved.size); prom_print_nl(); prom_print(RELOC(" reserved.lcd_size = 0x")); prom_print_hex(_lmb->reserved.lcd_size); prom_print_nl(); for (i=0; i < _lmb->reserved.cnt ;i++) { prom_print(RELOC(" reserved.region[0x")); prom_print_hex(i); prom_print(RELOC("].base = 0x")); prom_print_hex(_lmb->reserved.region[i].base); prom_print_nl(); prom_print(RELOC(" .physbase = 0x")); prom_print_hex(_lmb->reserved.region[i].physbase); prom_print_nl(); prom_print(RELOC(" .size = 0x")); prom_print_hex(_lmb->reserved.region[i].size); prom_print_nl(); prom_print(RELOC(" .type = 0x")); prom_print_hex(_lmb->reserved.region[i].type); prom_print_nl(); } } #endif /* DEBUG_PROM */ void prom_initialize_tce_table(void) { phandle node; ihandle phb_node; unsigned long offset = reloc_offset(); char compatible[64], path[64], type[64], model[64]; unsigned long i, table = 0; unsigned long base, vbase, align; unsigned int minalign, minsize; struct _of_tce_table *prom_tce_table = RELOC(of_tce_table); unsigned long tce_entry, *tce_entryp; #ifdef DEBUG_PROM prom_print(RELOC("starting prom_initialize_tce_table\n")); #endif /* Search all nodes looking for PHBs. */ for (node = 0; prom_next_node(&node); ) { compatible[0] = 0; type[0] = 0; model[0] = 0; call_prom(RELOC("getprop"), 4, 1, node, RELOC("compatible"), compatible, sizeof(compatible)); call_prom(RELOC("getprop"), 4, 1, node, RELOC("device_type"), type, sizeof(type)); call_prom(RELOC("getprop"), 4, 1, node, RELOC("model"), model, sizeof(model)); /* Keep the old logic in tack to avoid regression. */ if (compatible[0] != 0) { if((strstr(compatible, RELOC("python")) == NULL) && (strstr(compatible, RELOC("Speedwagon")) == NULL) && (strstr(compatible, RELOC("Winnipeg")) == NULL)) continue; } else if (model[0] != 0) { if ((strstr(model, RELOC("ython")) == NULL) && (strstr(model, RELOC("peedwagon")) == NULL) && (strstr(model, RELOC("innipeg")) == NULL)) continue; } if ((type[0] == 0) || (strstr(type, RELOC("pci")) == NULL)) { continue; } if (call_prom(RELOC("getprop"), 4, 1, node, RELOC("tce-table-minalign"), &minalign, sizeof(minalign)) < 0) { minalign = 0; } if (call_prom(RELOC("getprop"), 4, 1, node, RELOC("tce-table-minsize"), &minsize, sizeof(minsize)) < 0) { minsize = 4UL << 20; } /* Even though we read what OF wants, we just set the table * size to 4 MB. This is enough to map 2GB of PCI DMA space. * By doing this, we avoid the pitfalls of trying to DMA to * MMIO space and the DMA alias hole. */ minsize = 8UL << 20; /* Align to the greater of the align or size */ align = (minalign < minsize) ? minsize : minalign; /* Carve out storage for the TCE table. */ base = lmb_alloc(minsize, align); if ( !base ) { prom_print(RELOC("ERROR, cannot find space for TCE table.\n")); prom_exit(); } vbase = absolute_to_virt(base); /* Save away the TCE table attributes for later use. */ prom_tce_table[table].node = node; prom_tce_table[table].base = vbase; prom_tce_table[table].size = minsize; #ifdef DEBUG_PROM prom_print(RELOC("TCE table: 0x")); prom_print_hex(table); prom_print_nl(); prom_print(RELOC("\tnode = 0x")); prom_print_hex(node); prom_print_nl(); prom_print(RELOC("\tbase = 0x")); prom_print_hex(vbase); prom_print_nl(); prom_print(RELOC("\tsize = 0x")); prom_print_hex(minsize); prom_print_nl(); #endif /* Initialize the table to have a one-to-one mapping * over the allocated size. */ tce_entryp = (unsigned long *)base; for (i = 0; i < (minsize >> 3) ;tce_entryp++, i++) { tce_entry = (i << PAGE_SHIFT); tce_entry |= 0x3; *tce_entryp = tce_entry; } /* Call OF to setup the TCE hardware */ if (call_prom(RELOC("package-to-path"), 3, 1, node, path, 255) <= 0) { prom_print(RELOC("package-to-path failed\n")); } else { prom_print(RELOC("opened ")); prom_print(path); prom_print_nl(); } phb_node = (ihandle)call_prom(RELOC("open"), 1, 1, path); if ( (long)phb_node <= 0) { prom_print(RELOC("open failed\n")); } else { prom_print(RELOC("open success\n")); } call_prom(RELOC("call-method"), 6, 0, RELOC("set-64-bit-addressing"), phb_node, -1, minsize, base & 0xffffffff, (base >> 32) & 0xffffffff); call_prom(RELOC("close"), 1, 0, phb_node); table++; } /* Flag the first invalid entry */ prom_tce_table[table].node = 0; #ifdef DEBUG_PROM prom_print(RELOC("ending prom_initialize_tce_table\n")); #endif } /* * With CHRP SMP we need to use the OF to start the other * processors so we can't wait until smp_boot_cpus (the OF is * trashed by then) so we have to put the processors into * a holding pattern controlled by the kernel (not OF) before * we destroy the OF. * * This uses a chunk of low memory, puts some holding pattern * code there and sends the other processors off to there until * smp_boot_cpus tells them to do something. The holding pattern * checks that address until its cpu # is there, when it is that * cpu jumps to __secondary_start(). smp_boot_cpus() takes care * of setting those values. * * We also use physical address 0x4 here to tell when a cpu * is in its holding pattern code. * * Fixup comment... DRENG / PPPBBB - Peter * * -- Cort */ static void prom_hold_cpus(unsigned long mem) { unsigned long i; unsigned int reg; phandle node; unsigned long offset = reloc_offset(); char type[64], *path; int cpuid = 0; unsigned int interrupt_server[MAX_CPU_THREADS]; unsigned int cpu_threads, hw_cpu_num; int propsize; extern void __secondary_hold(void); extern unsigned long __secondary_hold_spinloop; extern unsigned long __secondary_hold_acknowledge; unsigned long *spinloop = __v2a(&__secondary_hold_spinloop); unsigned long *acknowledge = __v2a(&__secondary_hold_acknowledge); unsigned long secondary_hold = (unsigned long)__v2a(*PTRRELOC((unsigned long *)__secondary_hold)); struct naca_struct *_naca = RELOC(naca); struct systemcfg *_systemcfg = RELOC(systemcfg); struct paca_struct *_xPaca = PTRRELOC(&paca[0]); struct prom_t *_prom = PTRRELOC(&prom); /* Initially, we must have one active CPU. */ _systemcfg->processorCount = 1; #ifdef DEBUG_PROM prom_print(RELOC("prom_hold_cpus: start...\n")); prom_print(RELOC(" 1) spinloop = 0x")); prom_print_hex(spinloop); prom_print_nl(); prom_print(RELOC(" 1) *spinloop = 0x")); prom_print_hex(*spinloop); prom_print_nl(); prom_print(RELOC(" 1) acknowledge = 0x")); prom_print_hex(acknowledge); prom_print_nl(); prom_print(RELOC(" 1) *acknowledge = 0x")); prom_print_hex(*acknowledge); prom_print_nl(); prom_print(RELOC(" 1) secondary_hold = 0x")); prom_print_hex(secondary_hold); prom_print_nl(); #endif /* Set the common spinloop variable, so all of the secondary cpus * will block when they are awakened from their OF spinloop. * This must occur for both SMP and non SMP kernels, since OF will * be trashed when we move the kernel. */ *spinloop = 0; #ifdef CONFIG_HMT for (i=0; i < NR_CPUS; i++) { RELOC(hmt_thread_data)[i].pir = 0xdeadbeef; } #endif /* look for cpus */ for (node = 0; prom_next_node(&node); ) { type[0] = 0; call_prom(RELOC("getprop"), 4, 1, node, RELOC("device_type"), type, sizeof(type)); if (strcmp(type, RELOC("cpu")) != 0) continue; /* Skip non-configured cpus. */ call_prom(RELOC("getprop"), 4, 1, node, RELOC("status"), type, sizeof(type)); if (strcmp(type, RELOC("okay")) != 0) continue; reg = -1; call_prom(RELOC("getprop"), 4, 1, node, RELOC("reg"), &reg, sizeof(reg)); path = (char *) mem; memset(path, 0, 256); if ((long) call_prom(RELOC("package-to-path"), 3, 1, node, path, 255) < 0) continue; #ifdef DEBUG_PROM prom_print_nl(); prom_print(RELOC("cpuid = 0x")); prom_print_hex(cpuid); prom_print_nl(); prom_print(RELOC("cpu hw idx = 0x")); prom_print_hex(reg); prom_print_nl(); #endif _xPaca[cpuid].xHwProcNum = reg; /* Init the acknowledge var which will be reset by * the secondary cpu when it awakens from its OF * spinloop. */ *acknowledge = (unsigned long)-1; propsize = call_prom(RELOC("getprop"), 4, 1, node, RELOC("ibm,ppc-interrupt-server#s"), &interrupt_server, sizeof(interrupt_server)); if (propsize < 0) { /* no property. old hardware has no SMT */ cpu_threads = 1; interrupt_server[0] = reg; /* fake it with phys id */ } else { /* We have a threaded processor */ cpu_threads = propsize / sizeof(u32); if (cpu_threads > MAX_CPU_THREADS) { prom_print(RELOC("SMT: too many threads!\nSMT: found ")); prom_print_hex(cpu_threads); prom_print(RELOC(", max is ")); prom_print_hex(MAX_CPU_THREADS); prom_print_nl(); cpu_threads = 1; /* ToDo: panic? */ } } hw_cpu_num = interrupt_server[0]; if (hw_cpu_num != _prom->cpu) { /* Primary Thread of non-boot cpu */ prom_print_hex(cpuid); prom_print(RELOC(" : starting cpu ")); prom_print(path); prom_print(RELOC(" ... ")); call_prom(RELOC("start-cpu"), 3, 0, node, secondary_hold, cpuid); for(i = 0; (i < 100000000) && (*acknowledge == ((unsigned long)-1)); i++ ); if (*acknowledge == cpuid) { prom_print(RELOC("ok\n")); /* Set the number of active processors. */ _systemcfg->processorCount++; _xPaca[cpuid].active = 1; _xPaca[cpuid].available = 1; } else { prom_print(RELOC("failed: ")); prom_print_hex(*acknowledge); prom_print_nl(); /* prom_panic(RELOC("cpu failed to start")); */ } } else { prom_print_hex(cpuid); prom_print(RELOC(" : booting cpu ")); prom_print(path); prom_print_nl(); } /* Init paca for secondary threads. They start later. */ for (i=1; i < cpu_threads; i++) { cpuid++; _xPaca[cpuid].xHwProcNum = interrupt_server[i]; prom_print_hex(interrupt_server[i]); prom_print(RELOC(" : preparing thread ... ")); if (_naca->smt_state) { _xPaca[cpuid].available = 1; prom_print(RELOC("available")); } else { prom_print(RELOC("not available")); } prom_print_nl(); } cpuid++; } #ifdef CONFIG_HMT /* Only enable HMT on processors that provide support. */ if (__is_processor(PV_PULSAR) || __is_processor(PV_ICESTAR) || __is_processor(PV_SSTAR)) { prom_print(RELOC(" starting secondary threads\n")); for (i=0; i < _systemcfg->processorCount ;i++) { unsigned long threadid = _systemcfg->processorCount*2-1-i; if (i == 0) { unsigned long pir = _get_PIR(); if (__is_processor(PV_PULSAR)) { RELOC(hmt_thread_data)[i].pir = pir & 0x1f; } else { RELOC(hmt_thread_data)[i].pir = pir & 0x3ff; } } RELOC(hmt_thread_data)[i].threadid = threadid; #ifdef DEBUG_PROM prom_print(RELOC(" cpuid 0x")); prom_print_hex(i); prom_print(RELOC(" maps to threadid 0x")); prom_print_hex(threadid); prom_print_nl(); prom_print(RELOC(" pir 0x")); prom_print_hex(RELOC(hmt_thread_data)[i].pir); prom_print_nl(); #endif _xPaca[threadid].xHwProcNum = _xPaca[i].xHwProcNum+1; } _systemcfg->processorCount *= 2; } else { prom_print(RELOC("Processor is not HMT capable\n")); } #endif #ifdef DEBUG_PROM prom_print(RELOC("prom_hold_cpus: end...\n")); #endif } static void smt_setup(void) { char *p, *q; char my_smt_enabled = SMT_DYNAMIC; unsigned long my_smt_snooze_delay; ihandle prom_options = NULL; char option[9]; unsigned long offset = reloc_offset(); struct naca_struct *_naca = RELOC(naca); char found = 0; if (strstr(RELOC(cmd_line), RELOC("smt-enabled="))) { for (q = RELOC(cmd_line); (p = strstr(q, RELOC("smt-enabled="))) != 0; ) { q = p + 12; if (p > RELOC(cmd_line) && p[-1] != ' ') continue; found = 1; if (q[0] == 'o' && q[1] == 'f' && q[2] == 'f' && (q[3] == ' ' || q[3] == '\0')) { my_smt_enabled = SMT_OFF; } else if (q[0]=='o' && q[1] == 'n' && (q[2] == ' ' || q[2] == '\0')) { my_smt_enabled = SMT_ON; } else { my_smt_enabled = SMT_DYNAMIC; } } } if (!found) { prom_options = (ihandle)call_prom(RELOC("finddevice"), 1, 1, RELOC("/options")); if (prom_options != (ihandle) -1) { call_prom(RELOC("getprop"), 4, 1, prom_options, RELOC("ibm,smt-enabled"), option, sizeof(option)); if (option[0] != 0) { found = 1; if (!strcmp(option, "off")) my_smt_enabled = SMT_OFF; else if (!strcmp(option, "on")) my_smt_enabled = SMT_ON; else my_smt_enabled = SMT_DYNAMIC; } } } if (!found ) my_smt_enabled = SMT_DYNAMIC; /* default to on */ found = 0; if (my_smt_enabled) { if (strstr(RELOC(cmd_line), RELOC("smt-snooze-delay="))) { for (q = RELOC(cmd_line); (p = strstr(q, RELOC("smt-snooze-delay="))) != 0; ) { q = p + 17; if (p > RELOC(cmd_line) && p[-1] != ' ') continue; found = 1; /* Don't use simple_strtoul() because _ctype & others aren't RELOC'd */ my_smt_snooze_delay = 0; while (*q >= '0' && *q <= '9') { my_smt_snooze_delay = my_smt_snooze_delay * 10 + *q - '0'; q++; } } } if (!found) { prom_options = (ihandle)call_prom(RELOC("finddevice"), 1, 1, RELOC("/options")); if (prom_options != (ihandle) -1) { call_prom(RELOC("getprop"), 4, 1, prom_options, RELOC("ibm,smt-snooze-delay"), option, sizeof(option)); if (option[0] != 0) { found = 1; /* Don't use simple_strtoul() because _ctype & others aren't RELOC'd */ my_smt_snooze_delay = 0; q = option; while (*q >= '0' && *q <= '9') { my_smt_snooze_delay = my_smt_snooze_delay * 10 + *q - '0'; q++; } } } } if (!found) { my_smt_snooze_delay = 30000; /* default value */ } } else { my_smt_snooze_delay = 0; /* default value */ } _naca->smt_snooze_delay = my_smt_snooze_delay; _naca->smt_state = my_smt_enabled; } #ifdef CONFIG_PPCDBG extern char *trace_names[]; /* defined in udbg.c -- need a better interface */ void parse_ppcdbg_optionlist(const char *cmd, const char *cmdend) { unsigned long offset = reloc_offset(); char **_trace_names = PTRRELOC(&trace_names[0]); const char *all = RELOC("all"); struct naca_struct *_naca = RELOC(naca); const char *p, *pend; int onoff, i, cmdidx; unsigned long mask; char cmdbuf[30]; for (p = cmd, pend = strchr(p, ','); p < cmdend; pend = strchr(p, ',')) { if (pend == NULL || pend > cmdend) pend = cmdend; onoff = 1; /* default */ if (*p == '+' || *p == '-') { /* explicit on or off */ onoff = (*p == '+'); p++; } /* parse out p..pend here */ if (pend - p < sizeof(cmdbuf)) { strncpy(cmdbuf, p, pend - p); cmdbuf[pend - p] = '\0'; for (cmdidx = -1, i = 0; i < PPCDBG_NUM_FLAGS; i++) { if (_trace_names[i] && (strcmp(PTRRELOC(_trace_names[i]), cmdbuf) == 0)) { cmdidx = i; break; } } mask = 0; if (cmdidx >= 0) { mask = (1 << cmdidx); } else if (strcmp(cmdbuf, all) == 0) { mask = PPCDBG_ALL; } else { prom_print(RELOC("ppcdbg: unknown debug: ")); prom_print(cmdbuf); prom_print_nl(); } if (mask) { if (onoff) _naca->debug_switch |= mask; else _naca->debug_switch &= ~mask; } } p = pend+1; } } /* * Parse ppcdbg= cmdline option. * * Option names are listed in <asm/ppcdebug.h> in the trace_names * table. Multiple names may be listed separated by commas (no whitespace), * and each option may be preceeded by a + or - to force on or off state. * The special option "all" may also be used. They are processed strictly * left to right. Multiple ppcdbg= options are the command line are treated * as a single option list. * * Examples: ppcdbg=phb_init,buswalk * ppcdbg=all,-mm,-tce * * ToDo: add "group" names that map to common combinations of flags. */ void parse_ppcdbg_cmd_line(const char *line) { unsigned long offset = reloc_offset(); const char *ppcdbgopt = RELOC("ppcdbg="); struct naca_struct *_naca = RELOC(naca); const char *cmd, *end; _naca->debug_switch = PPC_DEBUG_DEFAULT; /* | PPCDBG_BUSWALK | PPCDBG_PHBINIT | PPCDBG_MM | PPCDBG_MMINIT | PPCDBG_TCEINIT | PPCDBG_TCE */ cmd = line; while (cmd && (cmd = strstr(cmd, ppcdbgopt)) != NULL) { cmd += 7; /* skip ppcdbg= */ for (end = cmd; *end != '\0' && *end != '\t' && *end != ' '; end++) ; /* scan to whitespace or end */ parse_ppcdbg_optionlist(cmd, end); } } #endif /* CONFIG_PPCDBG */ /* * Do minimal cmd_line parsing for early boot options. */ static void __init prom_parse_cmd_line(char *line) { #ifdef CONFIG_PPCDBG parse_ppcdbg_cmd_line(line); #endif } /* * We enter here early on, when the Open Firmware prom is still * handling exceptions and the MMU hash table for us. */ unsigned long __init prom_init(unsigned long r3, unsigned long r4, unsigned long pp, unsigned long r6, unsigned long r7, yaboot_debug_t *yaboot) { int chrp = 0; unsigned long mem; ihandle prom_mmu, prom_op, prom_root, prom_cpu; phandle cpu_pkg; unsigned long offset = reloc_offset(); long l, sz; char *p, *d; unsigned long phys; u32 getprop_rval; struct systemcfg *_systemcfg = RELOC(systemcfg); struct paca_struct *_xPaca = PTRRELOC(&paca[0]); struct prom_t *_prom = PTRRELOC(&prom); char *_cmd_line = PTRRELOC(&cmd_line[0]); /* Default machine type. */ _systemcfg->platform = PLATFORM_PSERIES; /* Get a handle to the prom entry point before anything else */ _prom->entry = pp; _prom->bi_recs = prom_bi_rec_verify((struct bi_record *)r6); if ( _prom->bi_recs != NULL ) { RELOC(klimit) = PTRUNRELOC((unsigned long)_prom->bi_recs + _prom->bi_recs->data[1]); } #ifdef DEBUG_YABOOT call_yaboot(yaboot->dummy,offset>>32,offset&0xffffffff); call_yaboot(yaboot->printf, RELOC("offset = 0x%08x%08x\n"), LONG_MSW(offset), LONG_LSW(offset)); #endif /* Default */ phys = KERNELBASE - offset; #ifdef DEBUG_YABOOT call_yaboot(yaboot->printf, RELOC("phys = 0x%08x%08x\n"), LONG_MSW(phys), LONG_LSW(phys)); #endif #ifdef DEBUG_YABOOT _prom->yaboot = yaboot; call_yaboot(yaboot->printf, RELOC("pp = 0x%08x%08x\n"), LONG_MSW(pp), LONG_LSW(pp)); call_yaboot(yaboot->printf, RELOC("prom = 0x%08x%08x\n"), LONG_MSW(_prom->entry), LONG_LSW(_prom->entry)); #endif /* First get a handle for the stdout device */ _prom->chosen = (ihandle)call_prom(RELOC("finddevice"), 1, 1, RELOC("/chosen")); #ifdef DEBUG_YABOOT call_yaboot(yaboot->printf, RELOC("prom->chosen = 0x%08x%08x\n"), LONG_MSW(_prom->chosen), LONG_LSW(_prom->chosen)); #endif if ((long)_prom->chosen <= 0) prom_exit(); if ((long)call_prom(RELOC("getprop"), 4, 1, _prom->chosen, RELOC("stdout"), &getprop_rval, sizeof(getprop_rval)) <= 0) prom_exit(); _prom->stdout = (ihandle)(unsigned long)getprop_rval; #ifdef DEBUG_YABOOT if (_prom->stdout == 0) { call_yaboot(yaboot->printf, RELOC("prom->stdout = 0x%08x%08x\n"), LONG_MSW(_prom->stdout), LONG_LSW(_prom->stdout)); } call_yaboot(yaboot->printf, RELOC("prom->stdout = 0x%08x%08x\n"), LONG_MSW(_prom->stdout), LONG_LSW(_prom->stdout)); #endif #ifdef DEBUG_YABOOT call_yaboot(yaboot->printf, RELOC("Location: 0x11\n")); #endif mem = RELOC(klimit) - offset; #ifdef DEBUG_YABOOT call_yaboot(yaboot->printf, RELOC("Location: 0x11b\n")); #endif /* Get the full OF pathname of the stdout device */ p = (char *) mem; memset(p, 0, 256); call_prom(RELOC("instance-to-path"), 3, 1, _prom->stdout, p, 255); RELOC(of_stdout_device) = PTRUNRELOC(p); mem += strlen(p) + 1; getprop_rval = 1; prom_root = (ihandle)call_prom(RELOC("finddevice"), 1, 1, RELOC("/")); if (prom_root != (ihandle)-1) { call_prom(RELOC("getprop"), 4, 1, prom_root, RELOC("#size-cells"), &getprop_rval, sizeof(getprop_rval)); } _prom->encode_phys_size = (getprop_rval==1) ? 32 : 64; /* Fetch the cmd_line */ sz = (long)call_prom(RELOC("getprop"), 4, 1, _prom->chosen, RELOC("bootargs"), _cmd_line, sizeof(cmd_line)-1); if (sz > 0) _cmd_line[sz] = '\0'; if (sz <=1 ) strcpy(_cmd_line,RELOC(CONFIG_CMDLINE)); prom_parse_cmd_line(_cmd_line); #ifdef DEBUG_PROM prom_print(RELOC("DRENG: Detect OF version...\n")); #endif /* Find the OF version */ prom_op = (ihandle)call_prom(RELOC("finddevice"), 1, 1, RELOC("/openprom")); if (prom_op != (ihandle)-1) { char model[64]; sz = (long)call_prom(RELOC("getprop"), 4, 1, prom_op, RELOC("model"), model, 64); if (sz > 0) { char *c; /* hack to skip the ibm chrp firmware # */ if ( strncmp(model,RELOC("IBM"),3) ) { for (c = model; *c; c++) if (*c >= '0' && *c <= '9') { _prom->version = *c - '0'; break; } } else chrp = 1; } } if (_prom->version >= 3) prom_print(RELOC("OF Version 3 detected.\n")); /* Determine which cpu is actually running right _now_ */ if ((long)call_prom(RELOC("getprop"), 4, 1, _prom->chosen, RELOC("cpu"), &getprop_rval, sizeof(getprop_rval)) <= 0) prom_exit(); prom_cpu = (ihandle)(unsigned long)getprop_rval; cpu_pkg = call_prom(RELOC("instance-to-package"), 1, 1, prom_cpu); call_prom(RELOC("getprop"), 4, 1, cpu_pkg, RELOC("reg"), &getprop_rval, sizeof(getprop_rval)); _prom->cpu = (int)(unsigned long)getprop_rval; _xPaca[0].xHwProcNum = _prom->cpu; #ifdef DEBUG_PROM prom_print(RELOC("Booting CPU hw index = 0x")); prom_print_hex(_prom->cpu); prom_print_nl(); #endif /* Get the boot device and translate it to a full OF pathname. */ p = (char *) mem; l = (long) call_prom(RELOC("getprop"), 4, 1, _prom->chosen, RELOC("bootpath"), p, 1<<20); if (l > 0) { p[l] = 0; /* should already be null-terminated */ RELOC(bootpath) = PTRUNRELOC(p); mem += l + 1; d = (char *) mem; *d = 0; call_prom(RELOC("canon"), 3, 1, p, d, 1<<20); RELOC(bootdevice) = PTRUNRELOC(d); mem = DOUBLEWORD_ALIGN(mem + strlen(d) + 1); } mem = prom_initialize_lmb(mem); mem = prom_bi_rec_reserve(mem); mem = check_display(mem); prom_instantiate_rtas(); /* Initialize some system info into the Naca early... */ mem = prom_initialize_naca(mem); smt_setup(); /* If we are on an SMP machine, then we *MUST* do the * following, regardless of whether we have an SMP * kernel or not. */ prom_hold_cpus(mem); #ifdef DEBUG_PROM prom_print(RELOC("copying OF device tree...\n")); #endif mem = copy_device_tree(mem); RELOC(klimit) = mem + offset; lmb_reserve(0, __pa(RELOC(klimit))); if (_systemcfg->platform == PLATFORM_PSERIES) prom_initialize_tce_table(); if ((long) call_prom(RELOC("getprop"), 4, 1, _prom->chosen, RELOC("mmu"), &getprop_rval, sizeof(getprop_rval)) <= 0) { prom_print(RELOC(" no MMU found\n")); prom_exit(); } /* We assume the phys. address size is 3 cells */ prom_mmu = (ihandle)(unsigned long)getprop_rval; if ((long)call_prom(RELOC("call-method"), 4, 4, RELOC("translate"), prom_mmu, (void *)(KERNELBASE - offset), (void *)1) != 0) { prom_print(RELOC(" (translate failed) ")); } else { prom_print(RELOC(" (translate ok) ")); phys = (unsigned long)_prom->args.rets[3]; } /* If OpenFirmware version >= 3, then use quiesce call */ if (_prom->version >= 3) { prom_print(RELOC("Calling quiesce ...\n")); call_prom(RELOC("quiesce"), 0, 0); phys = KERNELBASE - offset; } prom_print(RELOC("returning from prom_init\n")); return phys; } static int prom_set_color(ihandle ih, int i, int r, int g, int b) { unsigned long offset = reloc_offset(); return (int)(long)call_prom(RELOC("call-method"), 6, 1, RELOC("color!"), ih, (void *)(long) i, (void *)(long) b, (void *)(long) g, (void *)(long) r ); } /* * If we have a display that we don't know how to drive, * we will want to try to execute OF's open method for it * later. However, OF will probably fall over if we do that * we've taken over the MMU. * So we check whether we will need to open the display, * and if so, open it now. */ static unsigned long __init check_display(unsigned long mem) { phandle node; ihandle ih; int i; unsigned long offset = reloc_offset(); struct prom_t *_prom = PTRRELOC(&prom); char type[64], *path; static unsigned char default_colors[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0xaa, 0x00, 0xaa, 0x00, 0x00, 0xaa, 0xaa, 0xaa, 0x00, 0x00, 0xaa, 0x00, 0xaa, 0xaa, 0xaa, 0x00, 0xaa, 0xaa, 0xaa, 0x55, 0x55, 0x55, 0x55, 0x55, 0xff, 0x55, 0xff, 0x55, 0x55, 0xff, 0xff, 0xff, 0x55, 0x55, 0xff, 0x55, 0xff, 0xff, 0xff, 0x55, 0xff, 0xff, 0xff }; _prom->disp_node = 0; for (node = 0; prom_next_node(&node); ) { type[0] = 0; call_prom(RELOC("getprop"), 4, 1, node, RELOC("device_type"), type, sizeof(type)); if (strcmp(type, RELOC("display")) != 0) continue; /* It seems OF doesn't null-terminate the path :-( */ path = (char *) mem; memset(path, 0, 256); if ((long) call_prom(RELOC("package-to-path"), 3, 1, node, path, 255) < 0) continue; prom_print(RELOC("opening display ")); prom_print(path); ih = (ihandle)call_prom(RELOC("open"), 1, 1, path); if (ih == (ihandle)0 || ih == (ihandle)-1) { prom_print(RELOC("... failed\n")); continue; } prom_print(RELOC("... ok\n")); if (_prom->disp_node == 0) _prom->disp_node = (ihandle)(unsigned long)node; /* Setup a useable color table when the appropriate * method is available. Should update this to set-colors */ for (i = 0; i < 32; i++) if (prom_set_color(ih, i, RELOC(default_colors)[i*3], RELOC(default_colors)[i*3+1], RELOC(default_colors)[i*3+2]) != 0) break; #ifdef CONFIG_FB for (i = 0; i < LINUX_LOGO_COLORS; i++) if (prom_set_color(ih, i + 32, RELOC(linux_logo_red)[i], RELOC(linux_logo_green)[i], RELOC(linux_logo_blue)[i]) != 0) break; #endif /* CONFIG_FB */ /* * If this display is the device that OF is using for stdout, * move it to the front of the list. */ mem += strlen(path) + 1; i = RELOC(prom_num_displays)++; if (RELOC(of_stdout_device) != 0 && i > 0 && strcmp(PTRRELOC(RELOC(of_stdout_device)), path) == 0) { for (; i > 0; --i) RELOC(prom_display_paths[i]) = RELOC(prom_display_paths[i-1]); } RELOC(prom_display_paths[i]) = PTRUNRELOC(path); if (RELOC(prom_num_displays) >= FB_MAX) break; } return DOUBLEWORD_ALIGN(mem); } static int __init prom_next_node(phandle *nodep) { phandle node; unsigned long offset = reloc_offset(); if ((node = *nodep) != 0 && (*nodep = call_prom(RELOC("child"), 1, 1, node)) != 0) return 1; if ((*nodep = call_prom(RELOC("peer"), 1, 1, node)) != 0) return 1; for (;;) { if ((node = call_prom(RELOC("parent"), 1, 1, node)) == 0) return 0; if ((*nodep = call_prom(RELOC("peer"), 1, 1, node)) != 0) return 1; } } /* * Make a copy of the device tree from the PROM. */ static unsigned long __init copy_device_tree(unsigned long mem_start) { phandle root; unsigned long new_start; struct device_node **allnextp; unsigned long offset = reloc_offset(); unsigned long mem_end = mem_start + (8<<20); root = call_prom(RELOC("peer"), 1, 1, (phandle)0); if (root == (phandle)0) { prom_print(RELOC("couldn't get device tree root\n")); prom_exit(); } allnextp = &RELOC(allnodes); mem_start = DOUBLEWORD_ALIGN(mem_start); new_start = inspect_node(root, 0, mem_start, mem_end, &allnextp); *allnextp = 0; return new_start; } __init static unsigned long inspect_node(phandle node, struct device_node *dad, unsigned long mem_start, unsigned long mem_end, struct device_node ***allnextpp) { int l; phandle child; struct device_node *np; struct property *pp, **prev_propp; char *prev_name, *namep; unsigned char *valp; unsigned long offset = reloc_offset(); np = (struct device_node *) mem_start; mem_start += sizeof(struct device_node); memset(np, 0, sizeof(*np)); np->node = node; **allnextpp = PTRUNRELOC(np); *allnextpp = &np->allnext; if (dad != 0) { np->parent = PTRUNRELOC(dad); /* we temporarily use the `next' field as `last_child'. */ if (dad->next == 0) dad->child = PTRUNRELOC(np); else dad->next->sibling = PTRUNRELOC(np); dad->next = np; } /* get and store all properties */ prev_propp = &np->properties; prev_name = RELOC(""); for (;;) { pp = (struct property *) mem_start; namep = (char *) (pp + 1); pp->name = PTRUNRELOC(namep); if ((long) call_prom(RELOC("nextprop"), 3, 1, node, prev_name, namep) <= 0) break; mem_start = DOUBLEWORD_ALIGN((unsigned long)namep + strlen(namep) + 1); prev_name = namep; valp = (unsigned char *) mem_start; pp->value = PTRUNRELOC(valp); pp->length = (int)(long) call_prom(RELOC("getprop"), 4, 1, node, namep, valp, mem_end - mem_start); if (pp->length < 0) continue; mem_start = DOUBLEWORD_ALIGN(mem_start + pp->length); *prev_propp = PTRUNRELOC(pp); prev_propp = &pp->next; } /* Add a "linux_phandle" value */ if (np->node != NULL) { u32 ibm_phandle = 0; int len; /* First see if "ibm,phandle" exists and use its value */ len = (int) call_prom(RELOC("getprop"), 4, 1, node, RELOC("ibm,phandle"), &ibm_phandle, sizeof(ibm_phandle)); if (len < 0) { np->linux_phandle = np->node; } else { np->linux_phandle = ibm_phandle; } } *prev_propp = 0; /* get the node's full name */ l = (long) call_prom(RELOC("package-to-path"), 3, 1, node, (char *) mem_start, mem_end - mem_start); if (l >= 0) { np->full_name = PTRUNRELOC((char *) mem_start); *(char *)(mem_start + l) = 0; mem_start = DOUBLEWORD_ALIGN(mem_start + l + 1); } /* do all our children */ child = call_prom(RELOC("child"), 1, 1, node); while (child != (phandle)0) { mem_start = inspect_node(child, np, mem_start, mem_end, allnextpp); child = call_prom(RELOC("peer"), 1, 1, child); } return mem_start; } /* * finish_device_tree is called once things are running normally * (i.e. with text and data mapped to the address they were linked at). * It traverses the device tree and fills in the name, type, * {n_}addrs and {n_}intrs fields of each node. */ void __init finish_device_tree(void) { unsigned long mem = klimit; mem = finish_node(allnodes, mem, NULL, 0, 0); dev_tree_size = mem - (unsigned long) allnodes; mem = _ALIGN(mem, PAGE_SIZE); lmb_reserve(__pa(klimit), mem-klimit); klimit = mem; rtas.dev = find_devices("rtas"); } static unsigned long __init finish_node(struct device_node *np, unsigned long mem_start, interpret_func *ifunc, int naddrc, int nsizec) { struct device_node *child; int *ip; np->name = get_property(np, "name", 0); np->type = get_property(np, "device_type", 0); /* get the device addresses and interrupts */ if (ifunc != NULL) { mem_start = ifunc(np, mem_start, naddrc, nsizec); } mem_start = finish_node_interrupts(np, mem_start); /* Look for #address-cells and #size-cells properties. */ ip = (int *) get_property(np, "#address-cells", 0); if (ip != NULL) naddrc = *ip; ip = (int *) get_property(np, "#size-cells", 0); if (ip != NULL) nsizec = *ip; /* the f50 sets the name to 'display' and 'compatible' to what we * expect for the name -- Cort */ ifunc = NULL; if (!strcmp(np->name, "display")) np->name = get_property(np, "compatible", 0); if (!strcmp(np->name, "device-tree") || np->parent == NULL) ifunc = interpret_root_props; else if (np->type == 0) ifunc = NULL; else if (!strcmp(np->type, "pci") || !strcmp(np->type, "vci")) ifunc = interpret_pci_props; else if (!strcmp(np->type, "isa")) ifunc = interpret_isa_props; for (child = np->child; child != NULL; child = child->sibling) mem_start = finish_node(child, mem_start, ifunc, naddrc, nsizec); return mem_start; } /* This routine walks the interrupt tree for a given device node and gather * all necessary informations according to the draft interrupt mapping * for CHRP. The current version was only tested on Apple "Core99" machines * and may not handle cascaded controllers correctly. */ __init static unsigned long finish_node_interrupts(struct device_node *np, unsigned long mem_start) { /* Finish this node */ unsigned int *isizep, *asizep, *interrupts, *map, *map_mask, *reg; phandle *parent, map_parent; struct device_node *node, *parent_node; int l, isize, ipsize, asize, map_size, regpsize; /* Currently, we don't look at all nodes with no "interrupts" property */ interrupts = (unsigned int *)get_property(np, "interrupts", &l); if (interrupts == NULL) return mem_start; ipsize = l>>2; reg = (unsigned int *)get_property(np, "reg", &l); regpsize = l>>2; /* We assume default interrupt cell size is 1 (bugus ?) */ isize = 1; node = np; do { /* We adjust the cell size if the current parent contains an #interrupt-cells * property */ isizep = (unsigned int *)get_property(node, "#interrupt-cells", &l); if (isizep) isize = *isizep; /* We don't do interrupt cascade (ISA) for now, we stop on the first * controller found */ if (get_property(node, "interrupt-controller", &l)) { int i,j; np->intrs = (struct interrupt_info *) mem_start; np->n_intrs = ipsize / isize; mem_start += np->n_intrs * sizeof(struct interrupt_info); for (i = 0; i < np->n_intrs; ++i) { np->intrs[i].line = irq_offset_up(*interrupts++); np->intrs[i].sense = 1; if (isize > 1) np->intrs[i].sense = *interrupts++; for (j=2; j<isize; j++) interrupts++; } return mem_start; } /* We lookup for an interrupt-map. This code can only handle one interrupt * per device in the map. We also don't handle #address-cells in the parent * I skip the pci node itself here, may not be necessary but I don't like it's * reg property. */ if (np != node) map = (unsigned int *)get_property(node, "interrupt-map", &l); else map = NULL; if (map && l) { int i, found, temp_isize, temp_asize; map_size = l>>2; map_mask = (unsigned int *)get_property(node, "interrupt-map-mask", &l); asizep = (unsigned int *)get_property(node, "#address-cells", &l); if (asizep && l == sizeof(unsigned int)) asize = *asizep; else asize = 0; found = 0; while (map_size>0 && !found) { found = 1; for (i=0; i<asize; i++) { unsigned int mask = map_mask ? map_mask[i] : 0xffffffff; if (!reg || (i>=regpsize) || ((mask & *map) != (mask & reg[i]))) found = 0; map++; map_size--; } for (i=0; i<isize; i++) { unsigned int mask = map_mask ? map_mask[i+asize] : 0xffffffff; if ((mask & *map) != (mask & interrupts[i])) found = 0; map++; map_size--; } map_parent = *((phandle *)map); map+=1; map_size-=1; parent_node = find_phandle(map_parent); temp_isize = isize; temp_asize = 0; if (parent_node) { isizep = (unsigned int *)get_property(parent_node, "#interrupt-cells", &l); if (isizep) temp_isize = *isizep; asizep = (unsigned int *)get_property(parent_node, "#address-cells", &l); if (asizep && l == sizeof(unsigned int)) temp_asize = *asizep; } if (!found) { map += temp_isize + temp_asize; map_size -= temp_isize + temp_asize; } } if (found) { /* Mapped to a new parent. Use the reg and interrupts specified in * the map as the new search parameters. Then search from the parent. */ node = parent_node; reg = map; regpsize = temp_asize; interrupts = map + temp_asize; ipsize = temp_isize; continue; } } /* We look for an explicit interrupt-parent. */ parent = (phandle *)get_property(node, "interrupt-parent", &l); if (parent && (l == sizeof(phandle)) && (parent_node = find_phandle(*parent))) { node = parent_node; continue; } /* Default, get real parent */ node = node->parent; } while (node); return mem_start; } int prom_n_addr_cells(struct device_node* np) { int* ip; do { if (np->parent) np = np->parent; ip = (int *) get_property(np, "#address-cells", 0); if (ip != NULL) return *ip; } while (np->parent); /* No #address-cells property for the root node, default to 1 */ return 1; } int prom_n_size_cells(struct device_node* np) { int* ip; do { if (np->parent) np = np->parent; ip = (int *) get_property(np, "#size-cells", 0); if (ip != NULL) return *ip; } while (np->parent); /* No #size-cells property for the root node, default to 1 */ return 1; } static unsigned long __init interpret_pci_props(struct device_node *np, unsigned long mem_start, int naddrc, int nsizec) { struct address_range *adr; struct pci_reg_property *pci_addrs; int i, l; pci_addrs = (struct pci_reg_property *) get_property(np, "assigned-addresses", &l); if (pci_addrs != 0 && l >= sizeof(struct pci_reg_property)) { i = 0; adr = (struct address_range *) mem_start; while ((l -= sizeof(struct pci_reg_property)) >= 0) { adr[i].space = pci_addrs[i].addr.a_hi; adr[i].address = pci_addrs[i].addr.a_lo; adr[i].size = pci_addrs[i].size_lo; ++i; } np->addrs = adr; np->n_addrs = i; mem_start += i * sizeof(struct address_range); } return mem_start; } static unsigned long __init interpret_isa_props(struct device_node *np, unsigned long mem_start, int naddrc, int nsizec) { struct isa_reg_property *rp; struct address_range *adr; int i, l; rp = (struct isa_reg_property *) get_property(np, "reg", &l); if (rp != 0 && l >= sizeof(struct isa_reg_property)) { i = 0; adr = (struct address_range *) mem_start; while ((l -= sizeof(struct reg_property)) >= 0) { adr[i].space = rp[i].space; adr[i].address = rp[i].address + (adr[i].space? 0: _ISA_MEM_BASE); adr[i].size = rp[i].size; ++i; } np->addrs = adr; np->n_addrs = i; mem_start += i * sizeof(struct address_range); } return mem_start; } static unsigned long __init interpret_root_props(struct device_node *np, unsigned long mem_start, int naddrc, int nsizec) { struct address_range *adr; int i, l; unsigned int *rp; int rpsize = (naddrc + nsizec) * sizeof(unsigned int); rp = (unsigned int *) get_property(np, "reg", &l); if (rp != 0 && l >= rpsize) { i = 0; adr = (struct address_range *) mem_start; while ((l -= rpsize) >= 0) { adr[i].space = 0; adr[i].address = rp[naddrc - 1]; adr[i].size = rp[naddrc + nsizec - 1]; ++i; rp += naddrc + nsizec; } np->addrs = adr; np->n_addrs = i; mem_start += i * sizeof(struct address_range); } return mem_start; } /* * Work out the sense (active-low level / active-high edge) * of each interrupt from the device tree. */ void __init prom_get_irq_senses(unsigned char *senses, int off, int max) { struct device_node *np; int i, j; /* default to level-triggered */ memset(senses, 1, max - off); for (np = allnodes; np != 0; np = np->allnext) { for (j = 0; j < np->n_intrs; j++) { i = np->intrs[j].line; if (i >= off && i < max) senses[i-off] = np->intrs[j].sense; } } } /* * Construct and return a list of the device_nodes with a given name. */ struct device_node * find_devices(const char *name) { struct device_node *head, **prevp, *np; prevp = &head; for (np = allnodes; np != 0; np = np->allnext) { if (np->name != 0 && strcasecmp(np->name, name) == 0) { *prevp = np; prevp = &np->next; } } *prevp = 0; return head; } /* * Construct and return a list of the device_nodes with a given type. */ struct device_node * find_type_devices(const char *type) { struct device_node *head, **prevp, *np; prevp = &head; for (np = allnodes; np != 0; np = np->allnext) { if (np->type != 0 && strcasecmp(np->type, type) == 0) { *prevp = np; prevp = &np->next; } } *prevp = 0; return head; } /* * Returns all nodes linked together */ struct device_node * __openfirmware find_all_nodes(void) { struct device_node *head, **prevp, *np; prevp = &head; for (np = allnodes; np != 0; np = np->allnext) { *prevp = np; prevp = &np->next; } *prevp = 0; return head; } /* Checks if the given "compat" string matches one of the strings in * the device's "compatible" property */ int device_is_compatible(struct device_node *device, const char *compat) { const char* cp; int cplen, l; cp = (char *) get_property(device, "compatible", &cplen); if (cp == NULL) return 0; while (cplen > 0) { if (strncasecmp(cp, compat, strlen(compat)) == 0) return 1; l = strlen(cp) + 1; cp += l; cplen -= l; } return 0; } /* * Indicates whether the root node has a given value in its * compatible property. */ int machine_is_compatible(const char *compat) { struct device_node *root; root = find_path_device("/"); if (root == 0) return 0; return device_is_compatible(root, compat); } /* * Construct and return a list of the device_nodes with a given type * and compatible property. */ struct device_node * find_compatible_devices(const char *type, const char *compat) { struct device_node *head, **prevp, *np; prevp = &head; for (np = allnodes; np != 0; np = np->allnext) { if (type != NULL && !(np->type != 0 && strcasecmp(np->type, type) == 0)) continue; if (device_is_compatible(np, compat)) { *prevp = np; prevp = &np->next; } } *prevp = 0; return head; } /* * Find the device_node with a given full_name. */ struct device_node * find_path_device(const char *path) { struct device_node *np; for (np = allnodes; np != 0; np = np->allnext) if (np->full_name != 0 && strcasecmp(np->full_name, path) == 0) return np; return NULL; } /* * Find the device_node with a given phandle. */ static struct device_node * __init find_phandle(phandle ph) { struct device_node *np; for (np = allnodes; np != 0; np = np->allnext) if (np->linux_phandle == ph) return np; return NULL; } /* * Find a property with a given name for a given node * and return the value. */ unsigned char * get_property(struct device_node *np, const char *name, int *lenp) { struct property *pp; for (pp = np->properties; pp != 0; pp = pp->next) if (strcmp(pp->name, name) == 0) { if (lenp != 0) *lenp = pp->length; return pp->value; } return 0; } /* * Add a property to a node */ void __openfirmware prom_add_property(struct device_node* np, struct property* prop) { struct property **next = &np->properties; prop->next = NULL; while (*next) next = &(*next)->next; *next = prop; } #if 0 void __openfirmware print_properties(struct device_node *np) { struct property *pp; char *cp; int i, n; for (pp = np->properties; pp != 0; pp = pp->next) { printk(KERN_INFO "%s", pp->name); for (i = strlen(pp->name); i < 16; ++i) printk(" "); cp = (char *) pp->value; for (i = pp->length; i > 0; --i, ++cp) if ((i > 1 && (*cp < 0x20 || *cp > 0x7e)) || (i == 1 && *cp != 0)) break; if (i == 0 && pp->length > 1) { /* looks like a string */ printk(" %s\n", (char *) pp->value); } else { /* dump it in hex */ n = pp->length; if (n > 64) n = 64; if (pp->length % 4 == 0) { unsigned int *p = (unsigned int *) pp->value; n /= 4; for (i = 0; i < n; ++i) { if (i != 0 && (i % 4) == 0) printk("\n "); printk(" %08x", *p++); } } else { unsigned char *bp = pp->value; for (i = 0; i < n; ++i) { if (i != 0 && (i % 16) == 0) printk("\n "); printk(" %02x", *bp++); } } printk("\n"); if (pp->length > 64) printk(" ... (length = %d)\n", pp->length); } } } #endif void __init abort(void) { #ifdef CONFIG_XMON xmon(NULL); #endif for (;;) prom_exit(); } /* Verify bi_recs are good */ static struct bi_record * prom_bi_rec_verify(struct bi_record *bi_recs) { struct bi_record *first, *last; if ( bi_recs == NULL || bi_recs->tag != BI_FIRST ) return NULL; last = (struct bi_record *)bi_recs->data[0]; if ( last == NULL || last->tag != BI_LAST ) return NULL; first = (struct bi_record *)last->data[0]; if ( first == NULL || first != bi_recs ) return NULL; return bi_recs; } static unsigned long prom_bi_rec_reserve(unsigned long mem) { unsigned long offset = reloc_offset(); struct prom_t *_prom = PTRRELOC(&prom); struct bi_record *rec; if ( _prom->bi_recs != NULL) { for ( rec=_prom->bi_recs; rec->tag != BI_LAST; rec=bi_rec_next(rec) ) { switch (rec->tag) { #ifdef CONFIG_BLK_DEV_INITRD case BI_INITRD: lmb_reserve(rec->data[0], rec->data[1]); break; #endif /* CONFIG_BLK_DEV_INITRD */ } } /* The next use of this field will be after relocation * is enabled, so convert this physical address into a * virtual address. */ _prom->bi_recs = PTRUNRELOC(_prom->bi_recs); } return mem; }
27.123495
139
0.620506
[ "model" ]
919b4bf171775c0a9af0720e3802e6b443f471d8
6,938
h
C
src/Behaviors/Agents/Agent.h
parasol-ppl/PPL
04de04b23e0368e576d2136fee8729de44a3eda5
[ "BSD-3-Clause" ]
null
null
null
src/Behaviors/Agents/Agent.h
parasol-ppl/PPL
04de04b23e0368e576d2136fee8729de44a3eda5
[ "BSD-3-Clause" ]
null
null
null
src/Behaviors/Agents/Agent.h
parasol-ppl/PPL
04de04b23e0368e576d2136fee8729de44a3eda5
[ "BSD-3-Clause" ]
null
null
null
#ifndef AGENT_H_ #define AGENT_H_ #include <cstddef> #include <memory> #include <vector> #include "MPProblem/Robot/Control.h" class Cfg; class MPTask; class Robot; class StepFunction; class XMLNode; //////////////////////////////////////////////////////////////////////////////// /// The decision-making faculties of a robot. /// /// @details Agents are used with simulated robots. On each time step of the /// simulation, the agent decides what the robot will do and sends an /// appropriate command to the controller. //////////////////////////////////////////////////////////////////////////////// class Agent { protected: ///@name Internal State ///@{ Robot* const m_robot; ///< The robot that this agent controls. mutable bool m_initialized{false}; ///< Is the agent initialized? std::shared_ptr<MPTask> m_task; ///< The task this agent is working on. ControlSet m_currentControls; ///< The current control set. size_t m_stepsRemaining{0}; ///< Steps remaining on current controls. bool m_debug{true}; ///< Toggle debug messages. /// Specifies the type of agent for heterogenous multiagent teams. std::string m_capability; ///< Step function to define agent behaviors. std::unique_ptr<StepFunction> m_stepFunction; ///@} public: ///@name Construction ///@{ /// Create an agent for a robot. /// @param _r The robot which this agent will reason for. Agent(Robot* const _r); /// Create an agent for a robot. /// @param _r The robot which this agent will reason for. /// @param _node The XML node to parse. Agent(Robot* const _r, XMLNode& _node); /// Copy an agent for another robot. /// @param _r The destination robot. /// @param _a The agent to copy. Agent(Robot* const _r, const Agent& _a); /// Create a dynamically-allocated agent from an XML node. /// @param _r The robot which this agent will reason for. /// @param _node The XML node to parse. /// @return An agent of the type specified by _node. static std::unique_ptr<Agent> Factory(Robot* const _r, XMLNode& _node); /// Create a copy of this agent for another robot. This is provided so that /// we can copy an agent without knowing its type. /// @param _r The robot which this cloned agent will reason for. /// @return A copy of the agent. virtual std::unique_ptr<Agent> Clone(Robot* const _r) const = 0; virtual ~Agent(); ///@} ///@name Agent Properties ///@{ /// Get the robot object to which this agent belongs. Robot* GetRobot() const noexcept; /// Is this agent a child of some group/aggregate? virtual bool IsChild() const noexcept; ///@} ///@name Task Management ///@{ /// Set the task for this agent. /// @param _task The new task for this agent. Should be owned by the /// MPProblem. virtual void SetTask(const std::shared_ptr<MPTask> _task); /// Get the task that the agent is currently working on. std::shared_ptr<MPTask> GetTask() const noexcept; /// Resets the start constraint of the current task to the robot's current /// position. virtual void ResetStartConstraint(); ///@} ///@name Simulation Interface ///@{ /// Set up the agent before running. Anything that needs to be done only once /// on first starting should go here. virtual void Initialize() = 0; /// Decide what to do on each time step in the simulation. The agent should /// implement its decision by sending commands to the robot's controller. /// @param _dt The timestep length. virtual void Step(const double _dt) = 0; /// Tear down the agent. Release any resources and reset the object to its /// pre-initialize state. virtual void Uninitialize() = 0; /// Find the smallest time interval which is an integer multiple of the /// problem time resolution and larger than the hardware time (if any). size_t MinimumSteps() const; /// Check for proximity to other robots and return those that lie within /// some threshold. /// @WARNING This checks the distance between the robots' reference points; /// it does not indicate the minimum distance between their hulls. /// @param _distance The distance threshold. /// @return The vector of Robots within the threshold. std::vector<Agent*> ProximityCheck(const double _distance) const; ///@} ///@name Agent Control ///@{ /// Stop the robot in simulation (places 0s in all 6 velocity dofs). /// @WARNING Arbitrarily setting the velocity does not respect the robot's /// dynamics. It is suitable for debugging and freezing a scenario upon /// completion, but it is not physically realistic. void Halt(); /// Orders the agent to stop itself at its current position. It will ask the /// controller to choose actions which stay as close as possible to the /// current position. /// @param _steps The number of steps to stop for. void PauseAgent(const size_t _steps); ///@} ///@name Accessors ///@{ /// Get the type of agent const std::string& GetCapability() const noexcept; ///@} protected: /// Instruct the agent to enqueue a command for gathering sensor readings. void Localize(); /// Is the agent waiting on sensor data? bool IsLocalizing() const noexcept; /// Estimate the state of the robot from the last localization data. Cfg EstimateState(); /// Continue executing the last controls if time remains. /// @return True if time is left on the last controls, false if /// the agent is finished and needs new controls. bool ContinueLastControls(); /// Execute a set of controls on the simulated robot, and additionally on the hardware if /// present. /// @param _c The controls to execute. /// @param _steps The number of time steps to execute the control. virtual void ExecuteControls(const ControlSet& _c, const size_t _steps); /// Execute a set of controls on the simulated robot. /// @param _c The controls to execute. virtual void ExecuteControlsSimulation(const ControlSet& _c, const size_t _steps); /// Execute a set of controls on the hardware if present. /// @param _c The controls to execute. /// @param _steps The number of time steps to execute the control. virtual void ExecuteControlsHardware(const ControlSet& _c, const size_t _steps); ///@} private: ///@name Disabled Functions ///@{ /// Regular copy/move is disabled because each agent must be created for a /// specific robot object. Agent(const Agent&) = delete; Agent(Agent&&) = delete; Agent& operator=(const Agent&) = delete; Agent& operator=(Agent&&) = delete; ///@} }; #endif
32.881517
93
0.643557
[ "object", "vector" ]
91ae8746e8f0c8cef22bbb13522d2de47a5b5093
3,100
h
C
regexexpression.h
Monksc/regexsentenses
7167022abd88cd15d774e0e3df0e1cc6c4bbe24e
[ "MIT" ]
1
2021-06-17T14:02:06.000Z
2021-06-17T14:02:06.000Z
regexexpression.h
Monksc/regexsentenses
7167022abd88cd15d774e0e3df0e1cc6c4bbe24e
[ "MIT" ]
null
null
null
regexexpression.h
Monksc/regexsentenses
7167022abd88cd15d774e0e3df0e1cc6c4bbe24e
[ "MIT" ]
null
null
null
// // regexexpression.h // // // Created by Cameron Monks on 06/09/2021 // Copyright © 2021 cameronmonks. All rights reserved. // #ifndef regexexpression_h #define regexexpression_h #include "vector.h" struct regexcharacter { char minc; char maxc; char currentc; }; struct regexcharactergroup { struct vector characters; }; struct regexoptions { struct vector groups; size_t index; }; struct regexrange { struct regexoptions baseoption; struct vector options; unsigned minlen; unsigned maxlen; }; struct regexexpression { struct vector ranges; }; void regexexpression_init(struct regexexpression * self); void regexrange_init(struct regexrange * self, struct regexrange baseoption, unsigned minlen, unsigned maxlen); void regexoptions_init(struct regexoptions * self); void regexcharactergroup_init(struct regexcharactergroup * self); void regexexpression_deinit(struct regexexpression * self); void regexrange_deinit(struct regexrange * self); void regexoptions_deinit(struct regexoptions * self); void regexcharactergroup_deinit(struct regexcharactergroup * self); void regexexpression_copy(struct regexexpression * dst, const struct regexexpression * src); void regexrange_copy(struct regexrange * dst, const struct regexrange * src); void regexoptions_copy(struct regexoptions * dst, const struct regexoptions * src); void regexcharactergroup_copy(struct regexcharactergroup * dst, const struct regexcharactergroup * src); void regexcharacter_copy(struct regexcharacter * dst, const struct regexcharacter * src); void regexexpression_push(struct regexexpression * self, struct regexrange item); void regexrange_push(struct regexrange * self, struct regexoptions item); void regexoptions_push(struct regexoptions * self, struct regexcharactergroup item); void regexcharactergroup_push(struct regexcharactergroup * self, struct regexcharacter item); void regexexpression_debug(struct regexexpression * self); void regexrange_debug(struct regexrange * self); void regexoptions_debug(struct regexoptions * self); void regexcharactergroup_debug(struct regexcharactergroup * self); void regexcharacter_debug(struct regexcharacter * self); void regexexpression_print(struct regexexpression * self); void regexrange_print(struct regexrange * self); void regexoptions_print(struct regexoptions * self); void regexcharactergroup_print(struct regexcharactergroup * self); void regexcharacter_print(struct regexcharacter * self); void regexexpression_reset(struct regexexpression * self); void regexrange_reset(struct regexrange * self); void regexoptions_reset(struct regexoptions * self); void regexcharactergroup_reset(struct regexcharactergroup * self); void regexcharacter_reset(struct regexcharacter * self); int regexexpression_inc(struct regexexpression * self); int regexrange_inc(struct regexrange * self); int regexoptions_inc(struct regexoptions * self); int regexcharactergroup_inc(struct regexcharactergroup * self); int regexcharacter_inc(struct regexcharacter * self); #endif /* regexexpression_h */
32.978723
93
0.799677
[ "vector" ]
91b739bbd791c65ff6c9fc0cd4c605a5deee5a2e
922
h
C
courgette/rel32_finder_x86.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
courgette/rel32_finder_x86.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
courgette/rel32_finder_x86.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2015 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 COURGETTE_REL32_FINDER_X86_H_ #define COURGETTE_REL32_FINDER_X86_H_ #include <stdint.h> #include <vector> #include "courgette/image_utils.h" #include "courgette/rel32_finder.h" namespace courgette { // This implementation performs naive scan for opcodes having rel32 as // arguments, disregarding instruction alignment. class Rel32FinderX86 : public Rel32Finder { public: Rel32FinderX86(RVA relocs_start_rva, RVA relocs_end_rva); ~Rel32FinderX86() override = default; void Find(const uint8_t* start_pointer, const uint8_t* end_pointer, RVA start_rva, RVA end_rva, const std::vector<RVA>& abs32_locations) override; }; } // namespace courgette #endif // COURGETTE_REL32_FINDER_X86_H_
27.117647
73
0.745119
[ "vector" ]
91bcc2adc551af279383e9a6ed76b238edb4b3cf
721
h
C
VyperDisplayManager/input_parser.h
ScottyMac52/VDM
28829e7e7b8d81c55e49d88ab4c2833432c16082
[ "MIT" ]
null
null
null
VyperDisplayManager/input_parser.h
ScottyMac52/VDM
28829e7e7b8d81c55e49d88ab4c2833432c16082
[ "MIT" ]
null
null
null
VyperDisplayManager/input_parser.h
ScottyMac52/VDM
28829e7e7b8d81c55e49d88ab4c2833432c16082
[ "MIT" ]
null
null
null
#pragma once class input_parser { public: input_parser(int& argc, wchar_t** argv) { for (auto i = 0; i < argc; ++i) { this->tokens_.emplace_back(argv[i]); } }; [[nodiscard]] const std::wstring& get_cmd_option(const std::wstring& option) const { auto itr = std::find(this->tokens_.begin(), this->tokens_.end(), option); if (itr != this->tokens_.end() && ++itr != this->tokens_.end()) { return *itr; } static const std::wstring empty_string; return empty_string; }; [[nodiscard]] bool cmd_option_exists(const std::wstring& option) const { return std::find(this->tokens_.begin(), this->tokens_.end(), option) != this->tokens_.end(); }; private: std::vector <std::wstring> tokens_; };
23.258065
85
0.649098
[ "vector" ]
91d21dd14f5225445679255d19dbdef387fa52b1
3,150
h
C
06-class-design/readerEx.06.03/GRectangle.h
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
81
2018-11-15T21:23:19.000Z
2022-03-06T09:46:36.000Z
06-class-design/readerEx.06.03/GRectangle.h
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
null
null
null
06-class-design/readerEx.06.03/GRectangle.h
heavy3/programming-abstractions
e10eab5fe7d9ca7d7d4cc96551524707214e43a8
[ "MIT" ]
41
2018-11-15T21:23:24.000Z
2022-02-24T03:02:26.000Z
// // GRectangle.h // // This file mimics the interface exported for the // GRectangle class from the Stanford C++ library. // // -------------------------------------------------------------------------- // Attribution: "Programming Abstractions in C++" by Eric Roberts // Chapter 6, Exercise 3 // Stanford University, Autumn Quarter 2012 // http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1136/materials/CS106BX-Reader.pdf // -------------------------------------------------------------------------- // // Created by Glenn Streiff on 12/7/15. // Copyright © 2015 Glenn Streiff. All rights reserved. // #ifndef GRectangle_h #define GRectangle_h #include <string> #include <iostream> #include "error.h" // // Class: GRectangle // ----------------- // This class represents a rectangle on the graphics plane and is // conventionally used to denote the bounding box for an object. // class GRectangle { public: // // Constructor: GRectangle // Usage: GRectangle empty; // GRectangle r(x, y, width, height); // ----------------------------------------- // Creates a GRectangle object with the specified components. If these // parameters are not supplied, the default constructor sets these fields // to 0. // GRectangle(); GRectangle(double x, double y, double width, double height); // // Method: getX // Usage: double x = r.getX(); // --------------------------- // Returns the x component of the rectangle. // double getX() const; // // Method: getY // Usage: double x = r.getY(); // --------------------------- // Returns the y component of the rectangle. // double getY() const; // // Method: getWidth // Usage: double width = r.getWidth(); // ----------------------------------- // Returns the width component of the rectangle. // double getWidth() const; // // Method: getHeight // Usage: double height = r.getHeight(); // ----------------------------------- // Returns the height component of the rectangle. // double getHeight() const; // // Method: isEmpty // Usage: if (r.isEmpty()) ... // --------------------------- // Returns true if the rectangle is empty. // bool isEmpty() const; // // Method: contains // Usage: if (r.contains(pt)) ... // if (r.contains(x, y)) ... // -------------------------------- // Returns true if the rectangle contains the given point, which may be // specified either as a point or as distinct coordinates. // // bool contains(GPoint pt) const; bool contains(double x, double y) const; // // Method: toString // Usage: string str = r.toString(); // --------------------------------- // Converts the GRectangle to a string in the form // "(x, y, width, height)". // std::string toString() const; private: double x, y; double width, height; }; std::ostream & operator<<(std::ostream & os, GRectangle rect); #endif // GRectangle_h
25.403226
91
0.515556
[ "object" ]
91d47500d46006dc4cd2e7a74878d404d48711c7
3,592
h
C
Modules/Loadable/Models/Widgets/qMRMLModelDisplayNodeWidget.h
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Modules/Loadable/Models/Widgets/qMRMLModelDisplayNodeWidget.h
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Modules/Loadable/Models/Widgets/qMRMLModelDisplayNodeWidget.h
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
/*============================================================================== Program: 3D Slicer Copyright (c) Kitware Inc. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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 thes License. This file was originally developed by Julien Finet, Kitware Inc. and was partially funded by NIH grant 3P41RR013218-12S1 ==============================================================================*/ #ifndef __qMRMLModelDisplayNodeWidget_h #define __qMRMLModelDisplayNodeWidget_h // Qt includes #include <QWidget> // CTK includes #include <ctkVTKObject.h> // qMRML includes #include "qSlicerModelsModuleWidgetsExport.h" class qMRMLModelDisplayNodeWidgetPrivate; class vtkMRMLScene; class vtkMRMLNode; class vtkMRMLModelDisplayNode; class vtkMRMLColorNode; class vtkMRMLSelectionNode; class Q_SLICER_QTMODULES_MODELS_WIDGETS_EXPORT qMRMLModelDisplayNodeWidget : public QWidget { Q_OBJECT QVTK_OBJECT Q_PROPERTY(ControlMode autoScalarRange READ autoScalarRange WRITE setAutoScalarRange) Q_PROPERTY(double minimumValue READ minimumValue WRITE setMinimumValue) Q_PROPERTY(double maximumValue READ maximumValue WRITE setMaximumValue) Q_ENUMS(ControlMode) public: qMRMLModelDisplayNodeWidget(QWidget *parent=0); virtual ~qMRMLModelDisplayNodeWidget(); vtkMRMLModelDisplayNode* mrmlModelDisplayNode()const; vtkMRMLNode* mrmlDisplayableNode()const; bool scalarsVisibility()const; QString activeScalarName()const; vtkMRMLColorNode* scalarsColorNode()const; enum ControlMode { Auto = 0, Manual = 1 }; /// Set Auto/Manual mode void setAutoScalarRange(ControlMode autoScalarRange); ControlMode autoScalarRange() const; /// Get minimum of the scalar display range double minimumValue()const; /// Get maximum of the scalar display range double maximumValue()const; signals: /// /// Signal sent if the min/max value is updated void minMaxValuesChanged(double min, double max); /// /// Signal sent if the auto/manual value is updated void autoScalarRangeValueChanged(ControlMode value); public slots: /// Set the volume node to display void setMRMLModelDisplayNode(vtkMRMLModelDisplayNode *node); /// Utility function to be connected with generic signals void setMRMLModelDisplayNode(vtkMRMLNode *node); /// Utility function to be connected with generic signals, /// it internally shows the 1st display node. /// can be set from a model node or a model hierarchy node void setMRMLModelOrHierarchyNode(vtkMRMLNode* modelNode); void setScalarsVisibility(bool); void setActiveScalarName(const QString&); void setScalarsColorNode(vtkMRMLNode*); void setScalarsColorNode(vtkMRMLColorNode*); void setScalarsDisplayRange(double min, double max); void setScalarsScalarRangeFlag(); /// Set Auto/Manual mode void setAutoScalarRange(int autoScalarRange); /// Set min/max range void setMinimumValue(double min); void setMaximumValue(double max); protected slots: void updateWidgetFromMRML(); vtkMRMLSelectionNode* getSelectionNode(vtkMRMLScene *mrmlScene); protected: QScopedPointer<qMRMLModelDisplayNodeWidgetPrivate> d_ptr; private: Q_DECLARE_PRIVATE(qMRMLModelDisplayNodeWidget); Q_DISABLE_COPY(qMRMLModelDisplayNodeWidget); }; #endif
29.203252
91
0.754176
[ "model", "3d" ]
91d726bf22f481fe8f4c88671b9e2c14b90dc3c6
7,939
h
C
similarity_search/lshkit/include/lshkit/forest.h
huonw/nmslib
2e424ef7c6eff10ecaf47392fd99f93f645e752f
[ "Apache-2.0" ]
150
2016-06-03T16:39:13.000Z
2021-05-24T05:32:56.000Z
similarity_search/lshkit/include/lshkit/forest.h
huonw/nmslib
2e424ef7c6eff10ecaf47392fd99f93f645e752f
[ "Apache-2.0" ]
7
2016-06-03T13:43:21.000Z
2019-12-28T07:42:02.000Z
similarity_search/lshkit/include/lshkit/forest.h
huonw/nmslib
2e424ef7c6eff10ecaf47392fd99f93f645e752f
[ "Apache-2.0" ]
42
2016-05-18T05:53:00.000Z
2021-05-27T19:57:52.000Z
/* Copyright (C) 2008 Wei Dong <wdong@princeton.edu>. All Rights Reserved. This file is part of LSHKIT. LSHKIT 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. LSHKIT 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 LSHKIT. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __LSHKIT_FOREST__ #define __LSHKIT_FOREST__ /** * \file forest.h * \brief A preliminary implementation of LSH Forest index. * * This is a preliminary implementation of main memory LSH Forest index. * The implementation is largely based on the WWW'05 LSH Forest paper. * The descend and synchascend algorithms are implemented in a * different but equivalent way, so the candidate set do not have to * be explicitly generated. I also made a simplification to the synchascending * algorithm, so that the original line \code while (x > 0 and (|P| < cl or |distinct(P)| < m)) { \endcode * is simplified to \code while (x > 0 and |P| < M) { \endcode * the deduplication is left to the scanning process. * * The implementation is not efficient. The initial goal of this implementation * is to study the selectivity of the algorithm. I'll further optimize the * implementation if selectivity is proved competitive. * * Reference * * Mayank Bawa , Tyson Condie , Prasanna Ganesan, LSH forest: self-tuning * indexes for similarity search, Proceedings of the 14th international * conference on World Wide Web, May 10-14, 2005, Chiba, Japan. * */ #include <algorithm> #include <lshkit/common.h> #include <lshkit/topk.h> namespace lshkit { /// LSH Forest index /** * @param LSH LSH class. * @param KEY key type. */ template <typename LSH, typename KEY> class ForestIndex { BOOST_CONCEPT_ASSERT((LshConcept<LSH>)); public: typedef typename LSH::Parameter Parameter; typedef typename LSH::Domain Domain; typedef KEY Key; private: struct Tree { std::vector<LSH> lsh; // the hash functions struct Node { size_t size; // total # points in subtree std::vector<Node *> children; std::vector<Key> data; Node () : size(0) { } ~Node () { BOOST_FOREACH(Node *n, children) { if (n != 0) delete n; } } bool empty () const { return size == 0; } template <typename ACCESSOR> void insert (Tree *tree, unsigned depth, Key key, ACCESSOR &acc) { ++size; if (children.empty()) { data.push_back(key); if (depth < tree->lsh.size() && data.size() > 1) { // split LSH &lsh = tree->lsh[depth]; if (lsh.getRange() == 0) throw std::logic_error("LSH WITH UNLIMITED HASH VALUE CANNOT BE USED IN LSH FOREST."); children.resize(lsh.getRange()); BOOST_FOREACH(Key key, data) { unsigned h = lsh(acc(key)); if (children[h] == 0) { children[h] = new Node(); } children[h]->insert(tree, depth+1, key, acc); } data.clear(); } } else { unsigned h = tree->lsh[depth](acc(key)); if (children[h] == 0) { children[h] = new Node(); } children[h]->insert(tree, depth+1, key, acc); } } template <typename SCANNER> void scan (Domain val, SCANNER &scanner) const { if (!children.empty()) { BOOST_FOREACH(const Node *n, children) { if (n != 0) { n->scan(val, scanner); } } } if (!data.empty()) { BOOST_FOREACH(Key key, data) { scanner(key); } } } } *root; public: Tree (): root(0) { } template <typename ENGINE> void reset (const Parameter &param, ENGINE &engine, unsigned depth) { lsh.resize(depth); BOOST_FOREACH(LSH &h, lsh) { h.reset(param, engine); } root = new Node(); } ~Tree () { if (root != 0) delete root; } template <typename ACCESSOR> void insert (Key key, ACCESSOR &acc) { root->insert(this, 0, key, acc); } void lookup (Domain val, std::vector<const Node *> *nodes) const { const Node *cur = root; unsigned depth = 0; nodes->clear(); for (;;) { nodes->push_back(cur); if (cur->children.empty()) break; unsigned h = lsh[depth](val); cur = cur->children[h]; if (cur == 0) break; ++depth; } } }; friend struct Tree; std::vector<Tree> trees; public: ForestIndex() { } /// Initialize the LSH Forest index. /** * @param param LSH parameters. * @param engine random number generator. * @param L number of trees in the forest. * @param depth maximal depth of the forest. */ template <typename Engine> void init(const Parameter &param, Engine &engine, unsigned L, unsigned depth) { trees.resize(L); BOOST_FOREACH(Tree &t, trees) { t.reset(param, engine, depth); } } /// Insert a point to the forest. /** * @param key The key to be inserted. * @param acc The accessor to retrieve the data corresponding to keys. * * We might need to rebalance the trees, so an accessor is * needed to retrieve data points. */ template <typename ACCESSOR> void insert (Key key, ACCESSOR &acc) { BOOST_FOREACH(Tree &t, trees) { t.insert(key, acc); } } /// Query for K-NNs. /** * @param val the query object. * @param M lower bound of the total number of points to scan. * @param scanner the functional object to passed keys to. */ template <typename SCANNER> void query (Domain val, unsigned M, SCANNER &scanner) const { std::vector<std::vector<const typename Tree::Node *> > list(trees.size()); for (unsigned i = 0; i < trees.size(); ++i) { trees[i].lookup(val, &list[i]); } // Find the minimal depth covering at least M points unsigned d = 0; for (;;) { unsigned s = 0; for (unsigned i = 0; i < list.size(); ++i) { if (d < list[i].size()) { s += list[i][d]->size; } } if (s < M) break; ++d; } if (d > 0) --d; // recursively scan the nodes for (unsigned i = 0; i < list.size(); ++i) { if (d < list[i].size()) { list[i][d]->scan(val, scanner); } } } }; } #endif
29.295203
135
0.509888
[ "object", "vector" ]
91dcf567b68312eae791e70d28b75913f73e24f5
31,562
h
C
Engine/Source/Runtime/RHI/Public/RHIContext.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/RHI/Public/RHIContext.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/RHI/Public/RHIContext.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*============================================================================= RHIContext.h: Interface for RHI Contexts =============================================================================*/ #pragma once #include "Misc/AssertionMacros.h" #include "Math/Color.h" #include "Math/IntPoint.h" #include "Math/IntRect.h" #include "Math/Box2D.h" #include "Math/PerspectiveMatrix.h" #include "Math/TranslationMatrix.h" #include "Math/ScaleMatrix.h" #include "Math/Float16Color.h" #include "Modules/ModuleInterface.h" // NvFlow begin #include "GameWorks/RHINvFlow.h" // NvFlow end class FRHIDepthRenderTargetView; class FRHIRenderTargetView; class FRHISetRenderTargetsInfo; struct FResolveParams; struct FViewportBounds; enum class EAsyncComputeBudget; enum class EResourceTransitionAccess; enum class EResourceTransitionPipeline; FORCEINLINE FBoundShaderStateRHIRef RHICreateBoundShaderState( FVertexDeclarationRHIParamRef VertexDeclaration, FVertexShaderRHIParamRef VertexShader, FHullShaderRHIParamRef HullShader, FDomainShaderRHIParamRef DomainShader, FPixelShaderRHIParamRef PixelShader, FGeometryShaderRHIParamRef GeometryShader ); /** Context that is capable of doing Compute work. Can be async or compute on the gfx pipe. */ class IRHIComputeContext { public: /** * Compute queue will wait for the fence to be written before continuing. */ virtual void RHIWaitComputeFence(FComputeFenceRHIParamRef InFence) = 0; /** *Sets the current compute shader. */ virtual void RHISetComputeShader(FComputeShaderRHIParamRef ComputeShader) = 0; virtual void RHISetComputePipelineState(FRHIComputePipelineState* ComputePipelineState) { if (ComputePipelineState) { FRHIComputePipelineStateFallback* FallbackState = static_cast<FRHIComputePipelineStateFallback*>(ComputePipelineState); RHISetComputeShader(FallbackState->GetComputeShader()); } } virtual void RHIDispatchComputeShader(uint32 ThreadGroupCountX, uint32 ThreadGroupCountY, uint32 ThreadGroupCountZ) = 0; virtual void RHIDispatchIndirectComputeShader(FVertexBufferRHIParamRef ArgumentBuffer, uint32 ArgumentOffset) = 0; virtual void RHISetAsyncComputeBudget(EAsyncComputeBudget Budget) = 0; /** * Explicitly transition a UAV from readable -> writable by the GPU or vice versa. * Also explicitly states which pipeline the UAV can be used on next. For example, if a Compute job just wrote this UAV for a Pixel shader to read * you would do EResourceTransitionAccess::Readable and EResourceTransitionPipeline::EComputeToGfx * * @param TransitionType - direction of the transition * @param EResourceTransitionPipeline - How this UAV is transitioning between Gfx and Compute, if at all. * @param InUAVs - array of UAV objects to transition * @param NumUAVs - number of UAVs to transition * @param WriteComputeFence - Optional ComputeFence to write as part of this transition */ virtual void RHITransitionResources(EResourceTransitionAccess TransitionType, EResourceTransitionPipeline TransitionPipeline, FUnorderedAccessViewRHIParamRef* InUAVs, int32 NumUAVs, FComputeFenceRHIParamRef WriteComputeFence) = 0; /** Set the shader resource view of a surface. This is used for binding TextureMS parameter types that need a multi sampled view. */ virtual void RHISetShaderTexture(FComputeShaderRHIParamRef PixelShader, uint32 TextureIndex, FTextureRHIParamRef NewTexture) = 0; /** * Sets sampler state. * @param GeometryShader The geometry shader to set the sampler for. * @param SamplerIndex The index of the sampler. * @param NewState The new sampler state. */ virtual void RHISetShaderSampler(FComputeShaderRHIParamRef ComputeShader, uint32 SamplerIndex, FSamplerStateRHIParamRef NewState) = 0; /** * Sets a compute shader UAV parameter. * @param ComputeShader The compute shader to set the UAV for. * @param UAVIndex The index of the UAVIndex. * @param UAV The new UAV. */ virtual void RHISetUAVParameter(FComputeShaderRHIParamRef ComputeShader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV) = 0; /** * Sets a compute shader counted UAV parameter and initial count * @param ComputeShader The compute shader to set the UAV for. * @param UAVIndex The index of the UAVIndex. * @param UAV The new UAV. * @param InitialCount The initial number of items in the UAV. */ virtual void RHISetUAVParameter(FComputeShaderRHIParamRef ComputeShader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV, uint32 InitialCount) = 0; virtual void RHISetShaderResourceViewParameter(FComputeShaderRHIParamRef ComputeShader, uint32 SamplerIndex, FShaderResourceViewRHIParamRef SRV) = 0; virtual void RHISetShaderUniformBuffer(FComputeShaderRHIParamRef ComputeShader, uint32 BufferIndex, FUniformBufferRHIParamRef Buffer) = 0; virtual void RHISetShaderParameter(FComputeShaderRHIParamRef ComputeShader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) = 0; virtual void RHIPushEvent(const TCHAR* Name, FColor Color) = 0; virtual void RHIPopEvent() = 0; /** * Submit the current command buffer to the GPU if possible. */ virtual void RHISubmitCommandsHint() = 0; /** * Some RHI implementations (OpenGL) cache render state internally * Signal to RHI that cached state is no longer valid */ virtual void RHIInvalidateCachedState() {}; }; // These states are now set by the Pipeline State Object and are now deprecated class IRHIDeprecatedContext { public: /** * Set bound shader state. This will set the vertex decl/shader, and pixel shader * @param BoundShaderState - state resource */ virtual void RHISetBoundShaderState(FBoundShaderStateRHIParamRef BoundShaderState) = 0; virtual void RHISetDepthStencilState(FDepthStencilStateRHIParamRef NewState, uint32 StencilRef) = 0; virtual void RHISetRasterizerState(FRasterizerStateRHIParamRef NewState) = 0; // Allows to set the blend state, parameter can be created with RHICreateBlendState() virtual void RHISetBlendState(FBlendStateRHIParamRef NewState, const FLinearColor& BlendFactor) = 0; }; /** The interface RHI command context. Sometimes the RHI handles these. On platforms that can processes command lists in parallel, it is a separate object. */ class IRHICommandContext : public IRHIComputeContext, public IRHIDeprecatedContext { public: virtual ~IRHICommandContext() { } /** * Compute queue will wait for the fence to be written before continuing. */ virtual void RHIWaitComputeFence(FComputeFenceRHIParamRef InFence) override { if (InFence) { checkf(InFence->GetWriteEnqueued(), TEXT("ComputeFence: %s waited on before being written. This will hang the GPU."), *InFence->GetName().ToString()); } } /** *Sets the current compute shader. Mostly for compliance with platforms *that require shader setting before resource binding. */ virtual void RHISetComputeShader(FComputeShaderRHIParamRef ComputeShader) = 0; virtual void RHIDispatchComputeShader(uint32 ThreadGroupCountX, uint32 ThreadGroupCountY, uint32 ThreadGroupCountZ) = 0; virtual void RHIDispatchIndirectComputeShader(FVertexBufferRHIParamRef ArgumentBuffer, uint32 ArgumentOffset) = 0; virtual void RHISetAsyncComputeBudget(EAsyncComputeBudget Budget) override { } virtual void RHIAutomaticCacheFlushAfterComputeShader(bool bEnable) = 0; virtual void RHIFlushComputeShaderCache() = 0; // Useful when used with geometry shader (emit polygons to different viewports), otherwise SetViewPort() is simpler // @param Count >0 // @param Data must not be 0 virtual void RHISetMultipleViewports(uint32 Count, const FViewportBounds* Data) = 0; /** Clears a UAV to the multi-component value provided. */ virtual void RHIClearTinyUAV(FUnorderedAccessViewRHIParamRef UnorderedAccessViewRHI, const uint32* Values) = 0; /** * Resolves from one texture to another. * @param SourceTexture - texture to resolve from, 0 is silenty ignored * @param DestTexture - texture to resolve to, 0 is silenty ignored * @param bKeepOriginalSurface - true if the original surface will still be used after this function so must remain valid * @param ResolveParams - optional resolve params */ virtual void RHICopyToResolveTarget(FTextureRHIParamRef SourceTexture, FTextureRHIParamRef DestTexture, bool bKeepOriginalSurface, const FResolveParams& ResolveParams) = 0; /** * Explicitly transition a texture resource from readable -> writable by the GPU or vice versa. * We know rendertargets are only used as rendered targets on the Gfx pipeline, so these transitions are assumed to be implemented such * Gfx->Gfx and Gfx->Compute pipeline transitions are both handled by this call by the RHI implementation. Hence, no pipeline parameter on this call. * * @param TransitionType - direction of the transition * @param InTextures - array of texture objects to transition * @param NumTextures - number of textures to transition */ virtual void RHITransitionResources(EResourceTransitionAccess TransitionType, FTextureRHIParamRef* InTextures, int32 NumTextures) { if (TransitionType == EResourceTransitionAccess::EReadable) { const FResolveParams ResolveParams; for (int32 i = 0; i < NumTextures; ++i) { RHICopyToResolveTarget(InTextures[i], InTextures[i], true, ResolveParams); } } } /** * Explicitly transition a UAV from readable -> writable by the GPU or vice versa. * Also explicitly states which pipeline the UAV can be used on next. For example, if a Compute job just wrote this UAV for a Pixel shader to read * you would do EResourceTransitionAccess::Readable and EResourceTransitionPipeline::EComputeToGfx * * @param TransitionType - direction of the transition * @param EResourceTransitionPipeline - How this UAV is transitioning between Gfx and Compute, if at all. * @param InUAVs - array of UAV objects to transition * @param NumUAVs - number of UAVs to transition * @param WriteComputeFence - Optional ComputeFence to write as part of this transition */ virtual void RHITransitionResources(EResourceTransitionAccess TransitionType, EResourceTransitionPipeline TransitionPipeline, FUnorderedAccessViewRHIParamRef* InUAVs, int32 NumUAVs, FComputeFenceRHIParamRef WriteComputeFence) { if (WriteComputeFence) { WriteComputeFence->WriteFence(); } } void RHITransitionResources(EResourceTransitionAccess TransitionType, EResourceTransitionPipeline TransitionPipeline, FUnorderedAccessViewRHIParamRef* InUAVs, int32 NumUAVs) { RHITransitionResources(TransitionType, TransitionPipeline, InUAVs, NumUAVs, nullptr); } virtual void RHIBeginRenderQuery(FRenderQueryRHIParamRef RenderQuery) = 0; virtual void RHIEndRenderQuery(FRenderQueryRHIParamRef RenderQuery) = 0; virtual void RHIBeginOcclusionQueryBatch() = 0; virtual void RHIEndOcclusionQueryBatch() = 0; virtual void RHISubmitCommandsHint() = 0; // This method is queued with an RHIThread, otherwise it will flush after it is queued; without an RHI thread there is no benefit to queuing this frame advance commands virtual void RHIBeginDrawingViewport(FViewportRHIParamRef Viewport, FTextureRHIParamRef RenderTargetRHI) = 0; // This method is queued with an RHIThread, otherwise it will flush after it is queued; without an RHI thread there is no benefit to queuing this frame advance commands virtual void RHIEndDrawingViewport(FViewportRHIParamRef Viewport, bool bPresent, bool bLockToVsync) = 0; // This method is queued with an RHIThread, otherwise it will flush after it is queued; without an RHI thread there is no benefit to queuing this frame advance commands virtual void RHIBeginFrame() = 0; // This method is queued with an RHIThread, otherwise it will flush after it is queued; without an RHI thread there is no benefit to queuing this frame advance commands virtual void RHIEndFrame() = 0; /** * Signals the beginning of scene rendering. The RHI makes certain caching assumptions between * calls to BeginScene/EndScene. Currently the only restriction is that you can't update texture * references. */ // This method is queued with an RHIThread, otherwise it will flush after it is queued; without an RHI thread there is no benefit to queuing this frame advance commands virtual void RHIBeginScene() = 0; /** * Signals the end of scene rendering. See RHIBeginScene. */ // This method is queued with an RHIThread, otherwise it will flush after it is queued; without an RHI thread there is no benefit to queuing this frame advance commands virtual void RHIEndScene() = 0; /** * Signals the beginning and ending of rendering to a resource to be used in the next frame on a multiGPU system */ virtual void RHIBeginUpdateMultiFrameResource(FTextureRHIParamRef Texture) { /* empty default implementation */ } virtual void RHIEndUpdateMultiFrameResource(FTextureRHIParamRef Texture) { /* empty default implementation */ } virtual void RHIBeginUpdateMultiFrameResource(FUnorderedAccessViewRHIParamRef UAV) { /* empty default implementation */ } virtual void RHIEndUpdateMultiFrameResource(FUnorderedAccessViewRHIParamRef UAV) { /* empty default implementation */ } virtual void RHISetStreamSource(uint32 StreamIndex, FVertexBufferRHIParamRef VertexBuffer, uint32 Stride, uint32 Offset) = 0; virtual void RHISetStreamSource(uint32 StreamIndex, FVertexBufferRHIParamRef VertexBuffer, uint32 Offset) = 0; // @param MinX including like Win32 RECT // @param MinY including like Win32 RECT // @param MaxX excluding like Win32 RECT // @param MaxY excluding like Win32 RECT virtual void RHISetViewport(uint32 MinX, uint32 MinY, float MinZ, uint32 MaxX, uint32 MaxY, float MaxZ) = 0; virtual void RHISetStereoViewport(uint32 LeftMinX, uint32 RightMinX, uint32 LeftMinY, uint32 RightMinY, float MinZ, uint32 LeftMaxX, uint32 RightMaxX, uint32 LeftMaxY, uint32 RightMaxY, float MaxZ) { /* empty default implementation */ } // @param MinX including like Win32 RECT // @param MinY including like Win32 RECT // @param MaxX excluding like Win32 RECT // @param MaxY excluding like Win32 RECT virtual void RHISetScissorRect(bool bEnable, uint32 MinX, uint32 MinY, uint32 MaxX, uint32 MaxY) = 0; /** * This will set most relevant pipeline state. Legacy APIs are expected to set corresponding disjoint state as well. * @param GraphicsShaderState - the graphics pipeline state * This implementation is only in place while we transition/refactor. */ virtual void RHISetGraphicsPipelineState(FGraphicsPipelineStateRHIParamRef GraphicsState) { FRHIGraphicsPipelineStateFallBack* FallbackGraphicsState = static_cast<FRHIGraphicsPipelineStateFallBack*>(GraphicsState); auto& PsoInit = FallbackGraphicsState->Initializer; RHISetBoundShaderState( RHICreateBoundShaderState( PsoInit.BoundShaderState.VertexDeclarationRHI, PsoInit.BoundShaderState.VertexShaderRHI, PsoInit.BoundShaderState.HullShaderRHI, PsoInit.BoundShaderState.DomainShaderRHI, PsoInit.BoundShaderState.PixelShaderRHI, PsoInit.BoundShaderState.GeometryShaderRHI ).GetReference() ); RHISetDepthStencilState(FallbackGraphicsState->Initializer.DepthStencilState, 0); RHISetRasterizerState(FallbackGraphicsState->Initializer.RasterizerState); RHISetBlendState(FallbackGraphicsState->Initializer.BlendState, FLinearColor(1.0f, 1.0f, 1.0f)); } /** Set the shader resource view of a surface. This is used for binding TextureMS parameter types that need a multi sampled view. */ virtual void RHISetShaderTexture(FVertexShaderRHIParamRef VertexShader, uint32 TextureIndex, FTextureRHIParamRef NewTexture) = 0; /** Set the shader resource view of a surface. This is used for binding TextureMS parameter types that need a multi sampled view. */ virtual void RHISetShaderTexture(FHullShaderRHIParamRef HullShader, uint32 TextureIndex, FTextureRHIParamRef NewTexture) = 0; /** Set the shader resource view of a surface. This is used for binding TextureMS parameter types that need a multi sampled view. */ virtual void RHISetShaderTexture(FDomainShaderRHIParamRef DomainShader, uint32 TextureIndex, FTextureRHIParamRef NewTexture) = 0; /** Set the shader resource view of a surface. This is used for binding TextureMS parameter types that need a multi sampled view. */ virtual void RHISetShaderTexture(FGeometryShaderRHIParamRef GeometryShader, uint32 TextureIndex, FTextureRHIParamRef NewTexture) = 0; /** Set the shader resource view of a surface. This is used for binding TextureMS parameter types that need a multi sampled view. */ virtual void RHISetShaderTexture(FPixelShaderRHIParamRef PixelShader, uint32 TextureIndex, FTextureRHIParamRef NewTexture) = 0; /** Set the shader resource view of a surface. This is used for binding TextureMS parameter types that need a multi sampled view. */ virtual void RHISetShaderTexture(FComputeShaderRHIParamRef PixelShader, uint32 TextureIndex, FTextureRHIParamRef NewTexture) = 0; /** * Sets sampler state. * @param GeometryShader The geometry shader to set the sampler for. * @param SamplerIndex The index of the sampler. * @param NewState The new sampler state. */ virtual void RHISetShaderSampler(FComputeShaderRHIParamRef ComputeShader, uint32 SamplerIndex, FSamplerStateRHIParamRef NewState) = 0; /** * Sets sampler state. * @param GeometryShader The geometry shader to set the sampler for. * @param SamplerIndex The index of the sampler. * @param NewState The new sampler state. */ virtual void RHISetShaderSampler(FVertexShaderRHIParamRef VertexShader, uint32 SamplerIndex, FSamplerStateRHIParamRef NewState) = 0; /** * Sets sampler state. * @param GeometryShader The geometry shader to set the sampler for. * @param SamplerIndex The index of the sampler. * @param NewState The new sampler state. */ virtual void RHISetShaderSampler(FGeometryShaderRHIParamRef GeometryShader, uint32 SamplerIndex, FSamplerStateRHIParamRef NewState) = 0; /** * Sets sampler state. * @param GeometryShader The geometry shader to set the sampler for. * @param SamplerIndex The index of the sampler. * @param NewState The new sampler state. */ virtual void RHISetShaderSampler(FDomainShaderRHIParamRef DomainShader, uint32 SamplerIndex, FSamplerStateRHIParamRef NewState) = 0; /** * Sets sampler state. * @param GeometryShader The geometry shader to set the sampler for. * @param SamplerIndex The index of the sampler. * @param NewState The new sampler state. */ virtual void RHISetShaderSampler(FHullShaderRHIParamRef HullShader, uint32 SamplerIndex, FSamplerStateRHIParamRef NewState) = 0; /** * Sets sampler state. * @param GeometryShader The geometry shader to set the sampler for. * @param SamplerIndex The index of the sampler. * @param NewState The new sampler state. */ virtual void RHISetShaderSampler(FPixelShaderRHIParamRef PixelShader, uint32 SamplerIndex, FSamplerStateRHIParamRef NewState) = 0; /** * Sets a compute shader UAV parameter. * @param ComputeShader The compute shader to set the UAV for. * @param UAVIndex The index of the UAVIndex. * @param UAV The new UAV. */ virtual void RHISetUAVParameter(FComputeShaderRHIParamRef ComputeShader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV) = 0; /** * Sets a compute shader counted UAV parameter and initial count * @param ComputeShader The compute shader to set the UAV for. * @param UAVIndex The index of the UAVIndex. * @param UAV The new UAV. * @param InitialCount The initial number of items in the UAV. */ virtual void RHISetUAVParameter(FComputeShaderRHIParamRef ComputeShader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV, uint32 InitialCount) = 0; virtual void RHISetShaderResourceViewParameter(FPixelShaderRHIParamRef PixelShader, uint32 SamplerIndex, FShaderResourceViewRHIParamRef SRV) = 0; virtual void RHISetShaderResourceViewParameter(FVertexShaderRHIParamRef VertexShader, uint32 SamplerIndex, FShaderResourceViewRHIParamRef SRV) = 0; virtual void RHISetShaderResourceViewParameter(FComputeShaderRHIParamRef ComputeShader, uint32 SamplerIndex, FShaderResourceViewRHIParamRef SRV) = 0; virtual void RHISetShaderResourceViewParameter(FHullShaderRHIParamRef HullShader, uint32 SamplerIndex, FShaderResourceViewRHIParamRef SRV) = 0; virtual void RHISetShaderResourceViewParameter(FDomainShaderRHIParamRef DomainShader, uint32 SamplerIndex, FShaderResourceViewRHIParamRef SRV) = 0; virtual void RHISetShaderResourceViewParameter(FGeometryShaderRHIParamRef GeometryShader, uint32 SamplerIndex, FShaderResourceViewRHIParamRef SRV) = 0; virtual void RHISetShaderUniformBuffer(FVertexShaderRHIParamRef VertexShader, uint32 BufferIndex, FUniformBufferRHIParamRef Buffer) = 0; virtual void RHISetShaderUniformBuffer(FHullShaderRHIParamRef HullShader, uint32 BufferIndex, FUniformBufferRHIParamRef Buffer) = 0; virtual void RHISetShaderUniformBuffer(FDomainShaderRHIParamRef DomainShader, uint32 BufferIndex, FUniformBufferRHIParamRef Buffer) = 0; virtual void RHISetShaderUniformBuffer(FGeometryShaderRHIParamRef GeometryShader, uint32 BufferIndex, FUniformBufferRHIParamRef Buffer) = 0; virtual void RHISetShaderUniformBuffer(FPixelShaderRHIParamRef PixelShader, uint32 BufferIndex, FUniformBufferRHIParamRef Buffer) = 0; virtual void RHISetShaderUniformBuffer(FComputeShaderRHIParamRef ComputeShader, uint32 BufferIndex, FUniformBufferRHIParamRef Buffer) = 0; virtual void RHISetShaderParameter(FVertexShaderRHIParamRef VertexShader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) = 0; virtual void RHISetShaderParameter(FPixelShaderRHIParamRef PixelShader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) = 0; virtual void RHISetShaderParameter(FHullShaderRHIParamRef HullShader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) = 0; virtual void RHISetShaderParameter(FDomainShaderRHIParamRef DomainShader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) = 0; virtual void RHISetShaderParameter(FGeometryShaderRHIParamRef GeometryShader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) = 0; virtual void RHISetShaderParameter(FComputeShaderRHIParamRef ComputeShader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) = 0; virtual void RHISetStencilRef(uint32 StencilRef) {} virtual void RHISetBlendFactor(const FLinearColor& BlendFactor) {} virtual void RHISetRenderTargets(uint32 NumSimultaneousRenderTargets, const FRHIRenderTargetView* NewRenderTargets, const FRHIDepthRenderTargetView* NewDepthStencilTarget, uint32 NumUAVs, const FUnorderedAccessViewRHIParamRef* UAVs) = 0; virtual void RHISetRenderTargetsAndClear(const FRHISetRenderTargetsInfo& RenderTargetsInfo) = 0; // Bind the clear state of the currently set rendertargets. This is used by platforms which // need the state of the target when finalizing a hardware clear or a resource transition to SRV // The explicit bind is needed to support parallel rendering (propagate state between contexts). virtual void RHIBindClearMRTValues(bool bClearColor, bool bClearDepth, bool bClearStencil) {} virtual void RHIDrawPrimitive(uint32 PrimitiveType, uint32 BaseVertexIndex, uint32 NumPrimitives, uint32 NumInstances) = 0; virtual void RHIDrawPrimitiveIndirect(uint32 PrimitiveType, FVertexBufferRHIParamRef ArgumentBuffer, uint32 ArgumentOffset) = 0; virtual void RHIDrawIndexedIndirect(FIndexBufferRHIParamRef IndexBufferRHI, uint32 PrimitiveType, FStructuredBufferRHIParamRef ArgumentsBufferRHI, int32 DrawArgumentsIndex, uint32 NumInstances) = 0; // @param NumPrimitives need to be >0 virtual void RHIDrawIndexedPrimitive(FIndexBufferRHIParamRef IndexBuffer, uint32 PrimitiveType, int32 BaseVertexIndex, uint32 FirstInstance, uint32 NumVertices, uint32 StartIndex, uint32 NumPrimitives, uint32 NumInstances) = 0; virtual void RHIDrawIndexedPrimitiveIndirect(uint32 PrimitiveType, FIndexBufferRHIParamRef IndexBuffer, FVertexBufferRHIParamRef ArgumentBuffer, uint32 ArgumentOffset) = 0; /** * Preallocate memory or get a direct command stream pointer to fill up for immediate rendering . This avoids memcpys below in DrawPrimitiveUP * @param PrimitiveType The type (triangles, lineloop, etc) of primitive to draw * @param NumPrimitives The number of primitives in the VertexData buffer * @param NumVertices The number of vertices to be written * @param VertexDataStride Size of each vertex * @param OutVertexData Reference to the allocated vertex memory */ virtual void RHIBeginDrawPrimitiveUP(uint32 PrimitiveType, uint32 NumPrimitives, uint32 NumVertices, uint32 VertexDataStride, void*& OutVertexData) = 0; /** * Draw a primitive using the vertex data populated since RHIBeginDrawPrimitiveUP and clean up any memory as needed */ virtual void RHIEndDrawPrimitiveUP() = 0; /** * Preallocate memory or get a direct command stream pointer to fill up for immediate rendering . This avoids memcpys below in DrawIndexedPrimitiveUP * @param PrimitiveType The type (triangles, lineloop, etc) of primitive to draw * @param NumPrimitives The number of primitives in the VertexData buffer * @param NumVertices The number of vertices to be written * @param VertexDataStride Size of each vertex * @param OutVertexData Reference to the allocated vertex memory * @param MinVertexIndex The lowest vertex index used by the index buffer * @param NumIndices Number of indices to be written * @param IndexDataStride Size of each index (either 2 or 4 bytes) * @param OutIndexData Reference to the allocated index memory */ virtual void RHIBeginDrawIndexedPrimitiveUP(uint32 PrimitiveType, uint32 NumPrimitives, uint32 NumVertices, uint32 VertexDataStride, void*& OutVertexData, uint32 MinVertexIndex, uint32 NumIndices, uint32 IndexDataStride, void*& OutIndexData) = 0; /** * Draw a primitive using the vertex and index data populated since RHIBeginDrawIndexedPrimitiveUP and clean up any memory as needed */ virtual void RHIEndDrawIndexedPrimitiveUP() = 0; /** * Enabled/Disables Depth Bounds Testing with the given min/max depth. * @param bEnable Enable(non-zero)/disable(zero) the depth bounds test * @param MinDepth The minimum depth for depth bounds test * @param MaxDepth The maximum depth for depth bounds test. * The valid values for fMinDepth and fMaxDepth are such that 0 <= fMinDepth <= fMaxDepth <= 1 */ virtual void RHIEnableDepthBoundsTest(bool bEnable, float MinDepth, float MaxDepth) = 0; virtual void RHIPushEvent(const TCHAR* Name, FColor Color) = 0; virtual void RHIPopEvent() = 0; virtual void RHIUpdateTextureReference(FTextureReferenceRHIParamRef TextureRef, FTextureRHIParamRef NewTexture) = 0; // NvFlow begin virtual void NvFlowGetDeviceDesc(FRHINvFlowDeviceDesc* desc) {} virtual void NvFlowGetDepthStencilViewDesc(FTexture2DRHIParamRef depthSurface, FTexture2DRHIParamRef depthTexture, FRHINvFlowDepthStencilViewDesc* desc) {} virtual void NvFlowGetRenderTargetViewDesc(FRHINvFlowRenderTargetViewDesc* desc) {} virtual FShaderResourceViewRHIRef NvFlowCreateSRV(const FRHINvFlowResourceViewDesc* desc) { return FShaderResourceViewRHIRef(); } virtual FRHINvFlowResourceRW* NvFlowCreateResourceRW(const FRHINvFlowResourceRWViewDesc* desc, FShaderResourceViewRHIRef* pRHIRefSRV, FUnorderedAccessViewRHIRef* pRHIRefUAV) { return nullptr; } virtual void NvFlowReleaseResourceRW(FRHINvFlowResourceRW*) {} virtual void NvFlowReserveDescriptors(FRHINvFlowDescriptorReserveHandle* dstHandle, uint32 numDescriptors, uint64 lastFenceCompleted, uint64 nextFenceValue) {} virtual void NvFlowRestoreState() {} FRHINvFlowCleanup NvFlowCleanup; virtual void NvFlowWork(void(*workFunc)(void*,SIZE_T,IRHICommandContext*), void* paramData, SIZE_T numBytes) { if (workFunc) { workFunc(paramData, numBytes, this); } } // NvFlow end virtual TRefCountPtr<FRHIRenderPass> RHIBeginRenderPass(const FRHIRenderPassInfo& InInfo, const TCHAR* InName) { // Fallback... InInfo.Validate(); FRHISetRenderTargetsInfo RTInfo; InInfo.ConvertToRenderTargetsInfo(RTInfo); FRHIRenderPassFallback* RenderPass = new FRHIRenderPassFallback(InInfo, InName); RHISetRenderTargetsAndClear(RTInfo); return RenderPass; } virtual void RHIEndRenderPass(FRHIRenderPass* RenderPass) { FRHIRenderPassFallback* Fallback = (FRHIRenderPassFallback*)RenderPass; Fallback->SetEnded(); } virtual TRefCountPtr<FRHIParallelRenderPass> RHIBeginParallelRenderPass(const FRHIRenderPassInfo& InInfo, const TCHAR* InName) { // Fallback... InInfo.Validate(); FRHISetRenderTargetsInfo RTInfo; InInfo.ConvertToRenderTargetsInfo(RTInfo); RHISetRenderTargetsAndClear(RTInfo); return new FRHIParallelRenderPassFallback(InInfo, InName); } virtual void RHIEndParallelRenderPass(FRHIParallelRenderPass* RenderPass) { FRHIParallelRenderPassFallback* PassFallback = (FRHIParallelRenderPassFallback*)RenderPass; PassFallback->SetEnded(); } virtual TRefCountPtr<FRHIRenderSubPass> RHIBeginRenderSubPass(FRHIParallelRenderPass* RenderPass) { FRHIParallelRenderPassFallback* Fallback = (FRHIParallelRenderPassFallback*)RenderPass; return new FRHIRenderSubPassFallback(Fallback); } virtual void RHIEndRenderSubPass(FRHIParallelRenderPass* RenderPass, FRHIRenderSubPass* RenderSubPass) { FRHIParallelRenderPassFallback* PassFallback = (FRHIParallelRenderPassFallback*)RenderPass; FRHIRenderSubPassFallback* SubPassFallback = (FRHIRenderSubPassFallback*)RenderSubPass; check(SubPassFallback->GetParent() == RenderPass); SubPassFallback->SetEnded(); } virtual void RHICopyTexture(FTextureRHIParamRef SourceTexture, FTextureRHIParamRef DestTexture, const FResolveParams& ResolveParams) { RHICopyToResolveTarget(SourceTexture, DestTexture, true, ResolveParams); } // WaveWorks Start virtual const TArray<WaveWorksShaderInput>* RHIGetWaveWorksShaderInput() { return nullptr; } virtual const TArray<WaveWorksShaderInput>* RHIGetWaveWorksQuadTreeShaderInput() { return nullptr; } virtual FWaveWorksRHIRef RHICreateWaveWorks(const struct GFSDK_WaveWorks_Simulation_Settings& Settings, const struct GFSDK_WaveWorks_Simulation_Params& Params) { return nullptr; } virtual void RHISetWaveWorksState(FWaveWorksRHIParamRef State, const FMatrix& ViewMatrix, const TArray<uint32>& ShaderInputMappings) {} // WaveWorks End // NVCHANGE_BEGIN: Add HBAO+ #if WITH_GFSDK_SSAO virtual void RHIRenderHBAO( const FTextureRHIParamRef SceneDepthTextureRHI, const FMatrix& ProjectionMatrix, const FTextureRHIParamRef SceneNormalTextureRHI, const FMatrix& ViewMatrix, const FTextureRHIParamRef SceneColorTextureRHI, const GFSDK_SSAO_Parameters& AOParams) { checkNoEntry(); } #endif // NVCHANGE_END: Add HBAO+ // NVCHANGE_BEGIN: Add VXGI #if WITH_GFSDK_VXGI virtual void RHIVXGICleanupAfterVoxelization() { checkNoEntry(); } virtual void RHISetViewportsAndScissorRects(uint32 Count, const FViewportBounds* Viewports, const FScissorRect* ScissorRects) { checkNoEntry(); } virtual void RHIDispatchIndirectComputeShaderStructured(FStructuredBufferRHIParamRef ArgumentBuffer, uint32 ArgumentOffset) { checkNoEntry(); } virtual void RHICopyStructuredBufferData(FStructuredBufferRHIParamRef DestBuffer, uint32 DestOffset, FStructuredBufferRHIParamRef SrcBuffer, uint32 SrcOffset, uint32 DataSize) { checkNoEntry(); } virtual void RHIExecuteVxgiRenderingCommand(NVRHI::IRenderThreadCommand* pCommand) { checkNoEntry(); } #endif // NVCHANGE_END: Add VXGI };
47.966565
247
0.801343
[ "geometry", "render", "object" ]
91e4456dd17624825fa0b5b0f5cb713922f60b28
7,829
h
C
VkLayer_profiler_layer/profiler/profiler.h
lstalmir/VulkanProfiler
da06f27d71bf753bdef575ba1ed35e0acb8e84e7
[ "MIT" ]
1
2021-03-11T12:10:20.000Z
2021-03-11T12:10:20.000Z
VkLayer_profiler_layer/profiler/profiler.h
lstalmir/VulkanProfiler
da06f27d71bf753bdef575ba1ed35e0acb8e84e7
[ "MIT" ]
10
2020-12-09T15:14:11.000Z
2021-01-23T18:52:26.000Z
VkLayer_profiler_layer/profiler/profiler.h
lstalmir/VulkanProfiler
da06f27d71bf753bdef575ba1ed35e0acb8e84e7
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2021 Lukasz Stalmirski // // 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 "profiler_counters.h" #include "profiler_command_pool.h" #include "profiler_data_aggregator.h" #include "profiler_helpers.h" #include "profiler_data.h" #include "profiler_sync.h" #include "profiler_layer_objects/VkObject.h" #include "profiler_layer_objects/VkDevice_object.h" #include "profiler_layer_objects/VkQueue_object.h" #include <unordered_map> #include <unordered_set> #include <sstream> #include <string> #include "lockable_unordered_map.h" // Vendor APIs #include "intel/profiler_metrics_api.h" // Public interface #include "profiler_ext/VkProfilerEXT.h" namespace Profiler { class ProfilerCommandBuffer; /***********************************************************************************\ Structure: ProfilerConfig Description: Profiler configuration \***********************************************************************************/ struct ProfilerConfig { VkProfilerCreateFlagsEXT m_Flags; VkProfilerModeEXT m_Mode; VkProfilerSyncModeEXT m_SyncMode; }; /***********************************************************************************\ Class: DeviceProfiler Description: \***********************************************************************************/ class DeviceProfiler { public: DeviceProfiler(); static std::unordered_set<std::string> EnumerateOptionalDeviceExtensions(); static std::unordered_set<std::string> EnumerateOptionalInstanceExtensions(); VkResult Initialize( VkDevice_Object*, const VkProfilerCreateInfoEXT* ); void Destroy(); // Public interface VkResult SetMode( VkProfilerModeEXT ); VkResult SetSyncMode( VkProfilerSyncModeEXT ); DeviceProfilerFrameData GetData() const; ProfilerCommandBuffer& GetCommandBuffer( VkCommandBuffer commandBuffer ); DeviceProfilerCommandPool& GetCommandPool( VkCommandPool commandPool ); DeviceProfilerPipeline& GetPipeline( VkPipeline pipeline ); DeviceProfilerRenderPass& GetRenderPass( VkRenderPass renderPass ); void CreateCommandPool( VkCommandPool, const VkCommandPoolCreateInfo* ); void DestroyCommandPool( VkCommandPool ); void AllocateCommandBuffers( VkCommandPool, VkCommandBufferLevel, uint32_t, VkCommandBuffer* ); void FreeCommandBuffers( uint32_t, const VkCommandBuffer* ); void CreatePipelines( uint32_t, const VkGraphicsPipelineCreateInfo*, VkPipeline* ); void CreatePipelines( uint32_t, const VkComputePipelineCreateInfo*, VkPipeline* ); void DestroyPipeline( VkPipeline ); void CreateShaderModule( VkShaderModule, const VkShaderModuleCreateInfo* ); void DestroyShaderModule( VkShaderModule ); void CreateRenderPass( VkRenderPass, const VkRenderPassCreateInfo* ); void CreateRenderPass( VkRenderPass, const VkRenderPassCreateInfo2* ); void DestroyRenderPass( VkRenderPass ); void PreSubmitCommandBuffers( VkQueue, uint32_t, const VkSubmitInfo*, VkFence ); void PostSubmitCommandBuffers( VkQueue, uint32_t, const VkSubmitInfo*, VkFence ); void FinishFrame(); void AllocateMemory( VkDeviceMemory, const VkMemoryAllocateInfo* ); void FreeMemory( VkDeviceMemory ); void SetObjectName( VkObject, const char* ); void SetDefaultObjectName( VkObject ); void SetDefaultObjectName( VkPipeline ); template<typename VkObjectTypeEnumT> void SetObjectName( uint64_t, VkObjectTypeEnumT, const char* ); public: VkDevice_Object* m_pDevice; ProfilerConfig m_Config; mutable std::mutex m_SubmitMutex; mutable std::mutex m_PresentMutex; mutable std::mutex m_DataMutex; DeviceProfilerFrameData m_Data; ProfilerDataAggregator m_DataAggregator; uint32_t m_CurrentFrame; uint64_t m_LastFrameBeginTimestamp; CpuTimestampCounter m_CpuTimestampCounter; CpuEventFrequencyCounter m_CpuFpsCounter; ConcurrentMap<VkDeviceMemory, VkMemoryAllocateInfo> m_Allocations; DeviceProfilerMemoryData m_MemoryData; ConcurrentMap<VkCommandBuffer, std::unique_ptr<ProfilerCommandBuffer>> m_pCommandBuffers; ConcurrentMap<VkCommandPool, std::unique_ptr<DeviceProfilerCommandPool>> m_pCommandPools; ConcurrentMap<VkShaderModule, uint32_t> m_ShaderModuleHashes; ConcurrentMap<VkPipeline, DeviceProfilerPipeline> m_Pipelines; ConcurrentMap<VkRenderPass, DeviceProfilerRenderPass> m_RenderPasses; VkFence m_SubmitFence; VkPerformanceConfigurationINTEL m_PerformanceConfigurationINTEL; ProfilerMetricsApi_INTEL m_MetricsApiINTEL; DeviceProfilerSynchronization m_Synchronization; VkResult InitializeINTEL(); ProfilerShaderTuple CreateShaderTuple( const VkGraphicsPipelineCreateInfo& ); ProfilerShaderTuple CreateShaderTuple( const VkComputePipelineCreateInfo& ); void CreateInternalPipeline( DeviceProfilerPipelineType, const char* ); void SetDefaultObjectName( const DeviceProfilerPipeline& pipeline ); decltype(m_pCommandBuffers)::iterator FreeCommandBuffer( VkCommandBuffer ); decltype(m_pCommandBuffers)::iterator FreeCommandBuffer( decltype(m_pCommandBuffers)::iterator ); }; /***********************************************************************************\ Function: SetObjectName Description: Sets or restores default object name. \***********************************************************************************/ template<typename VkObjectTypeEnumT> inline void DeviceProfiler::SetObjectName( uint64_t objectHandle, VkObjectTypeEnumT objectType, const char* pObjectName ) { const auto objectTypeTraits = VkObject_Runtime_Traits::FromObjectType( objectType ); // Don't waste memory for storing unnecessary debug names if( objectTypeTraits.ShouldHaveDebugName ) { VkObject object( objectHandle, objectTypeTraits ); // VK_EXT_debug_utils // Revision 2 (2020-04-03): pObjectName can be nullptr if( (pObjectName) && (std::strlen( pObjectName ) > 0) ) { // Set custom object name SetObjectName( object, pObjectName ); } else { // Restore default debug name SetDefaultObjectName( object ); } } } }
37.104265
125
0.663048
[ "object" ]
91f6a110c840899c44900e7740021a81db4a1145
780
h
C
src/util/FileHandler.h
jarllarsson/loppan
64676c950facfedd88b4b5fbc589610251fb0c2b
[ "BSD-3-Clause" ]
null
null
null
src/util/FileHandler.h
jarllarsson/loppan
64676c950facfedd88b4b5fbc589610251fb0c2b
[ "BSD-3-Clause" ]
9
2015-04-25T13:50:29.000Z
2015-05-03T14:17:37.000Z
src/util/FileHandler.h
jarllarsson/loppan
64676c950facfedd88b4b5fbc589610251fb0c2b
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <string> #include <vector> class SettingsData; bool write_file_binary(std::string const & filename, char const * data, size_t const bytes); bool saveFloatArray(std::vector<float>* p_inData, const std::string& file_path); bool loadFloatArray(std::vector<float>* p_outData, const std::string& file_path); void saveFloatArrayPrompt(std::vector<float>* p_inData, int p_fileTypeIdx); void loadFloatArrayPrompt(std::vector<float>*& p_outData, int p_fileTypeIdx); bool writeSettings(SettingsData& p_settingsfile); bool loadSettings(SettingsData& p_settingsfile); bool saveMeasurementToCollectionFileAtRow(std::string& p_filePath, float p_average, float p_std, int p_rowIdx); std::string getAutoLoadFilenameSetting(const std::string& p_autoloadFilePath);
31.2
111
0.798718
[ "vector" ]
100b8ec6776e4c6d3cfde4df897cca5c5e2ceea0
6,221
h
C
Include/LInput/Buttons/Extensions/ButtonsStdExtension.h
TheNicker/LInput
59282e2a4b25aa29e142bb4878d703bfbe458d89
[ "MIT" ]
null
null
null
Include/LInput/Buttons/Extensions/ButtonsStdExtension.h
TheNicker/LInput
59282e2a4b25aa29e142bb4878d703bfbe458d89
[ "MIT" ]
null
null
null
Include/LInput/Buttons/Extensions/ButtonsStdExtension.h
TheNicker/LInput
59282e2a4b25aa29e142bb4878d703bfbe458d89
[ "MIT" ]
null
null
null
/* Copyright (c) 2020 Lior Lahav 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 <cstdint> #include <vector> #include <map> #include <set> #include <LLUtils/StopWatch.h> #include <LLUtils/Event.h> #include <LInput/Buttons/ButtonState.h> #include <LInput/Buttons/IButtonStateExtension.h> #include <Win32/HighPrecisionTimer.h> namespace LInput { enum class EventType { NotSet, Pressed, Released }; template <typename button_type> class ButtonStdExtension final : public IButtonStateExtension<button_type> { public: ButtonStdExtension(uint16_t id, uint16_t multipressRate, uint16_t repeatRate) : fID(id) , fMultiPressRate(multipressRate) , fRepeatRate(repeatRate) { timer.SetDueTime(fRepeatRate); timer.SetRepeatInterval(fRepeatRate); } /////////////////////// // Button event struct ButtonEvent { ButtonStdExtension* parent; uint64_t timeStamp; button_type button; EventType eventType; /// <summary> /// Press count - how many times the button has been pressed, e.g. down + up = 1 press /// </summary> uint16_t counter; /// <summary> /// how many times a signal has been sent to client that the button is pressed. /// </summary> uint16_t repeatCount; /// <summary> /// Total actuation time /// </summary> uint16_t actuationTime; }; LLUtils::Event<void(const ButtonEvent&)> OnButtonEvent; typedef std::vector<ButtonEvent> ListButtonEvent; /////////////////////// struct ButtonData { uint64_t timeStamp = 0; ButtonState buttonState = ButtonState::Up; uint16_t pressCounter = 0; uint64_t actuationTimeStamp = 0; uint64_t repeatTimeStamp = 0; uint16_t repeatCount = 0; }; ButtonData& GetButtonData(button_type buttonId) { auto it = mMapButttons.find(buttonId); if (it == mMapButttons.end()) it = mMapButttons.emplace(buttonId, ButtonData {}).first; return it->second; } void ProcessQueuedButtons() { for (auto& button : fPressedButtons) { auto& buttonData = GetButtonData(button); uint64_t now = static_cast<uint64_t>(fTimer.GetElapsedTimeInteger(LLUtils::StopWatch::Milliseconds)); if (static_cast<uint64_t>(now) - buttonData.repeatTimeStamp > fRepeatRate) { buttonData.repeatCount++; OnButtonEvent.Raise(ButtonEvent{ this, 0,button,EventType::Pressed,buttonData.pressCounter, buttonData.repeatCount , static_cast<uint16_t>(now - buttonData.actuationTimeStamp) }); buttonData.repeatTimeStamp = now; } } } void TimerCallback() { ProcessQueuedButtons(); } public: void SetRepeatRate(uint16_t repeatRate) { fRepeatRate = repeatRate; } uint16_t GetRepeatRate() const { return fRepeatRate; } uint16_t GetID() const { return fID; } // Get the state of a button whether it's down or up void SetButtonState(button_type button, ButtonState newState) override { ButtonData& buttonData = GetButtonData(button); const uint64_t currentTimeStamp = static_cast<uint64_t>(fTimer.GetElapsedTimeInteger(LLUtils::StopWatch::Milliseconds)); const bool multiPressTHreshold = buttonData.timeStamp != 0 && (currentTimeStamp - buttonData.timeStamp) < fMultiPressRate; if (buttonData.buttonState != newState) { if (newState == ButtonState::Down) { if (buttonData.buttonState == ButtonState::Up) { if (multiPressTHreshold == true) buttonData.pressCounter++; else buttonData.pressCounter = 0; if (fRepeatRate > 0) { fPressedButtons.insert(button); buttonData.actuationTimeStamp = currentTimeStamp; buttonData.repeatTimeStamp = currentTimeStamp; timer.Enable(true); } OnButtonEvent.Raise(ButtonEvent{this,0 ,button,EventType::Pressed,buttonData.pressCounter, buttonData.repeatCount ,0 }); } } if (newState == ButtonState::Up) { if (fRepeatRate > 0) { fPressedButtons.erase(button); if (fPressedButtons.empty() == true) timer.Enable(false); buttonData.actuationTimeStamp = 0; buttonData.repeatTimeStamp = 0; buttonData.repeatCount = 0; } OnButtonEvent.Raise(ButtonEvent{this, 0,button,EventType::Released,buttonData.pressCounter, buttonData.repeatCount ,0}); if (multiPressTHreshold == false) buttonData.pressCounter = 0; } buttonData.timeStamp = currentTimeStamp; buttonData.buttonState = newState; } } private: uint16_t fID = 0; /// <summary> /// time in millisecond between actuation that determines the time threshold between presses /// </summary> uint16_t fMultiPressRate = 250; /// <summary> /// the repeat rate in milliseconds, set to zero (0) to disable repeat rate /// </summary> uint16_t fRepeatRate = 15; ::Win32::HighPrecisionTimer timer = ::Win32::HighPrecisionTimer(std::bind(&ButtonStdExtension::TimerCallback, this)); LLUtils::StopWatch fTimer = LLUtils::StopWatch(true); using MapButtonToData = std::map<button_type, ButtonData>; MapButtonToData mMapButttons; /// <summary> /// used for sending key repeaet signals to the client /// </summary> std::set<button_type> fPressedButtons; }; }
28.022523
184
0.705514
[ "vector" ]
100ea21775b5070f65d0e1056273b98e2cb9dc9a
614
h
C
ctpParticle/HelloTriangleApplication/FlowFieldObject.h
lbondi7/CTP
79c7b74764ce32b4a7918174768a486ea9cb9815
[ "MIT" ]
1
2020-05-31T11:37:24.000Z
2020-05-31T11:37:24.000Z
ctpParticle/HelloTriangleApplication/FlowFieldObject.h
lbondi7/CTP
79c7b74764ce32b4a7918174768a486ea9cb9815
[ "MIT" ]
null
null
null
ctpParticle/HelloTriangleApplication/FlowFieldObject.h
lbondi7/CTP
79c7b74764ce32b4a7918174768a486ea9cb9815
[ "MIT" ]
null
null
null
#pragma once #include "Object.h" #include "Vertex.h" #include "Triangle.h" #include <vector> struct FfObject : public Object { ~FfObject(); void Load(const std::string& filepath); void Load(const std::string& filepath, const Transform& _transform); void Destroy(); void Update(); int GetGridNum(const glm::vec3& p1); std::vector<Triangle> triangles; std::array<std::vector<Triangle>, 8> brokenTriangles; glm::vec4 max = { -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX }; glm::vec4 min = { FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX }; private: std::vector<Vertex> vertices; std::vector<uint32_t> indices; };
19.806452
69
0.700326
[ "object", "vector", "transform" ]
101607785247a43597e71606f3888abfb67d9e23
13,444
c
C
parasail_c/util/templates/sg_trace_striped.c
andrewprivate/parasail-sys
6290bf353a6e6df47123fa2b7cb1631439329a05
[ "MIT" ]
null
null
null
parasail_c/util/templates/sg_trace_striped.c
andrewprivate/parasail-sys
6290bf353a6e6df47123fa2b7cb1631439329a05
[ "MIT" ]
null
null
null
parasail_c/util/templates/sg_trace_striped.c
andrewprivate/parasail-sys
6290bf353a6e6df47123fa2b7cb1631439329a05
[ "MIT" ]
null
null
null
/** * @file * * @author jeffrey.daily@gmail.com * * Copyright (c) 2015 Battelle Memorial Institute. */ #include "config.h" #include <stdint.h> #include <stdlib.h> %(HEADER)s #define SG_TRACE #define SG_SUFFIX %(SUFFIX)s #define SG_SUFFIX_PROF %(SUFFIX_PROF)s #include "sg_helper.h" #include "parasail.h" #include "parasail/memory.h" #include "parasail/internal_%(ISA)s.h" #define SWAP(A,B) { %(VTYPE)s* tmp = A; A = B; B = tmp; } #define NEG_INF %(NEG_INF)s %(FIXES)s static inline void arr_store( %(VTYPE)s *array, %(VTYPE)s vH, %(INDEX)s t, %(INDEX)s seglen, %(INDEX)s d) { %(VSTORE)s(array + (1LL*d*seglen+t), vH); } static inline %(VTYPE)s arr_load( %(VTYPE)s *array, %(INDEX)s t, %(INDEX)s seglen, %(INDEX)s d) { return %(VLOAD)s(array + (1LL*d*seglen+t)); } #define FNAME %(NAME_TRACE)s #define PNAME %(PNAME_TRACE)s parasail_result_t* FNAME( const char * const restrict s1, const int s1Len, const char * const restrict s2, const int s2Len, const int open, const int gap, const parasail_matrix_t *matrix, int s1_beg, int s1_end, int s2_beg, int s2_end) { parasail_profile_t *profile = parasail_profile_create_%(ISA)s_%(BITS)s_%(WIDTH)s(s1, s1Len, matrix); parasail_result_t *result = PNAME(profile, s2, s2Len, open, gap, s1_beg, s1_end, s2_beg, s2_end); parasail_profile_free(profile); return result; } parasail_result_t* PNAME( const parasail_profile_t * const restrict profile, const char * const restrict s2, const int s2Len, const int open, const int gap, int s1_beg, int s1_end, int s2_beg, int s2_end) { %(INDEX)s i = 0; %(INDEX)s j = 0; %(INDEX)s k = 0; const int s1Len = profile->s1Len; %(INDEX)s end_query = s1Len-1; %(INDEX)s end_ref = s2Len-1; const parasail_matrix_t *matrix = profile->matrix; const %(INDEX)s segWidth = %(LANES)s; /* number of values in vector unit */ const %(INDEX)s segLen = (s1Len + segWidth - 1) / segWidth; const %(INDEX)s offset = (s1Len - 1) %% segLen; const %(INDEX)s position = (segWidth - 1) - (s1Len - 1) / segLen; %(VTYPE)s* const restrict vProfile = (%(VTYPE)s*)profile->profile%(WIDTH)s.score; %(VTYPE)s* restrict pvHStore = parasail_memalign_%(VTYPE)s(%(ALIGNMENT)s, segLen); %(VTYPE)s* restrict pvHLoad = parasail_memalign_%(VTYPE)s(%(ALIGNMENT)s, segLen); %(VTYPE)s* const restrict pvE = parasail_memalign_%(VTYPE)s(%(ALIGNMENT)s, segLen); %(VTYPE)s* restrict pvEaStore = parasail_memalign_%(VTYPE)s(%(ALIGNMENT)s, segLen); %(VTYPE)s* restrict pvEaLoad = parasail_memalign_%(VTYPE)s(%(ALIGNMENT)s, segLen); %(VTYPE)s* const restrict pvHT = parasail_memalign_%(VTYPE)s(%(ALIGNMENT)s, segLen); %(INT)s* const restrict boundary = parasail_memalign_%(INT)s(%(ALIGNMENT)s, s2Len+1); %(VTYPE)s vGapO = %(VSET1)s(open); %(VTYPE)s vGapE = %(VSET1)s(gap); %(VTYPE)s vNegInf = %(VSET1)s(NEG_INF); %(INT)s score = NEG_INF; %(VTYPE)s vMaxH = vNegInf; %(VTYPE)s vPosMask = %(VCMPEQ)s(%(VSET1)s(position), %(VSET)s(%(POSITION_MASK)s)); %(SATURATION_CHECK_INIT)s parasail_result_t *result = parasail_result_new_trace(segLen, s2Len, %(ALIGNMENT)s, sizeof(%(VTYPE)s)); %(VTYPE)s vTIns = %(VSET1)s(PARASAIL_INS); %(VTYPE)s vTDel = %(VSET1)s(PARASAIL_DEL); %(VTYPE)s vTDiag = %(VSET1)s(PARASAIL_DIAG); %(VTYPE)s vTDiagE = %(VSET1)s(PARASAIL_DIAG_E); %(VTYPE)s vTInsE = %(VSET1)s(PARASAIL_INS_E); %(VTYPE)s vTDiagF = %(VSET1)s(PARASAIL_DIAG_F); %(VTYPE)s vTDelF = %(VSET1)s(PARASAIL_DEL_F); %(VTYPE)s vTMask = %(VSET1)s(PARASAIL_ZERO_MASK); %(VTYPE)s vFTMask = %(VSET1)s(PARASAIL_F_MASK); %(INIT_H_AND_E)s /* initialize uppder boundary */ { boundary[0] = 0; for (i=1; i<=s2Len; ++i) { int64_t tmp = s2_beg ? 0 : (-open-gap*(i-1)); boundary[i] = tmp < INT%(WIDTH)s_MIN ? INT%(WIDTH)s_MIN : tmp; } } for (i=0; i<segLen; ++i) { arr_store(result->trace->trace_table, vTDiagE, i, segLen, 0); } /* outer loop over database sequence */ for (j=0; j<s2Len; ++j) { %(VTYPE)s vEF_opn; %(VTYPE)s vE; %(VTYPE)s vE_ext; %(VTYPE)s vF; %(VTYPE)s vF_ext; %(VTYPE)s vFa; %(VTYPE)s vFa_ext; %(VTYPE)s vH; %(VTYPE)s vH_dag; const %(VTYPE)s* vP = NULL; /* Initialize F value to -inf. Any errors to vH values will be * corrected in the Lazy_F loop. */ vF = vNegInf; /* load final segment of pvHStore and shift left by %(BYTES)s bytes */ vH = %(VLOAD)s(&pvHStore[segLen - 1]); vH = %(VSHIFT)s(vH, %(BYTES)s); /* insert upper boundary condition */ vH = %(VINSERT)s(vH, boundary[j], 0); /* Correct part of the vProfile */ vP = vProfile + matrix->mapper[(unsigned char)s2[j]] * segLen; /* Swap the 2 H buffers. */ SWAP(pvHLoad, pvHStore) SWAP(pvEaLoad, pvEaStore) /* inner loop to process the query sequence */ for (i=0; i<segLen; ++i) { vE = %(VLOAD)s(pvE + i); /* Get max from vH, vE and vF. */ vH_dag = %(VADD)s(vH, %(VLOAD)s(vP + i)); vH = %(VMAX)s(vH_dag, vE); vH = %(VMAX)s(vH, vF); /* Save vH values. */ %(VSTORE)s(pvHStore + i, vH); %(SATURATION_CHECK_MID)s { %(VTYPE)s vTAll = arr_load(result->trace->trace_table, i, segLen, j); %(VTYPE)s case1 = %(VCMPEQ)s(vH, vH_dag); %(VTYPE)s case2 = %(VCMPEQ)s(vH, vF); %(VTYPE)s vT = %(VBLEND)s( %(VBLEND)s(vTIns, vTDel, case2), vTDiag, case1); %(VSTORE)s(pvHT + i, vT); vT = %(VOR)s(vT, vTAll); arr_store(result->trace->trace_table, vT, i, segLen, j); } vEF_opn = %(VSUB)s(vH, vGapO); /* Update vE value. */ vE_ext = %(VSUB)s(vE, vGapE); vE = %(VMAX)s(vEF_opn, vE_ext); %(VSTORE)s(pvE + i, vE); { %(VTYPE)s vEa = %(VLOAD)s(pvEaLoad + i); %(VTYPE)s vEa_ext = %(VSUB)s(vEa, vGapE); vEa = %(VMAX)s(vEF_opn, vEa_ext); %(VSTORE)s(pvEaStore + i, vEa); if (j+1<s2Len) { %(VTYPE)s cond = %(VCMPGT)s(vEF_opn, vEa_ext); %(VTYPE)s vT = %(VBLEND)s(vTInsE, vTDiagE, cond); arr_store(result->trace->trace_table, vT, i, segLen, j+1); } } /* Update vF value. */ vF_ext = %(VSUB)s(vF, vGapE); vF = %(VMAX)s(vEF_opn, vF_ext); if (i+1<segLen) { %(VTYPE)s vTAll = arr_load(result->trace->trace_table, i+1, segLen, j); %(VTYPE)s cond = %(VCMPGT)s(vEF_opn, vF_ext); %(VTYPE)s vT = %(VBLEND)s(vTDelF, vTDiagF, cond); vT = %(VOR)s(vT, vTAll); arr_store(result->trace->trace_table, vT, i+1, segLen, j); } /* Load the next vH. */ vH = %(VLOAD)s(pvHLoad + i); } /* Lazy_F loop: has been revised to disallow adjecent insertion and * then deletion, so don't update E(i, i), learn from SWPS3 */ vFa_ext = vF_ext; vFa = vF; for (k=0; k<segWidth; ++k) { int64_t tmp = s2_beg ? -open : (boundary[j+1]-open); %(INT)s tmp2 = tmp < INT%(WIDTH)s_MIN ? INT%(WIDTH)s_MIN : tmp; %(VTYPE)s vHp = %(VLOAD)s(&pvHLoad[segLen - 1]); vHp = %(VSHIFT)s(vHp, %(BYTES)s); vHp = %(VINSERT)s(vHp, boundary[j], 0); vEF_opn = %(VSHIFT)s(vEF_opn, %(BYTES)s); vEF_opn = %(VINSERT)s(vEF_opn, tmp2, 0); vF_ext = %(VSHIFT)s(vF_ext, %(BYTES)s); vF_ext = %(VINSERT)s(vF_ext, NEG_INF, 0); vF = %(VSHIFT)s(vF, %(BYTES)s); vF = %(VINSERT)s(vF, tmp2, 0); vFa_ext = %(VSHIFT)s(vFa_ext, %(BYTES)s); vFa_ext = %(VINSERT)s(vFa_ext, NEG_INF, 0); vFa = %(VSHIFT)s(vFa, %(BYTES)s); vFa = %(VINSERT)s(vFa, tmp2, 0); for (i=0; i<segLen; ++i) { vH = %(VLOAD)s(pvHStore + i); vH = %(VMAX)s(vH,vF); %(VSTORE)s(pvHStore + i, vH); %(SATURATION_CHECK_MID)s { %(VTYPE)s vTAll; %(VTYPE)s vT; %(VTYPE)s case1; %(VTYPE)s case2; %(VTYPE)s cond; vHp = %(VADD)s(vHp, %(VLOAD)s(vP + i)); case1 = %(VCMPEQ)s(vH, vHp); case2 = %(VCMPEQ)s(vH, vF); cond = %(VANDNOT)s(case1,case2); vTAll = arr_load(result->trace->trace_table, i, segLen, j); vT = %(VLOAD)s(pvHT + i); vT = %(VBLEND)s(vT, vTDel, cond); %(VSTORE)s(pvHT + i, vT); vTAll = %(VAND)s(vTAll, vTMask); vTAll = %(VOR)s(vTAll, vT); arr_store(result->trace->trace_table, vTAll, i, segLen, j); } /* Update vF value. */ { %(VTYPE)s vTAll = arr_load(result->trace->trace_table, i, segLen, j); %(VTYPE)s cond = %(VCMPGT)s(vEF_opn, vFa_ext); %(VTYPE)s vT = %(VBLEND)s(vTDelF, vTDiagF, cond); vTAll = %(VAND)s(vTAll, vFTMask); vTAll = %(VOR)s(vTAll, vT); arr_store(result->trace->trace_table, vTAll, i, segLen, j); } vEF_opn = %(VSUB)s(vH, vGapO); vF_ext = %(VSUB)s(vF, vGapE); { %(VTYPE)s vEa = %(VLOAD)s(pvEaLoad + i); %(VTYPE)s vEa_ext = %(VSUB)s(vEa, vGapE); vEa = %(VMAX)s(vEF_opn, vEa_ext); %(VSTORE)s(pvEaStore + i, vEa); if (j+1<s2Len) { %(VTYPE)s cond = %(VCMPGT)s(vEF_opn, vEa_ext); %(VTYPE)s vT = %(VBLEND)s(vTInsE, vTDiagE, cond); arr_store(result->trace->trace_table, vT, i, segLen, j+1); } } if (! %(VMOVEMASK)s( %(VOR)s( %(VCMPGT)s(vF_ext, vEF_opn), %(VCMPEQ)s(vF_ext, vEF_opn)))) goto end; /*vF = %(VMAX)s(vEF_opn, vF_ext);*/ vF = vF_ext; vFa_ext = %(VSUB)s(vFa, vGapE); vFa = %(VMAX)s(vEF_opn, vFa_ext); vHp = %(VLOAD)s(pvHLoad + i); } } end: { /* extract vector containing last value from the column */ %(VTYPE)s vCompare; vH = %(VLOAD)s(pvHStore + offset); vCompare = %(VAND)s(vPosMask, %(VCMPGT)s(vH, vMaxH)); vMaxH = %(VMAX)s(vH, vMaxH); if (%(VMOVEMASK)s(vCompare)) { end_ref = j; } } } /* max last value from all columns */ if (s2_end) { for (k=0; k<position; ++k) { vMaxH = %(VSHIFT)s(vMaxH, %(BYTES)s); } score = (%(INT)s) %(VEXTRACT)s(vMaxH, %(LAST_POS)s); end_query = s1Len-1; } /* max of last column */ if (s1_end) { /* Trace the alignment ending position on read. */ %(INT)s *t = (%(INT)s*)pvHStore; %(INDEX)s column_len = segLen * segWidth; for (i = 0; i<column_len; ++i, ++t) { %(INDEX)s temp = i / segWidth + i %% segWidth * segLen; if (temp >= s1Len) continue; if (*t > score) { score = *t; end_query = temp; end_ref = s2Len-1; } else if (*t == score && end_ref == s2Len-1 && temp < end_query) { end_query = temp; } } } if (!s1_end && !s2_end) { /* extract last value from the last column */ { %(VTYPE)s vH = %(VLOAD)s(pvHStore + offset); for (k=0; k<position; ++k) { vH = %(VSHIFT)s(vH, %(BYTES)s); } score = (%(INT)s) %(VEXTRACT)s (vH, %(LAST_POS)s); end_ref = s2Len - 1; end_query = s1Len - 1; } } %(SATURATION_CHECK_FINAL)s result->score = score; result->end_query = end_query; result->end_ref = end_ref; result->flag |= PARASAIL_FLAG_SG | PARASAIL_FLAG_STRIPED | PARASAIL_FLAG_TRACE | PARASAIL_FLAG_BITS_%(WIDTH)s | PARASAIL_FLAG_LANES_%(LANES)s; result->flag |= s1_beg ? PARASAIL_FLAG_SG_S1_BEG : 0; result->flag |= s1_end ? PARASAIL_FLAG_SG_S1_END : 0; result->flag |= s2_beg ? PARASAIL_FLAG_SG_S2_BEG : 0; result->flag |= s2_end ? PARASAIL_FLAG_SG_S2_END : 0; parasail_free(boundary); parasail_free(pvHT); parasail_free(pvEaLoad); parasail_free(pvEaStore); parasail_free(pvE); parasail_free(pvHLoad); parasail_free(pvHStore); return result; } SG_IMPL_ALL SG_IMPL_PROF_ALL
36.335135
107
0.504389
[ "vector" ]
101c1b57b65931455c088297ebe1595a7a9c3e89
402
h
C
src/pathfindingnode.h
Xpost2000/UntotenKraut
7de9456c10bd782e23b749cb0066c8df4fd37958
[ "MIT" ]
null
null
null
src/pathfindingnode.h
Xpost2000/UntotenKraut
7de9456c10bd782e23b749cb0066c8df4fd37958
[ "MIT" ]
null
null
null
src/pathfindingnode.h
Xpost2000/UntotenKraut
7de9456c10bd782e23b749cb0066c8df4fd37958
[ "MIT" ]
null
null
null
#ifndef PATHFINDING_NODE_H #define PATHFINDING_NODE_H #include <vector> struct Node{ Node(){} Node(int x, int y) : x(x), y(y){} int x, y; // position // calculating the value float globalValue=0; float localValue=0; bool operator==(Node& other){ return other.x == x && other.y==y; } bool visited=false; bool block=false; std::vector<Node*> neighbors; Node* parent=nullptr; }; #endif
16.08
36
0.674129
[ "vector" ]
101ddf0a3ddfd644ff4b7ab9689db19e6df21771
4,973
h
C
code/steps/header/model/wtg_models/wt_electrical_model/wt_electrical_model.h
changgang/steps
9b8ea474581885129d1c1a1c3ad40bc8058a7e0a
[ "MIT" ]
29
2019-10-30T07:04:10.000Z
2022-02-22T06:34:32.000Z
code/steps/header/model/wtg_models/wt_electrical_model/wt_electrical_model.h
changgang/steps
9b8ea474581885129d1c1a1c3ad40bc8058a7e0a
[ "MIT" ]
1
2021-09-25T15:29:59.000Z
2022-01-05T14:04:18.000Z
code/steps/header/model/wtg_models/wt_electrical_model/wt_electrical_model.h
changgang/steps
9b8ea474581885129d1c1a1c3ad40bc8058a7e0a
[ "MIT" ]
8
2019-12-20T16:13:46.000Z
2022-03-20T14:58:23.000Z
#ifndef WT_ELECTRICAL_MODEL_H #define WT_ELECTRICAL_MODEL_H #include "header/model/wtg_models/wt_electrical_model/wind_turbine_power_speed_lookup_table.h" #include "header/model/wtg_models/wtg_model.h" #include <complex> class WT_ELECTRICAL_MODEL : public WTG_MODEL { /* Wind electrical control model General inputs: vterm: wt generator terminal or remote AC voltage iterm: wt generator terminal current freq: terminal AC frequency pelec: wt generator active power generation qelec: wt generator reactive power generation speed: wt generator speed in pu speedref: wt generator speed reference in pu General output: ipcmd: active current command in pu iqcmd: reactive current command in pu */ public: WT_ELECTRICAL_MODEL(STEPS& toolkit); virtual ~WT_ELECTRICAL_MODEL(); public: // pe elctricla control common virtual string get_model_type() const; // get input complex<double> get_wt_generator_terminal_generation_in_MVA() const; complex<double> get_wt_generator_terminal_generation_in_pu_based_on_mbase() const; complex<double> get_terminal_bus_complex_voltage_in_pu() const; double get_terminal_bus_voltage_in_pu() const; complex<double> get_wt_generator_terminal_complex_current_in_pu() const; double get_wt_generator_terminal_current_in_pu() const; double get_terminal_bus_frequency_in_pu() const; double get_terminal_bus_frequency_deviation_in_pu() const; // reference void set_bus_to_regulate(unsigned int bus); unsigned int get_bus_to_regulate() const; void set_voltage_reference_in_pu(double vref); void set_voltage_reference_in_pu_with_bus_to_regulate(); double get_voltage_reference_in_pu() const; void set_frequency_reference_in_pu(double fref); double get_frequency_reference_in_pu() const; void set_active_power_reference_in_pu(double pref); double get_active_power_reference_in_pu() const; void set_reactive_power_reference_in_pu(double qref); double get_reactive_power_reference_in_pu() const; void set_power_factor_reference_in_pu(double pfref); double get_power_factor_reference_in_pu() const; void set_var_control_mode(PE_VAR_CONTROL_MODE mode); PE_VAR_CONTROL_MODE get_var_control_mode() const; double get_wt_generator_speed_in_pu() const; double get_wt_generator_speed_referance_in_pu() const; void set_wind_turbine_power_speed_lookup_table(WIND_TURBINE_POWER_SPEED_LOOKUP_TABLE table); WIND_TURBINE_POWER_SPEED_LOOKUP_TABLE get_wind_turbine_power_speed_lookup_table() const; double get_wind_turbine_reference_speed_with_power_in_pu(double power); public: // specific exciter virtual string get_model_name() const = 0; virtual bool setup_model_with_steps_string_vector(vector<string>& data) = 0; virtual bool setup_model_with_psse_string(string data) = 0; virtual bool setup_model_with_bpa_string(string data) = 0; virtual void setup_block_toolkit_and_parameters() = 0; virtual void initialize() = 0; virtual void run(DYNAMIC_MODE mode) = 0; virtual double get_active_current_command_in_pu_based_on_mbase() = 0; virtual double get_active_power_command_in_pu_based_on_mbase() const = 0; virtual double get_reactive_current_command_in_pu_based_on_mbase() = 0; virtual double get_reactive_power_command_in_pu_based_on_mbase() = 0; virtual double get_reactive_voltage_command_in_pu() const = 0; virtual void check() = 0; virtual void clear() = 0; virtual void report() = 0; virtual void save() = 0; virtual string get_standard_psse_string(bool export_internal_bus_number=false) const = 0; virtual void prepare_model_data_table() = 0; virtual double get_model_data_with_name(string par_name) const = 0; virtual void set_model_data_with_name(string par_name, double value) = 0; virtual double get_minimum_nonzero_time_constant_in_s() = 0; virtual void prepare_model_internal_variable_table() = 0; virtual double get_model_internal_variable_with_name(string var_name)= 0; virtual string get_dynamic_data_in_psse_format() const = 0; virtual string get_dynamic_data_in_bpa_format() const = 0; virtual string get_dynamic_data_in_steps_format() const = 0; private: unsigned int bus_to_regulate; double voltage_reference_in_pu; double frequency_reference_in_pu; double active_power_reference_in_pu; double reactive_power_reference_in_pu; double power_factor_reference_in_pu; PE_VAR_CONTROL_MODE pe_var_control_mode; WIND_TURBINE_POWER_SPEED_LOOKUP_TABLE power_speed_table; }; #endif // WT_ELECTRICAL_MODEL_H
46.046296
100
0.740599
[ "vector", "model" ]
102adc1ae3b21c1d7b34d698660e65a7335fe21e
1,131
h
C
tf2_src/game/client/tf/c_tf_ammo_pack.h
IamIndeedGamingAsHardAsICan03489/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
tf2_src/game/client/tf/c_tf_ammo_pack.h
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
null
null
null
tf2_src/game/client/tf/c_tf_ammo_pack.h
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #ifndef C_TF_AMMO_PACK_H #define C_TF_AMMO_PACK_H #ifdef _WIN32 #pragma once #endif #include "c_baseanimating.h" #include "engine/ivdebugoverlay.h" #include "c_tf_player.h" #include "engine/IEngineSound.h" #include "soundenvelope.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" class C_TFAmmoPack : public C_BaseAnimating, public ITargetIDProvidesHint { DECLARE_CLASS( C_TFAmmoPack, C_BaseAnimating ); public: DECLARE_CLIENTCLASS(); C_TFAmmoPack( void ); ~C_TFAmmoPack( void ); virtual int DrawModel( int flags ); virtual void OnDataChanged( DataUpdateType_t updateType ); virtual int GetWorldModelIndex( void ); virtual void ValidateModelIndex( void ); virtual bool Interpolate( float currentTime ); // ITargetIDProvidesHint public: virtual void DisplayHintTo( C_BasePlayer *pPlayer ); private: Vector m_vecInitialVelocity; short m_nWorldModelIndex; }; #endif // C_TF_AMMO_PACK_H
22.62
81
0.696729
[ "vector" ]
103680a0904c2041cf634682bc48f2ace8e6ac19
1,195
h
C
SYCalander/BMHCCalenderCondtionView.h
Ambtion/SYCalander
b3f8d1491d3116b1d7db2884f4111e4afa92a0cb
[ "MIT" ]
null
null
null
SYCalander/BMHCCalenderCondtionView.h
Ambtion/SYCalander
b3f8d1491d3116b1d7db2884f4111e4afa92a0cb
[ "MIT" ]
null
null
null
SYCalander/BMHCCalenderCondtionView.h
Ambtion/SYCalander
b3f8d1491d3116b1d7db2884f4111e4afa92a0cb
[ "MIT" ]
null
null
null
// // BMHCCalenderCondtionView.h // // Created by Linjunhou on 2016/11/21. // #import <UIKit/UIKit.h> #import "BMTHCalenderModel.h" @class BMHCCalenderCondtionView; @protocol BMHCCalenderCondtionViewDateSource <NSObject> - (BOOL)hcCalenderConditionView:(BMHCCalenderCondtionView *)pickerView hasTripWhenInDate:(BMTHCalenderModel *)model; - (BOOL)hcCalenderConditionView:(BMHCCalenderCondtionView *)pickerView hasForceTodayWhenInDate:(BMTHCalenderModel *)model; @end @protocol BMHCCalenderCondtionViewDelegate <NSObject> - (void)hccalenderCondtionView:(BMHCCalenderCondtionView *)calenderCondtionView DidSeltedTime:(NSInteger)year month:(NSInteger)month day:(NSInteger)day; @end @interface BMHCCalenderCondtionView : UIView @property(nonatomic,weak)id<BMHCCalenderCondtionViewDelegate> delegate; @property(nonatomic,weak)id<BMHCCalenderCondtionViewDateSource>dateSource; @property(nonatomic,strong)NSCalendar * commonCalendar; - (void)seletedContentDateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day; @end @interface BMHCCalenderCondtionView(EqualMetod) - (BOOL)date:(NSDate *)date isEqutalYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day; @end
29.875
152
0.821757
[ "model" ]
10549e6979671e8c9743bba03f0701d7b9696b9e
1,966
h
C
Source/Core/Numeric/LUDecomposer.h
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
Source/Core/Numeric/LUDecomposer.h
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
Source/Core/Numeric/LUDecomposer.h
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
/*****************************************************************************/ /** * @file LUDecomposer.h * @author Naohisa Sakamoto */ /*---------------------------------------------------------------------------- * * Copyright (c) Visualization Laboratory, Kyoto University. * All rights reserved. * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details. * * $Id: LUDecomposer.h 1365 2012-11-29 08:45:27Z naohisa.sakamoto@gmail.com $ */ /*****************************************************************************/ #ifndef KVS__LU_DECOMPOSER_H_INCLUDE #define KVS__LU_DECOMPOSER_H_INCLUDE #include <kvs/Matrix33> #include <kvs/Matrix44> #include <kvs/Matrix> #include <kvs/Vector> namespace kvs { /*===========================================================================*/ /** * @brief LU decomposition class. */ /*===========================================================================*/ template <typename T> class LUDecomposer { private: kvs::Matrix<T> m_l; ///< L matrix kvs::Matrix<T> m_u; ///< U matrix kvs::Matrix<T> m_lu; ///< LU matrix (marged L and U matrix by Crout's method) kvs::Vector<int> m_pivots; ///< pivot vector static size_t m_max_iterations; ///< maximum number of iterations public: static void SetMaxIterations( const size_t max_iterations ); public: LUDecomposer(); LUDecomposer( const kvs::Matrix33<T>& m ); LUDecomposer( const kvs::Matrix44<T>& m ); LUDecomposer( const kvs::Matrix<T>& m ); LUDecomposer& operator = ( const LUDecomposer& l ); const kvs::Matrix<T>& L() const; const kvs::Matrix<T>& U() const; const kvs::Matrix<T>& LU() const; const kvs::Vector<int>& pivots() const; void setMatrix( const kvs::Matrix33<T>& m ); void setMatrix( const kvs::Matrix44<T>& m ); void setMatrix( const kvs::Matrix<T>& m ); void decompose(); }; } // end of namespace kvs #endif // KVS__LU_DECOMPOSER_H_INCLUDE
28.085714
81
0.533062
[ "vector" ]
1056f11494483a2b0b0fbe253dbaa47c1231eb61
6,091
h
C
GPageKit/StretchyHeaderView/GStretchyHeaderView.h
GIKICoder/GPagerKit
3cb9cc9a64971987031922406ebe94f5e6958a62
[ "MIT" ]
1
2021-04-13T16:02:01.000Z
2021-04-13T16:02:01.000Z
GPageKit/StretchyHeaderView/GStretchyHeaderView.h
GIKICoder/GPagerKit
3cb9cc9a64971987031922406ebe94f5e6958a62
[ "MIT" ]
null
null
null
GPageKit/StretchyHeaderView/GStretchyHeaderView.h
GIKICoder/GPagerKit
3cb9cc9a64971987031922406ebe94f5e6958a62
[ "MIT" ]
null
null
null
// // GStretchyHeaderView.h // GPagerKitExample // // Created by GIKI on 2019/10/11. // Copyright © 2019 GIKI. All rights reserved. // // This code reference from GSKStretchyHeaderView! Thanks! // github: http://github.com/gskbyte #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** * Specifies where the contentView will stick to the top or the bottom of the header view. * This property is used when the scrollView bounces (scrollView.contentOffset < scrollView.contentInset.top) */ typedef NS_ENUM(NSUInteger, GStretchyHeaderViewContentAnchor) { /** * The content view sticks to the top of the header view when it bounces */ GStretchyHeaderViewContentAnchorTop = 0, /** * The content view sticks to the bottom of the header view when it bounces */ GStretchyHeaderViewContentAnchorBottom = 1 }; /** * Specifies wether how the stretchy header view will be expanded */ typedef NS_ENUM(NSUInteger, GStretchyHeaderViewExpansionMode) { /** * The header view will expand only at the top of the scroll view */ GStretchyHeaderViewExpansionModeTopOnly = 0, /** * The header view will expand as soon as the user scrolls down */ GStretchyHeaderViewExpansionModeImmediate = 1 }; @interface GStretchyHeaderView : UIView @property(nonatomic) GStretchyHeaderViewExpansionMode expansionMode; /** * The main view to which you add your custom content. */ @property(nonatomic, readonly) UIView *contentView; /** * The height of the header view when it's expanded. Default value is equal to the initial frame height, or 240 if unspecified. */ @property(nonatomic) IBInspectable CGFloat maximumContentHeight; /** * The minimum height of the header view. You usually want to set it to a value larger than 64 if you want to simulate a navigation bar. Defaults to 0. */ @property(nonatomic) IBInspectable CGFloat minimumContentHeight; /** * The contentInset for the contentView. Defaults to UIEdgeInsetsZero. */ @property(nonatomic) IBInspectable UIEdgeInsets contentInset; /** * Specifies wether the contentView sticks to the top or the bottom of the headerView. * Default value is GSKStretchyHeaderContentViewAnchorTop. * This has effect only if contentShrinks and/or contentExpands are set to NO. */ @property(nonatomic) GStretchyHeaderViewContentAnchor contentAnchor; /** * Indicates if the header view changes the scrollView insets automatically. You usually want to * enable this property, unless you have a table view with sticky visible section headers. * Have a look at this issue for more information: https://github.com/gskbyte/GStretchyHeaderView/issues/17 * Default value is YES. */ @property(nonatomic) BOOL manageScrollViewInsets; /** * Indicates if the view hierarchy of the containing scroll view should be manipulated to fix some artifacts, * such as section header and supplementary views appearing on top of this header view. * This may involve moving views behind the header view, like UICollectionReusableView and UITableViewHeaderFooterView, * and adjusting `zPosition` for some views on iOS 11. * * - Please see UIScrollView+GStretchyHeaderView.m for more information. * - Have a look at this issue for more information: https://github.com/gskbyte/GStretchyHeaderView/issues/63 * - OpenRadar issue: http://www.openradar.me/34308893 * * Default value is YES */ @property(nonatomic) BOOL manageScrollViewSubviewHierarchy; /** * Specifies wether the contentView height shrinks when scrolling up. Default is YES. */ @property(nonatomic) IBInspectable BOOL contentShrinks; /** * Specifies wether the contentView height will be increased when scrolling down. * Default is YES. */ @property(nonatomic) IBInspectable BOOL contentExpands; /// 设置HeaderView 高度, 并且重置ScrollView的offset /// @param maximumContentHeight HeaderView 高度 /// @param animated <#animated description#> - (void)setMaximumContentHeight:(CGFloat)maximumContentHeight resetAnimated:(BOOL)animated; /// 只更新headerView 高度. 不改变相对位置. /// @param maximumContentHeight 需要更新的headerView高度 /// @param animated animated description - (void)updateMaximumContentHeight:(CGFloat)maximumContentHeight animation:(BOOL)animated; /// 只更新headerView 高度. 不改变相对位置. /// @param maximumContentHeight 需要更新的headerView高度 /// @param diffOffset 内部控件需要改变的相对位置,增加- 减少+ /// @param animated <#animated description#> - (void)updateMaximumContentHeight:(CGFloat)maximumContentHeight offset:(CGFloat)diffOffset animation:(BOOL)animated; @end @protocol GStretchyHeaderViewStretchDelegate <NSObject> /** * Called when the stretchy header view's stretch factor changes * * @param headerView The header view this object is delegate of * @param stretchFactor The new stretch factor for the given header view */ - (void)stretchyHeaderView:(GStretchyHeaderView *)headerView didChangeStretchFactor:(CGFloat)stretchFactor; @end @interface GStretchyHeaderView (StretchFactor) /** * The stretch factor is the relation between the current content height and the maximum (1) and minimum (0) contentHeight. * Can be greater than 1 if contentViewBounces equals YES. */ @property (nonatomic, readonly) CGFloat stretchFactor; /** * The stretch delegate will be notified every time the stretchFactor changes. */ @property (nonatomic, weak) id<GStretchyHeaderViewStretchDelegate> stretchDelegate; /** * This method will be called every time the stretchFactor changes. * Can be overriden by subclasses to adjust subviews depending on the value of the stretchFactor. * @param stretchFactor The new stretchFactor */ - (void)didChangeStretchFactor:(CGFloat)stretchFactor; @end @interface GStretchyHeaderView (Layout) /** * This method will be called after the contentView performs -layoutSubviews. It can be useful to * retrieve initial values for views added to the contentView. The default implementation does nothing. */ - (void)contentViewDidLayoutSubviews; @end NS_ASSUME_NONNULL_END
33.838889
152
0.75472
[ "object" ]
10589609f3d49e01615f30f636184d2f2b891aa6
813
h
C
port/GraphQLParser/GraphQLParser/AST/GraphQLInlineFragment.h
d0si/GraphQL-cpp
42c35c97f239cc066455a11b37249697dcaed130
[ "MIT" ]
null
null
null
port/GraphQLParser/GraphQLParser/AST/GraphQLInlineFragment.h
d0si/GraphQL-cpp
42c35c97f239cc066455a11b37249697dcaed130
[ "MIT" ]
null
null
null
port/GraphQLParser/GraphQLParser/AST/GraphQLInlineFragment.h
d0si/GraphQL-cpp
42c35c97f239cc066455a11b37249697dcaed130
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <GraphQLParser/AST/ASTNode.h> #include <GraphQLParser/AST/GraphQLDirective.h> #include <GraphQLParser/AST/GraphQLSelectionSet.h> #include <GraphQLParser/AST/GraphQLNamedType.h> namespace GraphQLParser { namespace AST { class GraphQLInlineFragment : public ASTNode { public: GraphQLInlineFragment(); GraphQLInlineFragment(ASTNodeKind kind); GraphQLInlineFragment(GraphQLNamedType type_condition, std::vector<GraphQLDirective> directives, GraphQLSelectionSet selection_set); GraphQLInlineFragment(ASTNodeKind kind, GraphQLNamedType type_condition, std::vector<GraphQLDirective> directives, GraphQLSelectionSet selection_set); std::vector<GraphQLDirective> Directives; GraphQLSelectionSet SelectionSet; GraphQLNamedType TypeCondition; }; } }
31.269231
153
0.810578
[ "vector" ]
10604534fe25ecbd75d1124e9dbd12ed39c15654
2,053
h
C
include/render_meshmod/basicalgos.h
DeanoC/gfx_meshmod
585198a0c69fee64d44cd8902afa3c886e60ccca
[ "Apache-2.0" ]
null
null
null
include/render_meshmod/basicalgos.h
DeanoC/gfx_meshmod
585198a0c69fee64d44cd8902afa3c886e60ccca
[ "Apache-2.0" ]
null
null
null
include/render_meshmod/basicalgos.h
DeanoC/gfx_meshmod
585198a0c69fee64d44cd8902afa3c886e60ccca
[ "Apache-2.0" ]
null
null
null
#pragma once #include "al2o3_platform/platform.h" #include "render_meshmod/meshmod.h" #include "render_meshmod/mesh.h" #include "render_meshmod/data/aabb.h" #include "al2o3_cadt/vector.h" AL2O3_EXTERN_C MeshMod_DataAabb2F const* MeshMod_MeshComputeExtents2F(MeshMod_MeshHandle handle, MeshMod_VertexTag tag); AL2O3_EXTERN_C MeshMod_DataAabb3F const* MeshMod_MeshComputeExtents3F(MeshMod_MeshHandle handle, MeshMod_VertexTag tag); // afterwards MeshMod_PolygonConvexBRep from tri and/or quad brep type AL2O3_EXTERN_C void MeshMod_MeshToConvexBRep(MeshMod_MeshHandle handle); // afterward MeshMod_PolygonTriBRep from quad or convex brep types AL2O3_EXTERN_C void MeshMod_MeshTrianglate(MeshMod_MeshHandle handle); typedef int (*MeshMod_VertexSortFunc)(MeshMod_MeshHandle handle, MeshMod_VertexHandle, MeshMod_VertexHandle); typedef int (*MeshMod_EdgeSortFunc)(MeshMod_MeshHandle handle, MeshMod_EdgeHandle,MeshMod_EdgeHandle); typedef int (*MeshMod_PolygonSortFunc)(MeshMod_MeshHandle handle, MeshMod_PolygonHandle,MeshMod_PolygonHandle); // these sorts are currently single threaded, you can only sort 1 mesh at a time! caller has to destroy the vector returned AL2O3_EXTERN_C CADT_VectorHandle MeshMod_MeshVertexTagSort(MeshMod_MeshHandle handle, MeshMod_VertexTag tag, MeshMod_VertexSortFunc sortFunc); AL2O3_EXTERN_C CADT_VectorHandle MeshMod_MeshEdgeTagSort(MeshMod_MeshHandle handle, MeshMod_EdgeTag tag, MeshMod_EdgeSortFunc sortFunc); AL2O3_EXTERN_C CADT_VectorHandle MeshMod_MeshPolygonTagSort(MeshMod_MeshHandle handle, MeshMod_PolygonTag tag, MeshMod_PolygonSortFunc sortFunc); // Compute a similarity position ring in MeshMod_VertexSimilarTag user field 'P' (single threaded due to sort) AL2O3_EXTERN_C void MeshMod_MeshComputeSimilarPositions(MeshMod_MeshHandle handle, float similarity); AL2O3_EXTERN_C void MeshMod_MeshGenerateEdgeEndVertex(MeshMod_MeshHandle handle); AL2O3_EXTERN_C void MeshMod_MeshComputeVertex2Edges(MeshMod_MeshHandle handle); AL2O3_EXTERN_C void MeshMod_MeshComputeSimilarEdges(MeshMod_MeshHandle handle);
57.027778
145
0.868485
[ "mesh", "vector" ]
1061c6ea143b1b49378883a36535d1eec2fd3ae4
10,948
c
C
resis/ResFract.c
wisehackermonkey/magic
fb85e97b9233cff352d964823173c18527c714aa
[ "TCL", "X11", "MIT" ]
null
null
null
resis/ResFract.c
wisehackermonkey/magic
fb85e97b9233cff352d964823173c18527c714aa
[ "TCL", "X11", "MIT" ]
null
null
null
resis/ResFract.c
wisehackermonkey/magic
fb85e97b9233cff352d964823173c18527c714aa
[ "TCL", "X11", "MIT" ]
null
null
null
/* * ResFract.c * * routines to convert a maximum horizontal rectangles database * into one fractured in the manner of Horowitz's '83 Transactions * on CAD paper. * */ #ifndef lint static char rcsid[] __attribute__ ((unused)) = "$Header: /usr/cvsroot/magic-8.0/resis/ResFract.c,v 1.1.1.1 2008/02/03 20:43:50 tim Exp $"; #endif /* not lint */ #include <stdio.h> #include "utils/magic.h" #include "utils/geometry.h" #include "textio/txcommands.h" #include "tiles/tile.h" #include "utils/signals.h" #include "utils/hash.h" #include "database/database.h" #include "database/databaseInt.h" #include "utils/malloc.h" #include "windows/windows.h" #include "utils/main.h" extern Tile *ResSplitX(); Tile *resSrTile; Tile *resTopTile; Plane *resFracPlane; /* Forward declarations */ extern void ResCheckConcavity(); /* * -------------------------------------------------------------------- * * ResFracture -- Convert a maxiumum horizontal strips cell def into * one where the split at each concave corner is in the direction * with the least material of the same tiletype. This is done * using TiSplitX and TiJoinY. Joins are only done on tiles with * the same time; this implies that contacts should first be erased * using ResDissolve contacts. * * We can't use DBSrPaintArea because the fracturing * routines modify the database. This is essentially the same routine * except that has to be careful that it doesn't merge away the * current tile in the search. * * * -------------------------------------------------------------------- */ int ResFracture(plane, rect) Plane *plane; Rect *rect; { Point start; Tile *tpnew; TileType tt; resFracPlane = plane; start.p_x = rect->r_xbot; start.p_y = rect->r_ytop - 1; resSrTile = plane->pl_hint; GOTOPOINT(resSrTile, &start); /* Each iteration visits another tile on the LHS of the search area */ while (TOP(resSrTile) > rect->r_ybot) { /* Each iteration enumerates another tile */ enumerate: plane->pl_hint = resSrTile; if (SigInterruptPending) return (1); if ((tt = TiGetType(resSrTile)) != TT_SPACE) { resTopTile = RT(resSrTile); while (RIGHT(resTopTile) > LEFT(resSrTile)) { TileType ntt = TiGetType(resTopTile); if (ntt != tt) { resTopTile = BL(resTopTile); continue; } /* ok, we may have found a concave corner */ ResCheckConcavity(resSrTile, resTopTile, tt); if (resTopTile == NULL) break; if (BOTTOM(resTopTile) != TOP(resSrTile)) { resTopTile = RT(resSrTile); } else { resTopTile=BL(resTopTile); } } } tpnew = TR(resSrTile); if (LEFT(tpnew) < rect->r_xtop) { while (BOTTOM(tpnew) >= rect->r_ytop) tpnew = LB(tpnew); if (BOTTOM(tpnew) >= BOTTOM(resSrTile) || BOTTOM(resSrTile) <= rect->r_ybot) { resSrTile = tpnew; goto enumerate; } } /* Each iteration returns one tile further to the left */ while (LEFT(resSrTile) > rect->r_xbot) { if (BOTTOM(resSrTile) <= rect->r_ybot) return (0); tpnew = LB(resSrTile); resSrTile = BL(resSrTile); if (BOTTOM(tpnew) >= BOTTOM(resSrTile) || BOTTOM(resSrTile) <= rect->r_ybot) { resSrTile = tpnew; goto enumerate; } } /* At left edge -- walk down to next tile along the left edge */ for (resSrTile = LB(resSrTile); RIGHT(resSrTile) <= rect->r_xbot; resSrTile = TR(resSrTile)) /* Nothing */; } return (0); } /* *------------------------------------------------------------------------- * * ResCheckConcavity -- Called when two tiles of the same type are found. * These tiles can form concave edges 4 different ways; check for * each such case. When one is found, call the resWalk routines to * decide whether any tiles need to be split. * * Results: none. * * Side Effects: may change the plane on which it acts. Can also modify * the global variable resTopTile. * *------------------------------------------------------------------------- */ void ResCheckConcavity(bot, top, tt) Tile *bot, *top; TileType tt; { Tile *tp; int xlen, ylen; /* corner #1: * XXXXXXX * YYYYYYY * ^--here */ if (RIGHT(top) > RIGHT(bot) && TiGetType(TR(bot)) != tt) { int xpos = RIGHT(bot); int ypos = BOTTOM(top); xlen = xpos - resWalkleft(top, tt, xpos, ypos, NULL); ylen = resWalkup(top, tt, xpos, ypos, NULL) - ypos; if (xlen > ylen) { (void) resWalkup(top, tt, xpos, ypos, ResSplitX); } } if (resTopTile == NULL) return; /* corner #2: * v--here * XXXXXXX * YYYYYYY */ if (RIGHT(top) < RIGHT(bot)) { for (tp = TR(top); BOTTOM(tp) > BOTTOM(top); tp = LB(tp)); if (TiGetType(tp) != tt) { int xpos = RIGHT(top); int ypos = BOTTOM(top); xlen = xpos - resWalkleft(top, tt, xpos, ypos, NULL); ylen = ypos - resWalkdown(bot, tt, xpos, ypos, NULL); if (xlen > ylen) { (void) resWalkdown(bot,tt,xpos,ypos,ResSplitX); } } } if (resTopTile == NULL) return; /* corner #3: * XXXXXXX * YYYYYYY * ^--here */ if (LEFT(top) < LEFT(bot)) { for (tp = BL(bot); TOP(tp) < TOP(bot); tp = RT(tp)); if (TiGetType(tp) != tt) { int xpos = LEFT(bot); int ypos = BOTTOM(top); xlen = resWalkright(top, tt, xpos, ypos, NULL) - xpos; ylen = resWalkup(top, tt, xpos, ypos, NULL) - ypos; if (xlen > ylen) { (void) resWalkup(top, tt, xpos, ypos, ResSplitX); } } } if (resTopTile == NULL) return; /* corner #4: * v--here * XXXXXXX * YYYYYYY */ if (LEFT(top) > LEFT(bot) && TiGetType(BL(top)) != tt) { int xpos = LEFT(top); int ypos = BOTTOM(top); xlen = resWalkright(top, tt, xpos, ypos, NULL) - xpos; ylen = ypos - resWalkdown(bot, tt, xpos, ypos, NULL); if (xlen > ylen) { (void) resWalkdown(bot, tt, xpos, ypos, ResSplitX); } } } /* *------------------------------------------------------------------------- * * resWalk{up,down,left,right} -- move in the specified direction looking * for tiles of a given type. * * Results: returns the coordinate that is the farthest point in the specified * direction that one can walk and still be surrounded by material of * a given type. * * Side Effects: if func is non-NULL, it is called on each tile intersected * by the path. (Note that if the path moves along the edge of a tile, * func is not called.) * *------------------------------------------------------------------------- */ int resWalkup(tile, tt, xpos, ypos, func) Tile *tile; TileType tt; int xpos,ypos; Tile * (*func)(); { Point pt; Tile *tp; pt.p_x = xpos; while (TiGetType(tile) == tt) { if (xpos == LEFT(tile)) { /* walk up left edge */ for (tp = BL(tile); TOP(tp) <= ypos; tp = RT(tp)); for (; BOTTOM(tp) < TOP(tile); tp = RT(tp)) { if (TiGetType(tp) != tt) return(BOTTOM(tp)); } } else { if (func) tile = (*func)(tile,xpos); } pt.p_y = TOP(tile); GOTOPOINT(tile, &pt); } return(BOTTOM(tile)); } int resWalkdown(tile, tt, xpos, ypos, func) Tile *tile; TileType tt; int xpos, ypos; Tile * (*func)(); { Point pt; Tile *tp; Tile *endt; pt.p_x = xpos; while (TiGetType(tile) == tt) { if (xpos == LEFT(tile)) { /* walk up left edge */ endt = NULL; for (tp = BL(tile); BOTTOM(tp) < TOP(tile); tp = RT(tp)) { if (TiGetType(tp) != tt) { if (BOTTOM(tp) < ypos) endt = tp; } } if (endt) { return TOP(endt); } } else { if (func) tile = (*func)(tile, xpos); } pt.p_y = BOTTOM(tile) - 1; GOTOPOINT(tile, &pt); } return(TOP(tile)); } int resWalkright(tile, tt, xpos, ypos, func) Tile *tile; TileType tt; int xpos, ypos; Tile * (*func)(); { Point pt; Tile *tp; pt.p_y = ypos; while (TiGetType(tile) == tt) { if (ypos == BOTTOM(tile)) { /* walk along bottom edge */ for (tp = LB(tile); LEFT(tp) < xpos; tp = TR(tp)); for (; LEFT(tp) < RIGHT(tile); tp = TR(tp)) { if (TiGetType(tp) != tt) return(LEFT(tp)); } } else { if (func) tile = (*func)(tile, ypos); } pt.p_x = RIGHT(tile); GOTOPOINT(tile, &pt); } return(LEFT(tile)); } int resWalkleft(tile, tt, xpos, ypos, func) Tile *tile; TileType tt; int xpos, ypos; Tile * (*func)(); { Point pt; Tile *tp; Tile *endt; pt.p_y = ypos; while (TiGetType(tile) == tt) { if (ypos == BOTTOM(tile)) { /* walk along bottom edge */ endt = NULL; for (tp = LB(tile); LEFT(tp) < RIGHT(tile); tp = TR(tp)) { if (TiGetType(tp) != tt) { if (LEFT(tp) < xpos) endt = tp; } } if (endt) { return RIGHT(endt); } } else { if (func) tile = (*func)(tile, ypos); } pt.p_x = LEFT(tile) - 1; GOTOPOINT(tile, &pt); } return(RIGHT(tile)); } /* *------------------------------------------------------------------------- * * ResSplitX -- calls TiSplitX, sets the tiletype, * then tries to join tiles that share a common long edge. * * Results: returns new tile if tile was destroyed by a Join function. * * Side Effects: modifies the tile plane and the global variables * resSrTile and resTopTile. * *------------------------------------------------------------------------- */ Tile * ResSplitX(tile, x) Tile *tile; int x; { TileType tt = TiGetType(tile); Tile *tp = TiSplitX(tile, x); Tile *tp2; TiSetBody(tp,tt); /* check to see if we can combine with the tiles above or below us */ tp2 = RT(tile); if (TiGetType(tp2) == tt && LEFT(tp2) == LEFT(tile) && RIGHT(tp2) == RIGHT(tile)) { if (tp2 == resSrTile) { if (resTopTile == tile) resTopTile = NULL; TiJoinY(tp2, tile, resFracPlane); tile = tp2; } else { if (resTopTile == tp2) resTopTile = NULL; TiJoinY(tile, tp2, resFracPlane); } } tp2 = LB(tile); if (TiGetType(tp2) == tt && LEFT(tp2) == LEFT(tile) && RIGHT(tp2) == RIGHT(tile)) { if (tp2 == resSrTile) { if (resTopTile == tile) resTopTile = NULL; TiJoinY(tp2, tile, resFracPlane); tile = tp2; } else { if (resTopTile == tp2) resTopTile = NULL; TiJoinY(tile, tp2, resFracPlane); } } /* do the same checks with the newly created tile */ tp2 = RT(tp); if (TiGetType(tp2) == tt && LEFT(tp2) == LEFT(tp) && RIGHT(tp2) == RIGHT(tp)) { TiJoinY(tp2, tp, resFracPlane); tp = tp2; } tp2 = LB(tp); if (TiGetType(tp2) == tt && LEFT(tp2) == LEFT(tp) && RIGHT(tp2) == RIGHT(tp)) { TiJoinY(tp2, tp, resFracPlane); } return tile; }
22.480493
138
0.545122
[ "cad", "geometry" ]
dc29c716720daabb2cc47896d33f732ce9624fc4
12,504
h
C
extensions/gen/mojo/public/interfaces/bindings/tests/sample_service.mojom-params-data.h
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
6
2020-12-22T05:48:31.000Z
2022-02-08T19:49:49.000Z
extensions/gen/mojo/public/interfaces/bindings/tests/sample_service.mojom-params-data.h
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
4
2020-05-22T18:36:43.000Z
2021-05-19T10:20:23.000Z
extensions/gen/mojo/public/interfaces/bindings/tests/sample_service.mojom-params-data.h
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
2
2019-12-06T11:48:16.000Z
2021-09-16T04:44:47.000Z
// mojo/public/interfaces/bindings/tests/sample_service.mojom-params-data.h is auto generated by mojom_bindings_generator.py, do not edit // 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 MOJO_PUBLIC_INTERFACES_BINDINGS_TESTS_SAMPLE_SERVICE_MOJOM_PARAMS_DATA_H_ #define MOJO_PUBLIC_INTERFACES_BINDINGS_TESTS_SAMPLE_SERVICE_MOJOM_PARAMS_DATA_H_ #include "base/macros.h" #include "mojo/public/cpp/bindings/lib/bindings_internal.h" #include "mojo/public/cpp/bindings/lib/buffer.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" #endif namespace sample { namespace internal { class DefaultsSender_SendBar_Params_Data { public: static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<internal::Bar_Data> bar; private: friend class mojo::internal::MessageFragment<DefaultsSender_SendBar_Params_Data>; DefaultsSender_SendBar_Params_Data(); ~DefaultsSender_SendBar_Params_Data() = delete; }; static_assert(sizeof(DefaultsSender_SendBar_Params_Data) == 16, "Bad sizeof(DefaultsSender_SendBar_Params_Data)"); class DefaultsSender_SendFoo_Params_Data { public: static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<internal::Foo_Data> foo; private: friend class mojo::internal::MessageFragment<DefaultsSender_SendFoo_Params_Data>; DefaultsSender_SendFoo_Params_Data(); ~DefaultsSender_SendFoo_Params_Data() = delete; }; static_assert(sizeof(DefaultsSender_SendFoo_Params_Data) == 16, "Bad sizeof(DefaultsSender_SendFoo_Params_Data)"); class DefaultsSender_SendDefaultsTest_Params_Data { public: static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<internal::DefaultsTest_Data> defaults; private: friend class mojo::internal::MessageFragment<DefaultsSender_SendDefaultsTest_Params_Data>; DefaultsSender_SendDefaultsTest_Params_Data(); ~DefaultsSender_SendDefaultsTest_Params_Data() = delete; }; static_assert(sizeof(DefaultsSender_SendDefaultsTest_Params_Data) == 16, "Bad sizeof(DefaultsSender_SendDefaultsTest_Params_Data)"); class Service_Frobinate_Params_Data { public: static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<internal::Foo_Data> foo; int32_t baz; mojo::internal::Interface_Data port; uint8_t padfinal_[4]; private: friend class mojo::internal::MessageFragment<Service_Frobinate_Params_Data>; Service_Frobinate_Params_Data(); ~Service_Frobinate_Params_Data() = delete; }; static_assert(sizeof(Service_Frobinate_Params_Data) == 32, "Bad sizeof(Service_Frobinate_Params_Data)"); class Service_Frobinate_ResponseParams_Data { public: static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t result; uint8_t padfinal_[4]; private: friend class mojo::internal::MessageFragment<Service_Frobinate_ResponseParams_Data>; Service_Frobinate_ResponseParams_Data(); ~Service_Frobinate_ResponseParams_Data() = delete; }; static_assert(sizeof(Service_Frobinate_ResponseParams_Data) == 16, "Bad sizeof(Service_Frobinate_ResponseParams_Data)"); class Service_GetPort_Params_Data { public: static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Handle_Data receiver; uint8_t padfinal_[4]; private: friend class mojo::internal::MessageFragment<Service_GetPort_Params_Data>; Service_GetPort_Params_Data(); ~Service_GetPort_Params_Data() = delete; }; static_assert(sizeof(Service_GetPort_Params_Data) == 16, "Bad sizeof(Service_GetPort_Params_Data)"); class Port_PostMessageToPort_Params_Data { public: static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<mojo::internal::String_Data> message_text; mojo::internal::Interface_Data port; private: friend class mojo::internal::MessageFragment<Port_PostMessageToPort_Params_Data>; Port_PostMessageToPort_Params_Data(); ~Port_PostMessageToPort_Params_Data() = delete; }; static_assert(sizeof(Port_PostMessageToPort_Params_Data) == 24, "Bad sizeof(Port_PostMessageToPort_Params_Data)"); } // namespace internal class DefaultsSender_SendBar_ParamsDataView { public: DefaultsSender_SendBar_ParamsDataView() {} DefaultsSender_SendBar_ParamsDataView( internal::DefaultsSender_SendBar_Params_Data* data, mojo::Message* message) : data_(data), message_(message) {} bool is_null() const { return !data_; } inline void GetBarDataView( BarDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadBar(UserType* output) { auto* pointer = data_->bar.Get(); return mojo::internal::Deserialize<::sample::BarDataView>( pointer, output, message_); } private: internal::DefaultsSender_SendBar_Params_Data* data_ = nullptr; mojo::Message* message_ = nullptr; }; class DefaultsSender_SendFoo_ParamsDataView { public: DefaultsSender_SendFoo_ParamsDataView() {} DefaultsSender_SendFoo_ParamsDataView( internal::DefaultsSender_SendFoo_Params_Data* data, mojo::Message* message) : data_(data), message_(message) {} bool is_null() const { return !data_; } inline void GetFooDataView( FooDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadFoo(UserType* output) { auto* pointer = data_->foo.Get(); return mojo::internal::Deserialize<::sample::FooDataView>( pointer, output, message_); } private: internal::DefaultsSender_SendFoo_Params_Data* data_ = nullptr; mojo::Message* message_ = nullptr; }; class DefaultsSender_SendDefaultsTest_ParamsDataView { public: DefaultsSender_SendDefaultsTest_ParamsDataView() {} DefaultsSender_SendDefaultsTest_ParamsDataView( internal::DefaultsSender_SendDefaultsTest_Params_Data* data, mojo::Message* message) : data_(data), message_(message) {} bool is_null() const { return !data_; } inline void GetDefaultsDataView( DefaultsTestDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadDefaults(UserType* output) { auto* pointer = data_->defaults.Get(); return mojo::internal::Deserialize<::sample::DefaultsTestDataView>( pointer, output, message_); } private: internal::DefaultsSender_SendDefaultsTest_Params_Data* data_ = nullptr; mojo::Message* message_ = nullptr; }; class Service_Frobinate_ParamsDataView { public: Service_Frobinate_ParamsDataView() {} Service_Frobinate_ParamsDataView( internal::Service_Frobinate_Params_Data* data, mojo::Message* message) : data_(data), message_(message) {} bool is_null() const { return !data_; } inline void GetFooDataView( FooDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadFoo(UserType* output) { static_assert( mojo::internal::IsValidUserTypeForOptionalValue< ::sample::FooDataView, UserType>(), "Attempting to read the optional `foo` field into a type which " "cannot represent a null value. Either wrap the destination object " "with base::Optional, ensure that any corresponding " "{Struct/Union/Array/String}Traits define the necessary IsNull and " "SetToNull methods, or use `MaybeReadFoo` instead " "of `ReadFoo if you're fine with null values being " "silently ignored in this case."); auto* pointer = data_->foo.Get(); return mojo::internal::Deserialize<::sample::FooDataView>( pointer, output, message_); } template <typename UserType> WARN_UNUSED_RESULT bool ReadBaz(UserType* output) const { auto data_value = data_->baz; return mojo::internal::Deserialize<::sample::Service_BazOptions>( data_value, output); } Service_BazOptions baz() const { return ::mojo::internal::ToKnownEnumValueHelper( static_cast<::sample::Service_BazOptions>(data_->baz)); } template <typename UserType> UserType TakePort() { UserType result; bool ret = mojo::internal::Deserialize<mojo::InterfacePtrDataView<::sample::PortInterfaceBase>>( &data_->port, &result, message_); DCHECK(ret); return result; } private: internal::Service_Frobinate_Params_Data* data_ = nullptr; mojo::Message* message_ = nullptr; }; class Service_Frobinate_ResponseParamsDataView { public: Service_Frobinate_ResponseParamsDataView() {} Service_Frobinate_ResponseParamsDataView( internal::Service_Frobinate_ResponseParams_Data* data, mojo::Message* message) : data_(data) {} bool is_null() const { return !data_; } int32_t result() const { return data_->result; } private: internal::Service_Frobinate_ResponseParams_Data* data_ = nullptr; }; class Service_GetPort_ParamsDataView { public: Service_GetPort_ParamsDataView() {} Service_GetPort_ParamsDataView( internal::Service_GetPort_Params_Data* data, mojo::Message* message) : data_(data), message_(message) {} bool is_null() const { return !data_; } template <typename UserType> UserType TakeReceiver() { UserType result; bool ret = mojo::internal::Deserialize<mojo::InterfaceRequestDataView<::sample::PortInterfaceBase>>( &data_->receiver, &result, message_); DCHECK(ret); return result; } private: internal::Service_GetPort_Params_Data* data_ = nullptr; mojo::Message* message_ = nullptr; }; class Port_PostMessageToPort_ParamsDataView { public: Port_PostMessageToPort_ParamsDataView() {} Port_PostMessageToPort_ParamsDataView( internal::Port_PostMessageToPort_Params_Data* data, mojo::Message* message) : data_(data), message_(message) {} bool is_null() const { return !data_; } inline void GetMessageTextDataView( mojo::StringDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadMessageText(UserType* output) { auto* pointer = data_->message_text.Get(); return mojo::internal::Deserialize<mojo::StringDataView>( pointer, output, message_); } template <typename UserType> UserType TakePort() { UserType result; bool ret = mojo::internal::Deserialize<mojo::InterfacePtrDataView<::sample::PortInterfaceBase>>( &data_->port, &result, message_); DCHECK(ret); return result; } private: internal::Port_PostMessageToPort_Params_Data* data_ = nullptr; mojo::Message* message_ = nullptr; }; inline void DefaultsSender_SendBar_ParamsDataView::GetBarDataView( BarDataView* output) { auto pointer = data_->bar.Get(); *output = BarDataView(pointer, message_); } inline void DefaultsSender_SendFoo_ParamsDataView::GetFooDataView( FooDataView* output) { auto pointer = data_->foo.Get(); *output = FooDataView(pointer, message_); } inline void DefaultsSender_SendDefaultsTest_ParamsDataView::GetDefaultsDataView( DefaultsTestDataView* output) { auto pointer = data_->defaults.Get(); *output = DefaultsTestDataView(pointer, message_); } inline void Service_Frobinate_ParamsDataView::GetFooDataView( FooDataView* output) { auto pointer = data_->foo.Get(); *output = FooDataView(pointer, message_); } inline void Port_PostMessageToPort_ParamsDataView::GetMessageTextDataView( mojo::StringDataView* output) { auto pointer = data_->message_text.Get(); *output = mojo::StringDataView(pointer, message_); } } // namespace sample #if defined(__clang__) #pragma clang diagnostic pop #endif #endif // MOJO_PUBLIC_INTERFACES_BINDINGS_TESTS_SAMPLE_SERVICE_MOJOM_PARAMS_DATA_H_
30.950495
137
0.742802
[ "object" ]
dc346a322ab5b6d6e11595474899afd500ad7db4
3,621
h
C
component/oai-udm/src/api_server/model/DddTrafficDescriptor.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-udm/src/api_server/model/DddTrafficDescriptor.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-udm/src/api_server/model/DddTrafficDescriptor.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the OAI Public License, Version 1.1 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the * License at * * http://www.openairinterface.org/?page_id=698 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ /** * Nudm_EE * Nudm Event Exposure Service. © 2021, 3GPP Organizational Partners (ARIB, * ATIS, CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. * * The version of the OpenAPI document: 1.2.0-alpha.3 * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ /* * DddTrafficDescriptor.h * * */ #ifndef DddTrafficDescriptor_H_ #define DddTrafficDescriptor_H_ #include <nlohmann/json.hpp> namespace oai::udm::model { /// <summary> /// /// </summary> class DddTrafficDescriptor { public: DddTrafficDescriptor(); virtual ~DddTrafficDescriptor() = default; /// <summary> /// Validate the current data in the model. Throws a ValidationException on /// failure. /// </summary> void validate() const; /// <summary> /// Validate the current data in the model. Returns false on error and writes /// an error message into the given stringstream. /// </summary> bool validate(std::stringstream& msg) const; bool operator==(const DddTrafficDescriptor& rhs) const; bool operator!=(const DddTrafficDescriptor& rhs) const; ///////////////////////////////////////////// /// DddTrafficDescriptor members /// <summary> /// /// </summary> std::string getIpv4Addr() const; void setIpv4Addr(std::string const& value); bool ipv4AddrIsSet() const; void unsetIpv4Addr(); /// <summary> /// /// </summary> std::string getIpv6Addr() const; void setIpv6Addr(std::string const& value); bool ipv6AddrIsSet() const; void unsetIpv6Addr(); /// <summary> /// /// </summary> std::string getPortNumber() const; void setPortNumber(std::string const& value); bool portNumberIsSet() const; void unsetPortNumber(); /// <summary> /// /// </summary> std::string getMacAddr() const; void setMacAddr(std::string const& value); bool macAddrIsSet() const; void unsetMacAddr(); friend void to_json(nlohmann::json& j, const DddTrafficDescriptor& o); friend void from_json(const nlohmann::json& j, DddTrafficDescriptor& o); // Helper overload for validate. Used when one model stores another model and // calls it's validate. bool validate(std::stringstream& msg, const std::string& pathPrefix) const; protected: std::string m_Ipv4Addr; bool m_Ipv4AddrIsSet; std::string m_Ipv6Addr; bool m_Ipv6AddrIsSet; std::string m_PortNumber; bool m_PortNumberIsSet; std::string m_MacAddr; bool m_MacAddrIsSet; }; } // namespace oai::udm::model #endif /* DddTrafficDescriptor_H_ */
29.92562
81
0.689865
[ "model" ]
dc362352f138c5d00de9c991a82b6a23d9e6a11b
2,621
h
C
BTLoadingTest/Pods/BTHelp/Classes/BTPermission.h
StoneMover/BTLoading
d7cb93d998962b2e974a320eabbcc770c2129bce
[ "MIT" ]
3
2019-08-14T12:43:50.000Z
2020-06-11T06:44:39.000Z
BTLoadingTest/Pods/BTHelp/Classes/BTPermission.h
StoneMover/BTLoading
d7cb93d998962b2e974a320eabbcc770c2129bce
[ "MIT" ]
null
null
null
BTLoadingTest/Pods/BTHelp/Classes/BTPermission.h
StoneMover/BTLoading
d7cb93d998962b2e974a320eabbcc770c2129bce
[ "MIT" ]
1
2019-08-14T12:43:51.000Z
2019-08-14T12:43:51.000Z
// // BTPermission.h // doctor // // Created by stonemover on 2017/12/19. // Copyright © 2017年 stonemover. All rights reserved. // 直接调用每个权限的获取方法即可,未选择权限的情况下会弹出权限请求框,被拒绝则会提示用户去开启 // 已经拒绝情况会直接提示用户打开权限 // 已经获得授权的会直接在block中回调,isCamera等参数只是提供外部判断的一个方便的途径 #import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> NS_ASSUME_NONNULL_BEGIN typedef void(^BTPermissionSuccessBlock)(void); typedef void(^BTPermissionBlock)(NSInteger index); @interface BTPermission : NSObject + (instancetype)share; //请求获取相机权限 @property (nonatomic, assign) BOOL isCamera; - (void)getCameraPermission:(BTPermissionSuccessBlock)block; - (void)getCameraPermission:(NSString*_Nullable)meg success:(BTPermissionSuccessBlock)block; //请求获取相册权限 @property (nonatomic, assign) BOOL isAlbum; - (void)getAlbumPermission:(BTPermissionSuccessBlock)block; - (void)getAlbumPermission:(NSString*_Nullable)meg success:(BTPermissionSuccessBlock)block; //请求麦克风权限 @property (nonatomic, assign) BOOL isMic; - (void)getMicPermission:(BTPermissionSuccessBlock)block; - (void)getMicPermission:(NSString*_Nullable)meg success:(BTPermissionSuccessBlock)block; @end @protocol BTLocationDelegate <NSObject> - (void)locationSuccess:(NSString*)province city:(NSString*)city; @end @interface BTLocation : NSObject //开始定位 - (void)start; //停止定位 - (void)stop; //是否有定位权限 - (BOOL)isHasLocationPermission; @property (nonatomic, weak) id<BTLocationDelegate> delegate; @end typedef NS_ENUM(NSInteger,BTThirdMapType){ BTThirdMapApple = 0, BTThirdMapGaoDe, BTThirdMapBaiDu, BTThirdMapTencent }; typedef NS_ENUM(NSInteger,BTThirdMapGuideType){ BTThirdMapGuideWalking = 0, //步行 BTThirdMapGuideRiding, //骑行 BTThirdMapDriver, //驾车 BTThirdMapTransit // 公交 }; @class BTThirdMapModel; /// 该坐标体系基于高德,如果使用的为百度SDK,需要自己转换坐标 @interface BTThirdMapHelp : NSObject ///用来判断是否安装某个地图应用的url,如果后期改变可自己设置相应的值 @property (nonatomic, strong) NSMutableArray * thirdMapUrlArray; ///是否安装了相应的地图应用 - (BOOL)isCanOpenMap:(BTThirdMapType)type; ///打开相应的地图进行导航 - (void)guideTo:(CLLocationCoordinate2D)coordinate model:(BTThirdMapModel*)model; ///已安装的地图应用列表 - (NSArray<BTThirdMapModel*>*)installedArray; @end @interface BTThirdMapModel : NSObject - (instancetype)initWithType:(BTThirdMapType)type; @property (nonatomic, strong, readonly) NSString * name; /// 0:苹果地图,1:高德地图,2:百度地图,3:腾讯地图 @property (nonatomic, assign, readonly) BTThirdMapType type; /// 导航类型 @property (nonatomic, assign) BTThirdMapGuideType wayType; /// 腾讯跳转需要开发者key @property (nonatomic, strong,nullable) NSString * tencentDevKey; @end NS_ASSUME_NONNULL_END
21.308943
92
0.776421
[ "model" ]
dc393e818225ea97e3fc44d2c9cb66585c6cd53c
934
h
C
cpp/ITLCSPROJ/include/vitlcs.h
ajkd/Traffic-Light-Control-Using-Image-Processing-With-openCV
c1af2aec0e68a7a643ae8839fb14ee3213fe8ea7
[ "MIT" ]
null
null
null
cpp/ITLCSPROJ/include/vitlcs.h
ajkd/Traffic-Light-Control-Using-Image-Processing-With-openCV
c1af2aec0e68a7a643ae8839fb14ee3213fe8ea7
[ "MIT" ]
null
null
null
cpp/ITLCSPROJ/include/vitlcs.h
ajkd/Traffic-Light-Control-Using-Image-Processing-With-openCV
c1af2aec0e68a7a643ae8839fb14ee3213fe8ea7
[ "MIT" ]
null
null
null
#pragma once const int t_width = 30; const int t_height = 30; const int t_space = 50; const int t_x = 0; const int t_y = 15; const int t_r = 10; const int max_items = 5; #include <windows.h> #include <iostream> #include <string> #include <map> #include <vector> #include <fstream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc.hpp> #include "nlohmann/json.hpp" using json = nlohmann::json; using namespace cv; using namespace std; class vitlcs { private: map < string, string > tmap; Mat image; Scalar df = Scalar(0, 0, 0); Scalar wbg = Scalar(220, 220, 220); Scalar tbg = Scalar(128, 128, 128); Scalar off = Scalar(169, 169, 169); map < string, cv::Scalar> lc = { {"R",Scalar(0,0,255)}, {"Y",Scalar(0,255,255)}, {"G",Scalar(0,128,0)} }; public: vitlcs(); ~vitlcs(); string createtl(json tlr); string onoff(json tlr); };
21.227273
107
0.64454
[ "vector" ]
dc3a1dd99f1344fb7f6560de5eb95ce69e4e0db7
4,194
h
C
src/ofxAVFoundationGrabberEx.h
2bbb/ofxAVFoundationUtils
5dc72adf6230fd3dab815a9dce6cd6223ff4da9d
[ "MIT" ]
1
2021-06-17T01:08:32.000Z
2021-06-17T01:08:32.000Z
src/ofxAVFoundationGrabberEx.h
2bbb/ofxAVFoundationUtils
5dc72adf6230fd3dab815a9dce6cd6223ff4da9d
[ "MIT" ]
null
null
null
src/ofxAVFoundationGrabberEx.h
2bbb/ofxAVFoundationUtils
5dc72adf6230fd3dab815a9dce6cd6223ff4da9d
[ "MIT" ]
null
null
null
/* * ofxAVFoundationGrabberEx.h */ #pragma once #include "ofConstants.h" //------ #include <mutex> #include "ofVideoBaseTypes.h" #include "ofPixels.h" #include "ofTexture.h" #include "ofVec2f.h" namespace ofx { namespace AVFoundationUtils { enum class CaptureExposureMode : std::uint8_t { Locked = 0, Auto, ContinuousAuto }; enum class CaptureWhiteBalanceMode : std::uint8_t { Locked = 0, Auto, ContinuousAuto }; enum class CaptureFocusMode : std::uint8_t { Locked = 0, Auto, ContinuousAuto }; enum class CaptureDeviceTransportControlsPlaybackMode : std::uint8_t { NotPlayingMode = 0, PlayingMode }; class GrabberEx : virtual public ofBaseVideoGrabber{ public: GrabberEx(); ~GrabberEx(); void setDeviceID(int deviceID); void setDeviceUniqueID(const std::string &uniqueID); int getDeviceIDByUniqueID(const std::string &uniqueID) const; void setDesiredFrameRate(int capRate); bool setPixelFormat(ofPixelFormat PixelFormat); bool setup(int w, int h); void update(); bool isFrameNew() const; void close(); ofPixels& getPixels(); const ofPixels& getPixels() const; float getWidth() const{ return width; } float getHeight() const{ return height; } bool isInitialized() const; void updatePixelsCB(); std::vector <ofVideoDevice> listDevices() const; ofPixelFormat getPixelFormat() const; std::string getUniqueID() const; std::string getModelID() const; std::string getManufacturer() const; std::string getLocalizedName() const; bool adjustingExposure() const; CaptureExposureMode exposureMode() const; void setExposureMode(CaptureExposureMode mode); bool isExposureModeSupported(CaptureExposureMode mode) const; CaptureWhiteBalanceMode whiteBalanceMode() const; void setWhiteBalanceMode(CaptureWhiteBalanceMode mode); bool isWhiteBalanceModeSupported(CaptureWhiteBalanceMode mode) const; bool isAdjustingWhiteBalance() const; CaptureFocusMode focusMode() const; bool isFocusModeSupported(CaptureFocusMode mode) const; ofVec2f focusPointOfInterest() const; void setFocusPointOfInterest(ofVec2f focusPoint); bool isFocusPointOfInterestSupported() const; bool isAdjustingFocus() const; bool transportControlsSupported() const; CaptureDeviceTransportControlsPlaybackMode transportControlsPlaybackMode() const; float transportControlsSpeed() const; void setTransportControlsPlaybackSetting(CaptureDeviceTransportControlsPlaybackMode mode, float speed); protected: bool newFrame = false; bool bHavePixelsChanged = false; void clear(); int width, height; int device = 0; bool bIsInit = false; int fps = -1; ofTexture tex; ofPixels pixels; void *grabber_; public: ofPixelFormat pixelFormat; ofPixels pixelsTmp; bool bLock = false; std::mutex capMutex; }; }; }; using ofxAVFoundationGrabberEx = ofx::AVFoundationUtils::GrabberEx; using ofxAVFoundationCaptureExposureMode = ofx::AVFoundationUtils::CaptureExposureMode; using ofxAVFoundationCaptureWhiteBalanceMode = ofx::AVFoundationUtils::CaptureWhiteBalanceMode; using ofxAVFoundationCaptureFocusMode = ofx::AVFoundationUtils::CaptureFocusMode; using ofxAVFoundationCaptureDeviceTransportControlsPlaybackMode = ofx::AVFoundationUtils::CaptureDeviceTransportControlsPlaybackMode;
32.765625
133
0.606104
[ "vector" ]
dc5d82909143557529872b2bef6e03b454068555
3,074
h
C
src/blend2d/raster/rastercommand_p.h
ursine/blend2d
b694944dd0322019b807e702413e6ea4fa3354f6
[ "Zlib" ]
null
null
null
src/blend2d/raster/rastercommand_p.h
ursine/blend2d
b694944dd0322019b807e702413e6ea4fa3354f6
[ "Zlib" ]
null
null
null
src/blend2d/raster/rastercommand_p.h
ursine/blend2d
b694944dd0322019b807e702413e6ea4fa3354f6
[ "Zlib" ]
null
null
null
// [Blend2D] // 2D Vector Graphics Powered by a JIT Compiler. // // [License] // Zlib - See LICENSE.md file in the package. #ifndef BLEND2D_RASTER_RASTERCOMMAND_P_H #define BLEND2D_RASTER_RASTERCOMMAND_P_H #include "../geometry_p.h" #include "../image.h" #include "../path.h" #include "../pipedefs_p.h" #include "../region.h" #include "../zeroallocator_p.h" #include "../zoneallocator_p.h" #include "../raster/edgebuilder_p.h" #include "../raster/rasterdefs_p.h" //! \cond INTERNAL //! \addtogroup blend2d_internal_raster //! \{ struct BLRasterFetchData; //! Raster command type. enum BLRasterCommandType : uint32_t { BL_RASTER_COMMAND_TYPE_NONE = 0, BL_RASTER_COMMAND_TYPE_FILL_RECTA = 1, BL_RASTER_COMMAND_TYPE_FILL_RECTU = 2, BL_RASTER_COMMAND_TYPE_FILL_ANALYTIC = 3 }; //! Raster command flags. enum BLRasterCommandFlags : uint32_t { BL_RASTER_COMMAND_FLAG_FETCH_DATA = 0x01u }; //! Raster command data. struct BLRasterCommand { uint8_t type; uint8_t flags; uint16_t alpha; uint32_t pipeSignature; union { BLPipeFetchData::Solid solidData; BLRasterFetchData* fetchData; }; union { BLRectI rect; BLEdgeStorage<int>* edgeStorage; }; }; class BLRasterCommandQueue { public: BL_NONCOPYABLE(BLRasterCommandQueue) uint8_t* _cmdBuf; uint8_t* _cmdPtr; uint8_t* _cmdEnd; size_t _queueCapacity; BL_INLINE BLRasterCommandQueue() noexcept : _cmdBuf(nullptr), _cmdPtr(nullptr), _cmdEnd(nullptr), _queueCapacity(0) {} BL_INLINE ~BLRasterCommandQueue() noexcept { free(_cmdBuf); } BL_INLINE void swap(BLRasterCommandQueue& other) noexcept { std::swap(_cmdBuf, other._cmdBuf); std::swap(_cmdPtr, other._cmdPtr); std::swap(_cmdEnd, other._cmdEnd); std::swap(_queueCapacity, other._queueCapacity); } BL_INLINE bool empty() const noexcept { return _cmdPtr == _cmdBuf; } BL_INLINE bool full() const noexcept { return _cmdPtr == _cmdEnd; } BL_INLINE size_t queueSize() const noexcept { return (size_t)(_cmdPtr - _cmdBuf) / sizeof(BLRasterCommand); } BL_INLINE size_t queueCapacity() const noexcept { return _queueCapacity; } BL_INLINE BLResult clear() noexcept { _cmdPtr = _cmdBuf; return BL_SUCCESS; } BL_INLINE BLResult reset() noexcept { free(_cmdBuf); _cmdBuf = nullptr; _cmdPtr = nullptr; _cmdEnd = nullptr; _queueCapacity = 0; return BL_SUCCESS; } BLResult reset(size_t capacity) noexcept { BL_ASSERT(capacity > 0); if (capacity != _queueCapacity) { uint8_t* newPtr = nullptr; if (capacity == 0) { free(_cmdBuf); } else { newPtr = static_cast<uint8_t*>(realloc(_cmdBuf, capacity * sizeof(BLRasterCommand))); if (!newPtr) return blTraceError(BL_ERROR_OUT_OF_MEMORY); } _cmdBuf = newPtr; _cmdEnd = _cmdBuf + capacity * sizeof(BLRasterCommand); _queueCapacity = capacity; } _cmdPtr = _cmdBuf; return BL_SUCCESS; } }; //! \} //! \endcond #endif // BLEND2D_RASTER_RASTERCOMMAND_P_H
21.801418
93
0.688029
[ "vector", "solid" ]
dc5e7701a58e1c2301df1e4b35593ee5e1d1de2b
1,954
h
C
dtool/src/cppparser/cppManifest.h
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
3
2020-01-02T08:43:36.000Z
2020-07-05T08:59:02.000Z
dtool/src/cppparser/cppManifest.h
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
dtool/src/cppparser/cppManifest.h
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
1
2020-03-11T17:38:45.000Z
2020-03-11T17:38:45.000Z
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file cppManifest.h * @author drose * @date 1999-10-22 */ #ifndef CPPMANIFEST_H #define CPPMANIFEST_H #include "dtoolbase.h" #include "cppFile.h" #include "cppVisibility.h" #include "cppBisonDefs.h" #include "vector_string.h" class CPPExpression; class CPPType; /** * */ class CPPManifest { public: CPPManifest(const string &args, const cppyyltype &loc); CPPManifest(const string &macro, const string &definition); ~CPPManifest(); static string stringify(const string &source); string expand(const vector_string &args = vector_string()) const; CPPType *determine_type() const; void output(ostream &out) const; string _name; bool _has_parameters; int _num_parameters; int _variadic_param; cppyyltype _loc; CPPExpression *_expr; // Manifests don't have a visibility in the normal sense. Normally this // will be V_public. But a manifest that is defined between __begin_publish // and __end_publish will have a visibility of V_published. CPPVisibility _vis; private: void parse_parameters(const string &args, size_t &p, vector_string &parameter_names); void save_expansion(const string &exp, const vector_string &parameter_names); class ExpansionNode { public: ExpansionNode(int parm_number, bool stringify, bool paste); ExpansionNode(const string &str, bool paste = false); int _parm_number; bool _stringify; bool _paste; string _str; }; typedef vector<ExpansionNode> Expansion; Expansion _expansion; }; inline ostream &operator << (ostream &out, const CPPManifest &manifest) { manifest.output(out); return out; } #endif
24.123457
78
0.716479
[ "vector", "3d" ]
dc8528a20a8055d0501133a1f5b641b554d07ee0
2,774
c
C
lib/SPECTRUM/si1op3.c
Hoeijmakers/StarRotator
4e5857f7dc560acb171ca0739529831c10650ff1
[ "MIT" ]
null
null
null
lib/SPECTRUM/si1op3.c
Hoeijmakers/StarRotator
4e5857f7dc560acb171ca0739529831c10650ff1
[ "MIT" ]
4
2020-09-09T12:46:23.000Z
2020-09-09T13:40:24.000Z
lib/SPECTRUM/si1op3.c
Hoeijmakers/StarRotator
4e5857f7dc560acb171ca0739529831c10650ff1
[ "MIT" ]
null
null
null
#include <math.h> #include <errno.h> #include "spectrum.h" double partfn(double code,double T,double Ne); double si1op(nu,model,j) double nu; atmosphere *model; int j; { double hckt,A,H,waveno,x,u; u = partfn(14.0,model->T[j],model->Ne[j]); waveno = 3.335641e-11*nu; hckt = 1.438832/model->T[j]; H = 1.0e-30; /* 5948.497 A */ if(waveno >= 16810.969) { x = 0.0; A = x*9.0*exp(-49128.131*hckt)*model->stim[j]; H += A; } /* 5625.043 A */ if(waveno >= 17777.641) { x = 18.0e-18*pow(17777.641/waveno,3.0); A = x*15.0*exp(-48161.459*hckt)*model->stim[j]; H += A; } /* 5378.946 A */ if(waveno >= 18587.546) { x = 0.0; A = x*5.0*exp(-47351.554*hckt)*model->stim[j]; H += A; } /* 5360.482 A */ if(waveno >= 18655.039) { x = 0.0; A = x*3.0*exp(-47284.061*hckt)*model->stim[j]; H += A; } /* 4008.463 A */ if(waveno >= 24947.216) { x = 4.09e-18*pow(24947.216/waveno,2.0); A = x*3.0*exp(-40991.884*hckt)*model->stim[j]; H += A; } /* 3834.476 A */ if(waveno >= 26079.180) { x = 1.25e-18*pow(26079.180/waveno,2.0); A = x*9.0*exp(-39859.920*hckt)*model->stim[j]; H += A; } /* 1985.972 A */ if(waveno >= 50353.180) { x = 46.0e-18*pow(50353.180/waveno,5.0); x /= 3.0; A = x*1.0*exp(-15394.370*hckt)*model->stim[j]; H += A; } /* 1974.699 */ if(waveno >= 50640.630) { A *= 2.0 ; H += A; } /* 1682.123 A */ if(waveno >= 59448.700) { x = 35.0e-18*pow(59488.700/waveno,3.0); x /= 3.0; A = x*5.0*exp(- 6298.850*hckt)*model->stim[j]; H += A; } /* 1674.028 A */ if(waveno >= 59736.150) { A *= 2.0 ; H += A; } /* 1576.131 A */ if(waveno >= 63446.510) { x = 18.0e-18*pow(63446.510/waveno,3.0); A = x*15.0*exp(-45303.310*hckt)*model->stim[j]; H += A; } /* 1526.149 A */ if(waveno >= 65524.393) { x = 37.0e-18; if(waveno >= 74000.0) x = x*pow(74000.0/waveno,5.0); x /= 3.0; A = x*5.0*exp(-223.157*hckt)*model->stim[j]; H += A; } /* 1522.755 A */ if(waveno >= 65670.435) { A = x*3.0*exp(-77.115*hckt)*model->stim[j]; H += A; } /* 1520.969 A */ if(waveno >= 65747.550) { A = x*1.0*1.0*model->stim[j]; H += A; } /* 1519.483 A */ if(waveno >= 65811.843) { x *= 2.0; A = x*5.0*exp(-223.157*hckt)*model->stim[j]; H += A; } /* 1516.119 A */ if(waveno >= 65957.885) { A = x*3.0*exp(-77.115*hckt)*model->stim[j]; H += A; } /* 1514.348 A */ if(waveno >= 66035.000) { A = x*1.0*1.0*model->stim[j]; H += A; } /* 1325.842 A */ if(waveno >= 75423.767) { x = 15.0e-18*pow(75423.767/waveno,3.0); A = x*5.0*exp(-33326.053*hckt)*model->stim[j]; H += A; } return(H/u); }
18.870748
56
0.491709
[ "model" ]
dc8ada714e1cbe138b41994ece6456852e13050d
1,206
h
C
datasets/moon data prep/cpp_code/write_csv_int.h
Theeoi/MNXB01-Project
d62e97d5de9d595707c3a1fe65d807a77e496122
[ "MIT" ]
null
null
null
datasets/moon data prep/cpp_code/write_csv_int.h
Theeoi/MNXB01-Project
d62e97d5de9d595707c3a1fe65d807a77e496122
[ "MIT" ]
null
null
null
datasets/moon data prep/cpp_code/write_csv_int.h
Theeoi/MNXB01-Project
d62e97d5de9d595707c3a1fe65d807a77e496122
[ "MIT" ]
null
null
null
#include <string> #include <fstream> #include <vector> #include <utility> // std::pair void write_csv_int(std::string filename, std::vector<std::pair<std::string, std::vector<int>>> dataset){ // Make a CSV file with one or more columns of integer values // Each column of data is represented by the pair <column name, column data> // as std::pair<std::string, std::vector<int>> // The dataset is represented as a vector of these columns // Note that all columns should be the same size // Create an output filestream object std::ofstream myFile(filename); // Send column names to the stream for(int j = 0; j < dataset.size(); ++j) { myFile << dataset.at(j).first; if(j != dataset.size() - 1) myFile << ","; // No comma at end of line } myFile << "\n"; // Send data to the stream for(int i = 0; i < dataset.at(0).second.size(); ++i) { for(int j = 0; j < dataset.size(); ++j) { myFile << dataset.at(j).second.at(i); if(j != dataset.size() - 1) myFile << ","; // No comma at end of line } myFile << "\n"; } // Close the file myFile.close(); }
32.594595
104
0.572139
[ "object", "vector" ]
dc8d7c71188f3ffe49006af78efdc0074d70d08e
4,187
h
C
MathEngine/Expressions/Expression.h
antoniojkim/CalcPlusPlus
33cede17001e0a7038f99ea40dd6f9e433cf6454
[ "MIT" ]
null
null
null
MathEngine/Expressions/Expression.h
antoniojkim/CalcPlusPlus
33cede17001e0a7038f99ea40dd6f9e433cf6454
[ "MIT" ]
null
null
null
MathEngine/Expressions/Expression.h
antoniojkim/CalcPlusPlus
33cede17001e0a7038f99ea40dd6f9e433cf6454
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <map> #include <memory> #include <string> #include <vector> #include <gsl/gsl_complex.h> #include <gsl/gsl_math.h> #include "../Scanner/scanner.h" #include "../Utils/Types.h" class Expression; typedef std::shared_ptr<Expression> expression; typedef std::map<std::string, expression> Variables; extern const Variables emptyVars; typedef expression(*TransformerFunction)(expression); class Expression: public std::enable_shared_from_this<Expression> { public: const Scanner::Type kind; Expression(Scanner::Type kind); virtual ~Expression(); virtual expression simplify(); virtual expression derivative(const std::string& var); virtual expression integrate(const std::string& var); virtual bool isComplex() const = 0; virtual bool isEvaluable(const Variables& vars = emptyVars) const = 0; virtual bool isNumber() const { return false; } virtual expression eval(const Variables& vars = emptyVars) = 0; virtual double value(const Variables& vars = emptyVars) const = 0; virtual gsl_complex complex(const Variables& vars = emptyVars) const; virtual bool equals(expression, double precision=1e-15) const = 0; std::vector<double> array(); virtual expression at(const int index); virtual double get(const int index); virtual size_t shape(const int axis) const; virtual size_t size() const; virtual expression call(expression e); inline expression operator()(expression e){ return call(e); } virtual expression apply(TransformerFunction f); inline expression operator()(TransformerFunction f){ return apply(f); } inline bool is(Scanner::Type kind) const { return this->kind == kind; } virtual std::string repr() const; virtual int id() const; expression copy(); virtual std::ostream& print(std::ostream&, const bool pretty=false) const = 0; virtual std::ostream& postfix(std::ostream&) const = 0; private: struct gsl_expression_struct { Expression* e; const std::string var; Variables vars; gsl_expression_struct(Expression*, const std::string var = "x"); }; static double gsl_expression_function(double x, void* p); std::unique_ptr<gsl_expression_struct> gsl_params; public: virtual gsl_function function(const std::string& var = "x"); private: struct ExpressionIterator { expression e; size_t index; ExpressionIterator(expression e, size_t index); expression operator*(); bool operator==(const ExpressionIterator& other) const; bool operator!=(const ExpressionIterator& other) const; bool operator<(const ExpressionIterator& other) const; bool operator<=(const ExpressionIterator& other) const; bool operator>(const ExpressionIterator& other) const; bool operator>=(const ExpressionIterator& other) const; ExpressionIterator& operator++(); ExpressionIterator& operator--(); }; public: ExpressionIterator begin(); ExpressionIterator end(); }; std::ostream& operator<<(std::ostream&, const expression); #define EXPRESSION_PARTIAL_OVERRIDES \ bool isComplex() const override; \ bool isEvaluable(const Variables& vars = emptyVars) const override; \ bool equals(expression, double precision) const override; \ std::ostream& print(std::ostream&, const bool pretty = false) const override; \ std::ostream& postfix(std::ostream&) const override; #define EXPRESSION_OVERRIDES \ EXPRESSION_PARTIAL_OVERRIDES \ expression eval(const Variables& vars = emptyVars) override; \ double value(const Variables& vars = emptyVars) const override;
35.483051
86
0.624075
[ "shape", "vector" ]
40970e7fdc8c30352748aee6a25f12dd25b596cc
574
h
C
src/Foreach.h
turion64guy/PSPMania
ce837dca954c76fa7188552ade88becf243899bc
[ "Info-ZIP" ]
9
2015-06-10T21:46:09.000Z
2021-04-22T20:47:31.000Z
src/Foreach.h
turion64guy/PSPMania
ce837dca954c76fa7188552ade88becf243899bc
[ "Info-ZIP" ]
null
null
null
src/Foreach.h
turion64guy/PSPMania
ce837dca954c76fa7188552ade88becf243899bc
[ "Info-ZIP" ]
5
2016-06-24T12:06:12.000Z
2021-08-14T17:33:28.000Z
#ifndef Foreach_H #define Foreach_H #define FOREACH( elemType, vect, var ) \ for( vector<elemType>::iterator var = (vect).begin(); var != (vect).end(); ++var ) #define FOREACH_CONST( elemType, vect, var ) \ for( vector<elemType>::const_iterator var = (vect).begin(); var != (vect).end(); ++var ) #define FOREACHD( elemType, vect, var ) \ for( deque<elemType>::iterator var = (vect).begin(); var != (vect).end(); ++var ) #define FOREACHD_CONST( elemType, vect, var ) \ for( deque<elemType>::const_iterator var = (vect).begin(); var != (vect).end(); ++var ) #endif
38.266667
88
0.646341
[ "vector" ]
40a5a15daf84bf70ed41cb927eda06060401b4bc
7,234
h
C
features/encodedMultipleCBPatchFeaturesHistogram.h
csgcmai/lqp_face
db4ec672b352044692f8d1bcbfa181b35567b95c
[ "BSD-3-Clause" ]
1
2020-04-06T16:31:56.000Z
2020-04-06T16:31:56.000Z
features/encodedMultipleCBPatchFeaturesHistogram.h
csgcmai/lqp_face
db4ec672b352044692f8d1bcbfa181b35567b95c
[ "BSD-3-Clause" ]
null
null
null
features/encodedMultipleCBPatchFeaturesHistogram.h
csgcmai/lqp_face
db4ec672b352044692f8d1bcbfa181b35567b95c
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2013, Sibt ul Hussain <sibt.ul.hussain at gmail dot com> All rights reserved. Released under BSD License ------------------------- For license terms please see license.lic */ #ifndef ENCODEDMULTIPLECBPATCHFEATURESHISTOGRAM_H_ #define ENCODEDMULTIPLECBPATCHFEATURESHISTOGRAM_H_ #include"encodedMultipleCBPatchFeatures.h" // Histogram of all the features at Window Level, Twice Normalization once at cell level at 2nd at Window Level.. // Current Implementation only Supports Fix Dimension Windows... // Two Possibilties.. // First To Encode each cell against all the Cell CodeBooks and Negative CodeBooks and then to build histogram // over codebooks for the detection window. // Second To Encode each cell against its respective codeBook just like Pyramid style approach, and -ve // code book.. Now the possiblties are whether to keep the neg-cell code book as cell level or histogram all // the negative codebook contributions into a histogram at window level features... #define LIVE_COMPUTE // set int make file this flag #ifndef LIVE_COMPUTE // works on 64bit systems with more than 4gb of ram class EncodedMultipleCBPatchFeaturesHistogram: public EncodedMultipleCBPatchFeatures { public: EncodedMultipleCBPatchFeaturesHistogram(const LBPParams &lbpparam, UINT width_, UINT height_, UINT nplevels, ProcessImage &pim_, const PatchParams& pparam) : EncodedMultipleCBPatchFeatures(lbpparam, width_, height_, nplevels, pim_, pparam) { ncbs = cwidth * cheight + 1; // code books for each cell... featdim = ncenters * ncbs; // featdim to be used internally // windim = dimension of a window with size cwidth, cheight... if (cbtype == CBT_PosCellNegSep) { windim = (ncenters * 2 * (ncbs - 1)/**/); } else windim = featdim; // to quantize each cell against its own code book and negative code book hnormtype = pparam.hnormtype; tmpfeat.resize(featdim * cwidth * cheight, 0); } virtual ~EncodedMultipleCBPatchFeaturesHistogram() { } void BuildWindowHistogram(REAL *feat); void ComputeLBPFeatures(Image& imgref, UINT index, UINT winstride, UINT tlbpstride); virtual void GetFeatures(UINT index, int x, int y, int width_, int height_, vector<REAL>&feat); virtual void GetFeatures(UINT index, int x, int y, int width_, int height_, REAL *feat); virtual void GetFoldedFeatures(UINT index, int x, int y, int width_, int height_, vector<REAL>&feat); virtual void GetFoldedFeatures(UINT index, int x, int y, int width_, int height_, REAL *feat); virtual void DotProduct(UINT index, UINT fwidth, UINT fheight, vector<REAL>&filter, Store&response); virtual void DotProduct(UINT index, UINT fwidth, UINT fheight, REAL *filter, Store&response); virtual UINT GetDim(UINT width_, UINT height_) const { return GetFeatDim(width_, height_); } virtual UINT GetHOGDim(UINT width_, UINT height_) const { return 0; } virtual UINT GetLBPDim(UINT width_, UINT height_) const { return GetFeatDim(width_, height_);; } virtual UINT GetFoldedLBPDim(UINT width_, UINT height_) const { return GetFeatDim(width_, height_);; } virtual UINT GetFoldedHOGDim(UINT width_, UINT height_) const { return 0; } virtual UINT GetFoldedDim(UINT width_, UINT height_) const { return GetFeatDim(width_, height_); } private: UINT GetFeatDim(UINT width_, UINT height_) const { return /*(width_ / cellsize) * (height_ / cellsize) * celldim*/windim; } protected: UINT windim; // used for external feature dimension calculations... EncodedHistogramNormType hnormtype; vector<REAL> tmpfeat; // used during computation of features... }; #else class EncodedMultipleCBPatchFeaturesHistogram: public EncodedMultipleCBPatchFeatures { public: EncodedMultipleCBPatchFeaturesHistogram(const LBPParams &lbpparam, UINT width_, UINT height_, UINT nplevels, ProcessImage &pim_, const PatchParams& pparam) : EncodedMultipleCBPatchFeatures(lbpparam, width_, height_, nplevels, pim_, pparam) { ncbs = cwidth * cheight + 1; // code books for each cell... featdim = ncenters * ncbs; // featdim to be used internally if (cbtype == CBT_PosCellNegSep) { windim = (ncenters * 2 * (ncbs - 1)/**/); } else windim = featdim; hnormtype = pparam.hnormtype; tmpfeat.resize(featdim * cwidth * cheight, 0); } virtual ~EncodedMultipleCBPatchFeaturesHistogram() { } void BuildWindowHistogram(REAL *feat); void ComputeLBPFeatures(Image& imgref, UINT index, UINT winstride, UINT tlbpstride); virtual void GetFeatures(UINT index, int x, int y, int width_, int height_, vector<REAL>&feat); virtual void GetFeatures(UINT index, int x, int y, int width_, int height_, REAL *feat); virtual void GetFoldedFeatures(UINT index, int x, int y, int width_, int height_, vector<REAL>&feat); virtual void GetFoldedFeatures(UINT index, int x, int y, int width_, int height_, REAL *feat); virtual void DotProduct(UINT index, UINT fwidth, UINT fheight, vector<REAL>&filter, Store&response); virtual void DotProduct(UINT index, UINT fwidth, UINT fheight, REAL *filter, Store&response); virtual void PadFeatureMap(UINT index, UINT padx, UINT pady); virtual UINT GetDim(UINT width_, UINT height_) const { return GetFeatDim(width_, height_); } virtual UINT GetHOGDim(UINT width_, UINT height_) const { return 0; } virtual UINT GetLBPDim(UINT width_, UINT height_) const { return GetFeatDim(width_, height_);; } virtual UINT GetFoldedLBPDim(UINT width_, UINT height_) const { return GetFeatDim(width_, height_);; } virtual UINT GetFoldedHOGDim(UINT width_, UINT height_) const { return 0; } virtual UINT GetFoldedDim(UINT width_, UINT height_) const { return GetFeatDim(width_, height_); } virtual void InitalizeMaps(Image &, PyramidType); virtual void InitalizeMaps(Image &image); virtual void InitalizeMaps(Pyramid &pyobj, PyramidType sspace_); virtual UINT GetXSize(UINT index) { return blockinfo[index].GetX() * cell; } virtual UINT GetYSize(UINT index) { return blockinfo[index].GetY() * cell; } virtual REAL GetScale(UINT index) { return scaleinfo[index]; } void CheckIsComputed(const UINT &index) { if (computedindex != index && index < pyobj.GetNLevels()) { Image & imgref = pyobj.GetImageRef(index); lbpfeatures.Initialize(1, 0, featdim); UINT xbmax, ybmax, padx, pady; GetXYBlocks(imgref, xbmax, ybmax); lbpfeatures.SetFeature(xbmax, ybmax, pyobj.GetScale(index)); ComputeLBPFeatures(imgref, 0, cell, lbpstride); computedindex = index; padinfo[index].GetCoord(padx, pady); if (padx != 0 && pady != 0) { lbpfeatures.PadFeatureMap(0, padx, pady); xbmax = lbpfeatures.GetXBlock(0); ybmax = lbpfeatures.GetYBlock(0); blockinfo[index].SetCoord(xbmax, ybmax); } } } private: UINT GetFeatDim(UINT width_, UINT height_) const { return /*(width_ / cellsize) * (height_ / cellsize) * celldim*/windim; } protected: UINT windim; // used for external feature dimension calculations... EncodedHistogramNormType hnormtype; vector<REAL> tmpfeat; // used during computation of features... vector<Point<UINT> > padinfo; vector<Point<UINT> > blockinfo; vector<REAL> scaleinfo; int computedindex; }; #endif #endif /* ENCODEDMULTIPLECBPATCHFEATURESHISTOGRAM_H_ */
38.275132
113
0.74136
[ "vector" ]
40a5a928bf0f0745d56f8f77cc4e4de55620acc5
2,855
h
C
include/s2mMuscleOptimisation.h
CamWilhelm/biorbd
67d36e77d90cc09aa748c3acf2c2bdff5065d3c9
[ "MIT" ]
null
null
null
include/s2mMuscleOptimisation.h
CamWilhelm/biorbd
67d36e77d90cc09aa748c3acf2c2bdff5065d3c9
[ "MIT" ]
null
null
null
include/s2mMuscleOptimisation.h
CamWilhelm/biorbd
67d36e77d90cc09aa748c3acf2c2bdff5065d3c9
[ "MIT" ]
null
null
null
#ifndef S2MMUSCLEOPTIMISATION_H #define S2MMUSCLEOPTIMISATION_H #include <dlib/optimization.h> #include "biorbdConfig.h" #include "s2mMusculoSkeletalModel.h" #include "s2mMuscleState.h" #include "s2mKalmanReconsMarkers.h" class s2mGenCoord; class s2mMusculoSkeletalModel; class BIORBD_API s2mMuscleOptimisation { public: typedef dlib::matrix<double,1,1> parameter_vector; class OptimData{ public: OptimData(s2mMusculoSkeletalModel &m, const std::vector<s2mGenCoord>& Q, const std::vector<s2mGenCoord>& Qdot, const std::vector<s2mGenCoord>& Qddot, const std::vector<s2mGenCoord>& Tau, const std::vector<std::vector<s2mMuscleStateActual> > state, const unsigned int dofFlex) : m(&m),m_Q(Q),m_QDot(Qdot),m_QDDot(Qddot),m_Tau(Tau),m_s(state),m_dofFlex(dofFlex){ } ~OptimData(){} s2mMusculoSkeletalModel * m; std::vector<s2mGenCoord> Q() const {return m_Q;} s2mGenCoord Q(unsigned int i) const {return m_Q[i];} std::vector<s2mGenCoord> QDot() const {return m_QDot;} s2mGenCoord QDot(unsigned int i) const {return m_QDot[i];} std::vector<s2mGenCoord> QDDot() const {return m_QDDot;} s2mGenCoord QDDot(unsigned int i) const {return m_QDDot[i];} std::vector<s2mGenCoord> Tau() const {return m_Tau;} s2mGenCoord Tau(unsigned int i) const {return m_Tau[i];} std::vector<std::vector<s2mMuscleStateActual> > state() const {return m_s;} std::vector<s2mMuscleStateActual> state(unsigned int i) const {return m_s[i];} unsigned int dofFlex() const {return m_dofFlex;} private: std::vector<s2mGenCoord> m_Q; std::vector<s2mGenCoord> m_QDot; std::vector<s2mGenCoord> m_QDDot; std::vector<s2mGenCoord> m_Tau; std::vector<std::vector<s2mMuscleStateActual> > m_s; unsigned int m_dofFlex; }; s2mMuscleOptimisation(s2mMusculoSkeletalModel& m, const s2mKalmanRecons::s2mKalmanParam &kalmanParam); virtual ~s2mMuscleOptimisation(); /* Lunch an optimization from a model, with Q, Qdot, Qddot and muscleState */ double optimizeJointTorque(s2mMusculoSkeletalModel&, const s2mGenCoord&, const std::vector<s2mMuscleStateActual>&, unsigned int); static void optimizeJointTorque(std::vector<OptimData>& d, parameter_vector& x); protected: static double residual (const OptimData& data, const parameter_vector& x); // Optimization s2mKalmanReconsMarkers *m_kalman; double m_x0; // Solutions initiales }; #endif // S2MMUSCLEOPTIMISATION_H
38.066667
137
0.635727
[ "vector", "model" ]
40ab426223c0b7bd3ca1707bd279c30cd2b22468
1,387
h
C
editor/src/core/EditorRenderer.h
GasimGasimzada/liquid-engine
0d6c8b6b6ec508dc63b970dc23698caf1578147a
[ "MIT" ]
null
null
null
editor/src/core/EditorRenderer.h
GasimGasimzada/liquid-engine
0d6c8b6b6ec508dc63b970dc23698caf1578147a
[ "MIT" ]
null
null
null
editor/src/core/EditorRenderer.h
GasimGasimzada/liquid-engine
0d6c8b6b6ec508dc63b970dc23698caf1578147a
[ "MIT" ]
null
null
null
#pragma once #include "liquid/rhi/RenderGraph.h" #include "liquid/entity/EntityContext.h" #include "liquid/renderer/ShaderLibrary.h" #include "../editor-scene/EditorGrid.h" #include "../ui/IconRegistry.h" #include "EditorRendererStorage.h" namespace liquidator { /** * @brief Editor renderer * * Creates editor shaders and render pass */ class EditorRenderer { public: /** * @brief Create editor renderer * * @param registry Resource registry * @param shaderLibrary Shader library * @param iconRegistry Icon registry */ EditorRenderer(liquid::rhi::ResourceRegistry &registry, liquid::ShaderLibrary &shaderLibrary, IconRegistry &iconRegistry); /** * @brief Attach to render graph * * @param graph Render graph * @return Newly created render pass */ liquid::rhi::RenderGraphPass &attach(liquid::rhi::RenderGraph &graph); /** * @brief Update frame data * * @param entityContext Entity context * @param camera Camerae * @param editorGrid Editor grid */ void updateFrameData(liquid::EntityContext &entityContext, liquid::Entity camera, const EditorGrid &editorGrid); private: EditorRendererStorage mRenderStorage; liquid::rhi::ResourceRegistry &mRegistry; liquid::ShaderLibrary mShaderLibrary; IconRegistry &mIconRegistry; }; } // namespace liquidator
24.333333
76
0.697909
[ "render" ]
40b12219b7c912bd4074542a464af2145eadc71a
4,915
h
C
Endpoints/include/Endpoints/Endpoint.h
immortalkrazy/avs-device-sdk
703b06188eae146af396f58be4e47442d7ce5b1e
[ "Apache-2.0" ]
1,272
2017-08-17T04:58:05.000Z
2022-03-27T03:28:29.000Z
Endpoints/include/Endpoints/Endpoint.h
immortalkrazy/avs-device-sdk
703b06188eae146af396f58be4e47442d7ce5b1e
[ "Apache-2.0" ]
1,948
2017-08-17T03:39:24.000Z
2022-03-30T15:52:41.000Z
Endpoints/include/Endpoints/Endpoint.h
immortalkrazy/avs-device-sdk
703b06188eae146af396f58be4e47442d7ce5b1e
[ "Apache-2.0" ]
630
2017-08-17T06:35:59.000Z
2022-03-29T04:04:44.000Z
/* * Copyright 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. */ #ifndef ALEXA_CLIENT_SDK_ENDPOINTS_INCLUDE_ENDPOINTS_ENDPOINT_H_ #define ALEXA_CLIENT_SDK_ENDPOINTS_INCLUDE_ENDPOINTS_ENDPOINT_H_ #include <list> #include <mutex> #include <set> #include <unordered_map> #include <AVSCommon/AVS/AVSDiscoveryEndpointAttributes.h> #include <AVSCommon/AVS/CapabilityConfiguration.h> #include <AVSCommon/SDKInterfaces/DirectiveHandlerInterface.h> #include <AVSCommon/SDKInterfaces/Endpoints/EndpointIdentifier.h> #include <AVSCommon/SDKInterfaces/Endpoints/EndpointInterface.h> #include <AVSCommon/Utils/RequiresShutdown.h> namespace alexaClientSDK { namespace endpoints { /** * Provides an implementation for @c EndpointInterface. */ class Endpoint : public avsCommon::sdkInterfaces::endpoints::EndpointInterface { public: /// Alias to improve readability. /// @{ using EndpointIdentifier = avsCommon::sdkInterfaces::endpoints::EndpointIdentifier; using EndpointAttributes = avsCommon::avs::AVSDiscoveryEndpointAttributes; /// @} /** * Constructor. * * @param attributes The endpoint attributes. */ Endpoint(const EndpointAttributes& attributes); /** * Destructor. */ ~Endpoint(); /// @name @c EndpointInterface methods. /// @{ EndpointIdentifier getEndpointId() const override; EndpointAttributes getAttributes() const override; std::vector<avsCommon::avs::CapabilityConfiguration> getCapabilityConfigurations() const override; std::unordered_map< avsCommon::avs::CapabilityConfiguration, std::shared_ptr<avsCommon::sdkInterfaces::DirectiveHandlerInterface>> getCapabilities() const override; bool update(const std::shared_ptr<avsCommon::sdkInterfaces::endpoints::EndpointModificationData>& endpointModificationData) override; /// @} /** * Adds the capability configuration and its directive handler to the endpoint. * * @param capabilityConfiguration The capability agent configuration. * @param directiveHandler The @c DirectiveHandler for this capability. * @return True if successful, else false. */ bool addCapability( const avsCommon::avs::CapabilityConfiguration& capabilityConfiguration, std::shared_ptr<avsCommon::sdkInterfaces::DirectiveHandlerInterface> directiveHandler); /** * Removes the capability configuration from the endpoint. * * @param capabilityConfiguration The capability agent configuration. * @return True if successful, else false. */ bool removeCapability(const avsCommon::avs::CapabilityConfiguration& capabilityConfiguration); /** * This method is used to add capability configurations for interfaces that don't have any associated directive. * * @param capabilityConfiguration * @return @c true if successful; @c false otherwise. */ bool addCapabilityConfiguration(const avsCommon::avs::CapabilityConfiguration& capabilityConfiguration); /** * Validate the updated endpoint attributes. * * @param updatedAttributes The updated endpoint attributes. * @return @c true if valid; @c false otherwise. */ bool validateEndpointAttributes(const EndpointAttributes& updatedAttributes); /** * This method can be used to add other objects that require shutdown during endpoint destruction. * * @param requireShutdownObjects The list of objects that require explicit shutdown calls. */ void addRequireShutdownObjects( const std::list<std::shared_ptr<avsCommon::utils::RequiresShutdown>>& requireShutdownObjects); private: /// Mutex used to synchronize members(m_capabilities and m_attributes) access. mutable std::mutex m_mutex; /// The endpoint attributes. EndpointAttributes m_attributes; /// The map of capabilities and the handlers for their directives. std::unordered_map< avsCommon::avs::CapabilityConfiguration, std::shared_ptr<avsCommon::sdkInterfaces::DirectiveHandlerInterface>> m_capabilities; /// The list of objects that require explicit shutdown calls. std::set<std::shared_ptr<avsCommon::utils::RequiresShutdown>> m_requireShutdownObjects; }; } // namespace endpoints } // namespace alexaClientSDK #endif // ALEXA_CLIENT_SDK_ENDPOINTS_INCLUDE_ENDPOINTS_ENDPOINT_H_
36.679104
116
0.7353
[ "vector" ]
40bcf6a19e79864f3cc76e749301405002976820
21,085
c
C
rts/parallel/SysMan.c
matchwood/ghc
a8787ece1d6cd807fb3c76efd80753e7ffc87f1e
[ "BSD-3-Clause" ]
1
2019-03-02T10:20:54.000Z
2019-03-02T10:20:54.000Z
rts/parallel/SysMan.c
ilyasergey/GHC-XAppFix
fa7242d23be7bab749d4f3556282b2ffabecc44c
[ "BSD-3-Clause" ]
1
2015-11-11T09:02:10.000Z
2015-11-14T01:41:29.000Z
rts/parallel/SysMan.c
emorins/nahc
eb18f1f22c99eae0cb58a8a674a2d58434476376
[ "BSD-3-Clause" ]
2
2018-08-09T13:00:49.000Z
2022-03-02T14:24:03.000Z
/* ---------------------------------------------------------------------------- Time-stamp: <Wed Mar 21 2001 17:16:28 Stardate: [-30]6363.59 hwloidl> GUM System Manager Program Handles startup, shutdown and global synchronisation of the parallel system. The Parade/AQUA Projects, Glasgow University, 1994-1995. GdH/APART Projects, Heriot-Watt University, Edinburgh, 1997-2000. ------------------------------------------------------------------------- */ //@node GUM System Manager Program, , , //@section GUM System Manager Program //@menu //* General docu:: //* Includes:: //* Macros etc:: //* Variables:: //* Prototypes:: //* Aux startup and shutdown fcts:: //* Main fct:: //* Message handlers:: //* Auxiliary fcts:: //* Index:: //@end menu //@node General docu, Includes, GUM System Manager Program, GUM System Manager Program //@subsection General docu /* The Sysman task currently controls initiation, termination, of a parallel Haskell program running under GUM. In the future it may control global GC synchronisation and statistics gathering. Based on K. Hammond's SysMan.lc in Graph for PVM. SysMan is unusual in that it is not part of the executable produced by ghc: it is a free-standing program that spawns PVM tasks (logical PEs) to evaluate the program. After initialisation it runs in parallel with the PE tasks, awaiting messages. OK children, buckle down for some serious weirdness, it works like this ... o The argument vector (argv) for SysMan has one the following 2 shapes: ------------------------------------------------------------------------------- | SysMan path | debug flag | pvm-executable path | Num. PEs | Program Args ...| ------------------------------------------------------------------------------- ------------------------------------------------------------------- | SysMan path | pvm-executable path | Num. PEs | Program Args ... | ------------------------------------------------------------------- The "pvm-executable path" is an absolute path of where PVM stashes the code for each PE. The arguments passed on to each PE-executable spawned by PVM are: ------------------------------- | Num. PEs | Program Args ... | ------------------------------- The arguments passed to the Main-thread PE-executable are ------------------------------------------------------------------- | main flag | pvm-executable path | Num. PEs | Program Args ... | ------------------------------------------------------------------- o SysMan's algorithm is as follows. o use PVM to spawn (nPE-1) PVM tasks o fork SysMan to create the main-thread PE. This permits the main-thread to read and write to stdin and stdout. o Wait for all the PE-tasks to reply back saying they are ready and if they were the main thread or not. o Broadcast an array of the PE task-ids out to all of the PE-tasks. o Enter a loop awaiting incoming messages, e.g. failure, Garbage-collection, termination. The forked Main-thread algorithm, in SysMan, is as follows. o disconnects from PVM. o sets a flag in argv to indicate that it is the main thread. o `exec's a copy of the pvm-executable (i.e. the program being run) The pvm-executable run by each PE-task, is initialised as follows. o Registers with PVM, obtaining a task-id. o If it was main it gets SysMan's task-id from argv otherwise it can use pvm_parent. oSends a ready message to SysMan together with a flag indicating if it was main or not. o Receives from SysMan the array of task-ids of the other PEs. o If the number of task-ids sent was larger than expected then it must have been a task generated after the rest of the program had started, so it sends its own task-id message to all the tasks it was told about. o Begins execution. */ //@node Includes, Macros etc, General docu, GUM System Manager Program //@subsection Includes /* Evidently not Posix */ /* #include "PosixSource.h" */ #include "Rts.h" #include "ParTypes.h" #include "LLC.h" #include "Parallel.h" #include "ParallelRts.h" // stats only //@node Macros etc, Variables, Includes, GUM System Manager Program //@subsection Macros etc /* SysMan is put on top of the GHC routine that does the RtsFlags handling. So, we cannot use the standard macros. For the time being we use a macro that is fixed at compile time. */ #ifdef IF_PAR_DEBUG #undef IF_PAR_DEBUG #endif /* debugging enabled */ //#define IF_PAR_DEBUG(c,s) { s; } /* debugging disabled */ #define IF_PAR_DEBUG(c,s) /* nothing */ void *stgMallocBytes (int n, char *msg); //@node Variables, Prototypes, Macros etc, GUM System Manager Program //@subsection Variables /* The following definitions included so that SysMan can be linked with Low Level Communications module (LLComms). They are not used in SysMan. */ GlobalTaskId mytid; static unsigned PEsArrived = 0; static GlobalTaskId gtids[MAX_PES]; static GlobalTaskId sysman_id, sender_id; static unsigned PEsTerminated = 0; static rtsBool Finishing = rtsFalse; static long PEbuffer[MAX_PES]; nat nSpawn = 0; // current no. of spawned tasks (see gtids) nat nPEs = 0; // number of PEs specified on startup nat nextPE; /* PVM-ish variables */ char *petask, *pvmExecutable; char **pargv; int cc, spawn_flag = PvmTaskDefault; #if 0 && defined(PAR_TICKY) /* ToDo: use allGlobalParStats to collect stats of all PEs */ GlobalParStats *allGlobalParStats[MAX_PES]; #endif //@node Prototypes, Aux startup and shutdown fcts, Variables, GUM System Manager Program //@subsection Prototypes /* prototypes for message handlers called from the main loop of SysMan */ void newPE(int nbytes, int opcode, int sender_id); void readyPE(int nbytes, int opcode, int sender_id); void finishPE(int nbytes, int opcode, int sender_id, int exit_code); //@node Aux startup and shutdown fcts, Main fct, Prototypes, GUM System Manager Program //@subsection Aux startup and shutdown fcts /* Create the PE Tasks. We spawn (nPEs-1) pvm threads: the Main Thread (which starts execution and performs IO) is created by forking SysMan */ static int createPEs(int total_nPEs) { int i, spawn_nPEs, iSpawn = 0, nArch, nHost; struct pvmhostinfo *hostp; int sysman_host; spawn_nPEs = total_nPEs-1; if (spawn_nPEs > 0) { IF_PAR_DEBUG(verbose, fprintf(stderr, "==== [%x] Spawning %d PEs(%s) ...\n", sysman_id, spawn_nPEs, petask); fprintf(stderr, " args: "); for (i = 0; pargv[i]; ++i) fprintf(stderr, "%s, ", pargv[i]); fprintf(stderr, "\n")); pvm_config(&nHost,&nArch,&hostp); sysman_host=pvm_tidtohost(sysman_id); /* create PEs on the specific machines in the specified order! */ for (i=0; (iSpawn<spawn_nPEs) && (i<nHost); i++) if (hostp[i].hi_tid != sysman_host) { checkComms(pvm_spawn(petask, pargv, spawn_flag+PvmTaskHost, hostp[i].hi_name, 1, gtids+iSpawn), "SysMan startup"); IF_PAR_DEBUG(verbose, fprintf(stderr, "==== [%x] Spawned PE %d onto %s\n", sysman_id, i, hostp[i].hi_name)); iSpawn++; } /* create additional PEs anywhere you like */ if (iSpawn<spawn_nPEs) { checkComms(pvm_spawn(petask, pargv, spawn_flag, "", spawn_nPEs-iSpawn, gtids+iSpawn), "SysMan startup"); IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] Spawned %d additional PEs anywhere\n", sysman_id, spawn_nPEs-iSpawn)); } } #if 0 /* old code with random placement of PEs; make that a variant? */ # error "Broken startup in SysMan" { /* let pvm place the PEs anywhere; not used anymore */ checkComms(pvm_spawn(petask, pargv, spawn_flag, "", spawn_nPEs, gtids),"SysMan startup"); IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] Spawned\n", sysman_id)); } #endif // iSpawn=spawn_nPEs; return iSpawn; } /* Check if this pvm task is in the list of tasks we spawned and are waiting on, if so then remove it. */ static rtsBool alreadySpawned (GlobalTaskId g) { unsigned int i; for (i=0; i<nSpawn; i++) if (g==gtids[i]) { nSpawn--; gtids[i] = gtids[nSpawn]; //the last takes its place return rtsTrue; } return rtsFalse; } static void broadcastFinish(void) { int i,j; int tids[MAX_PES]; /* local buffer of all surviving PEs */ for (i=0, j=0; i<nPEs; i++) if (PEbuffer[i]) tids[j++]=PEbuffer[i]; //extract valid tids IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] Broadcasting Finish to %d PEs; initiating shutdown\n", sysman_id, j)); /* ToDo: move into LLComms.c */ pvm_initsend(PvmDataDefault); pvm_mcast(tids,j,PP_FINISH); } static void broadcastPEtids (void) { nat i; IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] SysMan sending PE table to all PEs\n", sysman_id); /* debugging */ fprintf(stderr,"++++ [%x] PE table as seen by SysMan:\n", mytid); for (i = 0; i < nPEs; i++) { fprintf(stderr,"++++ PEbuffer[%d] = %x\n", i, PEbuffer[i]); } ) broadcastOpN(PP_PETIDS, PEGROUP, nPEs, &PEbuffer); } //@node Main fct, Message handlers, Aux startup and shutdown fcts, GUM System Manager Program //@subsection Main fct //@cindex main int main (int argc, char **argv) { int rbufid; int opcode, nbytes, nSpawn; unsigned int i; setbuf(stdout, NULL); // disable buffering of stdout setbuf(stderr, NULL); // disable buffering of stderr IF_PAR_DEBUG(verbose, fprintf(stderr, "==== RFP: GdH enabled SysMan reporting for duty\n")); if (argc > 1) { if (*argv[1] == '-') { spawn_flag = PvmTaskDebug; argv[1] = argv[0]; argv++; argc--; } sysman_id = pvm_mytid(); /* This must be the first PVM call */ if (sysman_id<0) { fprintf(stderr, "==== PVM initialisation failure\n"); exit(EXIT_FAILURE); } /* Get the full path and filename of the pvm executable (stashed in some PVM directory), and the number of PEs from the command line. */ pvmExecutable = argv[1]; nPEs = atoi(argv[2]); if (nPEs==0) { /* as usual 0 means infinity: use all PEs specified in PVM config */ int nArch, nHost; struct pvmhostinfo *hostp; /* get info on PVM config */ pvm_config(&nHost,&nArch,&hostp); nPEs=nHost; sprintf(argv[2],"%d",nPEs); /* ToCheck: does this work on all archs */ } /* get the name of the binary to execute */ if ((petask = getenv(PETASK)) == NULL) // PETASK set by driver petask = PETASK; IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] nPEs: %d; executable: |%s|\n", sysman_id, nPEs, petask)); /* Check that we can create the number of PE and IMU tasks requested. ^^^ This comment is most entertaining since we haven't been using IMUs for the last 10 years or so -- HWL */ if ((nPEs > MAX_PES) || (nPEs<1)) { fprintf(stderr,"==** SysMan: No more than %d PEs allowed (%d requested)\n Reconfigure GUM setting MAX_PE in ghc/includes/Parallel.h to a higher value\n", MAX_PES, nPEs); exit(EXIT_FAILURE); } IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] is SysMan Task\n", sysman_id)); /* Initialise the PE task arguments from Sysman's arguments */ pargv = argv + 2; /* Initialise list of all PE identifiers */ PEsArrived=0; nextPE=1; for (i=0; i<nPEs; i++) PEbuffer[i]=0; /* start up the required number of PEs */ nSpawn = createPEs(nPEs); /* Create the MainThread PE by forking SysMan. This arcane coding is required to allow MainThread to read stdin and write to stdout. PWT 18/1/96 */ //nPEs++; /* Record that the number of PEs is increasing */ if ((cc = fork())) { checkComms(cc,"SysMan fork"); /* Parent continues as SysMan */ PEbuffer[0]=0; /* we accept the first main and assume its valid. */ PEsArrived=1; /* assume you've got main */ IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] Sysman successfully initialized!\n", sysman_id)); //@cindex message handling loop /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Main message handling loop */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* Process incoming messages */ while (1) { if ((rbufid = pvm_recv(ANY_TASK, ANY_OPCODE)) < 0) { pvm_perror("==** Sysman: Receiving Message (pvm_recv)"); /* never reached */ } pvm_bufinfo(rbufid, &nbytes, &opcode, &sender_id); /* very low level debugging IF_PAR_DEBUG(verbose, fprintf(stderr,"== [%x] SysMan: Message received by SysMan: rbufid=%x, nbytes = %d, opcode = %x, sender_id = %x\n", sysman_id, rbufid, nbytes, opcode, sender_id)); */ switch (opcode) { case PP_NEWPE: /* a new PE is registering for work */ newPE(nbytes, opcode, sender_id); break; case PP_READY: /* startup complete; let PEs start working */ readyPE(nbytes, opcode, sender_id); break; case PP_GC_INIT: /* start global GC */ /* This Function not yet implemented for GUM */ fprintf(stderr,"==** Global GC requested by PE %x. Not yet implemented for GUM!\n", sender_id); break; case PP_STATS_ON: /* enable statistics gathering */ fprintf(stderr,"==** PP_STATS_ON requested by %x. Not yet implemented for GUM!\n", sender_id); break; case PP_STATS_OFF: /* disable statistics gathering */ fprintf(stderr,"==** PP_STATS_OFF requested by %x. Not yet implemented for GUM!\n", sender_id); break; case PP_FINISH: { int exit_code = getExitCode(nbytes, &sender_id); finishPE(nbytes, opcode, sender_id, exit_code); break; default: { /* char *opname = GetOpName(opcode); fprintf(stderr,"Sysman: Unrecognised opcode %s (%x)\n", opname,opcode); */ fprintf(stderr,"==** Qagh: Sysman: Unrecognised opcode (%x)\n", opcode); } break; } /* switch */ } /* else */ } /* while 1 */ /* end of SysMan!! */ } else { /* forked main thread begins here */ IF_PAR_DEBUG(verbose, fprintf(stderr, "==== Main Thread PE has been forked; doing an execv(%s,...)\n", pvmExecutable)); pvmendtask(); // Disconnect from PVM to avoid confusion: // executable reconnects // RFP: assumes that length(arvv[0])>=9 !!! sprintf(argv[0],"-%08X",sysman_id); /*flag that its the Main Thread PE and include sysman's id*/ execv(pvmExecutable,argv); /* Parent task becomes Main Thread PE */ } /* else */ } /* argc > 1 */ } /* main */ //@node Message handlers, Auxiliary fcts, Main fct, GUM System Manager Program //@subsection Message handlers /* Received PP_NEWPE: A new PE has been added to the configuration. */ void newPE(int nbytes, int opcode, int sender_id) { IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] SysMan detected a new host\n", sysman_id)); /* Determine the new machine... assume its the last on the config list? */ if (nSpawn < MAX_PES) { int nArch,nHost; struct pvmhostinfo *hostp; /* get conmfiguration of PVM machine */ pvm_config(&nHost,&nArch,&hostp); nHost--; checkComms(pvm_spawn(petask, pargv, spawn_flag+PvmTaskHost, hostp[nHost].hi_name, 1, gtids+nSpawn), "SysMan loop"); nSpawn++; IF_PAR_DEBUG(verbose, fprintf(stderr, "==== [%x] Spawned onto %s\n", sysman_id, hostp[nHost].hi_name)); } } /* Received PP_READY: Let it be known that PE @sender_id@ participates in the computation. */ void readyPE(int nbytes, int opcode, int sender_id) { int i = 0, flag = 1; long isMain; int nArch, nHost; struct pvmhostinfo *hostp; //ASSERT(opcode==PP_READY); IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] SysMan received PP_READY message from %x\n", sysman_id, sender_id)); pvm_config(&nHost,&nArch,&hostp); GetArg1(isMain); //if ((isMain && (PEbuffer[0]==0)) || alreadySpawned(sender_id)) { if (nPEs >= MAX_PES) { fprintf(stderr,"==== [%x] SysMan doesn't need PE %d (max %d PEs allowed)\n", sysman_id, sender_id, MAX_PES); pvm_kill(sender_id); } else { if (isMain) { IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] SysMan found Main PE %x\n", sysman_id, sender_id)); PEbuffer[0]=sender_id; } else { /* search for PE in list of PEs */ for(i=1; i<nPEs; i++) if (PEbuffer[i]==sender_id) { flag=0; break; } /* it's a new PE: add it to the list of PEs */ if (flag) PEbuffer[nextPE++] = sender_id; IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] SysMan: found PE %d as [%x] on host %s\n", sysman_id, PEsArrived, sender_id, hostp[PEsArrived].hi_name)); PEbuffer[PEsArrived++] = sender_id; } /* enable better handling of unexpected terminations */ checkComms( pvm_notify(PvmTaskExit, PP_FINISH, 1, &sender_id), "SysMan loop"); /* finished registration of all PEs => enable notification */ if ((PEsArrived==nPEs) && PEbuffer[0]) { checkComms( pvm_notify(PvmHostAdd, PP_NEWPE, -1, 0), "SysMan startup"); IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] SysMan initialising notificaton for new hosts\n", sysman_id)); } /* finished notification => send off the PE ids */ if ((PEsArrived>=nPEs) && PEbuffer[0]) { if (PEsArrived>nPEs) { IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] Weird: %d PEs registered, but we only asked for %d\n", sysman_id, PEsArrived, nPEs)); // nPEs=PEsArrived; } broadcastPEtids(); } } } /* Received PP_FINISH: Shut down the corresponding PE. Check whether it is a regular shutdown or an uncontrolled termination. */ void finishPE(int nbytes, int opcode, int sender_id, int exitCode) { int i; IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] SysMan received PP_FINISH message from %x (exit code: %d)\n", sysman_id, sender_id, exitCode)); /* Is it relevant to us? Count the first message */ for (i=0; i<nPEs; i++) if (PEbuffer[i] == sender_id) { PEsTerminated++; PEbuffer[i]=0; /* handle exit code */ if (exitCode<0) { /* a task exit before a controlled finish? */ fprintf(stderr,"==== [%x] Termination at %x with exit(%d)\n", sysman_id, sender_id, exitCode); } else if (exitCode>0) { /* an abnormal exit code? */ fprintf(stderr,"==== [%x] Uncontrolled termination at %x with exit(%d)\n", sysman_id, sender_id, exitCode); } else if (!Finishing) { /* exitCode==0 which is good news */ if (i!=0) { /* someone other than main PE terminated first? */ fprintf(stderr,"==== [%x] Unexpected early termination at %x\n", sysman_id, sender_id); } else { /* start shutdown by broadcasting FINISH to other PEs */ IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] Initiating shutdown (requested by [%x] RIP) (exit code: %d)\n", sysman_id, sender_id, exitCode)); Finishing = rtsTrue; broadcastFinish(); } } else { /* we are in a shutdown already */ IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] Finish from %x during shutdown (%d PEs terminated so far; %d total)\n", sysman_id, sender_id, PEsTerminated, nPEs)); } if (PEsTerminated >= nPEs) { IF_PAR_DEBUG(verbose, fprintf(stderr,"==== [%x] Global Shutdown, Goodbye!! (SysMan has received FINISHes from all PEs)\n", sysman_id)); //broadcastFinish(); /* received finish from everybody; now, we can exit, too */ exit(EXIT_SUCCESS); /* Qapla'! */ } } } //@node Auxiliary fcts, Index, Message handlers, GUM System Manager Program //@subsection Auxiliary fcts /* Needed here because its used in loads of places like LLComms etc */ //@cindex stg_exit /* * called from STG-land to exit the program */ void stg_exit(I_ n) { fprintf(stderr, "==// [%x] %s in SysMan code; sending PP_FINISH to all PEs ...\n", mytid,(n!=0)?"FAILURE":"FINISH"); broadcastFinish(); //broadcastFinish(); pvm_exit(); exit(n); } //@node Index, , Auxiliary fcts, GUM System Manager Program //@subsection Index //@index //* main:: @cindex\s-+main //* message handling loop:: @cindex\s-+message handling loop //* stgMallocBytes:: @cindex\s-+stgMallocBytes //* stg_exit:: @cindex\s-+stg_exit //@end index
32.388633
164
0.605786
[ "vector" ]
40c23e8031cdbeccc5fe02185557ce49aa79a833
533
h
C
autokernel_plugin/src/fc/fc.h
Hconk/AutoKernel
edfb409efe37e2aea5350961e3a8160c11856853
[ "Apache-2.0" ]
null
null
null
autokernel_plugin/src/fc/fc.h
Hconk/AutoKernel
edfb409efe37e2aea5350961e3a8160c11856853
[ "Apache-2.0" ]
null
null
null
autokernel_plugin/src/fc/fc.h
Hconk/AutoKernel
edfb409efe37e2aea5350961e3a8160c11856853
[ "Apache-2.0" ]
1
2020-12-11T06:26:10.000Z
2020-12-11T06:26:10.000Z
#include <stdio.h> #include <math.h> extern "C" { #include "sys_port.h" #include "tengine_errno.h" #include "tengine_log.h" #include "vector.h" #include "tengine_ir.h" #include "tengine_op.h" #include "../../dev/cpu/cpu_node_ops.h" // include op param header file here, locate in src/op/ #include "fc_param.h" } #include "HalideBuffer.h" // include the c_header file here #include "halide_fc.h" void RegisterAutoKernelFc();
22.208333
60
0.577861
[ "vector" ]
40c57bd047184a11b351df26e1ab954db07ff8fa
720
h
C
model/src/ActivitySelectStmtImpl.h
mballance-sf/open-ps
a5ed44ce30bfe59462801ca7de4361d16950bcd2
[ "Apache-2.0" ]
null
null
null
model/src/ActivitySelectStmtImpl.h
mballance-sf/open-ps
a5ed44ce30bfe59462801ca7de4361d16950bcd2
[ "Apache-2.0" ]
null
null
null
model/src/ActivitySelectStmtImpl.h
mballance-sf/open-ps
a5ed44ce30bfe59462801ca7de4361d16950bcd2
[ "Apache-2.0" ]
null
null
null
/* * ActivitySelectStmtImpl.h * * Created on: May 27, 2018 * Author: ballance */ #pragma once #include "BaseItemImpl.h" #include "IActivitySelectStmt.h" class ActivitySelectStmtImpl : public virtual BaseItemImpl, public virtual IActivitySelectStmt { public: ActivitySelectStmtImpl( const std::vector<IActivitySelectBranchStmt *> &branches); virtual ~ActivitySelectStmtImpl(); virtual IActivityStmt::ActivityStmtType getStmtType() const { return IActivityStmt::ActivityStmt_Select; } virtual const std::vector<IActivitySelectBranchStmt *> &getBranches() const { return m_branches; } virtual IActivityStmt *clone() const; private: std::vector<IActivitySelectBranchStmt *> m_branches; };
21.818182
96
0.7625
[ "vector" ]
40c9e0e30224ed3775daa5883a27fb27be343a78
2,404
h
C
itensor/mps/integrators.h
alexwie/ITensor
867dcc6bb0de152b5e5d19969cb09dd8ed1d53fc
[ "Apache-2.0" ]
313
2015-03-06T21:58:52.000Z
2022-03-29T08:58:06.000Z
itensor/mps/integrators.h
alexwie/ITensor
867dcc6bb0de152b5e5d19969cb09dd8ed1d53fc
[ "Apache-2.0" ]
267
2015-02-26T12:52:57.000Z
2022-02-04T20:21:52.000Z
itensor/mps/integrators.h
alexwie/ITensor
867dcc6bb0de152b5e5d19969cb09dd8ed1d53fc
[ "Apache-2.0" ]
169
2015-01-12T01:27:56.000Z
2022-03-24T08:24:55.000Z
// // Copyright 2018 The Simons Foundation, 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 __ITENSOR_INTEGRATORS_H #define __ITENSOR_INTEGRATORS_H #include "itensor/global.h" namespace itensor { // // 4th Order Runge-Kutta. // Assumes a time-independent Force. // The vector v should be 1 indexed. // template <class Tensor, typename Deriv> void rungeKutta4(const Deriv& D, Real tstep, std::vector<Tensor>& v, const Args& args = Args::global()) { int N = int(v.size())-1; while(!v.at(N) && N > 1) --N; if(N <= 0) Error("Empty vector v (v should be 1-indexed)"); std::vector<Tensor> k1,k2,k3,k4; k1 = D(v); //d = v + (tstep/2)*k1 std::vector<Tensor> d(v); for(int j = 1; j <= N; ++j) { d.at(j) += (tstep/2.)*k1.at(j); } k2 = D(d); //d = v + (tstep/2)*k2 d = v; for(int j = 1; j <= N; ++j) { d.at(j) += (tstep/2.)*k2.at(j); } k3 = D(d); //d = v + (tstep)*k3 d = v; for(int j = 1; j <= N; ++j) { d.at(j) += (tstep)*k3.at(j); } k4 = D(d); for(int j = 1; j <= N; ++j) { v.at(j) += (tstep/6.)*(k1.at(j) + 2*k2.at(j) + 2*k3.at(j) + k4.at(j)); } } template <class Tensor, typename Deriv> void midpointMethod(const Deriv& D, Real tstep, std::vector<Tensor>& v, const Args& args = Args::global()) { int N = int(v.size())-1; while(!v.at(N) && N > 1) --N; if(N <= 0) Error("Empty vector v (v should be 1-indexed)"); std::vector<Tensor> k1,k2,k3,k4; k1 = D(v); std::vector<Tensor> d(v); for(int j = 1; j <= N; ++j) { d.at(j) += (tstep/2.)*k1.at(j); } k2 = D(d); for(int j = 1; j <= N; ++j) { v.at(j) += tstep*k2.at(j); } } } //namespace itensor #endif
23.339806
78
0.542845
[ "vector" ]
40d6a14d9720bb6ffd54f97b887e831392cd8864
1,425
h
C
libnuklei/io/nuklei/CrdObservationIO.h
chungying/nuklei
23db2a55a1b3260cf913d0ac10b3b27c000ae1a6
[ "BSD-3-Clause" ]
null
null
null
libnuklei/io/nuklei/CrdObservationIO.h
chungying/nuklei
23db2a55a1b3260cf913d0ac10b3b27c000ae1a6
[ "BSD-3-Clause" ]
null
null
null
libnuklei/io/nuklei/CrdObservationIO.h
chungying/nuklei
23db2a55a1b3260cf913d0ac10b3b27c000ae1a6
[ "BSD-3-Clause" ]
null
null
null
// (C) Copyright Renaud Detry 2007-2015. // Distributed under the GNU General Public License and under the // BSD 3-Clause License (See accompanying file LICENSE.txt). /** @file */ #ifndef NUKLEI_CRDOBSERVATIONSERIAL_H #define NUKLEI_CRDOBSERVATIONSERIAL_H #include <nuklei/Definitions.h> #include <nuklei/ObservationIO.h> #include <nuklei/CrdObservation.h> namespace nuklei { class CrdReader : public ObservationReader { public: CrdReader(const std::string &observationFileName); ~CrdReader(); Observation::Type type() const { return Observation::CRD; } void reset(); protected: void init_(); std::auto_ptr<Observation> readObservation_(); private: std::ifstream in_; std::string observationFileName; }; class CrdWriter : public ObservationWriter { public: CrdWriter(const std::string &observationFileName, bool syncpc = false); ~CrdWriter(); Observation::Type type() const { return Observation::CRD; } void init(); void reset(); std::auto_ptr<Observation> templateObservation() const { return std::auto_ptr<Observation>(new CrdObservation); } void writeObservation(const Observation &o); void writeBuffer(); private: std::string observationFileName_; bool syncpc_; // write "syncpc" on the first line. std::vector<Vector3> points_; }; } #endif
21.923077
75
0.675088
[ "vector" ]
40d9d7104965e6707506fc67d680842c02ff5cf4
4,835
c
C
boastmath/src/matrix.c
elementbound/boaster
e70728def59d78c91d2194fb7dfca9ec6f4c64d2
[ "MIT" ]
2
2020-07-04T20:51:37.000Z
2020-10-01T19:38:04.000Z
boastmath/src/matrix.c
elementbound/boaster
e70728def59d78c91d2194fb7dfca9ec6f4c64d2
[ "MIT" ]
null
null
null
boastmath/src/matrix.c
elementbound/boaster
e70728def59d78c91d2194fb7dfca9ec6f4c64d2
[ "MIT" ]
null
null
null
/* * This file contains code parts based on the Mesa library's implementation of * matrix operations. These parts are marked as such by a comment. * * Included the Mesa license: * Mesa 3-D graphics library * * Copyright (C) 1999-2005 Brian Paul All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <math.h> #include "include/boastmath/matrix.h" #include "include/boastmath/vector.h" #define R(row, col) result[(row) * 4 + (col)] #define A(row, col) a[(row) * 4 + (col)] #define B(row, col) b[(row) * 4 + (col)] #define RV(i) result[i] #define V(i) v[i] // Based on the Mesa implementation // See: https://gitlab.freedesktop.org/mesa/mesa/-/blob/master/src/mesa/math/m_matrix.c void bm_matmul (bm_mat4 result, bm_mat4 a, bm_mat4 b) { #pragma GCC unroll 4 #pragma GCC ivdep for (int i = 0; i < 4; i++) { const float ai0 = A(i, 0); const float ai1 = A(i, 1); const float ai2 = A(i, 2); const float ai3 = A(i, 3); R(i, 0) = ai0 * B(0, 0) + ai1 * B(1, 0) + ai2 * B(2, 0) + ai3 * B(3, 0); R(i, 1) = ai0 * B(0, 1) + ai1 * B(1, 1) + ai2 * B(2, 1) + ai3 * B(3, 1); R(i, 2) = ai0 * B(0, 2) + ai1 * B(1, 2) + ai2 * B(2, 2) + ai3 * B(3, 2); R(i, 3) = ai0 * B(0, 3) + ai1 * B(1, 3) + ai2 * B(2, 3) + ai3 * B(3, 3); } } void bm_mattrans (bm_vec4 result, bm_mat4 a, bm_vec4 v) { RV(0) = V(0) * A(0, 0) + V(1) * A(0, 1) + V(2) * A(0, 2) + V(3) * A(0, 3); RV(1) = V(0) * A(1, 0) + V(1) * A(1, 1) + V(2) * A(1, 2) + V(3) * A(1, 3); RV(2) = V(0) * A(2, 0) + V(1) * A(2, 1) + V(2) * A(2, 2) + V(3) * A(2, 3); RV(3) = V(0) * A(3, 0) + V(1) * A(3, 1) + V(2) * A(3, 2) + V(3) * A(3, 3); } // See: http://songho.ca/opengl/gl_camera.html#lookat void bm_mat_lookat ( bm_mat4 result, float fromX, float fromY, float fromZ, float atX, float atY, float atZ, float upX, float upY, float upZ ) { bm_vec4 from = {fromX, fromY, fromZ}; bm_vec4 at = {atX, atY, atZ, 0.0}; bm_vec4 up = {upX, upY, upZ, 0.0}; bm_vec4 forward = { fromX - atX, fromY - atY, fromZ - atZ, 0.0 }; bm_vecnormalize(forward); bm_vec4 left; bm_veccross(left, up, forward); bm_vecnormalize(left); bm_veccross(up, forward, left); R(0, 0) = left[0]; R(0, 1) = left[1]; R(0, 2) = left[2]; R(0, 3) = -left[0] * fromX - left[1] * fromY - left[2] * fromZ; R(1, 0) = up[0]; R(1, 1) = up[1]; R(1, 2) = up[2]; R(1, 3) = -up[0] * fromX - up[1] * fromY - up[2] * fromZ; R(2, 0) = forward[0]; R(2, 1) = forward[1]; R(2, 2) = forward[2]; R(2, 3) = -forward[0] * fromX - forward[1] * fromY - forward[2] * fromZ; R(3, 0) = 0.0; R(3, 1) = 0.0; R(3, 2) = 0.0; R(3, 3) = 1.0; } // See: http://www.songho.ca/opengl/gl_projectionmatrix.html#perspective void bm_mat_perspective ( bm_mat4 result, float left, float right, float top, float bottom, float near, float far // (float) wherever you are ) { R(0, 0) = (2 * near) / (right - left); R(0, 1) = 0.0; R(0, 2) = (right + left) / (right - left); R(0, 3) = 0.0; R(1, 0) = 0.0; R(1, 1) = (2 * near) / (top - bottom); R(1, 2) = (top + bottom) / (top - bottom); R(1, 3) = 0.0; R(2, 0) = 0.0; R(2, 1) = 0.0; R(2, 2) = -(far + near) / (far - near); R(2, 3) = -(2 * near * far) / (far - near); R(3, 0) = 0.0; R(3, 1) = 0.0; R(3, 2) = -1.0; R(3, 3) = 0.0; } void bm_mat_perspective_fov ( bm_mat4 result, float aspect, float fov, float near, float far ) { const float width = 2.0 * near * tanf(fov / 2.0); const float height = width * aspect; bm_mat_perspective(result, -width / 2.0, width / 2.0, -height / 2.0, height / 2.0, near, far ); }
32.449664
87
0.568769
[ "vector" ]
40e12de1b23595ec89d48c18cecadce406bb3e88
2,378
h
C
Source/WebCore/workers/ServiceWorker.h
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
Source/WebCore/workers/ServiceWorker.h
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
9
2020-04-18T18:47:18.000Z
2020-04-18T18:52:41.000Z
Source/WebCore/workers/ServiceWorker.h
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2017 Apple 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 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. */ #pragma once #if ENABLE(SERVICE_WORKER) #include "EventTarget.h" #include <heap/Strong.h> namespace JSC { class ExecState; class JSValue; } namespace WebCore { class Frame; class ServiceWorker final : public EventTargetWithInlineData { public: static Ref<ServiceWorker> create(Frame& frame) { return adoptRef(*new ServiceWorker(frame)); } virtual ~ServiceWorker() = default; enum class State { Installing, Installed, Activating, Activated, Redundant, }; const String& scriptURL() const; State state() const; ExceptionOr<void> postMessage(JSC::ExecState&, JSC::JSValue message, Vector<JSC::Strong<JSC::JSObject>>&&); private: explicit ServiceWorker(Frame&); virtual EventTargetInterface eventTargetInterface() const; virtual ScriptExecutionContext* scriptExecutionContext() const; void refEventTarget() final { ref(); } void derefEventTarget() final { deref(); } }; } // namespace WebCore #endif // ENABLE(SERVICE_WORKER)
33.027778
111
0.735492
[ "vector" ]
40e785d9a54ba385c3a2c772c2ba7d86ae60b307
3,551
h
C
Code/Math/UniformTransform.h
mooming/Kronecker
952cd025bd0a31fe49f0f0d5e11c35474917300c
[ "MIT" ]
null
null
null
Code/Math/UniformTransform.h
mooming/Kronecker
952cd025bd0a31fe49f0f0d5e11c35474917300c
[ "MIT" ]
null
null
null
Code/Math/UniformTransform.h
mooming/Kronecker
952cd025bd0a31fe49f0f0d5e11c35474917300c
[ "MIT" ]
null
null
null
// Copyright Hansol Park (anav96@naver.com, mooming.go@gmail.com). All rights reserved. #ifndef UniformTransform_h #define UniformTransform_h #include "Vector3.h" #include "Quaternion.h" #include "Matrix3x3.h" #include "Matrix4x4.h" namespace HE { template <typename Number> class UniformTransform { using This = UniformTransform; using Vec3 = Vector3<Number>; using Quat = Quaternion<Number>; using Mat3x3 = Matrix3x3<Number>; using Mat4x4 = Matrix4x4<Number>; public: Quat rotation; Number scale; Vec3 translation; public: UniformTransform() : rotation(), translation(), scale(1) { } UniformTransform(std::nullptr_t) : rotation(nullptr), translation(nullptr) { } UniformTransform(const Vec3& translation, const Quat& rotation, Number scale) : rotation(rotation), translation(translation), scale(scale) { } UniformTransform(const Mat4x4& mat) { Assert(mat.IsOrthogonal()); Vec3 c1 = Vec3(mat.m11, mat.m21, mat.m31); Vec3 c2 = Vec3(mat.m12, mat.m22, mat.m32); Vec3 c3 = Vec3(mat.m13, mat.m23, mat.m33); constexpr float oneThird = 1.0f / 3.0f; scale = (c1.Normalize() + c2.Normalize() + c3.Normalize()) * oneThird; Assert(IsEqual(scale, c2.Normalize())); Assert(IsEqual(scale, c3.Normalize())); Mat3x3 rotMat = nullptr; rotMat.m11 = c1.x; rotMat.m21 = c1.y; rotMat.m31 = c1.z; rotMat.m12 = c2.x; rotMat.m22 = c2.y; rotMat.m32 = c2.z; rotMat.m13 = c3.x; rotMat.m23 = c3.y; rotMat.m33 = c3.z; rotation = static_cast<Quat> (rotMat); } inline bool operator==(const This& rhs) { return rotation == rhs.rotation && scale == rhs.scale && translation == rhs.translation; } inline bool operator!=(const This& rhs) { return !(*this == rhs); } template <typename T> inline T operator*(const T& rhs) const { return Transform(rhs); } Vec3 Transform(const Vec3& x) const { return rotation * (scale * x) + translation; } Vec3 InverseTransform(const Vec3& x) const { return (rotation.Inverse() * (x - translation) / scale); } This Transform(const This& rhs) const { This result(nullptr); result.scale = scale * rhs.scale; result.rotation = rotation * rhs.rotation; result.translation = rotation * (scale * rhs.translation) + translation; return result; } This Inverse() const { This inverse(nullptr); scale = 1.0f / scale; rotation.Invert(); translation = rotation * translation * (-scale); return inverse; } Mat4x4 ToMatrix() const { Mat4x4 mat = rotation.ToMat4x4() * Mat4x4::CreateDiagonal(Float4(scale, scale, scale, 1.0f)); mat.SetTranslation(translation); return mat; } }; using UniformTRS = UniformTransform<float>; template <typename T> inline std::ostream& operator<<(std::ostream& os, const UniformTransform<T>& local) { using namespace std; os << "Uniform Transform" << endl; os << "Position: (" << local.translation.x << ", " << local.translation.y << ", " << local.translation.z << ")" << endl; auto r = local.rotation.EulerAngles(); os << "Rotation: (" << r.x << ", " << r.y << ", " << r.z << ")" << endl; os << "Scale: (" << local.scale << ")" << endl; return os; } } #ifdef __UNIT_TEST__ #include "System/TestCase.h" namespace HE { class UniformTransformTest : public TestCase { public: UniformTransformTest() : TestCase("UniformTransformTest") { } protected: virtual bool DoTest() override; }; } #endif //__UNIT_TEST__ #endif //UniformTransform_h
20.766082
96
0.647986
[ "transform" ]
40eed34d3cef183db829307f8c38b0306c8682d0
1,896
h
C
CI3-16/src/ReadingClub.h
pemesteves/AEDA_1819-exercises
c8158547a53865c3910e420208b853579d0971c6
[ "MIT" ]
2
2018-11-28T10:59:27.000Z
2018-12-21T14:33:12.000Z
CI3-16/src/ReadingClub.h
pemesteves/AEDA_1819-exercises
c8158547a53865c3910e420208b853579d0971c6
[ "MIT" ]
null
null
null
CI3-16/src/ReadingClub.h
pemesteves/AEDA_1819-exercises
c8158547a53865c3910e420208b853579d0971c6
[ "MIT" ]
1
2018-11-18T23:41:41.000Z
2018-11-18T23:41:41.000Z
/* * ReadingClub.h * * Created on: 11/12/2016 * Author: RRossetti */ #ifndef SRC_READINGCLUB_H_ #define SRC_READINGCLUB_H_ #include "Book.h" #include "User.h" #include "BST.h" #include <vector> #include <tr1/unordered_set> #include <queue> using namespace std; struct userRecordHash { int operator() (const UserRecord& ur) const { return ur.getEMail().length()*ur.getName().length(); } bool operator() (const UserRecord& ur1, const UserRecord& ur2) const { return ur1.getEMail() == ur2.getEMail(); } }; typedef tr1::unordered_set<UserRecord, userRecordHash, userRecordHash> HashTabUserRecord; class ReadingClub { vector<Book*> books; BST<BookCatalogItem> catalogItems; HashTabUserRecord userRecords; priority_queue<User> readerCandidates; public: ReadingClub(); ReadingClub(vector<Book*> books); void addBook(Book* book); void addBooks(vector<Book*> books); vector<Book*> getBooks() const; // Part I - BST BookCatalogItem getCatalogItem(string title, string author); void addCatalogItem(Book* book); BST<BookCatalogItem> getCatalogItems() const; // Part II - Hash Table vector<UserRecord> getUserRecords() const; void setUserRecords(vector<UserRecord>& urs); // Part III - Piority Queue priority_queue<User> getBestReaderCandidates() const; void setBestReaderCandidates(priority_queue<User>& candidates); // TODO: Implement methods below... // Part I - BST /* A */ void generateCatalog(); /* B */ vector<Book*> getAvailableItems(Book* book) const; /* C */ bool borrowBookFromCatalog(Book* book, User* reader); // Part II - Hash Table /* D */ void addUserRecord(User* user); /* E */ void changeUserEMail(User* user, string newEMail); // Part III - Piority Queue /* F */ void addBestReaderCandidates(const vector<User>& candidates, int min); /* G */ int awardReaderChampion(User& champion); }; #endif /* SRC_READINGCLUB_H_ */
24.623377
89
0.719409
[ "vector" ]
40f7f6b0f75b0f907797439b912bcf2869ecf371
254
h
C
Assignment2_MatthewFerreira/SDL_Project/UIFactory.h
adityadutta/Assignment2_GAME203
ff15cd91f0d2bea3b74433e0877569515d0f18ea
[ "MIT" ]
null
null
null
Assignment2_MatthewFerreira/SDL_Project/UIFactory.h
adityadutta/Assignment2_GAME203
ff15cd91f0d2bea3b74433e0877569515d0f18ea
[ "MIT" ]
null
null
null
Assignment2_MatthewFerreira/SDL_Project/UIFactory.h
adityadutta/Assignment2_GAME203
ff15cd91f0d2bea3b74433e0877569515d0f18ea
[ "MIT" ]
null
null
null
#ifndef UIFACTORY_H #define UIFACTORY_H #include <SDL.h> class UIFactory { public: virtual bool OnCreate() = 0; virtual void OnDestroy() = 0; virtual void Update(const float time) = 0; virtual void Render(SDL_Surface *screenSurface) = 0; }; #endif
18.142857
53
0.728346
[ "render" ]
dc06174567b05085920da7f5de31726914bfecd0
750
h
C
Root/HookHolder.h
TelepathicFart/Rafflesia
9376e06b5a7ab3f712677f31504021c1b62c3f09
[ "MIT" ]
5
2021-05-11T02:52:31.000Z
2021-09-03T05:10:53.000Z
Root/HookHolder.h
TelepathicFart/Rafflesia
9376e06b5a7ab3f712677f31504021c1b62c3f09
[ "MIT" ]
null
null
null
Root/HookHolder.h
TelepathicFart/Rafflesia
9376e06b5a7ab3f712677f31504021c1b62c3f09
[ "MIT" ]
1
2022-02-24T13:56:26.000Z
2022-02-24T13:56:26.000Z
#pragma once #include <string> #include <memory> #include <unordered_map> #include <vector> #include "Hook.h" #include "Module.h" class HookHolder { public: HookHolder(); void createHook(Module& module, const std::string& symbol_name, DWORD func) noexcept; void createHook(Module& module, const std::string& symbol_name, DWORD offset, DWORD func) noexcept; void createHook(const std::string& symbol_name, DWORD address, DWORD func) noexcept; void unHook() noexcept; LPVOID getTrampoline(const std::string& symbol_name) noexcept; private: std::vector<std::shared_ptr<Hook>> hooks; std::unordered_map<std::string, LPVOID> trampolines; void doCreateHook(uint64_t target_addr, uint64_t callback_addr, const std::string& symbol_name); };
25
100
0.762667
[ "vector" ]
dc06dfada145d4e4d9a2079029d1d80647d85c00
2,738
h
C
d912pxy/d912pxy_surface_layer.h
Throne3d/d912pxy
0fe44067baf6f7f01a17496e8eda640a4375c63b
[ "MIT" ]
1
2021-01-23T18:33:00.000Z
2021-01-23T18:33:00.000Z
d912pxy/d912pxy_surface_layer.h
GameFuzzy/d912pxy
69c66325eee53989be567a5967fa51ba3aaf25a8
[ "MIT" ]
null
null
null
d912pxy/d912pxy_surface_layer.h
GameFuzzy/d912pxy
69c66325eee53989be567a5967fa51ba3aaf25a8
[ "MIT" ]
null
null
null
/* MIT License Copyright(c) 2018-2019 megai2 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 "stdafx.h" class d912pxy_surface_layer: public IDirect3DSurface9 { public: d912pxy_surface_layer(d912pxy_surface* iBase, UINT32 iSubres, UINT32 iBSize, UINT32 iWPitch, UINT32 iWidth, UINT32 imemPerPix); ~d912pxy_surface_layer(); /*** IUnknown methods ***/ D912PXY_METHOD(QueryInterface)(THIS_ REFIID riid, void** ppvObj); D912PXY_METHOD_(ULONG, AddRef)(THIS); D912PXY_METHOD_(ULONG, Release)(THIS); /*** IDirect3DResource9 methods ***/ D912PXY_METHOD(GetDevice)(THIS_ IDirect3DDevice9** ppDevice); D912PXY_METHOD(SetPrivateData)(THIS_ REFGUID refguid, CONST void* pData, DWORD SizeOfData, DWORD Flags); D912PXY_METHOD(GetPrivateData)(THIS_ REFGUID refguid, void* pData, DWORD* pSizeOfData); D912PXY_METHOD(FreePrivateData)(THIS_ REFGUID refguid); D912PXY_METHOD_(DWORD, SetPriority)(THIS_ DWORD PriorityNew); D912PXY_METHOD_(DWORD, GetPriority)(THIS); D912PXY_METHOD_(void, PreLoad)(THIS); D912PXY_METHOD_(D3DRESOURCETYPE, GetType)(THIS); D912PXY_METHOD(GetContainer)(THIS_ REFIID riid, void** ppContainer); D912PXY_METHOD(GetDesc)(THIS_ D3DSURFACE_DESC *pDesc); D912PXY_METHOD(LockRect)(THIS_ D3DLOCKED_RECT* pLockedRect, CONST RECT* pRect, DWORD Flags); D912PXY_METHOD(UnlockRect)(THIS); D912PXY_METHOD(GetDC)(THIS_ HDC *phdc); D912PXY_METHOD(ReleaseDC)(THIS_ HDC hdc); void SetDirtyRect(UINT32 left, UINT32 right, UINT32 top, UINT32 bottom); HRESULT UnlockRectEx(UINT32 transform); void* SurfacePixel(UINT32 x, UINT32 y); private: UINT isDrect; D3DRECT drect; d912pxy_surface * base; UINT32 subres; UINT32 lockDepth; void* surfMem; UINT wPitch; UINT width; UINT memPerPix; UINT intRefc; };
34.658228
128
0.788897
[ "transform" ]
dc0b99d9baa9866d0456812bba845021c0e2058d
282
c
C
clientNektar/Veclib/memory/ivector.c
LiuYangMage/RLFluidControl
bb8ae17e2e01ceced440a37538c08d2648ae9339
[ "MIT" ]
21
2020-03-10T13:40:18.000Z
2021-12-21T01:50:24.000Z
clientNektar/Veclib/memory/ivector.c
LiuYangMage/RLFluidControl
bb8ae17e2e01ceced440a37538c08d2648ae9339
[ "MIT" ]
2
2020-05-06T19:29:16.000Z
2021-05-24T02:02:17.000Z
clientNektar/Veclib/memory/ivector.c
LiuYangMage/RLFluidControl
bb8ae17e2e01ceced440a37538c08d2648ae9339
[ "MIT" ]
11
2020-04-18T02:51:29.000Z
2022-03-28T08:04:42.000Z
/* * Single-precision integer vector */ int *ivector(nl,nh) int nl,nh; { int *v; v=(int *)malloc((unsigned) (nh-nl+1)*sizeof(int)); if (!v) error_handler("allocation failure in ivector()"); return v-nl; } void free_ivector(v,nl,nh) int *v,nl,nh; { free((char*) (v+nl)); }
14.1
58
0.624113
[ "vector" ]
dc0e24f93d0276857c9b2d0357432a083dc62a0b
2,200
h
C
rvh/sim/dlsc_rvh_source.h
herocodemaster/dls_cores
02770db064f85024da8d3418592aca1b6a7ed83a
[ "FSFAP" ]
1
2021-01-29T19:51:26.000Z
2021-01-29T19:51:26.000Z
rvh/sim/dlsc_rvh_source.h
herocodemaster/dls_cores
02770db064f85024da8d3418592aca1b6a7ed83a
[ "FSFAP" ]
null
null
null
rvh/sim/dlsc_rvh_source.h
herocodemaster/dls_cores
02770db064f85024da8d3418592aca1b6a7ed83a
[ "FSFAP" ]
1
2021-02-01T08:01:25.000Z
2021-02-01T08:01:25.000Z
#ifndef DLSC_RVH_SOURCE_H_INCLUDED #define DLSC_RVH_SOURCE_H_INCLUDED #include <vector> #include <systemc.h> #include <stdexcept> #include <scv.h> template <typename T> SC_MODULE(dlsc_rvh_source) { public: sc_in<bool> clk; sc_in<bool> ready; sc_out<bool> valid; sc_out<T> data; sc_port<sc_fifo_in_if<T> > data_fifo; dlsc_rvh_source(sc_module_name nm); SC_HAS_PROCESS(dlsc_rvh_source); void set_percent_valid(int percent); void flush(); private: scv_smart_ptr<bool> valid_bool; void data_thread(); }; template <typename T> dlsc_rvh_source<T>::dlsc_rvh_source(sc_module_name nm) : clk("clk"), ready("ready"), valid("valid"), data("data"), data_fifo("data_fifo"), sc_module(nm) { SC_THREAD(data_thread); set_percent_valid(100); } template <typename T> void dlsc_rvh_source<T>::set_percent_valid(int percent) { if(percent < 0 || percent > 100) { throw std::invalid_argument("invalid percent"); } scv_bag<bool> b_dist; if(percent != 100) b_dist.push(false,100-percent); if(percent != 0) b_dist.push(true,percent); valid_bool->set_mode(b_dist); } template <typename T> void dlsc_rvh_source<T>::flush() { // must wait to allow pending fifo writes to register wait(SC_ZERO_TIME); // wait for fifo to be empty while(data_fifo->num_available() > 0) { wait(clk.posedge_event()); } } template <typename T> void dlsc_rvh_source<T>::data_thread() { valid = 0; wait(clk.posedge_event()); while(true) { // allowed to assert new datum if: // - we're not currently asserting a datum // - or a datum has just been accepted if(!valid || ready) { T d; valid_bool->next(); if(*valid_bool) { if(!data_fifo->nb_read(d)) { valid = 0; data_fifo->read(d); wait(clk.posedge_event()); } data = d; valid = 1; } else { valid = 0; } } wait(clk.posedge_event()); } } #endif
22.222222
154
0.579091
[ "vector" ]
dc1212925012b895663f65dce2d29a2975e6ca52
1,531
h
C
ISObject.h
justinmeiners/c-foundation
8c6ce4552980f13b247f894828a587627a2ad812
[ "Unlicense" ]
2
2019-07-28T15:14:34.000Z
2022-02-25T03:46:02.000Z
ISObject.h
justinmeiners/c-foundation
8c6ce4552980f13b247f894828a587627a2ad812
[ "Unlicense" ]
null
null
null
ISObject.h
justinmeiners/c-foundation
8c6ce4552980f13b247f894828a587627a2ad812
[ "Unlicense" ]
null
null
null
/* Created By: Justin Meiners (2013) */ #ifndef IS_OBJECT_H #define IS_OBJECT_H #include <stdlib.h> #include <assert.h> #include <string.h> typedef const void* ISObjectRef; typedef struct { /* this could also include functions for comparison, hashing, or whatever core functionality objects required */ const char* _name; void (*_deallocFunc)(ISObjectRef object); ISObjectRef (*_copyFunc)(ISObjectRef object); } ISObjectClass; /* C Standard A pointer to a structure object, suitably converted, points to its initial member and vice versa. This allows the ISObjectBase to be accessible from any struct that contains it as the first member. */ typedef struct { /* this structure must be the first item in every ISObject */ int retainCount; ISObjectClass* objectClass; } ISObjectBase; extern void ISObjectBaseInit(ISObjectBase* base, ISObjectClass* objClass); extern int ISObjectRetainCount(ISObjectRef object); /* +1 retain count */ extern ISObjectRef ISRetain(ISObjectRef object); /* -1 retain count, calls objects dealloc method when retainCount < 1 */ extern void ISRelease(ISObjectRef object); /* adds the object to the current autorelease pool, object will be released when the pool is destroyed */ extern ISObjectRef ISAutorelease(ISObjectRef object); extern ISObjectRef ISCopy(ISObjectRef object); /* adds a new pool to the stack */ extern void ISAutoreleasePoolPush(); /* removes a pool from the stack releasing all objects */ extern void ISAutoreleasePoolPop(); #endif
27.339286
105
0.757675
[ "object" ]
dc1800df053a503f5722d19860a23a02d789147f
11,963
h
C
src/script/standard.h
xuing/btchd
804b2914c3eefd1704a5860ff423eef74a25d620
[ "MIT" ]
null
null
null
src/script/standard.h
xuing/btchd
804b2914c3eefd1704a5860ff423eef74a25d620
[ "MIT" ]
null
null
null
src/script/standard.h
xuing/btchd
804b2914c3eefd1704a5860ff423eef74a25d620
[ "MIT" ]
null
null
null
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_SCRIPT_STANDARD_H #define BITCOIN_SCRIPT_STANDARD_H #include <script/interpreter.h> #include <uint256.h> #include <boost/variant.hpp> #include <stdint.h> #include <memory> static const bool DEFAULT_ACCEPT_DATACARRIER = true; class CKeyID; class CScript; /** A reference to a CScript: the Hash160 of its serialization (see script.h) */ class CScriptID : public uint160 { public: CScriptID() : uint160() {} CScriptID(const CScript& in); CScriptID(const uint160& in) : uint160(in) {} }; /** * Default setting for nMaxDatacarrierBytes. 8000 bytes of data, * +1 for OP_RETURN, +2 for the pushdata opcodes. */ static const unsigned int MAX_OP_RETURN_RELAY = 8003; /** * A data carrying output is an unspendable output containing data. The script * type is designated as TX_NULL_DATA. */ extern bool fAcceptDatacarrier; /** Maximum size of TX_NULL_DATA scripts that this node considers standard. */ extern unsigned nMaxDatacarrierBytes; /** * Mandatory script verification flags that all new blocks must comply with for * them to be valid. (but old blocks may not comply with) Currently just P2SH, * but in the future other flags may be added, such as a soft-fork to enforce * strict DER encoding. * * Failing one of these tests may trigger a DoS ban - see CheckInputs() for * details. */ static const unsigned int MANDATORY_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC; enum txnouttype { TX_NONSTANDARD, // 'standard' transaction types: TX_PUBKEY, TX_PUBKEYHASH, TX_SCRIPTHASH, TX_MULTISIG, TX_NULL_DATA, //!< unspendable OP_RETURN script that carries data TX_WITNESS_V0_SCRIPTHASH, TX_WITNESS_V0_KEYHASH, TX_WITNESS_UNKNOWN, //!< Only for Witness versions not already defined above }; class CNoDestination { public: friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; } friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; } }; struct WitnessV0ScriptHash : public uint256 { WitnessV0ScriptHash() : uint256() {} explicit WitnessV0ScriptHash(const uint256& hash) : uint256(hash) {} using uint256::uint256; }; struct WitnessV0KeyHash : public uint160 { WitnessV0KeyHash() : uint160() {} explicit WitnessV0KeyHash(const uint160& hash) : uint160(hash) {} using uint160::uint160; }; //! CTxDestination subtype to encode any future Witness version struct WitnessUnknown { unsigned int version; unsigned int length; unsigned char program[40]; friend bool operator==(const WitnessUnknown& w1, const WitnessUnknown& w2) { if (w1.version != w2.version) return false; if (w1.length != w2.length) return false; return std::equal(w1.program, w1.program + w1.length, w2.program); } friend bool operator<(const WitnessUnknown& w1, const WitnessUnknown& w2) { if (w1.version < w2.version) return true; if (w1.version > w2.version) return false; if (w1.length < w2.length) return true; if (w1.length > w2.length) return false; return std::lexicographical_compare(w1.program, w1.program + w1.length, w2.program, w2.program + w2.length); } }; /** * A txout script template with a specific destination. It is either: * * CNoDestination: no destination set * * CKeyID: TX_PUBKEYHASH destination (P2PKH) * * CScriptID: TX_SCRIPTHASH destination (P2SH) * * WitnessV0ScriptHash: TX_WITNESS_V0_SCRIPTHASH destination (P2WSH) * * WitnessV0KeyHash: TX_WITNESS_V0_KEYHASH destination (P2WPKH) * * WitnessUnknown: TX_WITNESS_UNKNOWN destination (P2W???) * A CTxDestination is the internal data type encoded in a bitcoin address */ typedef boost::variant<CNoDestination, CKeyID, CScriptID, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown> CTxDestination; /** Check whether a CTxDestination is a CNoDestination. */ bool IsValidDestination(const CTxDestination& dest); /** Get the name of a txnouttype as a C string, or nullptr if unknown. */ const char* GetTxnOutputType(txnouttype t); /** * Parse a scriptPubKey and identify script type for standard scripts. If * successful, returns script type and parsed pubkeys or hashes, depending on * the type. For example, for a P2SH script, vSolutionsRet will contain the * script hash, for P2PKH it will contain the key hash, etc. * * @param[in] scriptPubKey Script to parse * @param[out] typeRet The script type * @param[out] vSolutionsRet Vector of parsed pubkeys and hashes * @return True if script matches standard template */ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet); /** * Parse a standard scriptPubKey for the destination address. Assigns result to * the addressRet parameter and returns true if successful. For multisig * scripts, instead use ExtractDestinations. Currently only works for P2PK, * P2PKH, P2SH, P2WPKH, and P2WSH scripts. */ bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet); CTxDestination ExtractDestination(const CScript& scriptPubKey); /** * Parse a standard scriptPubKey with one or more destination addresses. For * multisig scripts, this populates the addressRet vector with the pubkey IDs * and nRequiredRet with the n required to spend. For other destinations, * addressRet is populated with a single value and nRequiredRet is set to 1. * Returns true if successful. Currently does not extract address from * pay-to-witness scripts. * * Note: this function confuses destinations (a subset of CScripts that are * encodable as an address) with key identifiers (of keys involved in a * CScript), and its use should be phased out. */ bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet); /** * Generate a Bitcoin scriptPubKey for the given CTxDestination. Returns a P2PKH * script for a CKeyID destination, a P2SH script for a CScriptID, and an empty * script for CNoDestination. */ CScript GetScriptForDestination(const CTxDestination& dest); /** Generate a P2PK script for the given pubkey. */ CScript GetScriptForRawPubKey(const CPubKey& pubkey); /** Generate a multisig script. */ CScript GetScriptForMultisig(int nRequired, const std::vector<CPubKey>& keys); /** * Generate a pay-to-witness script for the given redeem script. If the redeem * script is P2PK or P2PKH, this returns a P2WPKH script, otherwise it returns a * P2WSH script. * * TODO: replace calls to GetScriptForWitness with GetScriptForDestination using * the various witness-specific CTxDestination subtypes. */ CScript GetScriptForWitness(const CScript& redeemscript); /** Utility function to get account ID. */ CAccountID ExtractAccountID(const CPubKey& pubkey); CAccountID ExtractAccountID(const CScript& scriptPubKey); CAccountID ExtractAccountID(const CTxDestination& dest); /** opreturn type. See https://btchd.org/wiki/datacarrier */ enum DatacarrierType : unsigned int { // Range DATACARRIER_TYPE_MIN = 0x0000000f, DATACARRIER_TYPE_MAX = 0x10000000, // Type of consensus relevant //! See https://btchd.org/wiki/datacarrier/bind-plotter DATACARRIER_TYPE_BINDPLOTTER = 0x00000010, //! See https://btchd.org/wiki/datacarrier/rental DATACARRIER_TYPE_RENTAL = 0x00000011, //! See https://btchd.org/wiki/datacarrier/contract DATACARRIER_TYPE_CONTRACT = 0x00000012, //! See https://btchd.org/wiki/datacarrier/text DATACARRIER_TYPE_TEXT = 0x00000013, }; /** Datacarrier payload */ struct DatacarrierPayload { const DatacarrierType type; explicit DatacarrierPayload(DatacarrierType typeIn) : type(typeIn) {} virtual ~DatacarrierPayload() {} }; typedef std::shared_ptr<DatacarrierPayload> CDatacarrierPayloadRef; /** For bind plotter */ struct BindPlotterPayload : public DatacarrierPayload { uint64_t id; BindPlotterPayload() : DatacarrierPayload(DATACARRIER_TYPE_BINDPLOTTER), id(0) {} const uint64_t& GetId() const { return id; } // Checkable cast for CDatacarrierPayloadRef static BindPlotterPayload * As(CDatacarrierPayloadRef &ref) { assert(ref->type == DATACARRIER_TYPE_BINDPLOTTER); return (BindPlotterPayload*) ref.get(); } static const BindPlotterPayload * As(const CDatacarrierPayloadRef &ref) { assert(ref->type == DATACARRIER_TYPE_BINDPLOTTER); return (const BindPlotterPayload*) ref.get(); } }; /** For rental */ struct RentalPayload : public DatacarrierPayload { CAccountID borrowerAccountID; RentalPayload() : DatacarrierPayload(DATACARRIER_TYPE_RENTAL) {} const CAccountID& GetBorrowerAccountID() const { return borrowerAccountID; } // Checkable cast for CDatacarrierPayloadRef static RentalPayload * As(CDatacarrierPayloadRef &ref) { assert(ref->type == DATACARRIER_TYPE_RENTAL); return (RentalPayload*) ref.get(); } static const RentalPayload * As(const CDatacarrierPayloadRef &ref) { assert(ref->type == DATACARRIER_TYPE_RENTAL); return (const RentalPayload*) ref.get(); } }; /** For text */ struct TextPayload : public DatacarrierPayload { std::string text; TextPayload() : DatacarrierPayload(DATACARRIER_TYPE_TEXT) {} const std::string& GetText() const { return text; } // Checkable cast for CDatacarrierPayloadRef static TextPayload * As(CDatacarrierPayloadRef &ref) { assert(ref->type == DATACARRIER_TYPE_TEXT); return (TextPayload*) ref.get(); } static const TextPayload * As(const CDatacarrierPayloadRef &ref) { assert(ref->type == DATACARRIER_TYPE_TEXT); return (const TextPayload*) ref.get(); } }; /** The bind plotter lock amount */ static const CAmount PROTOCOL_BINDPLOTTER_LOCKAMOUNT = 10 * CENT; /** The bind plotter transaction fee */ static const CAmount PROTOCOL_BINDPLOTTER_MINFEE = 10 * CENT; /** The height for bind plotter default maximum relative tip height */ static const int PROTOCOL_BINDPLOTTER_DEFAULTMAXALIVE = 24; /** The height for bind plotter maximum relative tip height */ static const int PROTOCOL_BINDPLOTTER_MAXALIVE = 288 * 7; /** The bind plotter script size */ static const int PROTOCOL_BINDPLOTTER_SCRIPTSIZE = 109; /** Check whether a string is a valid passphrase. */ bool IsValidPassphrase(const std::string& passphrase); /** Check whether a string is a valid plotter ID. */ bool IsValidPlotterID(const std::string& strPlotterId, uint64_t *id = nullptr); /** Generate a bind plotter script. */ CScript GetBindPlotterScriptForDestination(const CTxDestination& dest, const std::string& passphrase, int lastActiveHeight); uint64_t GetBindPlotterIdFromScript(const CScript &script); /** The minimal rental amount */ static const CAmount PROTOCOL_RENTAL_AMOUNT_MIN = 1 * COIN; /** The rental script size */ static const int PROTOCOL_RENTAL_SCRIPTSIZE = 27; /** Generate a rental script. */ CScript GetRentalScriptForDestination(const CTxDestination& dest); /** The text script maximum size. OP_RETURN(1) + type(5) + size(4) */ static const int PROTOCOL_TEXT_MAXSIZE = MAX_OP_RETURN_RELAY - 10; /** Get text script */ CScript GetTextScript(const std::string& text); /** Parse a datacarrier transaction. */ CDatacarrierPayloadRef ExtractTransactionDatacarrier(const CTransaction& tx, int nHeight); CDatacarrierPayloadRef ExtractTransactionDatacarrier(const CTransaction& tx, int nHeight, bool& fReject, int& lastActiveHeight); CDatacarrierPayloadRef ExtractTransactionDatacarrierUnlimit(const CTransaction& tx, int nHeight); #endif // BITCOIN_SCRIPT_STANDARD_H
36.696319
135
0.743041
[ "vector" ]
dc1bedc6408aa392b766bc55c61bb1a187eff886
2,451
h
C
inc/feral/feraluser.h
bSchnepp/Feral
8931c89da418076c15205f03e93b664504fb29ff
[ "BSL-1.0" ]
13
2018-04-27T00:04:09.000Z
2022-01-06T15:00:24.000Z
inc/feral/feraluser.h
bSchnepp/Feral
8931c89da418076c15205f03e93b664504fb29ff
[ "BSL-1.0" ]
44
2018-09-01T04:05:21.000Z
2021-02-21T22:02:57.000Z
inc/feral/feraluser.h
bSchnepp/feral-next
8931c89da418076c15205f03e93b664504fb29ff
[ "BSL-1.0" ]
2
2018-04-28T12:54:41.000Z
2021-03-17T14:18:28.000Z
/* Copyright (c) 2018, Brian Schnepp Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _FERAL_FERAL_USER_H_ #define _FERAL_FERAL_USER_H_ #if defined(__cplusplus) extern "C" { #endif #include <feral/stdtypes.h> typedef enum { PORT_TYPE_RECIEVE, PORT_TYPE_SEND, PORT_TYPE_SEND_ONCE, PORT_TYPE_BIDIRECTIONAL, } PORT_PURPOSE; typedef enum { PORT_RIGHT_CREATE, PORT_RIGHT_DELETE, PORT_RIGHT_LINK, PORT_RIGHT_CREATE_LINK, PORT_RIGHT_DELETE_LINK, PORT_RIGHT_ALL, } PORT_CREATION_RIGHT; typedef struct FERALUSER { WSTRING Name; UINT64 UserID;// Up to 2^64 user accounts. Should be plenty for // the overwhelming majority of all use cases. WSTRING Home;// typically A:/Users/<NAME>, but could also be // under a parent's home. FERALTIME* CreationDate; FERALTIME* ExpirationDate;// If null, does not ever expire. BOOLEAN UsesPassword; BOOLEAN SystemAccount;// Is this account for a service? (ie, // some daemon like a port of PulseAudio // or something) struct FERALUSER* Parent; } FERALUSER; typedef struct { FERALUSER User; PORT_PURPOSE Purpose; } FERALPORT_USER_IDENTITIES; #if defined(__cplusplus) } #endif #endif
29.53012
79
0.768666
[ "object" ]
09ac52042ae2cc33c93511323d94802f0665b07f
24,856
h
C
graphics/cgal/Surface_mesher/include/CGAL/enriched_polyhedron.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
4
2016-03-30T14:31:52.000Z
2019-02-02T05:01:32.000Z
graphics/cgal/Surface_mesher/include/CGAL/enriched_polyhedron.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
graphics/cgal/Surface_mesher/include/CGAL/enriched_polyhedron.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
// -*- tab-width: 2 -*- // Copyright (c) 2006-2007 INRIA Sophia-Antipolis (France). // 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$ // // Author(s) : Pierre Alliez /////////////////////////////////////////////////////////////////////////// // // // Class: Enriched_polyhedron // // // /////////////////////////////////////////////////////////////////////////// #ifndef _POLYGON_MESH_ #define _POLYGON_MESH_ // CGAL stuff #include <CGAL/Cartesian.h> #include <CGAL/Polyhedron_3.h> #include <CGAL/HalfedgeDS_default.h> #include <list> #include <CGAL/gl.h> // a refined facet with a normal and a tag template <class Refs, class T, class P, class Norm> class Enriched_facet : public CGAL::HalfedgeDS_face_base<Refs, T> { // tag int m_tag; // normal Norm m_normal; public: // life cycle // no constructors to repeat, since only // default constructor mandatory Enriched_facet() { } // tag const int& tag() const { return m_tag; } int& tag() { return m_tag; } void tag(const int& i) { m_tag = i; } // normal typedef Norm Normal_3; Normal_3& normal() { return m_normal; } const Normal_3& normal() const { return m_normal; } }; // a refined halfedge with a general tag and // a binary tag to indicate wether it belongs // to the control mesh or not template <class Refs, class Tprev, class Tvertex, class Tface, class Norm> class Enriched_halfedge : public CGAL::HalfedgeDS_halfedge_base<Refs,Tprev,Tvertex,Tface> { private: // general purpose tag int m_tag; // option for edge superimposing bool m_control_edge; bool m_sharp; public: // life cycle Enriched_halfedge() { m_control_edge = true; m_sharp = false; } // tag const int& tag() const { return m_tag; } int& tag() { return m_tag; } void tag(const int& t) { m_tag = t; } // control edge bool& control_edge() { return m_control_edge; } const bool& control_edge() const { return m_control_edge; } // sharp bool& sharp() { return m_sharp; } const bool& sharp() const { return m_sharp; } }; // a refined vertex with a normal and a tag template <class Refs, class T, class P, class Norm> class Enriched_vertex : public CGAL::HalfedgeDS_vertex_base<Refs, T, P> { // tag int m_tag; // normal Norm m_normal; public: // life cycle Enriched_vertex() {} // repeat mandatory constructors Enriched_vertex(const P& pt) : CGAL::HalfedgeDS_vertex_base<Refs, T, P>(pt) { } // normal typedef Norm Normal_3; Normal_3& normal() { return m_normal; } const Normal_3& normal() const { return m_normal; } // tag int& tag() { return m_tag; } const int& tag() const { return m_tag; } void tag(const int& t) { m_tag = t; } }; // A redefined items class for the Polyhedron_3 // with a refined vertex class that contains a // member for the normal vector and a refined // facet with a normal vector instead of the // plane equation (this is an alternative // solution instead of using // Polyhedron_traits_with_normals_3). struct Enriched_items : public CGAL::Polyhedron_items_3 { // wrap vertex template<class Refs, class Traits> struct Vertex_wrapper { typedef typename Traits::Point_3 Point; typedef typename Traits::Vector_3 Normal; typedef Enriched_vertex<Refs, CGAL::Tag_true, Point, Normal> Vertex; }; // wrap face template<class Refs, class Traits> struct Face_wrapper { typedef typename Traits::Point_3 Point; typedef typename Traits::Vector_3 Normal; typedef Enriched_facet<Refs, CGAL::Tag_true, Point, Normal> Face; }; // wrap halfedge template<class Refs, class Traits> struct Halfedge_wrapper { typedef typename Traits::Vector_3 Normal; typedef Enriched_halfedge<Refs, CGAL::Tag_true, CGAL::Tag_true, CGAL::Tag_true, Normal> Halfedge; }; }; static const double PI = 3.1415926535897932384626; // compute facet normal struct Facet_normal // (functor) { template<class Facet> void operator()(Facet& f) { typename Facet::Normal_3 sum = CGAL::NULL_VECTOR; typename Facet::Halfedge_around_facet_circulator h = f.facet_begin(); do { typename Facet::Normal_3 normal = CGAL::cross_product(h->next()->vertex()->point() - h->vertex()->point(), h->next()->next()->vertex()->point() - h->next()->vertex()->point()); double sqnorm = normal * normal; if (sqnorm != 0) normal = normal / (float)std::sqrt(sqnorm); sum = sum + normal; } while (++h != f.facet_begin()); float sqnorm = sum * sum; if (sqnorm != 0.0) f.normal() = sum / std::sqrt(sqnorm); else { f.normal() = CGAL::NULL_VECTOR; // TRACE("degenerate face\n"); } } }; // compute vertex normal struct Vertex_normal // (functor) { template<class Vertex> void operator()(Vertex& v) { typename Vertex::Normal_3 normal = CGAL::NULL_VECTOR; typename Vertex::Halfedge_around_vertex_const_circulator pHalfedge = v.vertex_begin(); typename Vertex::Halfedge_around_vertex_const_circulator begin = pHalfedge; CGAL_For_all(pHalfedge,begin) if(!pHalfedge->is_border()) normal = normal + pHalfedge->facet()->normal(); float sqnorm = normal * normal; if (sqnorm != 0.0f) v.normal() = normal / (float)std::sqrt(sqnorm); else v.normal() = CGAL::NULL_VECTOR; } }; //********************************************************* template <class kernel, class items, template < class T, class I, class A> class HDS = CGAL::HalfedgeDS_default > class Enriched_polyhedron : public CGAL::Polyhedron_3<kernel,items,HDS> { public : typedef typename kernel::FT FT; typedef typename kernel::Point_3 Point; typedef typename kernel::Vector_3 Vector; typedef typename kernel::Iso_cuboid_3 Iso_cuboid; typedef CGAL::Polyhedron_3<kernel,items,HDS> Base; typedef typename Base::Vertex_handle Vertex_handle; typedef typename Base::Vertex_iterator Vertex_iterator; typedef typename Base::Halfedge_handle Halfedge_handle; typedef typename Base::Halfedge_iterator Halfedge_iterator; typedef typename Base::Halfedge_around_facet_circulator Halfedge_around_facet_circulator; typedef typename Base::Halfedge_around_vertex_circulator Halfedge_around_vertex_circulator; typedef typename Base::Edge_iterator Edge_iterator; typedef typename Base::Facet_iterator Facet_iterator; typedef typename Base::Facet_handle Facet_handle; typedef typename Base::Facet Facet; using Base::vertices_begin; using Base::vertices_end; using Base::edges_begin; using Base::edges_end; using Base::halfedges_begin; using Base::halfedges_end; using Base::facets_begin; using Base::facets_end; using Base::size_of_halfedges; using Base::size_of_facets; using Base::size_of_vertices; private : // bounding box Iso_cuboid m_bbox; // type bool m_pure_quad; bool m_pure_triangle; public : enum Vertex_type { SMOOTH, // 0 sharp edge DART, // 1 CREASE_REGULAR, // 2 - with two non-sharp edges on each side CREASE_IRREGULAR, // 2 CORNER }; // 3 and more public : // life cycle Enriched_polyhedron() { m_pure_quad = false; m_pure_triangle = false; } virtual ~Enriched_polyhedron() { } // type bool is_pure_triangle() { return m_pure_triangle; } bool is_pure_quad() { return m_pure_quad; } // normals (per facet, then per vertex) void compute_normals_per_facet() { std::for_each(facets_begin(),facets_end(),::Facet_normal()); } void compute_normals_per_vertex() { std::for_each(vertices_begin(),vertices_end(),::Vertex_normal()); } void compute_normals() { compute_normals_per_facet(); compute_normals_per_vertex(); } // bounding box Iso_cuboid& bbox() { return m_bbox; } const Iso_cuboid bbox() const { return m_bbox; } // compute bounding box void compute_bounding_box() { CGAL_assertion(size_of_vertices() != 0); FT xmin,xmax,ymin,ymax,zmin,zmax; Vertex_iterator pVertex = vertices_begin(); xmin = xmax = pVertex->point().x(); ymin = ymax = pVertex->point().y(); zmin = zmax = pVertex->point().z(); for(; pVertex != vertices_end(); pVertex++) { const Point& p = pVertex->point(); xmin = std::min(xmin,p.x()); ymin = std::min(ymin,p.y()); zmin = std::min(zmin,p.z()); xmax = std::max(xmax,p.x()); ymax = std::max(ymax,p.y()); zmax = std::max(zmax,p.z()); } m_bbox = Iso_cuboid(xmin,ymin,zmin, xmax,ymax,zmax); } // bounding box FT xmin() { return m_bbox.xmin(); } FT xmax() { return m_bbox.xmax(); } FT ymin() { return m_bbox.ymin(); } FT ymax() { return m_bbox.ymax(); } FT zmin() { return m_bbox.zmin(); } FT zmax() { return m_bbox.zmax(); } Point center() { FT cx = (FT)0.5 * (xmin() + xmax()); FT cy = (FT)0.5 * (ymin() + ymax()); FT cz = (FT)0.5 * (zmin() + zmax()); return Point(cx,cy,cz); } FT size() { FT dx = xmax() - xmin(); FT dy = ymax() - ymin(); FT dz = zmax() - zmin(); return std::max(dx,std::max(dy,dz)); } // degree of a face static unsigned int degree(Facet_handle pFace) { return CGAL::circulator_size(pFace->facet_begin()); } // valence of a vertex static unsigned int valence(Vertex_handle pVertex) { return CGAL::circulator_size(pVertex->vertex_begin()); } // check wether a vertex is on a boundary or not static bool is_border(Vertex_handle pVertex) { Halfedge_around_vertex_circulator pHalfEdge = pVertex->vertex_begin(); if(pHalfEdge == NULL) // isolated vertex return true; Halfedge_around_vertex_circulator d = pHalfEdge; CGAL_For_all(pHalfEdge,d) if(pHalfEdge->is_border()) return true; return false; } // get any border halfedge attached to a vertex Halfedge_handle get_border_halfedge(Vertex_handle pVertex) { Halfedge_around_vertex_circulator pHalfEdge = pVertex->vertex_begin(); Halfedge_around_vertex_circulator d = pHalfEdge; CGAL_For_all(pHalfEdge,d) if(pHalfEdge->is_border()) return pHalfEdge; return NULL; } // tag all vertices void tag_vertices(const int tag) { for(Vertex_iterator vit = vertices_begin(), end = vertices_end(); vit != end; ++vit) vit->tag(tag); } // tag all halfedges void tag_halfedges(const int tag) { for(Halfedge_iterator pHalfedge = halfedges_begin(); pHalfedge != halfedges_end(); pHalfedge++) pHalfedge->tag(tag); } // tag all facets void tag_facets(const int tag) { for(Facet_iterator pFacet = facets_begin(); pFacet != facets_end(); pFacet++) pFacet->tag() = tag; } // set index for all vertices void set_index_vertices() { int index = 0; for(Vertex_iterator pVertex = vertices_begin(); pVertex != vertices_end(); pVertex++) pVertex->tag(index++); } // set index for all edges void set_index_edges() { int index = 0; for(Edge_iterator he = edges_begin(); he != edges_end(); he++) { he->tag(index); he->opposite()->tag(index); index++; } } // is pure degree ? bool is_pure_degree(unsigned int d) { for(Facet_iterator pFace = facets_begin(); pFace != facets_end(); pFace++) if(degree(pFace) != d) return false; return true; } // compute type void compute_type() { m_pure_quad = is_pure_degree(4); m_pure_triangle = is_pure_degree(3); } // compute facet center void compute_facet_center(Facet_handle pFace, Point& center) { Halfedge_around_facet_circulator pHalfEdge = pFace->facet_begin(); Halfedge_around_facet_circulator end = pHalfEdge; Vector vec(0.0,0.0,0.0); int degree = 0; CGAL_For_all(pHalfEdge,end) { vec = vec + (pHalfEdge->vertex()->point()-CGAL::ORIGIN); degree++; } center = CGAL::ORIGIN + (vec/FT(degree)); } void gl_draw_direct_triangles(bool smooth_shading, bool use_normals, bool inverse_normals = false) { // draw triangles ::glBegin(GL_TRIANGLES); Facet_iterator pFacet = facets_begin(); for(;pFacet != facets_end();pFacet++) gl_draw_facet(pFacet,smooth_shading,use_normals,inverse_normals); ::glEnd(); // end polygon assembly } void gl_draw_direct(bool smooth_shading, bool use_normals, bool inverse_normals = false) { // draw polygons Facet_iterator pFacet = facets_begin(); for(;pFacet != facets_end();pFacet++) { // begin polygon assembly ::glBegin(GL_POLYGON); gl_draw_facet(pFacet,smooth_shading,use_normals,inverse_normals); ::glEnd(); // end polygon assembly } } void gl_draw_facet(Facet_handle pFacet, bool smooth_shading, bool use_normals, bool inverse_normals = false) { // one normal per face if(use_normals && !smooth_shading) { const typename Facet::Normal_3& normal = pFacet->normal(); if(inverse_normals) ::glNormal3f(-normal[0],-normal[1],-normal[2]); else ::glNormal3f(normal[0],normal[1],normal[2]); } // revolve around current face to get vertices Halfedge_around_facet_circulator pHalfedge = pFacet->facet_begin(); do { // one normal per vertex if(use_normals && smooth_shading) { const typename Facet::Normal_3& normal = pHalfedge->vertex()->normal(); if(inverse_normals) ::glNormal3f(-normal[0],-normal[1],-normal[2]); else ::glNormal3f(normal[0],normal[1],normal[2]); } // polygon assembly is performed per vertex const Point& point = pHalfedge->vertex()->point(); ::glVertex3d(point[0],point[1],point[2]); } while(++pHalfedge != pFacet->facet_begin()); } // superimpose edges void superimpose_edges(bool skip_ordinary_edges = true, bool skip_control_edges = false) { ::glBegin(GL_LINES); for(Edge_iterator h = edges_begin(); h != edges_end(); h++) { if(h->sharp()) continue; // ignore this edges if(skip_ordinary_edges && !h->control_edge()) continue; // ignore control edges if(skip_control_edges && h->control_edge()) continue; // assembly and draw line segment const Point& p1 = h->prev()->vertex()->point(); const Point& p2 = h->vertex()->point(); ::glVertex3f(p1[0],p1[1],p1[2]); ::glVertex3f(p2[0],p2[1],p2[2]); } ::glEnd(); } bool is_sharp(Halfedge_handle he, const double angle_sharp) { Facet_handle f1 = he->facet(); Facet_handle f2 = he->opposite()->facet(); if(f1 == Facet_handle() || f2 == Facet_handle() ) return false; const Vector& n1 = f1->normal(); const Vector& n2 = f2->normal(); if(angle_deg(n1,n2) > angle_sharp) return true; else return false; } Vertex_type type(Vertex_handle v) { unsigned int nb = nb_sharp_edges(v); switch(nb) { case 0: return SMOOTH; case 1: return DART; case 2: // crease vertex - may be regular or not return crease_type(v); default: // 3 and more return CORNER; } } // regular crease vertex must have valence 6, with // exactly two smooth edges on each side. Vertex_type crease_type(Vertex_handle v) { if(valence(v) != 6) return CREASE_IRREGULAR; // valence = 6 - let us check regularity // pick first sharp edge Halfedge_around_vertex_circulator he = v->vertex_begin(); Halfedge_around_vertex_circulator end = he; CGAL_For_all(he,end) if(he->sharp()) break; // next two must be smooth for(int i=0;i<2;i++) if(++he->sharp()) return CREASE_IRREGULAR; // next one must be sharp if(!++he->sharp()) return CREASE_IRREGULAR; // next two must be smooth for(int i=0;i<2;i++) if(++he->sharp()) return CREASE_IRREGULAR; return CREASE_REGULAR; } // return true if succeds void incident_points_on_crease(Vertex_handle v, Point& a, Point& b) { #ifdef _DEBUG Vertex_type vertex_type = type(v,angle_sharp); ASSERT(vertex_type == CREASE_IRREGULAR || vertex_type == CREASE_REGULAR); #endif // _DEBUG // pick first sharp edge Halfedge_around_vertex_circulator he = v->vertex_begin(); Halfedge_around_vertex_circulator end = he; CGAL_For_all(he,end) if(he->sharp()) break; a = he->opposite()->vertex()->point(); // pick next sharp edge he++; CGAL_For_all(he,end) if(he->sharp()) break; b = he->opposite()->vertex()->point(); } // return nb of sharp edges incident to v unsigned int nb_sharp_edges(Vertex_handle v) const { Halfedge_around_vertex_circulator he = v->vertex_begin(); Halfedge_around_vertex_circulator end = he; unsigned int nb_sharp_edges = 0; CGAL_For_all(he,end) if(he->sharp()) nb_sharp_edges++; return nb_sharp_edges; } // Angle between two vectors (in degrees) // we use this formula // uv = |u||v| cos(u,v) // u ^ v = w // |w| = |u||v| |sin(u,v)| //************************************************** static double angle_deg(const Vector &u, const Vector &v) { static const double conv = 1.0/PI*180.0; return conv * angle_rad(u,v); } static FT len(const Vector &v) { return (FT)std::sqrt(CGAL_NTS to_double(v*v)); } // Angle between two vectors (in rad) // uv = |u||v| cos(u,v) // u ^ v = w // |w| = |u||v| |sin(u,v)| //************************************************** static double angle_rad(const Vector &u, const Vector &v) { // check double product = len(u)*len(v); if(product == 0) return 0.0; // cosine double dot = (u*v); double cosine = dot / product; // sine Vector w = CGAL::cross_product(u,v); double AbsSine = len(w) / product; if(cosine >= 0) return std::asin(fix_sine(AbsSine)); else return PI-std::asin(fix_sine(AbsSine)); } //********************************************** // fix sine //********************************************** static double fix_sine(double sine) { if(sine >= 1) return 1; else if(sine <= -1) return -1; else return sine; } unsigned int tag_sharp_edges(const double angle_sharp) { unsigned int nb = 0; for(Halfedge_iterator he = edges_begin(); he != edges_end(); he++) { const bool tag = is_sharp(he,angle_sharp); he->sharp() = tag; he->opposite()->sharp() = tag; nb += tag ? 1 : 0; } return nb; } // draw edges void gl_draw_sharp_edges(const float line_width, unsigned char r, unsigned char g, unsigned char b) { ::glLineWidth(line_width); ::glColor3ub(r,g,b); ::glBegin(GL_LINES); for(Halfedge_iterator he = edges_begin(); he != edges_end(); he++) { if(he->sharp()) { const Point& a = he->opposite()->vertex()->point(); const Point& b = he->vertex()->point(); ::glVertex3d(a[0],a[1],a[2]); ::glVertex3d(b[0],b[1],b[2]); } } ::glEnd(); } void gl_draw_boundaries() { ::glBegin(GL_LINES); for(Halfedge_iterator he = halfedges_begin(); he != halfedges_end(); he++) { if(he->is_border()) { const Point& a = he->vertex()->point(); const Point& b = he->opposite()->vertex()->point(); ::glVertex3d(a.x(),a.y(),a.z()); ::glVertex3d(b.x(),b.y(),b.z()); } } ::glEnd(); } // draw bounding box void gl_draw_bounding_box() { ::glBegin(GL_LINES); // along x axis ::glVertex3f(m_bbox.xmin(),m_bbox.ymin(),m_bbox.zmin()); ::glVertex3f(m_bbox.xmax(),m_bbox.ymin(),m_bbox.zmin()); ::glVertex3f(m_bbox.xmin(),m_bbox.ymin(),m_bbox.zmax()); ::glVertex3f(m_bbox.xmax(),m_bbox.ymin(),m_bbox.zmax()); ::glVertex3f(m_bbox.xmin(),m_bbox.ymax(),m_bbox.zmin()); ::glVertex3f(m_bbox.xmax(),m_bbox.ymax(),m_bbox.zmin()); ::glVertex3f(m_bbox.xmin(),m_bbox.ymax(),m_bbox.zmax()); ::glVertex3f(m_bbox.xmax(),m_bbox.ymax(),m_bbox.zmax()); // along y axis ::glVertex3f(m_bbox.xmin(),m_bbox.ymin(),m_bbox.zmin()); ::glVertex3f(m_bbox.xmin(),m_bbox.ymax(),m_bbox.zmin()); ::glVertex3f(m_bbox.xmin(),m_bbox.ymin(),m_bbox.zmax()); ::glVertex3f(m_bbox.xmin(),m_bbox.ymax(),m_bbox.zmax()); ::glVertex3f(m_bbox.xmax(),m_bbox.ymin(),m_bbox.zmin()); ::glVertex3f(m_bbox.xmax(),m_bbox.ymax(),m_bbox.zmin()); ::glVertex3f(m_bbox.xmax(),m_bbox.ymin(),m_bbox.zmax()); ::glVertex3f(m_bbox.xmax(),m_bbox.ymax(),m_bbox.zmax()); // along z axis ::glVertex3f(m_bbox.xmin(),m_bbox.ymin(),m_bbox.zmin()); ::glVertex3f(m_bbox.xmin(),m_bbox.ymin(),m_bbox.zmax()); ::glVertex3f(m_bbox.xmin(),m_bbox.ymax(),m_bbox.zmin()); ::glVertex3f(m_bbox.xmin(),m_bbox.ymax(),m_bbox.zmax()); ::glVertex3f(m_bbox.xmax(),m_bbox.ymin(),m_bbox.zmin()); ::glVertex3f(m_bbox.xmax(),m_bbox.ymin(),m_bbox.zmax()); ::glVertex3f(m_bbox.xmax(),m_bbox.ymax(),m_bbox.zmin()); ::glVertex3f(m_bbox.xmax(),m_bbox.ymax(),m_bbox.zmax()); ::glEnd(); } // count #boundaries unsigned int nb_boundaries() { unsigned int nb = 0; tag_halfedges(0); for(Halfedge_iterator he = halfedges_begin(); he != halfedges_end(); he++) { if(he->is_border() && he->tag() == 0) { nb++; Halfedge_handle curr = he; do { curr = curr->next(); curr->tag(1); } while(curr != he); } } return nb; } // tag component void tag_component(Facet_handle pSeedFacet, const int tag_free, const int tag_done) { pSeedFacet->tag() = tag_done; std::list<Facet_handle> facets; facets.push_front(pSeedFacet); while(!facets.empty()) { Facet_handle pFacet = facets.front(); facets.pop_front(); pFacet->tag() = tag_done; Halfedge_around_facet_circulator pHalfedge = pFacet->facet_begin(); Halfedge_around_facet_circulator end = pHalfedge; CGAL_For_all(pHalfedge,end) { Facet_handle pNFacet = pHalfedge->opposite()->facet(); if(pNFacet != NULL && pNFacet->tag() == tag_free) { facets.push_front(pNFacet); pNFacet->tag() = tag_done; } } } } // count #components unsigned int nb_components() { unsigned int nb = 0; tag_facets(0); for(Facet_iterator pFacet = facets_begin(); pFacet != facets_end(); pFacet++) { if(pFacet->tag() == 0) { nb++; tag_component(pFacet,0,1); } } return nb; } // compute the genus // V - E + F + B = 2 (C - G) // C -> #connected components // G : genus // B : #boundaries int genus() { int c = nb_components(); int b = nb_boundaries(); int v = size_of_vertices(); int e = size_of_halfedges()/2; int f = size_of_facets(); return genus(c,v,f,e,b); } int genus(int c, int v, int f, int e, int b) { return (2*c+e-b-f-v)/2; } }; #endif // _POLYGON_MESH_
26.414453
182
0.593378
[ "mesh", "vector" ]
09ae57bb886671155866ce7d046fd06b43b7dcfa
686
h
C
include/rcnn/data/samplers/build.h
kerry-Cho/maskrcnn_benchmark.cpp
f110f7b6d6ac87b919b8f7aa95527c68f74d234a
[ "MIT" ]
99
2019-05-01T15:23:45.000Z
2022-01-30T05:11:40.000Z
include/rcnn/data/samplers/build.h
conanhung/maskrcnn_benchmark.cpp
eab9787d3140e003662a31a8e01f7ae39469e9a0
[ "MIT" ]
18
2019-05-21T11:31:44.000Z
2020-04-03T09:59:27.000Z
include/rcnn/data/samplers/build.h
conanhung/maskrcnn_benchmark.cpp
eab9787d3140e003662a31a8e01f7ae39469e9a0
[ "MIT" ]
27
2019-05-12T05:41:08.000Z
2021-02-07T01:58:01.000Z
#pragma once #include "samplers/samplers.h" #include "datasets/coco_datasets.h" #include <torch/data/samplers/base.h> namespace rcnn{ namespace data{ std::shared_ptr<torch::data::samplers::Sampler<>> make_data_sampler(int dataset_size, bool shuffle/*, distributed*/); std::vector<int> _quantize(std::vector<int> bins, std::vector<int> x); std::vector<float> _compute_aspect_ratios(COCODataset dataset); std::shared_ptr<torch::data::samplers::Sampler<>> make_batch_data_sampler(COCODataset dataset, bool is_train, int start_iter); } }
38.111111
117
0.606414
[ "vector" ]
09b1719526beebd70443e88f39ffbbb9c8b91e27
3,310
h
C
bibliotecas.h
alejandro13041/aleatory_ip
45624d8ecc0f4c8374a7fd44f8330ec2234367d8
[ "Apache-2.0" ]
null
null
null
bibliotecas.h
alejandro13041/aleatory_ip
45624d8ecc0f4c8374a7fd44f8330ec2234367d8
[ "Apache-2.0" ]
null
null
null
bibliotecas.h
alejandro13041/aleatory_ip
45624d8ecc0f4c8374a7fd44f8330ec2234367d8
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string.h> #include <stdlib.h> #include <windows.h> #include <time.h> #include <conio.h> #include <vector> #include <algorithm> #include <iterator> #include <array> using namespace std; void aleatory_port(long ip,long PTs[]){ unsigned int n = 0; for( int i = 0; i < ip; ++i){ n++; if( n == 10){ PTs[i] = 23; n = 0; }else{ PTs[i] = 80; } } cout<<"complete aleatory port"; cout<<"."; Sleep(1000); cout<<"."; Sleep(1000); cout<<"."<<endl; cout<<endl; } void clasification_counter_ip(long iph,string IPch[]){ unsigned long i1 = 0; unsigned long i2 = 0; unsigned long i3 = 0; unsigned long i4 = 0; unsigned long i5 = 0; for (int i = 0; i < iph; ++i){ if(IPch[i] =="A"){ i1++; }else if (IPch[i] =="B"){ i2++; }else if (IPch[i] =="C"){ i3++; }else if (IPch[i] =="D"){ i4++; }else if (IPch[i] =="E"){ i5++; } else{ continue; } } cout<<"complete"; cout<<"."; Sleep(1000); cout<<"."; Sleep(1000); cout<<"."<<endl; cout<<endl; cout<<"[A]:"<<i1<<endl; cout<<"[B]:"<<i2<<endl; cout<<"[C]:"<<i3<<endl; cout<<"[D]:"<<i4<<endl; cout<<"[E]:"<<i5<<endl; } void aleatory_ip(long ip,string IPs[],string IPc[]){ volatile int n1[ip]; volatile int n2[ip]; volatile int n3[ip]; volatile int n4[ip]; int j = 0; int k = 0; string IPa[ip]; for (int i = 0; i < ip; ++i){ n1[i] = 0 + rand() % 255; n2[i] = 0 + rand() % 255; n3[i] = 0 + rand() % 255; n4[i] = 0 + rand() % 255; } for (int i = 0; i < ip; ++i){ IPs[i] = to_string(n1[i]) + '.' + to_string(n2[i]) + '.' + to_string(n3[i]) + '.' + to_string(n4[i]) ; } for (int i = 0; i <ip; ++i){ (n1[i]>=0 and n1[i]<=127) ? IPc[i]="A":IPc[i]=IPc[i]; (n1[i]>=128 and n1[i]<=191) ? IPc[i]="B":IPc[i]=IPc[i]; (n1[i]>=192 and n1[i]<=233) ? IPc[i]="C":IPc[i]=IPc[i]; (n1[i]>=224 and n1[i]<=239) ? IPc[i]="D":IPc[i]=IPc[i]; (n1[i]>=240 and n1[i]<=255) ? IPc[i]="E":IPc[i]=IPc[i]; } for (int i = 0; i < ip; ++i){ if (IPs[i] =="127.0.0.0") { continue; } else if (IPs[i] =="0.0.0.0") { continue; } else if (IPs[i] =="3.0.0.0") { continue; } else if (IPs[i] =="15.0.0.0") { continue; } else if (IPs[i] =="56.0.0.0") { continue; } else if (IPs[i] =="10.0.0.0") { continue; } else if (IPs[i] =="192.168.0.0") { continue; } else if (IPs[i] =="172.16.0.0") { continue; } else if (IPs[i] =="100.64.0.0") { continue; } else{ IPa[j] = IPs[i]; j++; } } for (int i = 0; i < ip; ++i){ IPs[i] = IPa[i]; } j = 0; k = 0; for(int i = 0; i < ip; i++){ for(j = i + 1; j < ip; j++){ if(IPs[i] == IPs[j]){ k = j; while(k < ip -1){ IPs[k] = IPs[k+1]; ++k; } --ip; --j; } } } cout<<"complete aleatory ip"; cout<<"."; Sleep(1000); cout<<"."; Sleep(1000); cout<<"."<<endl; cout<<endl; }
14.776786
58
0.419637
[ "vector" ]
09b239dc680706e38fb6eead8f71dde639a7e963
722
h
C
src/essence.game/packets/square/incoming/ConnectRequest.h
Deluze/qpang-essence-emulator
943189161fd1fb8022221f24524a18244724edd6
[ "MIT" ]
15
2019-12-04T14:36:09.000Z
2021-06-11T12:00:04.000Z
src/essence.game/packets/square/incoming/ConnectRequest.h
Deluze/qpang-essence-emulator
943189161fd1fb8022221f24524a18244724edd6
[ "MIT" ]
6
2019-12-24T11:28:01.000Z
2020-03-31T00:14:50.000Z
src/essence.game/packets/square/incoming/ConnectRequest.h
Deluze/qpang-essence-emulator
943189161fd1fb8022221f24524a18244724edd6
[ "MIT" ]
21
2019-12-04T14:35:56.000Z
2022-02-14T20:59:31.000Z
#pragma once #include <cstdint> #include <string> #include <exception> #include "core/communication/packet/PacketEvent.h" #include "qpang/Game.h" #include "qpang/player/Player.h" #include "packets/square/outgoing/SquareList.h" class ConnectRequest : public PacketEvent { public: void handle(QpangConnection::Ptr conn, QpangPacket& packet) override { const auto playerId = packet.readInt(); const auto nickname = packet.readString(16); auto player = Game::instance()->getPlayer(playerId); if (player == nullptr) return; player->setSquareConn(conn); conn->setPlayer(player); std::vector<Square::Ptr> squares = Game::instance()->getSquareManager()->list(); conn->send(SquareList(squares)); } };
21.878788
82
0.725762
[ "vector" ]
09c0b5fb45248a2011979c6d0f942ab8bc093a2d
3,613
h
C
include/apt-pkg/pkgrecords.h
Sakurai07/apt4droid
0b007a38ad0e42ba34eef84bbb609dc4ac8a8ef2
[ "MIT" ]
null
null
null
include/apt-pkg/pkgrecords.h
Sakurai07/apt4droid
0b007a38ad0e42ba34eef84bbb609dc4ac8a8ef2
[ "MIT" ]
null
null
null
include/apt-pkg/pkgrecords.h
Sakurai07/apt4droid
0b007a38ad0e42ba34eef84bbb609dc4ac8a8ef2
[ "MIT" ]
null
null
null
// -*- mode: cpp; mode: fold -*- // Description /*{{{*/ /* ###################################################################### Package Records - Allows access to complete package description records directly from the file. The package record system abstracts the actual parsing of the package files. This is different than the generators parser in that it is used to access information not generate information. No information touched by the generator should be parable from here as it can always be retrieved directly from the cache. ##################################################################### */ /*}}}*/ #ifndef PKGLIB_PKGRECORDS_H #define PKGLIB_PKGRECORDS_H #include <apt-pkg/hashes.h> #include <apt-pkg/macros.h> #include <apt-pkg/pkgcache.h> #include <string> #include <vector> class APT_PUBLIC pkgRecords /*{{{*/ { public: class Parser; private: /** \brief dpointer placeholder (for later in case we need it) */ void * const d; pkgCache &Cache; std::vector<Parser *>Files; public: // Lookup function Parser &Lookup(pkgCache::VerFileIterator const &Ver); Parser &Lookup(pkgCache::DescFileIterator const &Desc); // Construct destruct explicit pkgRecords(pkgCache &Cache); virtual ~pkgRecords(); }; /*}}}*/ class APT_PUBLIC pkgRecords::Parser /*{{{*/ { protected: virtual bool Jump(pkgCache::VerFileIterator const &Ver) = 0; virtual bool Jump(pkgCache::DescFileIterator const &Desc) = 0; public: friend class pkgRecords; // These refer to the archive file for the Version virtual std::string FileName() {return std::string();}; virtual std::string SourcePkg() {return std::string();}; virtual std::string SourceVer() {return std::string();}; /** return all known hashes in this record. * * For authentication proposes packages come with hashsums which * this method is supposed to parse and return so that clients can * choose the hash to be used. */ virtual HashStringList Hashes() const { return HashStringList(); }; // These are some general stats about the package virtual std::string Maintainer() {return std::string();}; /** return short description in language from record. * * @see #LongDesc */ virtual std::string ShortDesc(std::string const &/*lang*/) {return std::string();}; /** return long description in language from record. * * If \b lang is empty the "best" available language will be * returned as determined by the APT::Languages configuration. * If a (requested) language can't be found in this record an empty * string will be returned. */ virtual std::string LongDesc(std::string const &/*lang*/) {return std::string();}; std::string ShortDesc() {return ShortDesc("");}; std::string LongDesc() {return LongDesc("");}; virtual std::string Name() {return std::string();}; virtual std::string Homepage() {return std::string();} // An arbitrary custom field virtual std::string RecordField(const char * /*fieldName*/) { return std::string();}; // The record in binary form virtual void GetRec(const char *&Start,const char *&Stop) {Start = Stop = 0;}; Parser(); virtual ~Parser(); private: void * const d; APT_HIDDEN std::string GetHashFromHashes(char const * const type) const { HashStringList const hashes = Hashes(); HashString const * const hs = hashes.find(type); return hs != NULL ? hs->HashValue() : ""; }; }; /*}}}*/ #endif
32.258929
88
0.631885
[ "vector" ]
09c99be3a35e2fbaa6bb780c04a095c54c5b2dfa
17,301
c
C
platform/pal_uefi_dt/src/pal_pe.c
semihalf-bernacki-grzegorz/bsa-acs
a1cf7ac63fd8234a0e248750c36a072fd40704bf
[ "Apache-2.0" ]
3
2021-05-23T16:30:10.000Z
2021-07-26T10:33:35.000Z
platform/pal_uefi_dt/src/pal_pe.c
ghuqingxin/bsa-acs
e970b0b9eb322df6e9cda437663627ab5832d8fc
[ "Apache-2.0" ]
13
2021-05-23T16:21:34.000Z
2022-03-30T21:02:10.000Z
platform/pal_uefi_dt/src/pal_pe.c
ghuqingxin/bsa-acs
e970b0b9eb322df6e9cda437663627ab5832d8fc
[ "Apache-2.0" ]
36
2021-01-24T11:02:37.000Z
2022-03-16T14:53:31.000Z
/** @file * Copyright (c) 2016-2018, 2021 Arm Limited or its affiliates. All rights reserved. * SPDX-License-Identifier : Apache-2.0 * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #include <Library/BaseLib.h> #include <Library/BaseMemoryLib.h> #include <Library/UefiBootServicesTableLib.h> #include <Library/UefiLib.h> #include "Include/IndustryStandard/Acpi61.h" #include <Include/libfdt.h> #include <Protocol/AcpiTable.h> #include <Protocol/Cpu.h> #include "include/pal_uefi.h" #include "include/pal_dt.h" #include "include/pal_dt_spec.h" static EFI_ACPI_6_1_MULTIPLE_APIC_DESCRIPTION_TABLE_HEADER *gMadtHdr; UINT8 *gSecondaryPeStack; UINT64 gMpidrMax; static UINT32 g_num_pe; static char pmu_dt_arr[][PMU_COMPATIBLE_STR_LEN] = { "arm,armv8-pmuv3", "arm,cortex-a73-pmu", "arm,cortex-a72-pmu", "arm,cortex-a57-pmu", "arm,cortex-a53-pmu", "arm,cortex-a35-pmu", "arm,cortex-a17-pmu", "arm,cortex-a15-pmu", "arm,cortex-a12-pmu", "arm,cortex-a9-pmu", "arm,cortex-a8-pmu", "arm,cortex-a7-pmu", "arm,cortex-a5-pmu", "arm,arm11mpcore-pmu", "arm,arm1176-pmu", "arm,arm1136-pmu" }; #define SIZE_STACK_SECONDARY_PE 0x100 //256 bytes per core #define UPDATE_AFF_MAX(src,dest,mask) ((dest & mask) > (src & mask) ? (dest & mask) : (src & mask)) UINT64 pal_get_madt_ptr(); VOID ArmCallSmc ( IN OUT ARM_SMC_ARGS *Args ); /** @brief Return the base address of the region allocated for Stack use for the Secondary PEs. @param None @return base address of the Stack **/ UINT64 PalGetSecondaryStackBase() { return (UINT64)gSecondaryPeStack; } /** @brief Return the number of PEs in the System. @param None @return num_of_pe **/ UINT32 pal_pe_get_num() { return (UINT32)g_num_pe; } /** @brief Returns the Max of each 8-bit Affinity fields in MPIDR. @param None @return Max MPIDR **/ UINT64 PalGetMaxMpidr() { return gMpidrMax; } /** @brief Allocate memory region for secondary PE stack use. SIZE of stack for each PE is a #define @param mpidr Pass MIPDR register content @return None **/ VOID PalAllocateSecondaryStack(UINT64 mpidr) { EFI_STATUS Status; UINT32 NumPe, Aff0, Aff1, Aff2, Aff3; Aff0 = ((mpidr & 0x00000000ff) >> 0); Aff1 = ((mpidr & 0x000000ff00) >> 8); Aff2 = ((mpidr & 0x0000ff0000) >> 16); Aff3 = ((mpidr & 0xff00000000) >> 32); NumPe = ((Aff3+1) * (Aff2+1) * (Aff1+1) * (Aff0+1)); if (gSecondaryPeStack == NULL) { Status = gBS->AllocatePool ( EfiBootServicesData, (NumPe * SIZE_STACK_SECONDARY_PE), (VOID **) &gSecondaryPeStack); if (EFI_ERROR(Status)) { bsa_print(ACS_PRINT_ERR, L"\n FATAL - Allocation for Seconday stack failed %x \n", Status); } pal_pe_data_cache_ops_by_va((UINT64)&gSecondaryPeStack, CLEAN_AND_INVALIDATE); } } /** @brief This API fills in the PE_INFO Table with information about the PEs in the system. This is achieved by parsing the ACPI - MADT table. @param PeTable - Address where the PE information needs to be filled. @return None **/ VOID pal_pe_create_info_table(PE_INFO_TABLE *PeTable) { EFI_ACPI_6_1_GIC_STRUCTURE *Entry = NULL; PE_INFO_ENTRY *Ptr = NULL; UINT32 TableLength = 0; UINT32 Length = 0; UINT64 MpidrAff0Max = 0, MpidrAff1Max = 0, MpidrAff2Max = 0, MpidrAff3Max = 0; if (PeTable == NULL) { bsa_print(ACS_PRINT_ERR, L" Input PE Table Pointer is NULL. Cannot create PE INFO \n"); return; } pal_pe_create_info_table_dt(PeTable); return; gMadtHdr = (EFI_ACPI_6_1_MULTIPLE_APIC_DESCRIPTION_TABLE_HEADER *) pal_get_madt_ptr(); if (gMadtHdr != NULL) { TableLength = gMadtHdr->Header.Length; bsa_print(ACS_PRINT_INFO, L" MADT is at %x and length is %x \n", gMadtHdr, TableLength); } PeTable->header.num_of_pe = 0; Entry = (EFI_ACPI_6_1_GIC_STRUCTURE *) (gMadtHdr + 1); Length = sizeof (EFI_ACPI_6_1_MULTIPLE_APIC_DESCRIPTION_TABLE_HEADER); Ptr = PeTable->pe_info; do { if (Entry->Type == EFI_ACPI_6_1_GIC) { //Fill in the cpu num and the mpidr in pe info table Ptr->mpidr = Entry->MPIDR; Ptr->pe_num = PeTable->header.num_of_pe; Ptr->pmu_gsiv = Entry->PerformanceInterruptGsiv; bsa_print(ACS_PRINT_DEBUG, L" MPIDR %x PE num %d \n", Ptr->mpidr, Ptr->pe_num); pal_pe_data_cache_ops_by_va((UINT64)Ptr, CLEAN_AND_INVALIDATE); Ptr++; PeTable->header.num_of_pe++; MpidrAff0Max = UPDATE_AFF_MAX(MpidrAff0Max, Entry->MPIDR, 0x000000ff); MpidrAff1Max = UPDATE_AFF_MAX(MpidrAff1Max, Entry->MPIDR, 0x0000ff00); MpidrAff2Max = UPDATE_AFF_MAX(MpidrAff2Max, Entry->MPIDR, 0x00ff0000); MpidrAff3Max = UPDATE_AFF_MAX(MpidrAff3Max, Entry->MPIDR, 0xff00000000); } Length += Entry->Length; Entry = (EFI_ACPI_6_1_GIC_STRUCTURE *) ((UINT8 *)Entry + (Entry->Length)); }while(Length < TableLength); gMpidrMax = MpidrAff0Max | MpidrAff1Max | MpidrAff2Max | MpidrAff3Max; g_num_pe = PeTable->header.num_of_pe; pal_pe_data_cache_ops_by_va((UINT64)PeTable, CLEAN_AND_INVALIDATE); pal_pe_data_cache_ops_by_va((UINT64)&gMpidrMax, CLEAN_AND_INVALIDATE); PalAllocateSecondaryStack(gMpidrMax); } /** @brief Install Exception Handler using UEFI CPU Architecture protocol's Register Interrupt Handler API @param ExceptionType - AARCH64 Exception type @param esr - Function pointer of the exception handler @return status of the API **/ UINT32 pal_pe_install_esr(UINT32 ExceptionType, VOID (*esr)(UINT64, VOID *)) { EFI_STATUS Status; EFI_CPU_ARCH_PROTOCOL *Cpu; // Get the CPU protocol that this driver requires. Status = gBS->LocateProtocol (&gEfiCpuArchProtocolGuid, NULL, (VOID **)&Cpu); if (EFI_ERROR (Status)) { return Status; } // Unregister the default exception handler. Status = Cpu->RegisterInterruptHandler (Cpu, ExceptionType, NULL); if (EFI_ERROR (Status)) { return Status; } // Register to receive interrupts Status = Cpu->RegisterInterruptHandler (Cpu, ExceptionType, (EFI_CPU_INTERRUPT_HANDLER)esr); if (EFI_ERROR (Status)) { return Status; } return EFI_SUCCESS; } /** @brief Make the SMC call using AARCH64 Assembly code SMC calls can take up to 7 arguments and return up to 4 return values. Therefore, the 4 first fields in the ARM_SMC_ARGS structure are used for both input and output values. @param Argumets to pass to the EL3 firmware @return None **/ VOID pal_pe_call_smc(ARM_SMC_ARGS *ArmSmcArgs) { ArmCallSmc (ArmSmcArgs); } VOID ModuleEntryPoint(); /** @brief Make a PSCI CPU_ON call using SMC instruction. Pass PAL Assembly code entry as the start vector for the PSCI ON call @param Argumets to pass to the EL3 firmware @return None **/ VOID pal_pe_execute_payload(ARM_SMC_ARGS *ArmSmcArgs) { ArmSmcArgs->Arg2 = (UINT64)ModuleEntryPoint; pal_pe_call_smc(ArmSmcArgs); } /** @brief Update the ELR to return from exception handler to a desired address @param context - exception context structure @param offset - address with which ELR should be updated @return None **/ VOID pal_pe_update_elr(VOID *context, UINT64 offset) { ((EFI_SYSTEM_CONTEXT_AARCH64*)context)->ELR = offset; } /** @brief Get the Exception syndrome from UEFI exception handler @param context - exception context structure @return ESR **/ UINT64 pal_pe_get_esr(VOID *context) { return ((EFI_SYSTEM_CONTEXT_AARCH64*)context)->ESR; } /** @brief Get the FAR from UEFI exception handler @param context - exception context structure @return FAR **/ UINT64 pal_pe_get_far(VOID *context) { return ((EFI_SYSTEM_CONTEXT_AARCH64*)context)->FAR; } VOID DataCacheCleanInvalidateVA(UINT64 addr); VOID DataCacheCleanVA(UINT64 addr); VOID DataCacheInvalidateVA(UINT64 addr); /** @brief Perform cache maintenance operation on an address @param addr - address on which cache ops to be performed @param type - type of cache ops @return None **/ VOID pal_pe_data_cache_ops_by_va(UINT64 addr, UINT32 type) { switch(type){ case CLEAN_AND_INVALIDATE: DataCacheCleanInvalidateVA(addr); break; case CLEAN: DataCacheCleanVA(addr); break; case INVALIDATE: DataCacheInvalidateVA(addr); break; default: DataCacheCleanInvalidateVA(addr); } } /** @brief This API fills in the PE_INFO_TABLE with information about PMU in the system. This is achieved by parsing the DT. @param PeTable - Address where the PMU information needs to be filled. @return None **/ VOID pal_pe_info_table_pmu_gsiv_dt(PE_INFO_TABLE *PeTable) { int i, offset, prop_len; UINT64 dt_ptr = 0; UINT32 *Pintr; int index = 0; int interrupt_cell, interrupt_frame_count; PE_INFO_ENTRY *Ptr = NULL; int intr_type = 0; int curr_pmu_intr_num = 0, prev_pmu_intr_num = 0; if (PeTable == NULL) return; dt_ptr = pal_get_dt_ptr(); if (dt_ptr == 0) { bsa_print(ACS_PRINT_ERR, L" dt_ptr is NULL \n"); return; } Ptr = PeTable->pe_info; for (i = 0; i < (sizeof(pmu_dt_arr)/PMU_COMPATIBLE_STR_LEN); i++) { /* Search for pmu nodes*/ offset = fdt_node_offset_by_compatible((const void *)dt_ptr, -1, pmu_dt_arr[i]); if (offset < 0) { bsa_print(ACS_PRINT_DEBUG, L" PMU compatible value not found for index:%d\n", i); continue; /* Search for next compatible item*/ } while (offset != -FDT_ERR_NOTFOUND) { /* Get interrupts property from frame */ Pintr = (UINT32 *) fdt_getprop_namelen((void *)dt_ptr, offset, "interrupts", 10, &prop_len); if ((prop_len < 0) || (Pintr == NULL)) { bsa_print(ACS_PRINT_ERR, L" PROPERTY interrupts offset %x, Error %d\n", offset, prop_len); return; } interrupt_cell = fdt_interrupt_cells((const void *)dt_ptr, offset); bsa_print(ACS_PRINT_DEBUG, L" interrupt_cell %d\n", interrupt_cell); if (interrupt_cell < INTERRUPT_CELLS_MIN || interrupt_cell > INTERRUPT_CELLS_MAX) { bsa_print(ACS_PRINT_ERR, L" Invalid interrupt cell : %d \n", interrupt_cell); return; } interrupt_frame_count = ((prop_len/sizeof(int))/interrupt_cell); bsa_print(ACS_PRINT_DEBUG, L" interrupt frame count : %d \n", interrupt_frame_count); if (interrupt_frame_count == 0) { bsa_print(ACS_PRINT_ERR, L" interrupt_frame_count is invalid\n"); return; } index = 0; /* Handle PMU node with multiple/single SPI/PPI frames * the pmu_gsiv should be in same order of CPU nodes */ for (i = 0; i < interrupt_frame_count; i++) { if ((interrupt_cell == 3) || (interrupt_cell == 4)) { intr_type = fdt32_to_cpu(Pintr[index++]); curr_pmu_intr_num = fdt32_to_cpu(Pintr[index++]); index++; /*Skip flag*/ if (interrupt_cell == 4) index++; /*Skip CPU affinity */ } else { /* Skip PMU node , if interrupt type not mentioned*/ Ptr = PeTable->pe_info; for (i = 0; i < PeTable->header.num_of_pe; i++) { Ptr->pmu_gsiv = 0; /* Set to zero*/ Ptr++; } bsa_print(ACS_PRINT_WARN, L" PMU interrupt type not mentioned\n"); return; } bsa_print(ACS_PRINT_DEBUG, L" intr_type : %d \n", intr_type); bsa_print(ACS_PRINT_DEBUG, L" pmu_intr_num : %d \n", curr_pmu_intr_num); if (intr_type == INTERRUPT_TYPE_PPI) { curr_pmu_intr_num += PPI_OFFSET; if ((prev_pmu_intr_num != 0) && (curr_pmu_intr_num != prev_pmu_intr_num)) { Ptr = PeTable->pe_info; for (i = 0; i < PeTable->header.num_of_pe; i++) { Ptr->pmu_gsiv = 0; /* Set to zero*/ Ptr++; } bsa_print(ACS_PRINT_WARN, L" PMU interrupt number mismatch found\n"); return; } if (prev_pmu_intr_num == 0) { /* Update table first time with same id*/ for (i = 0; i < PeTable->header.num_of_pe; i++) { Ptr->pmu_gsiv = curr_pmu_intr_num; Ptr++; } } prev_pmu_intr_num = curr_pmu_intr_num; } else { curr_pmu_intr_num += SPI_OFFSET; Ptr->pmu_gsiv = curr_pmu_intr_num; Ptr++; } } offset = fdt_node_offset_by_compatible((const void *)dt_ptr, offset, pmu_dt_arr[i]); } } } /** @brief This API fills in the PE_INFO Table with information about the PEs in the system. This is achieved by parsing the DT blob. @param PeTable - Address where the PE information needs to be filled. @return None **/ VOID pal_pe_create_info_table_dt(PE_INFO_TABLE *PeTable) { PE_INFO_ENTRY *Ptr = NULL; UINT64 dt_ptr; UINT32 *prop_val; UINT32 reg_val[2]; UINT64 MpidrAff0Max = 0, MpidrAff1Max = 0, MpidrAff2Max = 0, MpidrAff3Max = 0; int prop_len, addr_cell, size_cell; int offset, parent_offset; dt_ptr = pal_get_dt_ptr(); if (dt_ptr == 0) { bsa_print(ACS_PRINT_ERR, L" dt_ptr is NULL\n"); return; } PeTable->header.num_of_pe = 0; /* Find the first cpu node offset in DT blob */ offset = fdt_node_offset_by_prop_value((const void *) dt_ptr, -1, "device_type", "cpu", 4); if (offset != -FDT_ERR_NOTFOUND) { parent_offset = fdt_parent_offset((const void *) dt_ptr, offset); bsa_print(ACS_PRINT_DEBUG, L" NODE cpu offset %d\n", offset); size_cell = fdt_size_cells((const void *) dt_ptr, parent_offset); bsa_print(ACS_PRINT_DEBUG, L" NODE cpu size cell %d\n", size_cell); if (size_cell != 0) { bsa_print(ACS_PRINT_ERR, L" Invalid size cell for node cpu\n"); return; } addr_cell = fdt_address_cells((const void *) dt_ptr, parent_offset); bsa_print(ACS_PRINT_DEBUG, L" NODE cpu addr cell %d\n", addr_cell); if (addr_cell <= 0 || addr_cell > 2) { bsa_print(ACS_PRINT_ERR, L" Invalid address cell for node cpu\n"); return; } } else { bsa_print(ACS_PRINT_ERR, L" No CPU node found \n"); return; } Ptr = PeTable->pe_info; /* Perform a DT traversal till all cpu node are parsed */ while (offset != -FDT_ERR_NOTFOUND) { bsa_print(ACS_PRINT_DEBUG, L" SUBNODE cpu%d offset %x\n", PeTable->header.num_of_pe, offset); prop_val = (UINT32 *)fdt_getprop_namelen((void *)dt_ptr, offset, "reg", 3, &prop_len); if ((prop_len < 0) || (prop_val == NULL)) { bsa_print(ACS_PRINT_ERR, L" PROPERTY reg offset %x, Error %d\n", offset, prop_len); return; } reg_val[0] = fdt32_to_cpu(prop_val[0]); bsa_print(ACS_PRINT_DEBUG, L" reg_val<0> = %x\n", reg_val[0]); if (addr_cell == 2) { reg_val[1] = fdt32_to_cpu(prop_val[1]); bsa_print(ACS_PRINT_DEBUG, L" reg_val<1> = %x\n", reg_val[1]); Ptr->mpidr = (((INT64)(reg_val[0] & PROPERTY_MASK_PE_AFF3) << 32) | (reg_val[1] & PROPERTY_MASK_PE_AFF0_AFF2)); } else { Ptr->mpidr = (reg_val[0] & PROPERTY_MASK_PE_AFF0_AFF2); } Ptr->pe_num = PeTable->header.num_of_pe; pal_pe_data_cache_ops_by_va((UINT64)Ptr, CLEAN_AND_INVALIDATE); PeTable->header.num_of_pe++; MpidrAff0Max = UPDATE_AFF_MAX(MpidrAff0Max, Ptr->mpidr, 0x000000ff); MpidrAff1Max = UPDATE_AFF_MAX(MpidrAff1Max, Ptr->mpidr, 0x0000ff00); MpidrAff2Max = UPDATE_AFF_MAX(MpidrAff2Max, Ptr->mpidr, 0x00ff0000); MpidrAff3Max = UPDATE_AFF_MAX(MpidrAff3Max, Ptr->mpidr, 0xff00000000); Ptr++; offset = fdt_node_offset_by_prop_value((const void *) dt_ptr, offset, "device_type", "cpu", 4); } gMpidrMax = MpidrAff0Max | MpidrAff1Max | MpidrAff2Max | MpidrAff3Max; g_num_pe = PeTable->header.num_of_pe; pal_pe_info_table_pmu_gsiv_dt(PeTable); pal_pe_info_table_gmaint_gsiv_dt(PeTable); pal_pe_data_cache_ops_by_va((UINT64)PeTable, CLEAN_AND_INVALIDATE); pal_pe_data_cache_ops_by_va((UINT64)&gMpidrMax, CLEAN_AND_INVALIDATE); PalAllocateSecondaryStack(gMpidrMax); dt_dump_pe_table(PeTable); }
30.352632
103
0.644876
[ "vector" ]
09d5798ea1cb47fc292f16db5a79eda6b1cb9687
7,520
h
C
Headers/java/util/UUID.h
tcak76/j2objc
bb9415df98c3fdd1e5e3f4b9e27049d0b2e42633
[ "MIT" ]
11
2015-12-10T13:23:54.000Z
2019-04-23T02:41:13.000Z
Headers/java/util/UUID.h
tcak76/j2objc
bb9415df98c3fdd1e5e3f4b9e27049d0b2e42633
[ "MIT" ]
7
2015-11-05T22:45:53.000Z
2017-11-05T14:36:36.000Z
Headers/java/util/UUID.h
tcak76/j2objc
bb9415df98c3fdd1e5e3f4b9e27049d0b2e42633
[ "MIT" ]
40
2015-12-10T07:30:58.000Z
2022-03-15T02:50:10.000Z
// // Generated by the J2ObjC translator. DO NOT EDIT! // source: android/libcore/luni/src/main/java/java/util/UUID.java // #include "../../J2ObjC_header.h" #pragma push_macro("INCLUDE_ALL_JavaUtilUUID") #ifdef RESTRICT_JavaUtilUUID #define INCLUDE_ALL_JavaUtilUUID 0 #else #define INCLUDE_ALL_JavaUtilUUID 1 #endif #undef RESTRICT_JavaUtilUUID #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #if !defined (JavaUtilUUID_) && (INCLUDE_ALL_JavaUtilUUID || defined(INCLUDE_JavaUtilUUID)) #define JavaUtilUUID_ #define RESTRICT_JavaIoSerializable 1 #define INCLUDE_JavaIoSerializable 1 #include "../../java/io/Serializable.h" #define RESTRICT_JavaLangComparable 1 #define INCLUDE_JavaLangComparable 1 #include "../../java/lang/Comparable.h" @class IOSByteArray; /*! @brief UUID is an immutable representation of a 128-bit universally unique identifier (UUID). <p> There are multiple, variant layouts of UUIDs, but this class is based upon variant 2 of <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC 4122</a>, the Leach-Salz variant. This class can be used to model alternate variants, but most of the methods will be unsupported in those cases; see each method for details. @since 1.5 */ @interface JavaUtilUUID : NSObject < JavaIoSerializable, JavaLangComparable > #pragma mark Public /*! @brief <p> Constructs an instance with the specified bits. @param mostSigBits The 64 most significant bits of the UUID. @param leastSigBits The 64 least significant bits of the UUID. */ - (instancetype)initWithLong:(jlong)mostSigBits withLong:(jlong)leastSigBits; /*! @brief <p> The clock sequence value of the version 1, variant 2 UUID as per <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC 4122</a>. @return a <code>long</code> value. @throws UnsupportedOperationException if <code>version()</code> is not 1. */ - (jint)clockSequence; /*! @brief <p> Compares this UUID to the specified UUID. The natural ordering of UUIDs is based upon the value of the bits from most significant to least significant. @param uuid the UUID to compare to. @return a value of -1, 0 or 1 if this UUID is less than, equal to or greater than <code>uuid</code>. */ - (jint)compareToWithId:(JavaUtilUUID *)uuid; /*! @brief <p> Compares this UUID to another object for equality. If <code>object</code> is not <code>null</code>, is a UUID instance, and all bits are equal, then <code>true</code> is returned. @param object the <code>Object</code> to compare to. @return <code>true</code> if this UUID is equal to <code>object</code> or <code>false</code> if not. */ - (jboolean)isEqual:(id)object; /*! @brief <p> Parses a UUID string with the format defined by <code>toString()</code>. @param uuid the UUID string to parse. @return an UUID instance. @throws NullPointerException if <code>uuid</code> is <code>null</code>. @throws IllegalArgumentException if <code>uuid</code> is not formatted correctly. */ + (JavaUtilUUID *)fromStringWithNSString:(NSString *)uuid; /*! @brief <p> The 64 least significant bits of the UUID. @return the 64 least significant bits. */ - (jlong)getLeastSignificantBits; /*! @brief <p> The 64 most significant bits of the UUID. @return the 64 most significant bits. */ - (jlong)getMostSignificantBits; /*! @brief <p> Returns a hash value for this UUID that is consistent with the <code>equals(Object)</code> method. @return an <code>int</code> value. */ - (NSUInteger)hash; /*! @brief <p> Generates a variant 2, version 3 (name-based, MD5-hashed) UUID as per <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC 4122</a>. @param name the name used as byte array to create an UUID. @return an UUID instance. */ + (JavaUtilUUID *)nameUUIDFromBytesWithByteArray:(IOSByteArray *)name; /*! @brief <p> The node value of the version 1, variant 2 UUID as per <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC 4122</a>. @return a <code>long</code> value. @throws UnsupportedOperationException if <code>version()</code> is not 1. */ - (jlong)node; /*! @brief <p> Generates a variant 2, version 4 (randomly generated number) UUID as per <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC 4122</a>. @return an UUID instance. */ + (JavaUtilUUID *)randomUUID; /*! @brief <p> The timestamp value of the version 1, variant 2 UUID as per <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC 4122</a>. @return a <code>long</code> value. @throws UnsupportedOperationException if <code>version()</code> is not 1. */ - (jlong)timestamp; /*! @brief <p> Returns a string representation of this UUID in the following format, as per <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC 4122</a>. @code UUID = time-low &quot;-&quot; time-mid &quot;-&quot; time-high-and-version &quot;-&quot; clock-seq-and-reserved clock-seq-low &quot;-&quot; node time-low = 4hexOctet time-mid = 2hexOctet time-high-and-version = 2hexOctet clock-seq-and-reserved = hexOctet clock-seq-low = hexOctet node = 6hexOctet hexOctet = hexDigit hexDigit hexDigit = &quot;0&quot; / &quot;1&quot; / &quot;2&quot; / &quot;3&quot; / &quot;4&quot; / &quot;5&quot; / &quot;6&quot; / &quot;7&quot; / &quot;8&quot; / &quot;9&quot; / &quot;a&quot; / &quot;b&quot; / &quot;c&quot; / &quot;d&quot; / &quot;e&quot; / &quot;f&quot; / &quot;A&quot; / &quot;B&quot; / &quot;C&quot; / &quot;D&quot; / &quot;E&quot; / &quot;F&quot; @endcode @return a String instance. */ - (NSString *)description; /*! @brief <p> The variant of the UUID as per <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC 4122</a>. <ul> <li>0 - Reserved for NCS compatibility</li> <li>2 - RFC 4122/Leach-Salz</li> <li>6 - Reserved for Microsoft Corporation compatibility</li> <li>7 - Reserved for future use</li> </ul> @return an <code>int</code> value. */ - (jint)variant; /*! @brief <p> The version of the variant 2 UUID as per <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC 4122</a>. If the variant is not 2, then the version will be 0. <ul> <li>1 - Time-based UUID</li> <li>2 - DCE Security UUID</li> <li>3 - Name-based with MD5 hashing UUID (<code>nameUUIDFromBytes(byte[])</code>)</li> <li>4 - Randomly generated UUID (<code>randomUUID()</code>)</li> <li>5 - Name-based with SHA-1 hashing UUID</li> </ul> @return an <code>int</code> value. */ - (jint)version__; @end J2OBJC_EMPTY_STATIC_INIT(JavaUtilUUID) FOUNDATION_EXPORT void JavaUtilUUID_initWithLong_withLong_(JavaUtilUUID *self, jlong mostSigBits, jlong leastSigBits); FOUNDATION_EXPORT JavaUtilUUID *new_JavaUtilUUID_initWithLong_withLong_(jlong mostSigBits, jlong leastSigBits) NS_RETURNS_RETAINED; FOUNDATION_EXPORT JavaUtilUUID *create_JavaUtilUUID_initWithLong_withLong_(jlong mostSigBits, jlong leastSigBits); FOUNDATION_EXPORT JavaUtilUUID *JavaUtilUUID_randomUUID(); FOUNDATION_EXPORT JavaUtilUUID *JavaUtilUUID_nameUUIDFromBytesWithByteArray_(IOSByteArray *name); FOUNDATION_EXPORT JavaUtilUUID *JavaUtilUUID_fromStringWithNSString_(NSString *uuid); J2OBJC_TYPE_LITERAL_HEADER(JavaUtilUUID) #endif #pragma clang diagnostic pop #pragma pop_macro("INCLUDE_ALL_JavaUtilUUID")
30.322581
175
0.690691
[ "object", "model" ]
09e3fa3888a790c188ded9f2381581894ef51760
4,393
h
C
libraries/libwidget/widgets/TextField.h
MaheshBharadwaj/skift
3414cfe6c2686f6ce607752033c54eda6c971435
[ "MIT" ]
null
null
null
libraries/libwidget/widgets/TextField.h
MaheshBharadwaj/skift
3414cfe6c2686f6ce607752033c54eda6c971435
[ "MIT" ]
null
null
null
libraries/libwidget/widgets/TextField.h
MaheshBharadwaj/skift
3414cfe6c2686f6ce607752033c54eda6c971435
[ "MIT" ]
null
null
null
#pragma once #include <libgraphic/Painter.h> #include <libwidget/Widget.h> #include <libwidget/model/TextModel.h> class TextField : public Widget { private: RefPtr<TextModel> _model; TextCursor _cursor{}; int _hscroll_offset = 0; public: TextField(Widget *parent, RefPtr<TextModel> model) : Widget(parent), _model(model) { } ~TextField() { } void paint(Painter &painter, Recti rectangle) override { __unused(rectangle); painter.push(); painter.transform(content_bound().position()); int advance = 0; auto metrics = font()->metrics(); int baseline = content_bound().height() / 2 + metrics.capheight() / 2; auto paint_cursor = [&](Painter &painter, int position) { Vec2 cursor_position{position, metrics.fullascend(baseline)}; Vec2 cursor_size{2, metrics.fulllineheight()}; Rect cursor_bound{cursor_position, cursor_size}; painter.fill_rectangle(cursor_bound, color(THEME_ACCENT)); }; auto &line = _model->line(0); for (size_t j = 0; j < line.length(); j++) { Codepoint codepoint = line[j]; if (j == _cursor.column()) { paint_cursor(painter, advance); } if (codepoint == U'\t') { advance += 8 * 4; } else if (codepoint == U'\r') { // ignore } else { auto span = _model->span_at(0, j); auto glyph = font()->glyph(codepoint); painter.draw_glyph(*font(), glyph, {advance, baseline}, color(span.foreground())); advance += glyph.advance; } } if (line.length() == _cursor.column()) { paint_cursor(painter, advance); } painter.pop(); } void scroll_to_cursor() { } void event(Event *event) override { if (event->type == Event::KEYBOARD_KEY_TYPED) { if (event->keyboard.key == KEYBOARD_KEY_UP && event->keyboard.modifiers & KEY_MODIFIER_ALT) { _model->move_line_up_at(_cursor); scroll_to_cursor(); } else if (event->keyboard.key == KEYBOARD_KEY_DOWN && event->keyboard.modifiers & KEY_MODIFIER_ALT) { _model->move_line_down_at(_cursor); scroll_to_cursor(); } else if (event->keyboard.key == KEYBOARD_KEY_UP) { _cursor.move_up_within(*_model); scroll_to_cursor(); } else if (event->keyboard.key == KEYBOARD_KEY_DOWN) { _cursor.move_down_within(*_model); scroll_to_cursor(); } else if (event->keyboard.key == KEYBOARD_KEY_LEFT) { _cursor.move_left_within(*_model); scroll_to_cursor(); } else if (event->keyboard.key == KEYBOARD_KEY_RIGHT) { _cursor.move_right_within(*_model); scroll_to_cursor(); } if (event->keyboard.key == KEYBOARD_KEY_HOME) { _cursor.move_home_within(_model->line(_cursor.line())); scroll_to_cursor(); } else if (event->keyboard.key == KEYBOARD_KEY_END) { _cursor.move_end_within(_model->line(_cursor.line())); scroll_to_cursor(); } else if (event->keyboard.key == KEYBOARD_KEY_BKSPC) { _model->backspace_at(_cursor); scroll_to_cursor(); } else if (event->keyboard.key == KEYBOARD_KEY_DELETE) { _model->delete_at(_cursor); scroll_to_cursor(); } else if (event->keyboard.key == KEYBOARD_KEY_ENTER) { // ignore } else if (event->keyboard.codepoint != 0) { _model->append_at(_cursor, event->keyboard.codepoint); scroll_to_cursor(); } should_repaint(); event->accepted = true; } } };
28.341935
110
0.498065
[ "model", "transform" ]
09e7a5968c55534446ef404bfbb2c256b20a5967
4,922
c
C
benchmark/benchmark.c
VishrutPatel/CSC-501-Project2
42d2e0d0bd82c845627b65347875a4cfa5c37391
[ "MIT" ]
null
null
null
benchmark/benchmark.c
VishrutPatel/CSC-501-Project2
42d2e0d0bd82c845627b65347875a4cfa5c37391
[ "MIT" ]
null
null
null
benchmark/benchmark.c
VishrutPatel/CSC-501-Project2
42d2e0d0bd82c845627b65347875a4cfa5c37391
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////// // North Carolina State University // // // // Copyright 2016 // //////////////////////////////////////////////////////////////////////// // // This program is free software; you can redistribute it and/or modify it // under the terms and conditions of the GNU General Public License, // version 2, as published by the Free Software Foundation. // // This program is distributed in the hope 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. // //////////////////////////////////////////////////////////////////////// // // Author: Hung-Wei Tseng, Yu-Chia Liu // // Description: // Running Applications on Memory Container // //////////////////////////////////////////////////////////////////////// #include <mcontainer.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <sys/time.h> #include <sys/mman.h> #include <sys/syscall.h> int main(int argc, char *argv[]) { // variable initialization int i = 0; int number_of_processes = 1, number_of_objects = 1024, max_size_of_objects = 8192, number_of_containers = 1; int a, j, cid, size, stat, child_pid, devfd, max_size_of_objects_with_buffer; char filename[256]; char *mapped_data, *data; unsigned long long msec_time; FILE *fp; struct timeval current_time; pid_t *pid; // takes arguments from command line interface. if (argc < 4) { fprintf(stderr, "Usage: %s number_of_objects max_size_of_objects number_of_processes number_of_containers\n", argv[0]); exit(1); } number_of_objects = atoi(argv[1]); max_size_of_objects = atoi(argv[2]); number_of_processes = atoi(argv[3]); number_of_containers = atoi(argv[4]); max_size_of_objects_with_buffer = max_size_of_objects + 100; pid = (pid_t *) calloc(number_of_processes - 1, sizeof(pid_t)); // open the kernel module to use it devfd = open("/dev/mcontainer", O_RDWR); if (devfd < 0) { fprintf(stderr, "Device open failed"); exit(1); } // parent process forks children for (i = 0; i < (number_of_processes - 1); i++) { child_pid = fork(); if (child_pid == 0) { break; } else { pid[i] = child_pid; } } data = (char *) malloc(max_size_of_objects_with_buffer * sizeof(char)); // create the log file srand((int)time(NULL) + (int)getpid()); sprintf(filename, "mcontainer.%d.log", (int)getpid()); fp = fopen(filename, "w"); // create/link this process to a container. cid = getpid() % number_of_containers; mcontainer_create(devfd, cid); // Writing to objects for (i = 0; i < number_of_objects; i++) { mcontainer_lock(devfd, i); mapped_data = (char *)mcontainer_alloc(devfd, i, max_size_of_objects); // error handling if (!mapped_data) { fprintf(stderr, "Failed in mcontainer_alloc()\n"); exit(1); } // generate a random number to write into the object. a = rand() + 1; // starts to write the data to that address. gettimeofday(&current_time, NULL); for (j = 0; j < max_size_of_objects_with_buffer - 10; j = strlen(data)) { sprintf(data, "%s%d", data, a); } strncpy(mapped_data, data, max_size_of_objects-1); mapped_data[max_size_of_objects-1] = '\0'; // prints out the result into the log fprintf(fp, "S\t%d\t%d\t%ld\t%d\t%d\t%s\n", getpid(), cid, current_time.tv_sec * 1000000 + current_time.tv_usec, i, max_size_of_objects, mapped_data); mcontainer_unlock(devfd, i); memset(data, 0, max_size_of_objects_with_buffer); } // try delete something i = rand() % number_of_objects; mcontainer_lock(devfd, i); mcontainer_free(devfd, i); fprintf(fp, "D\t%d\t%d\t%ld\t%d\t%d\t%s\n", getpid(), cid, current_time.tv_sec * 1000000 + current_time.tv_usec, i, max_size_of_objects, mapped_data); mcontainer_unlock(devfd, i); // done with works, cleanup and wait for other processes. mcontainer_delete(devfd); close(devfd); if (child_pid != 0) { for (i = 0; i < (number_of_processes - 1); i++) { waitpid(pid[i], &stat, 0); } } free(pid); free(data); return 0; }
30.955975
158
0.58269
[ "object" ]
09e8a34721250c953b2431b1274d40bb624f9203
2,937
h
C
src/file_io/past_sample_io.h
ut-amrl/pom_localization
999bc059e1e141a726b7b3c2131294f979785add
[ "BSD-3-Clause" ]
1
2021-12-16T23:56:11.000Z
2021-12-16T23:56:11.000Z
src/file_io/past_sample_io.h
ut-amrl/pom_localization
999bc059e1e141a726b7b3c2131294f979785add
[ "BSD-3-Clause" ]
1
2022-02-25T18:49:13.000Z
2022-02-25T18:49:13.000Z
src/file_io/past_sample_io.h
ut-amrl/pom_localization
999bc059e1e141a726b7b3c2131294f979785add
[ "BSD-3-Clause" ]
null
null
null
// // Created by amanda on 2/21/21. // #ifndef AUTODIFF_GP_PAST_SAMPLE_IO_H #define AUTODIFF_GP_PAST_SAMPLE_IO_H #include <eigen3/Eigen/Dense> #include <fstream> #include <pose_optimization/pose_graph_generic.h> #include <base_lib/pose_reps.h> #include <unsupported/Eigen/MatrixFunctions> #include "file_io_utils.h" namespace file_io { struct PastSample2d { std::string semantic_class_; double transl_x_; double transl_y_; double theta_; /** * This is in the 0-1 range (exclusive -- don't want to get infinite values in the GP). */ double value_; }; void readPastSample2dLine(const std::string &line_in_file, PastSample2d &past_sample_data) { std::stringstream ss(line_in_file); std::vector<double> data; bool first_entry = true; while (ss.good()) { std::string substr; getline(ss, substr, ','); if (first_entry) { first_entry = false; past_sample_data.semantic_class_ = substr; } else { data.push_back(std::stod(substr)); } } past_sample_data.transl_x_ = data[0]; past_sample_data.transl_y_ = data[1]; past_sample_data.theta_ = data[2]; past_sample_data.value_ = data[3]; } void readPastSample2dsFromFile(const std::string &file_name, std::vector<PastSample2d> &past_samples) { std::ifstream file_obj(file_name); std::string line; bool first_line = true; while (std::getline(file_obj, line)) { if (first_line) { first_line = false; continue; } PastSample2d past_sample; readPastSample2dLine(line, past_sample); past_samples.emplace_back(past_sample); } } void writePastSamplesHeaderToFile(std::ofstream &file_stream) { writeCommaSeparatedStringsLineToFile({"semantic_class", "transl_x", "transl_y", "theta", "value"}, file_stream); } void writePastSample2dLineToFile(const PastSample2d &past_sample, std::ofstream &file_stream) { writeCommaSeparatedStringsLineToFile({past_sample.semantic_class_, std::to_string(past_sample.transl_x_), std::to_string(past_sample.transl_y_), std::to_string(past_sample.theta_), std::to_string(past_sample.value_)}, file_stream); } void writePastSamples2dToFile(const std::string &file_name, const std::vector<PastSample2d> &past_samples) { std::ofstream csv_file(file_name, std::ios::trunc); writePastSamplesHeaderToFile(csv_file); for (const PastSample2d &past_sample : past_samples) { writePastSample2dLineToFile(past_sample, csv_file); } csv_file.close(); } } #endif //AUTODIFF_GP_PAST_SAMPLE_IO_H
32.633333
120
0.625809
[ "vector" ]
09ec3dffe00c5d5b88d067c614aec0bb8fafe942
15,661
h
C
D4D/eGUI/D4D/graphic_objects/d4d_label.h
hyller/GladiatorLibrary
38d99f345db80ebb00116e54c91eada7968fa447
[ "Unlicense" ]
7
2018-07-22T14:29:58.000Z
2021-05-03T04:40:13.000Z
D4D/eGUI/D4D/graphic_objects/d4d_label.h
hyller/GladiatorLibrary
38d99f345db80ebb00116e54c91eada7968fa447
[ "Unlicense" ]
null
null
null
D4D/eGUI/D4D/graphic_objects/d4d_label.h
hyller/GladiatorLibrary
38d99f345db80ebb00116e54c91eada7968fa447
[ "Unlicense" ]
5
2019-02-13T14:50:51.000Z
2020-07-24T09:05:22.000Z
/************************************************************************** * * Copyright 2014 by Petr Gargulak. eGUI Community. * Copyright 2009-2013 by Petr Gargulak. Freescale Semiconductor, Inc. * *************************************************************************** * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License Version 3 * or later (the "LGPL"). * * As a special exception, the copyright holders of the eGUI project give you * permission to link the eGUI sources with independent modules to produce an * executable, regardless of the license terms of these independent modules, * and to copy and distribute the resulting executable under terms of your * choice, provided that you also meet, for each linked independent module, * the terms and conditions of the license of that module. * An independent module is a module which is not derived from or based * on this library. * If you modify the eGUI sources, you may extend this exception * to your version of the eGUI sources, but you are not obligated * to do so. If you do not wish to do so, delete this * exception statement from your 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. * * You should have received a copy of the GNU General Public License * and the GNU Lesser General Public License along with this program. * If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************//*! * * @file d4d_label.h * * @author Petr Gargulak * * @version 0.0.40.0 * * @date Jan-14-2014 * * @brief D4D Driver label object header file * *******************************************************************************/ #ifndef __D4D_LABEL_H #define __D4D_LABEL_H extern const D4D_OBJECT_SYS_FUNCTION d4d_labelSysFunc; /****************************************************************************** * D4D LABEL setting constants * *//*! @addtogroup doxd4d_label_const * @{ *******************************************************************************/ /*! @brief This is label init flags. If not defined, it sets to (\ref D4D_OBJECT_F_VISIBLE | \ref D4D_OBJECT_F_ENABLED | \ref D4D_OBJECT_F_FOCUSRECT) as a default.*/ #ifndef D4D_LBL_F_DEFAULT #define D4D_LBL_F_DEFAULT (D4D_OBJECT_F_VISIBLE | D4D_OBJECT_F_ENABLED | D4D_OBJECT_F_FOCUSRECT) #endif /*! @brief This is label init text properties. If not defined, it sets to (\ref D4D_ALIGN_H_CENTER_MASK | \ref D4D_ALIGN_V_CENTER_MASK) as a default.*/ #ifndef D4D_LBL_TXT_PRTY_DEFAULT #define D4D_LBL_TXT_PRTY_DEFAULT (D4D_ALIGN_H_CENTER_MASK | D4D_ALIGN_V_CENTER_MASK) #endif /*! @brief This is label init font properties. If not defined, it sets to ( 0 ) as a default.*/ #ifndef D4D_LBL_FNT_PRTY_DEFAULT #define D4D_LBL_FNT_PRTY_DEFAULT ( 0 ) #endif /*! @} End of doxd4d_label_const */ /****************************************************************************** * Types ******************************************************************************/ // label configuration (goes to ROM by default) typedef struct { D4D_STRING textBuff; // label text } D4D_LABEL; /****************************************************************************** * Macros ******************************************************************************/ // getting the LABEL structure from general OBJECT #define D4D_GET_LABEL(pObj) ((D4D_LABEL*)((pObj)->pParam)) /****************************************************************************** * D4D LABEL setting public macros * *//*! @addtogroup doxd4d_label_macro * @{ *******************************************************************************/ /**************************************************************************/ /*! * @brief Macro that create the Label object structure in memory including all substructures * @param type - type of object <\ref D4D_CONST; \ref D4D_NO_CONST> * @param name - name of label object * @param text - title text of label * @param x - coordination of label in X axis * @param y - coordination of label in Y axis * @param cx - size of label in X axis (width) * @param cy - size of label in Y axis (height) * @param radius - radius of corners * @param pMargin - pointer to margin structure (*\ref D4D_MARGIN)(Could be NULL) * @param pRelations - pointer to object relation array (Could be NULL) * @param flags - bitmask that specifies initial \ref doxd4d_object_const_flags * @param pScheme - pointer to color scheme. In case that this parameter is NULL, the default scheme color will be used for draw object * @param fontId - Identification number of the used title text font * @param pUser - user data of object * @param pOnUsrMsg -Pointer to an on user message callback function \ref D4D_ON_USR_MSG. This callback is called before this * message event is sent to the object itself. The message can be skipped by the \ref D4D_MSG_SKIP * return value, in a normal case the return value must be \ref D4D_MSG_NOSKIP * @note This macro create complete D4D_LABEL structure, including the object data sub structure. Is used to define all properties of label. The code example: @code _D4D_DECLARE_LABEL(D4D_CONST, my_label, D4D_DEFSTR("My label"), 10, 10, 120, 120, 6, NULL, NULL, (D4D_LABEL_F_DEFAULT), NULL, MY_FONT, NULL, NULL) @endcode *******************************************************************************/ #define _D4D_DECLARE_LABEL(type, name, text, x, y, cx, cy, radius, pMargin, pRelations, flags, pScheme, fontId, pUser, pOnUsrMsg) \ static D4D_STR_PROPERTIES name##_strPrties = { D4D_LBL_FNT_PRTY_DEFAULT, D4D_LBL_TXT_PRTY_DEFAULT}; \ static type D4D_LABEL name##_params = \ { \ { text, D4D_TEXT_LEN(text), fontId, &name##_strPrties, D4D_OBJECT_MAX_TEXT_LEN(text), 0} /* textBuff */ \ }; \ \ D4D_DECLARE_OBJECT(type, name, x, y, cx, cy, radius, pMargin, pRelations, pOnUsrMsg, &d4d_labelSysFunc, &(name##_params), flags, pUser, pScheme) /**************************************************************************/ /*! * @brief Macro that create the Label object structure in memory including all substructures with restricted count of parameters to simplify definition * @param name - name of label object * @param text - title text of label * @param x - coordination of label in X axis * @param y - coordination of label in Y axis * @param cx - size of label in X axis (width) * @param cy - size of label in Y axis (height) * @param flags - bitmask that specifies initial \ref doxd4d_object_const_flags * @param pScheme - pointer to color scheme. In case that this parameter is NULL, the default scheme color will be used for draw object * @param fontId - Identification number of the used title text font * @param pUser - user data of object * @param pOnUsrMsg -Pointer to an on user message callback function \ref D4D_ON_USR_MSG. This callback is called before this * message event is sent to the object itself. The message can be skipped by the \ref D4D_MSG_SKIP * return value, in a normal case the return value must be \ref D4D_MSG_NOSKIP * @note This macro create complete D4D_LABEL structure, including the object data sub structure. Is used to define all properties of label.If * there is missing parameter that is needed by user application used the full macro \ref _D4D_DECLARE_LABEL instead of this one. The code example: @code D4D_DECLARE_LABEL(my_label, D4D_DEFSTR("My label"), 10, 10, 120, 120, (D4D_LABEL_F_DEFAULT), NULL, MY_FONT, NULL, NULL) @endcode *******************************************************************************/ #define D4D_DECLARE_LABEL(name, text, x, y, cx, cy, flags, pScheme, fontId, pUser, pOnUsrMsg) \ _D4D_DECLARE_LABEL(D4D_CONST, name, text, x, y, cx, cy, 0, NULL, NULL, flags, pScheme, fontId, pUser, pOnUsrMsg) /**************************************************************************/ /*! * @brief Macro that create the Label object structure in memory including all substructures with restricted count of parameters to simplify definition * The missing parameters are replaced by default values. * @param name - name of label object * @param text - title text of label * @param x - coordination of label in X axis * @param y - coordination of label in Y axis * @param cx - size of label in X axis (width) * @param cy - size of label in Y axis (height) * @param fontId - Identification number of the used title text font * @note This macro create complete D4D_LABEL structure, including the object data sub structure. Is used to define all properties of label.If * there is missing parameter that is needed by user application used the full macro \ref _D4D_DECLARE_LABEL instead of this one. * The main advantage is less parameters of this macro against the full version. The code example: @code D4D_DECLARE_STD_LABEL(my_label, D4D_DEFSTR("My label"), 10, 10, 120, 120, MY_FONT) @endcode *******************************************************************************/ #define D4D_DECLARE_STD_LABEL(name, text, x, y, cx, cy, fontId) \ D4D_DECLARE_LABEL(name, text, x, y, cx, cy, (D4D_LBL_F_DEFAULT) , NULL, fontId, NULL, NULL) // Rounded button definition /**************************************************************************/ /*! * @brief Macro that create the rounded Label object structure in memory including all substructures with restricted count of parameters to simplify definition * @param name - name of label object * @param text - title text of label * @param x - coordination of label in X axis * @param y - coordination of label in Y axis * @param cx - size of label in X axis (width) * @param cy - size of label in Y axis (height) * @param radius - radius of corners * @param flags - bitmask that specifies initial \ref doxd4d_object_const_flags * @param pScheme - pointer to color scheme. In case that this parameter is NULL, the default scheme color will be used for draw object * @param fontId - Identification number of the used title text font * @param pUser - user data of object * @param pOnUsrMsg -Pointer to an on user message callback function \ref D4D_ON_USR_MSG. This callback is called before this * message event is sent to the object itself. The message can be skipped by the \ref D4D_MSG_SKIP * return value, in a normal case the return value must be \ref D4D_MSG_NOSKIP * @note This macro create complete D4D_LABEL structure, including the object data sub structure. Is used to define all properties of label.If * there is missing parameter that is needed by user application used the full macro \ref _D4D_DECLARE_LABEL instead of this one. The code example: @code D4D_DECLARE_LABEL(my_label, D4D_DEFSTR("My label"), 10, 10, 120, 120, (D4D_LABEL_F_DEFAULT), NULL, MY_FONT, NULL, NULL) @endcode *******************************************************************************/ #define D4D_DECLARE_RLABEL(name, text, x, y, cx, cy, radius, flags, pScheme, fontId, pUser, pOnUsrMsg) \ _D4D_DECLARE_LABEL(D4D_CONST, name, text, x, y, cx, cy, radius, NULL, NULL, flags, pScheme, fontId, pUser, pOnUsrMsg) /**************************************************************************/ /*! * @brief Macro that create the rounded Label object structure in memory including all substructures with restricted count of parameters to simplify definition * The missing parameters are replaced by default values. * @param name - name of label object * @param text - title text of label * @param x - coordination of label in X axis * @param y - coordination of label in Y axis * @param cx - size of label in X axis (width) * @param cy - size of label in Y axis (height) * @param radius - radius of corners * @param fontId - Identification number of the used title text font * @note This macro create complete D4D_LABEL structure, including the object data sub structure. Is used to define all properties of label.If * there is missing parameter that is needed by user application used the full macro \ref _D4D_DECLARE_LABEL instead of this one. * The main advantage is less parameters of this macro against the full version. The code example: @code D4D_DECLARE_STD_LABEL(my_label, D4D_DEFSTR("My label"), 10, 10, 120, 120, MY_FONT) @endcode *******************************************************************************/ #define D4D_DECLARE_STD_RLABEL(name, text, x, y, cx, cy, radius, fontId) \ D4D_DECLARE_RLABEL(name, text, x, y, cx, cy, radius, (D4D_LBL_F_DEFAULT) , NULL, fontId, NULL, NULL) // IN RAM instantions macros /**************************************************************************/ /*! * @brief Same as \ref D4D_DECLARE_LABEL, but is created in RAM instead of the ROM memory *******************************************************************************/ #define D4D_DECLARE_LABEL_INRAM(name, text, x, y, cx, cy, flags, pScheme, fontId, pUser, pOnUsrMsg) \ _D4D_DECLARE_LABEL(D4D_NO_CONST, name, text, x, y, cx, cy, 0, NULL, NULL, flags, pScheme, fontId, pUser, pOnUsrMsg) /**************************************************************************/ /*! * @brief Same as \ref D4D_DECLARE_STD_LABEL, but is created in RAM instead of the ROM memory *******************************************************************************/ #define D4D_DECLARE_STD_LABEL_INRAM(name, text, x, y, cx, cy, font) \ D4D_DECLARE_LABEL_INRAM(name, text, x, y, cx, cy, (D4D_LBL_F_DEFAULT) , NULL, font, NULL, NULL) // Rounded button definition /**************************************************************************/ /*! * @brief Same as \ref D4D_DECLARE_RLABEL, but is created in RAM instead of the ROM memory *******************************************************************************/ #define D4D_DECLARE_RLABEL_INRAM(name, text, x, y, cx, cy, radius, flags, pScheme, fontId, pUser, pOnUsrMsg) \ _D4D_DECLARE_LABEL(D4D_NO_CONST, name, text, x, y, cx, cy, radius, NULL, NULL, flags, pScheme, fontId, pUser, pOnUsrMsg) /**************************************************************************/ /*! * @brief Same as \ref D4D_DECLARE_STD_RLABEL, but is created in RAM instead of the ROM memory *******************************************************************************/ #define D4D_DECLARE_STD_RLABEL_INRAM(name, text, x, y, cx, cy, radius, font) \ D4D_DECLARE_RLABEL_INRAM(name, text, x, y, cx, cy, radius, (D4D_LBL_F_DEFAULT) , NULL, font, NULL, NULL) /*! @} End of doxd4d_label_macro */ /****************************************************************************** * Global variables ******************************************************************************/ /****************************************************************************** * Global functions ******************************************************************************/ /********************************************************* * * Object API * *********************************************************/ // Obsolete functions, replaced by any general #define D4D_LabelSetText D4D_SetText #endif /* __D4D_LABEL_H */
53.633562
160
0.591725
[ "object" ]
09f0de8f2aa1669adf61fb4917a1c651ebcb6ed1
7,655
h
C
PWGJE/EMCALJetTasks/Tracks/AliReducedHighPtEvent.h
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWGJE/EMCALJetTasks/Tracks/AliReducedHighPtEvent.h
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWGJE/EMCALJetTasks/Tracks/AliReducedHighPtEvent.h
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
/** * \file AliReducedHighPtEvent.h * \brief Reduced event structure for high-\f$ p_{t} \f$ analysis * * In this file a simple reduced event structure containing * - event information * - reconstructed EMCAL trigger information * - reconstructed EMCAL cluster * - generated particles (if created from Monte-Carlo events) * - Monte-Carlo event information (if created from Monte-Carlo events) * - reconstructed tracks * is created * * \author Markus Fasel <markus.fasel@cern.ch>, Lawrence Berkeley National Laboratory * \date Apr 14, 2015 */ #ifndef ALIREDUCEDHIGHPTEVENT_H #define ALIREDUCEDHIGHPTEVENT_H /* Copyright(c) 1998-2015, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ #include <vector> #include <TObject.h> #include "AliReducedPatchContainer.h" class TObjArray; /** * \namespace HighPtTracks * \brief Namespace for classes creating trees of events with jets * * This namespace contains classes descibing reduced events with high * jets. A jet event consists of the following classes. * - AliReducedJetEvent * - AliReducedJetParticle * - AliReducedJetConstituent * - AliReducedMatchedTrack * The task AliHighPtReconstructionEfficiency produces the reduced jet events * and is included in the namespace as well. Also the helper class AliParticleMap * is part of this namespace. */ namespace HighPtTracks { class AliReducedEmcalCluster; class AliReducedGeneratedParticle; class AliReducedReconstructedTrack; class AliReducedMCHeader; /** * \class AliReducedHighPtEvent * \brief Event structure for high-pt analysis */ class AliReducedHighPtEvent : public TObject { public: AliReducedHighPtEvent(Bool_t doAlloc = kFALSE); AliReducedHighPtEvent(const AliReducedHighPtEvent &ref); AliReducedHighPtEvent &operator=(const AliReducedHighPtEvent &ref); virtual ~AliReducedHighPtEvent(); void Copy(TObject &target) const; /** * Get the cluster container * \return The cluster container */ TObjArray *GetClusterContainer() { return fReducedClusterInfo; } std::vector<HighPtTracks::AliReducedEmcalCluster *> GetClusterVector() const; /** * Get the particle container (at generator level) * \return The particle container */ TObjArray *GetParticleContainer() { return fReducedParticleInfo; } std::vector<HighPtTracks::AliReducedGeneratedParticle *> GetParticleVector() const; /** * Get the container with reconstructed tracks * \return Container with reconstructed tracks */ TObjArray *GetTrackContainer() { return fReducedTrackInfo; } std::vector<HighPtTracks::AliReducedReconstructedTrack *> GetTrackVector() const; AliReducedEmcalCluster * GetClusterForIndex(Int_t index); AliReducedGeneratedParticle *GetParticleForIndex(Int_t index); /** * Get the container with trigger patches * \return container with trigger patches */ AliReducedPatchContainer *GetPatchContainer() { return fReducedPatchInfo; } /** * Get the centrality percentile of the event * \return centrality percentile of the event */ Float_t GetCentralityPercentile() const { return fCentralityPercentile; } /** * Get the z-position of the primary vertex * \return z-position of the primary vertex */ Float_t GetVertexZ() const { return fVertexZ; } /** * Get the Monte-Carlo header * \return The Monte-Carlo header (NULL if not set) */ AliReducedMCHeader *GetMonteCarloHeader() { return fMCHeader; } /** * Check if event is a min. bias event * \return true if event is a min. bias event, false otherwise */ Bool_t IsMinBias() const { return fIsMinBias; } /** * Check if event is triggered as Gamma low * \return true if event is a gamma low event, false otherwise */ Bool_t IsGammaLowFromString() const { return fGammaTriggerString[0]; } /** * Check if event is triggered as Gamma high * \return true if event is a gamma high event, false otherwise */ Bool_t IsGammaHighFromString() const { return fGammaTriggerString[1]; } /** * Check if event is triggered as Jet low * \return true if event is a jet low event, false otherwise */ Bool_t IsJetLowFromString() const { return fJetTriggerString[0]; } /** * Check if event is triggered as Jet high * \return true if event is a jet high event, false otherwise */ Bool_t IsJetHighFromString() const { return fJetTriggerString[1]; } /** * Get the run number * \return Run number */ Int_t GetRunNumber() const { return fRunNumber; } void AddReducedCluster(AliReducedEmcalCluster *cluster); void AddReducedGeneratedParticle(AliReducedGeneratedParticle *part); void AddReducedReconstructedParticle(AliReducedReconstructedTrack *trk); /** * Set the z-Position of the primary vertex * \param vz z-Position of the primary vertex */ void SetVertexZ(Float_t vz) { fVertexZ = vz; } /** * Set the event centrality percentile * \param cent Event centrality percentile */ void SetCentralityPercentile(Float_t cent) { fCentralityPercentile = cent; } /** * Set the trigger decision from the trigger string * \param isGammaLow If true event is triggered as gamma low event * \param isGammaHigh If true event is triggered as gamma high event * \param isJetLow If true event is triggered as jet low event * \param isJetHigh If true event is triggered as jet high event */ void SetDecisionFromTriggerString(Bool_t isGammaLow, Bool_t isGammaHigh, Bool_t isJetLow, Bool_t isJetHigh) { fGammaTriggerString[0] = isGammaLow; fGammaTriggerString[1] = isGammaHigh; fJetTriggerString[0] = isJetLow; fJetTriggerString[1] = isJetHigh; } /** * Flag event as min. bias event * \param isMinBias If true evnet is a min. bias event */ void SetMinBiasEvent(Bool_t isMinBias) { fIsMinBias = isMinBias; } /** * Set the reduced MC event header * \param header The Monte-Carlo event header */ void SetMonteCarloHeader(AliReducedMCHeader *header) { fMCHeader = header; } /** * Set the run number * \param runnumber The run number */ void SetRunNumber(Int_t runnumber) { fRunNumber = runnumber; } protected: Int_t fRunNumber; ///< Run number Float_t fCentralityPercentile; ///< Centrality percentile Float_t fVertexZ; ///< z-position of the primary vertex AliReducedMCHeader *fMCHeader; ///< Reduced Monte-Carlo header Bool_t fJetTriggerString[2]; ///< jet trigger selection from trigger string Bool_t fGammaTriggerString[2]; ///< gamma trigger selection from trigger string Bool_t fIsMinBias; ///< Flag event as min. bias event AliReducedPatchContainer *fReducedPatchInfo; ///< Container for reduced trigger patches TObjArray *fReducedClusterInfo; ///< Container for reduced EMCAL clusters TObjArray *fReducedParticleInfo; ///< Container for reduced true particles TObjArray *fReducedTrackInfo; ///< Container for reduced reconstructed tracks /// \cond CLASSIMP ClassDef(AliReducedHighPtEvent, 2); /// \endcond }; } /* namespace HighPtTracks */ #endif /* ALIREDUCEDHIGHPTEVENT_H */
39.25641
126
0.680993
[ "vector" ]
09f8bf83ab0ab129dfda6a6e60da09c38ba20e51
928
h
C
release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/staging/tidspbridge/include/dspbridge/dehdefs.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
4
2017-05-17T11:27:04.000Z
2020-05-24T07:23:26.000Z
release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/staging/tidspbridge/include/dspbridge/dehdefs.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
1
2018-08-21T03:44:27.000Z
2018-08-21T03:44:27.000Z
release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/staging/tidspbridge/include/dspbridge/dehdefs.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
5
2017-10-11T08:09:11.000Z
2020-10-14T04:10:13.000Z
/* * dehdefs.h * * DSP-BIOS Bridge driver support functions for TI OMAP processors. * * Definition for Bridge driver module DEH. * * Copyright (C) 2005-2006 Texas Instruments, Inc. * * This package is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifndef DEHDEFS_ #define DEHDEFS_ #include <dspbridge/mbx_sh.h> /* shared mailbox codes */ /* DEH object manager */ struct deh_mgr; /* Magic code used to determine if DSP signaled exception. */ #define DEH_BASE MBX_DEH_BASE #define DEH_USERS_BASE MBX_DEH_USERS_BASE #define DEH_LIMIT MBX_DEH_LIMIT #endif /* _DEHDEFS_H */
28.121212
71
0.740302
[ "object" ]
09ffaf661e9f78404f919cba1546a1b44105846d
4,782
h
C
cuda_assembler/cubin_info.h
sundersoft2/utility
9dadd9bc8680cf6ef2d7115bda56ab5f475c0543
[ "Unlicense" ]
null
null
null
cuda_assembler/cubin_info.h
sundersoft2/utility
9dadd9bc8680cf6ef2d7115bda56ab5f475c0543
[ "Unlicense" ]
null
null
null
cuda_assembler/cubin_info.h
sundersoft2/utility
9dadd9bc8680cf6ef2d7115bda56ab5f475c0543
[ "Unlicense" ]
null
null
null
const int params_initial_offset=0x140; struct nv_info_entry { int id=-1; //2 bytes int size=-1; //2 bytes string symbol_name; //first 4 bytes of data if present string data; void append(string& res, elf_file& elf) { if (!symbol_name.empty()) { assert(data.size()>=4); uint32& i=*(uint32*)&(data[0]); assert(i==0); i=elf.symbols_by_name.at(symbol_name); } assert(((uint16)id)==id); assert(((uint16)size)==size); append_string(res, (uint16)id); append_string(res, (uint16)size); res+=data; } void assign_null(uint16 t_id) { id=t_id; size=0; symbol_name.clear(); data.clear(); } void assign_no_data(uint16 t_id, uint16 t_size) { id=t_id; size=t_size; symbol_name.clear(); data.clear(); } void assign_index_value(uint16 t_id, string t_symbol_name, uint32 t_value) { id=t_id; size=8; symbol_name=t_symbol_name; data.clear(); append_string(data, (uint32)0); append_string(data, (uint32)t_value); } void assign_value(uint16 t_id, uint32 t_value) { id=t_id; size=4; symbol_name.clear(); data.clear(); append_string(data, (uint32)t_value); } void assign_array(uint16 t_id, vector<uint32> t_value) { id=t_id; size=t_value.size()*4; symbol_name.clear(); data.clear(); for (uint32 v : t_value) { append_string(data, (uint32)v); } } //.nv.info: nv_info_entry& max_stack_size(string t_symbol_name, uint32 value) { assign_index_value(0x2304, t_symbol_name, value); //EIATTR_MAX_STACK_SIZE return *this; } nv_info_entry& min_stack_size(string t_symbol_name, uint32 value) { assign_index_value(0x1204, t_symbol_name, value); //EIATTR_MIN_STACK_SIZE return *this; } nv_info_entry& frame_size(string t_symbol_name, uint32 value) { assign_index_value(0x1104, t_symbol_name, value); //EIATTR_FRAME_SIZE return *this; } //.nv.info.[kernel]: nv_info_entry& header() { assign_null(0x2a01); //EIATTR_SW1850030_WAR return *this; } nv_info_entry& param_cbank(string t_symbol_name, uint32 params_size) { assert(params_size<=0x1000); uint32 params_offset=params_initial_offset; assign_index_value(0x0a04, t_symbol_name, params_offset | (params_size<<16)); //EIATTR_PARAM_CBANK return *this; } nv_info_entry& param_cbank_size(uint32 params_size) { assert(params_size<=0x1000); assign_no_data(0x1903, params_size); //EIATTR_CBANK_PARAM_SIZE return *this; } nv_info_entry& param_info(uint32 t_ordinal, uint32 t_offset, uint32 t_size) { uint32 index=0; //no idea what this does uint32 magic=0x1f000; //pointee's logAlignment + space + cbank. cbank is 0x1f and the rest are 0s. no idea what these do assert(t_ordinal<=0xffff); assert(t_offset<=0xffff); assert(t_size<=0x3fff); id=0x1704; //EIATTR_KPARAM_INFO size=12; symbol_name.clear(); data.clear(); append_string(data, (uint32)index); append_string(data, (uint32)(t_ordinal | (t_offset<<16))); append_string(data, (uint32)(magic | (t_size<<18))); return *this; } nv_info_entry& max_reg_count(uint32 value) { assert(value<=0xff); assign_no_data(0x1b03, value); //EIATTR_MAXREG_COUNT return *this; } nv_info_entry& shfl_offsets(vector<uint32> t_value) { assign_array(0x2804, t_value); //EIATTR_COOP_GROUP_INSTR_OFFSETS return *this; } nv_info_entry& exit_offsets(vector<uint32> t_value) { assign_array(0x1c04, t_value); //EIATTR_EXIT_INSTR_OFFSETS return *this; } nv_info_entry& s2r_ctaid_offsets(vector<uint32> t_value) { assign_array(0x1d04, t_value); //EIATTR_S2RCTAID_INSTR_OFFSETS return *this; } nv_info_entry& required_num_tids(uint32 value) { assign_value(0x1004, value); //EIATTR_REQNTID return *this; } nv_info_entry& max_threads(uint32 value) { assign_value(0x0504, value); //EIATTR_MAX_THREADS return *this; } nv_info_entry& crs_stack_size(uint32 value) { assign_value(0x1e04, value); //EIATTR_CRS_STACK_SIZE return *this; } nv_info_entry& ctaid_z_used() { assign_null(0x0401); //EIATTR_CTAIDZ_USED return *this; } nv_info_entry& externs(vector<uint32> t_value) { assign_array(0x0f04, t_value); //EIATTR_EXTERNS return *this; } };
28.634731
128
0.622125
[ "vector" ]
67079eaa87fb28bb887bdc6c0cb5ed7c78da5cf4
3,483
c
C
MyPkg/Library/AppCommonLib/AppCommonLib.c
James992927108/uEFI_Edk2_Practice
2cac7618dfee10bfa5104a2e167c85425fde0100
[ "BSD-2-Clause" ]
null
null
null
MyPkg/Library/AppCommonLib/AppCommonLib.c
James992927108/uEFI_Edk2_Practice
2cac7618dfee10bfa5104a2e167c85425fde0100
[ "BSD-2-Clause" ]
null
null
null
MyPkg/Library/AppCommonLib/AppCommonLib.c
James992927108/uEFI_Edk2_Practice
2cac7618dfee10bfa5104a2e167c85425fde0100
[ "BSD-2-Clause" ]
null
null
null
#include <AppCommonLib.h> #include <Library/AppFrameWork.h> #include <Library/AppCommon.h> EFI_STATUS AppPrintBuffer( UINT16 *Buffer ) { UINTN i; for (i = 0; i<=0xFF; i++){ if((i%10)==0){ if (i != 0); Print(L"\n"); Print(L"%.3d: ", i); } Print(L"%.4X ", Buffer[i]); } return EFI_SUCCESS; } /* Search a given PCI classcode and return it's PCI address */ BOOLEAN EFIAPI AppProbePCIByClassCode( UINT8 mBassCode, UINT8 mSubClass, UINT8 *mInterface OPTIONAL, UINT64 *mPCI_ADDRESS ) { EFI_STATUS Status; BOOLEAN Found; UINTN HandleCount; UINTN ThisBus; UINTN Bus, Dev, Func; UINTN Seg, Index; UINTN Count; PCI_DEVICE_INDEPENDENT_REGION *Hdr; PCI_TYPE_GENERIC PciHeader; EFI_PCI_IO_PROTOCOL *Pci; EFI_HANDLE *HandleBuffer; Found = FALSE; ZeroMem(mPCI_ADDRESS, sizeof(EFI_APP_FRAMEWORK_TABLE)*APP_MAX_CONTROLLER); //init Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiPciIoProtocolGuid, \ NULL, &HandleCount, &HandleBuffer); if (EFI_ERROR(Status)){ Print(L"No PCI devices found!!\n"); return FALSE; } Count = 0; for (ThisBus = 0; ThisBus <= PCI_MAX_BUS; ThisBus++){ for (Index = 0; Index < HandleCount; Index++){ Status = gBS->HandleProtocol(HandleBuffer[Index], &gEfiPciIoProtocolGuid, (VOID **)&Pci); if(!EFI_ERROR(Status)){ Pci->GetLocation(Pci, &Seg, &Bus, &Dev, &Func); if (ThisBus != Bus) continue; Status = Pci->Pci.Read(Pci, EfiPciWidthUint32, 0, sizeof(PciHeader)/sizeof(UINT32), &PciHeader); if (!EFI_ERROR(Status)){ Hdr = &PciHeader.Bridge.Hdr; if ((Hdr->ClassCode[2] == mBassCode) && (Hdr->ClassCode[1] == mSubClass)){ if (mInterface != NULL){ if (Hdr->ClassCode[0] == *mInterface){ mPCI_ADDRESS[Count++] = PCI_LIB_ADDRESS(Bus, Dev, Func, 0); Found = TRUE; } }else{ mPCI_ADDRESS[Count++] = PCI_LIB_ADDRESS(Bus, Dev, Func, 0); Found = TRUE; } } //endif ((Hdr->ClassCode[2] == mBassCode) } //endif (!EFI_ERROR(Status)) } //endif (!EFI_ERROR(Status)) 1st }//for HandleCount }//for ThisBus return Found; } EFI_STATUS AppAhciIdentify( EFI_ATA_PASS_THRU_PROTOCOL *ATApt, UINT16 Port, UINT16 PortMultiplier, UINT8 *Buffer512B ) { EFI_STATUS Status; EFI_ATA_PASS_THRU_COMMAND_PACKET Packet; EFI_ATA_STATUS_BLOCK Asb; EFI_ATA_COMMAND_BLOCK Acb; Status = EFI_SUCCESS; ZeroMem(Buffer512B, sizeof(512*sizeof(UINT8))); // // Initialize Packet buffer. // ZeroMem ((char *)&Packet, sizeof(Packet)); ZeroMem ((char *)&Acb, sizeof(Acb)); ZeroMem ((char *)&Asb, sizeof(Asb)); Packet.Asb = &Asb; Packet.Acb = &Acb; Packet.InDataBuffer = Buffer512B; Packet.InTransferLength = 512; Packet.Protocol = EFI_ATA_PASS_THRU_PROTOCOL_PIO_DATA_IN; Packet.Length = EFI_ATA_PASS_THRU_LENGTH_BYTES; Packet.Timeout = ATA_PASS_THRU_TIMEOUT; Acb.AtaCommand = ATA_CMD_IDENTIFY; Status = ATApt->PassThru(ATApt, Port, PortMultiplier, &Packet, NULL); if (EFI_ERROR(Status)){ Acb.AtaCommand = ATAPI_CMD_IDENTIFY; //for ATAPI Indentify(ODD) Status = ATApt->PassThru(ATApt, Port, PortMultiplier, &Packet, NULL); } return Status; }
25.057554
104
0.612403
[ "3d" ]
67151914ba813bae348f692f070a695ca280f2a3
5,312
h
C
Plugins/my.awesomeproject.exampleplugin/src/internal/AwesomeView.h
cmosquer/MyMITKProjects
8bb82ae0fba2b77bae417079d4516876edb30949
[ "BSD-3-Clause" ]
1
2021-06-27T09:35:22.000Z
2021-06-27T09:35:22.000Z
Plugins/my.awesomeproject.exampleplugin/src/internal/AwesomeView.h
cmosquer/MyMITKProjects
8bb82ae0fba2b77bae417079d4516876edb30949
[ "BSD-3-Clause" ]
null
null
null
Plugins/my.awesomeproject.exampleplugin/src/internal/AwesomeView.h
cmosquer/MyMITKProjects
8bb82ae0fba2b77bae417079d4516876edb30949
[ "BSD-3-Clause" ]
null
null
null
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef AwesomeView_h #define AwesomeView_h #include <berryISelectionListener.h> #include <QmitkAbstractView.h> #include <mitkSurface.h> #include "vtkRANSACPlane.h" #include <vector> #include <vtkSmartPointer.h> #include <mitkLookupTable.h> #include <mitkPointSet.h> #include <qtablewidget.h> #include <QTableWidget> // There's an item "AwesomeViewControls.ui" in the UI_FILES list in // files.cmake. The Qt UI Compiler will parse this file and generate a // header file prefixed with "ui_", which is located in the build directory. // Use Qt Creator to view and edit .ui files. The generated header file // provides a class that contains all of the UI widgets. #include <ui_AwesomeViewControls.h> // All views in MITK derive from QmitkAbstractView. You have to override // at least the two methods CreateQtPartControl() and SetFocus(). class AwesomeView : public QmitkAbstractView { // As QmitkAbstractView derives from QObject and we want to use the Qt // signal and slot mechanism, we must not forget the Q_OBJECT macro. // This header file also has to be listed in MOC_H_FILES in files.cmake, // in order that the Qt Meta-Object Compiler can find and process this // class declaration. Q_OBJECT public: // This is a tricky one and will give you some headache later on in // your debug sessions if it has been forgotten. Also, don't forget // to initialize it in the implementation file. static const std::string VIEW_ID; std::vector<vtkSmartPointer<vtkRANSACPlane> > planoIO; std::vector<vtkSmartPointer<vtkRANSACPlane> > planoPQ; std::vector<vtkSmartPointer<vtkPlaneSource> > planoOBJ; int N_casos; std::vector<int*> semaforo_desempeno; //int N=10; //Cantidad de casos i.e. cant de planos objetivos //int ann_starts[N]={0}; //int ann_ends[N]={0}; mitk::LookupTable::Pointer mitkLut; int flag_SeInicio; //Widget de resultados: QWidget *resultsWidget; QPushButton *pbExport; QTableWidget *tableWidget; QLabel *titulo; QWidget *ppppp; double *distancias; double *angulos; AwesomeView(); // In this method we initialize the GUI components and connect the // associated signals and slots. void CreateQtPartControl(QWidget* parent) override; private slots: //void CalcularInliersPQ_conPlanoObjetivo(); vtkSmartPointer<vtkPolyData> CalcularInliersPQ_sinPointSet(); void AjustarPlanoPQ(); void AjustarPlanoIO(); //double Hausdorff(vtkPolyData *pq, vtkPolyData *hueso); void onUL(double); void onLL(double); void onBox_Indicadores(); double box_Planos(int); void Colorimetria(); double Iniciar(); void onCalcularInliers(); void onPlaneNumber(int); void onDefinirTotal(); void onModo(); void onEstimar(); void onRestringirAlHueso(); void onExportarDatos(); private: // Typically a one-liner. Set the focus to the default widget. void SetFocus() override; // This method is conveniently called whenever the selection of Data Manager // items changes. void OnSelectionChanged( berry::IWorkbenchPart::Pointer source, const QList<mitk::DataNode::Pointer>& dataNodes) override; int RestringirAlHueso(int PQ_o_IO); vtkRANSACPlane* AjustarPlano(vtkPolyData* inliers); int CalcularInliersPQ(int case_number); double CalcularIndicadorISO(vtkPolyData *plano_ejecutado, vtkPlane *plano_objetivo); double CalcularIndicadorPpk(vtkPolyData *plano_ejecutado, vtkPlane *plano_objetivo); double CalcularIndicadorTolerancia(vtkPolyData *plano_ejecutado, vtkPlane *plano_objetivo); // mitk::DataNode* encontrarNodo(QRegExp regexp); void OpenAnnotations(); void GetPlanosObjetivo(); int DefinirTotalIO(QTableWidget *tableWidget); int DefinirTotalPQ(QTableWidget *tableWidget); int DefinirComparacion(QTableWidget *tableWidget); void dividirPuntosIntraoperatorios(vtkPoints *total_puntos); void ExportarDatos_DosMetodos(QTableWidget *tableWidget, QString file_name); void ExportarDatos_UnMetodo(QTableWidget *tableWidget, QString file_name); double* CalcularIndicadorTumor(vtkPolyData *tumor, vtkPolyData *bounded_plane, int tipo); vtkSmartPointer<vtkPolyData> RestringirPlanoAlHueso(vtkRANSACPlane *plano_ejecutado, vtkPlaneSource *plano_objetivo); void box_Indicadores(int item, double* results); vtkSmartPointer<vtkDoubleArray> CalcularDistancias(vtkPolyData *boundedPlane, vtkPlane *plano_objetivo); int GetColorIndicador(int type, double value); //double CalcularIndicadorPpk(vtkRANSACPlane *plano_ejecutado, vtkPlaneSource *plano_objetivo); void CalcularIndicadoresPlanos(vtkPolyData *boundedPlane_PQ, vtkPolyData *boundedPlane_IO, int case_number); //double CalcularIndicadorISO(vtkPolyData* plano_ejecutado, vtkPolyData* plano_objetivo); // Generated from the associated UI file, it encapsulates all the widgets // of our view. Ui::AwesomeViewControls m_Controls; }; #endif
37.942857
119
0.761483
[ "object", "vector" ]
671a6e87643c0dfffb1a9bdee0c1d3d7125a7186
994
h
C
rightTrapezoid.h
marcus-elia/complete-random-city
5888cb6bb3f6487b9bf34c871980fc0a077aa279
[ "MIT" ]
1
2021-03-11T08:25:18.000Z
2021-03-11T08:25:18.000Z
rightTrapezoid.h
marcus-elia/complete-random-city
5888cb6bb3f6487b9bf34c871980fc0a077aa279
[ "MIT" ]
2
2020-04-26T16:00:13.000Z
2020-10-07T22:23:26.000Z
rightTrapezoid.h
marcus-elia/complete-random-city
5888cb6bb3f6487b9bf34c871980fc0a077aa279
[ "MIT" ]
null
null
null
#ifndef COMPLETE_RANDOM_CITY_RIGHTTRAPEZOID_H #define COMPLETE_RANDOM_CITY_RIGHTTRAPEZOID_H #include "solid.h" class RightTrapezoid : public Solid { private: double upperZWidth; public: RightTrapezoid(); RightTrapezoid(Point inputCenter, RGBAcolor inputColor, double inputXWidth, double inputYWidth, double inputZWidth, RGBAcolor inputLineColor, double inputUpperZWidth); RightTrapezoid(Point inputCenter, RGBAcolor inputColor, double inputXWidth, double inputYWidth, double inputZWidth, RGBAcolor inputLineColor, double inputUpperZWidth, Point inputLocation, Point inputLookingAt, double inputSpeed, Point inputVelocity, Point inputOwnerCenter); void initializeCorners(); void lookAt(Point &p); void draw() const; void drawLines() const; void drawFaces() const; std::experimental::optional<Point> correctCollision(Point p, int buffer); void printDebugStats(); }; #endif //COMPLETE_RANDOM_CITY_RIGHTTRAPEZOID_H
29.235294
94
0.765594
[ "solid" ]
671ac84aa07b3ef2a606da6ae0c0e817c7235839
10,347
c
C
vendor/swftools/lib/drawer.c
svenskan/pronunciation
b48297751fd65ec04c0b4a8eea34ee3033d19b0e
[ "MIT" ]
1
2018-04-25T22:29:34.000Z
2018-04-25T22:29:34.000Z
vendor/swftools/lib/drawer.c
svenskan/pronunciation
b48297751fd65ec04c0b4a8eea34ee3033d19b0e
[ "MIT" ]
null
null
null
vendor/swftools/lib/drawer.c
svenskan/pronunciation
b48297751fd65ec04c0b4a8eea34ee3033d19b0e
[ "MIT" ]
null
null
null
/* drawer.c part of swftools A generic structure for providing vector drawing. (Helper routines, spline approximation, simple text drawers) Copyright (C) 2003 Matthias Kramm <kramm@quiss.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 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <memory.h> #include <math.h> #include <ctype.h> #include "drawer.h" static char* getToken(const char**p) { const char*start; char*result; while(**p && strchr(" ,()\t\n\r", **p)) { (*p)++; } start = *p; /* SVF pathdata can exclude whitespace after L and M commands. Ref: http://www.w3.org/TR/SVG11/paths.html#PathDataGeneralInformation This allows us to use svg files output from gnuplot. Also checks for relative MoveTo and LineTo (m and l). 051106 Magnus Lundin, lundin@mlu.mine.nu */ if (strchr("LMlm", **p) && (isdigit(*(*p+1))||strchr("+-", *(*p+1)))) { (*p)++; } else while(**p && !strchr(" ,()\t\n\r", **p)) { (*p)++; } result = (char*)malloc((*p)-start+1); memcpy(result,start,(*p)-start+1); result[(*p)-start] = 0; return result; } void draw_conicTo(drawer_t*draw, FPOINT* c, FPOINT* to) { FPOINT* pos = &draw->pos; FPOINT c1,c2; c1.x = (pos->x + 2 * c->x) / 3; c1.y = (pos->y + 2 * c->y) / 3; c2.x = (2 * c->x + to->x) / 3; c2.y = (2 * c->y + to->y) / 3; draw_cubicTo(draw, &c1,&c2,to); draw->pos = *to; } /* convenience routine */ static void draw_conicTo2(drawer_t*draw, double x1, double y1, double x2, double y2) { FPOINT c1,c2; c1.x = x1; c1.y = y1; c2.x = x2; c2.y = y2; draw_conicTo(draw, &c1, &c2); } /* convenience routine */ static void draw_moveTo2(drawer_t*draw, double x, double y) { FPOINT c; c.x = x; c.y = y; draw->moveTo(draw, &c); } /* convenience routine */ static void draw_lineTo2(drawer_t*draw, double x, double y) { FPOINT c; c.x = x; c.y = y; draw->lineTo(draw, &c); } static float getFloat(const char** p) { char* token = getToken(p); float result = atof(token); free(token); return result; } void draw_string(drawer_t*draw, const char*string) { const char*p = string; while(*p) { char*token = getToken(&p); if(!token) break; if (!*token) { free(token); break; } if(!strncmp(token, "moveTo", 6) || !strncmp(token, "M", 1) //svg ) { FPOINT to; to.x = getFloat(&p); to.y = getFloat(&p); draw->moveTo(draw, &to); } else if(!strncmp(token, "lineTo", 6) || !strncmp(token, "L", 1) //svg ) { FPOINT to; to.x = getFloat(&p); to.y = getFloat(&p); draw->lineTo(draw, &to); } else if(!strncmp(token, "curveTo", 7) || !strncmp(token, "splineTo", 8)) { FPOINT mid,to; mid.x = getFloat(&p); mid.y = getFloat(&p); to.x = getFloat(&p); to.y = getFloat(&p); draw->splineTo(draw, &mid, &to); } else if(!strncmp(token, "conicTo", 5)) { FPOINT mid,to; mid.x = getFloat(&p); mid.y = getFloat(&p); to.x = getFloat(&p); to.y = getFloat(&p); draw_conicTo(draw, &mid, &to); } else if(!strncmp(token, "circle", 6)) { int mx,my,r; double r2; mx = getFloat(&p); my = getFloat(&p); r = getFloat(&p); r2 = 0.70710678118654757*r; draw_moveTo2(draw, mx, my-r); draw_conicTo2(draw, mx+r2, my-r2, mx+r, my); draw_conicTo2(draw, mx+r2, my+r2, mx, my+r); draw_conicTo2(draw, mx-r2, my+r2, mx-r, my); draw_conicTo2(draw, mx-r2, my-r2, mx, my-r); } else if(!strncmp(token, "box", 3)) { int x1,y1,x2,y2; x1 = getFloat(&p); y1 = getFloat(&p); x2 = getFloat(&p); y2 = getFloat(&p); draw_moveTo2(draw, x1, y1); draw_lineTo2(draw, x1, y2); draw_lineTo2(draw, x2, y2); draw_lineTo2(draw, x2, y1); draw_lineTo2(draw, x1, y1); } else if(!strncmp(token, "cubicTo", 5) || !strncmp(token, "C", 1) //svg ) { FPOINT mid1,mid2,to; mid1.x = getFloat(&p); mid1.y = getFloat(&p); mid2.x = getFloat(&p); mid2.y = getFloat(&p); to.x = getFloat(&p); to.y = getFloat(&p); draw_cubicTo(draw, &mid1, &mid2, &to); } else if(!strncmp(token, "z", 1) //svg ) { // ignore } else fprintf(stderr, "drawer: Warning: unknown primitive '%s'\n", token); free(token); } } struct SPLINEPOINT { double x,y; }; struct qspline { struct SPLINEPOINT start; struct SPLINEPOINT control; struct SPLINEPOINT end; }; struct cspline { struct SPLINEPOINT start; struct SPLINEPOINT control1; struct SPLINEPOINT control2; struct SPLINEPOINT end; }; static inline struct SPLINEPOINT cspline_getpoint(const struct cspline*s, double t) { struct SPLINEPOINT p; double tt = t*t; double ttt = tt*t; double mt = (1-t); double mtmt = mt*(1-t); double mtmtmt = mtmt*(1-t); p.x= s->end.x*ttt + 3*s->control2.x*tt*mt + 3*s->control1.x*t*mtmt + s->start.x*mtmtmt; p.y= s->end.y*ttt + 3*s->control2.y*tt*mt + 3*s->control1.y*t*mtmt + s->start.y*mtmtmt; return p; } static struct SPLINEPOINT qspline_getpoint(const struct qspline*s, double t) { struct SPLINEPOINT p; p.x= s->end.x*t*t + 2*s->control.x*t*(1-t) + s->start.x*(1-t)*(1-t); p.y= s->end.y*t*t + 2*s->control.y*t*(1-t) + s->start.y*(1-t)*(1-t); return p; } static int approximate3(const struct cspline*s, struct qspline*q, int size, double quality2) { unsigned int gran = 0; unsigned int istep = 0x80000000; unsigned int istart = 0; int num = 0; int level = 0; while(istart<0x80000000) { unsigned int iend = istart + istep; double start = istart/(double)0x80000000; double end = iend/(double)0x80000000; struct qspline test; double pos,qpos; char left = 0,recurse=0; int t; int probes = 15; /* create simple approximation: a qspline which run's through the qspline point at 0.5 */ test.start = cspline_getpoint(s, start); test.control = cspline_getpoint(s, (start+end)/2); test.end = cspline_getpoint(s, end); /* fix the control point: move it so that the new spline does runs through it */ test.control.x = -(test.end.x + test.start.x)/2 + 2*(test.control.x); test.control.y = -(test.end.y + test.start.y)/2 + 2*(test.control.y); /* depending on where we are in the spline, we either try to match the left or right tangent */ if(start<0.5) left=1; /* get derivative */ pos = left?start:end; qpos = pos*pos; test.control.x = s->end.x*(3*qpos) + 3*s->control2.x*(2*pos-3*qpos) + 3*s->control1.x*(1-4*pos+3*qpos) + s->start.x*(-3+6*pos-3*qpos); test.control.y = s->end.y*(3*qpos) + 3*s->control2.y*(2*pos-3*qpos) + 3*s->control1.y*(1-4*pos+3*qpos) + s->start.y*(-3+6*pos-3*qpos); if(left) { test.control.x *= (end-start)/2; test.control.y *= (end-start)/2; test.control.x += test.start.x; test.control.y += test.start.y; } else { test.control.x *= -(end-start)/2; test.control.y *= -(end-start)/2; test.control.x += test.end.x; test.control.y += test.end.y; } #define PROBES #ifdef PROBES /* measure the spline's accurancy, by taking a number of probes */ for(t=0;t<probes;t++) { struct SPLINEPOINT qr1,qr2,cr1,cr2; double pos = 0.5/(probes*2)*(t*2+1); double dx,dy; double dist1,dist2; qr1 = qspline_getpoint(&test, pos); cr1 = cspline_getpoint(s, start+pos*(end-start)); dx = qr1.x - cr1.x; dy = qr1.y - cr1.y; dist1 = dx*dx+dy*dy; if(dist1>quality2) { recurse=1;break; } qr2 = qspline_getpoint(&test, (1-pos)); cr2 = cspline_getpoint(s, start+(1-pos)*(end-start)); dx = qr2.x - cr2.x; dy = qr2.y - cr2.y; dist2 = dx*dx+dy*dy; if(dist2>quality2) { recurse=1;break; } } #else // quadratic error: *much* faster! /* convert control point representation to d*x^3 + c*x^2 + b*x + a */ double dx,dy; dx= s->end.x - s->control2.x*3 + s->control1.x*3 - s->start.x; dy= s->end.y - s->control2.y*3 + s->control1.y*3 - s->start.y; /* we need to do this for the subspline between [start,end], not [0,1] as a transformation of t->a*t+b does nothing to highest coefficient of the spline except multiply it with a^3, we just need to modify d here. */ {double m = end-start; dx*=m*m*m; dy*=m*m*m; } /* use the integral over (f(x)-g(x))^2 between 0 and 1 to measure the approximation quality. (it boils down to const*d^2) */ recurse = (dx*dx + dy*dy > quality2); #endif if(recurse && istep>1 && size-level > num) { istep >>= 1; level++; } else { *q++ = test; num++; istart += istep; while(!(istart & istep)) { level--; istep <<= 1; } } } return num; } void draw_cubicTo(drawer_t*draw, FPOINT* control1, FPOINT* control2, FPOINT* to) { struct qspline q[128]; struct cspline c; //double quality = 80; double maxerror = 1;//(500-(quality*5)>1?500-(quality*5):1)/20.0; int t,num; c.start.x = draw->pos.x; c.start.y = draw->pos.y; c.control1.x = control1->x; c.control1.y = control1->y; c.control2.x = control2->x; c.control2.y = control2->y; c.end.x = to->x; c.end.y = to->y; num = approximate3(&c, q, 128, maxerror*maxerror); for(t=0;t<num;t++) { FPOINT mid; FPOINT to; mid.x = q[t].control.x; mid.y = q[t].control.y; to.x = q[t].end.x; to.y = q[t].end.y; draw->splineTo(draw, &mid, &to); } }
26.462916
92
0.584807
[ "vector" ]
671f684f52cf5bccafe534976de7267268a008eb
1,973
h
C
deprecated/algorithms/GlobalOptimizationGraph/CooridinatesManager.h
mfkiwl/GAAS
29ab17d3e8a4ba18edef3a57c36d8db6329fac73
[ "BSD-3-Clause" ]
2,111
2019-01-29T07:01:32.000Z
2022-03-29T06:48:14.000Z
algorithms/GlobalOptimizationGraph/CooridinatesManager.h
Wayne-xixi/GAAS
308ff4267ccc6fcad77eef07e21fa006cc2cdd5f
[ "BSD-3-Clause" ]
131
2019-02-18T10:56:18.000Z
2021-09-27T12:07:00.000Z
algorithms/GlobalOptimizationGraph/CooridinatesManager.h
Wayne-xixi/GAAS
308ff4267ccc6fcad77eef07e21fa006cc2cdd5f
[ "BSD-3-Clause" ]
421
2019-02-12T07:59:18.000Z
2022-03-27T05:22:01.000Z
#ifndef COORDINATE_MANAGER_H #define COORDINATE_MANAGER_H #include <g2o/core/block_solver.h> #include <g2o/core/optimization_algorithm_gauss_newton.h> #include <g2o/core/optimization_algorithm_levenberg.h> #include <g2o/solvers/linear_solver_eigen.h> #include <g2o/core/robust_kernel_impl.h> #include <g2o/core/optimizable_graph.h> #include "G2OTypes.h" #include "G2OTypes_EdgeSLAMPRV.h" #include <opencv2/core/persistence.hpp> #include <memory> #include <iostream> #include <ros/ros.h> #include <sensor_msgs/NavSatFix.h> #include <nav_msgs/Odometry.h> #include <geometry_msgs/PoseStamped.h> #include "GPSExpand.h" #include "CallbacksBufferBlock.h" #include <cmath> #include <deque> #include <opencv2/opencv.hpp> #include "GOG_Frame.h" class CoordinateManager { public: CoordinateManager(vector<shared_ptr<Scene>>& p_scene_vec) { } CoordinateManager(const string& scene_file_list_path) { std::ifstream ifstr_json( scene_file_list_path); json json_obj; ifstr_json>>json_obj; auto scenes = json_obj["scenes"]; json::iterator it; for(it = scenes.begin();it!=scenes.end();++it) { auto scene_obj = it.value(); std::string scene_file_path(scene_obj["scene_path"].get<string>()); shared_ptr<SceneRetriever> pSR( new SceneRetriever(voc_path,scene_file_path) ); double lon,lat; lon = scene_obj["gps_longitude"].get<double>(); lat = scene_obj["gps_latitude"].get<double>(); shared_ptr<MultiSceneNode> pNode(new MultiSceneNode(pSR,lon,lat)); this->insertSceneIntoKDTree(pNode);//gps indexed! if (scene_obj.find("sfm_model_path")!=scene_obj.end()) { pNode->setSfMModelPath(scene_obj["sfm_model_path"].get<string>()); } } } std::pair<Vector3d,Matrix3d> local_to_local_transform(int scene_index,Vector3d xyz,Matrix3d rotation); }; #endif
32.344262
106
0.684744
[ "vector" ]
67218402c26669466b686c59be9187ff73d3555d
2,173
h
C
Fusin/include/IOCodes/FusinGamepad.h
LegendaryMauricius/Fusin
36364b708257630be8b3f1aec27c9f711d255ab1
[ "MIT" ]
null
null
null
Fusin/include/IOCodes/FusinGamepad.h
LegendaryMauricius/Fusin
36364b708257630be8b3f1aec27c9f711d255ab1
[ "MIT" ]
null
null
null
Fusin/include/IOCodes/FusinGamepad.h
LegendaryMauricius/Fusin
36364b708257630be8b3f1aec27c9f711d255ab1
[ "MIT" ]
null
null
null
#ifndef _FUSIN_GAMEPAD_H #define _FUSIN_GAMEPAD_H #include "IOCodes/FusinIOCode.h" #include <vector> namespace Fusin { /* Returns the DT_GAMEPAD, IO_BUTTON IOCode for the specified button */ IOCode _FUSIN_EXPORT GamepadButton(Index b); /* Returns the DT_GAMEPAD, IO_AXIS IOCode for the specified gamepad axis. */ IOCode _FUSIN_EXPORT GamepadAxis(Index a); /* Returns the DT_GAMEPAD, IO_AXIS IOCode for the specified gamepad axis' positive direction. */ IOCode _FUSIN_EXPORT GamepadPositiveAxis(Index a); /* Returns the DT_GAMEPAD, IO_AXIS IOCode for the specified gamepad axis' negative direction. */ IOCode _FUSIN_EXPORT GamepadNegativeAxis(Index a); const IOCode GAMEPAD_X_AXIS = GamepadAxis(0); const IOCode GAMEPAD_Y_AXIS = GamepadAxis(1); const IOCode GAMEPAD_Z_AXIS = GamepadAxis(2); const IOCode GAMEPAD_ROTATION_Z_AXIS = GamepadAxis(3); const IOCode GAMEPAD_DPAD_ANGLE = IOCode(DT_GAMEPAD, IO_ANGLE, 0); const IOCode GAMEPAD_DPAD_UP = IOCode(DT_GAMEPAD, IO_DIRECTION, 0); const IOCode GAMEPAD_DPAD_DOWN = IOCode(DT_GAMEPAD, IO_DIRECTION, 1); const IOCode GAMEPAD_DPAD_LEFT = IOCode(DT_GAMEPAD, IO_DIRECTION, 2); const IOCode GAMEPAD_DPAD_RIGHT = IOCode(DT_GAMEPAD, IO_DIRECTION, 3); const IOCode GAMEPAD_X_POSITIVE = GAMEPAD_X_AXIS.positiveVersion(); const IOCode GAMEPAD_X_NEGATIVE = GAMEPAD_X_AXIS.negativeVersion(); const IOCode GAMEPAD_Y_POSITIVE = GAMEPAD_Y_AXIS.positiveVersion(); const IOCode GAMEPAD_Y_NEGATIVE = GAMEPAD_Y_AXIS.negativeVersion(); const IOCode GAMEPAD_Z_POSITIVE = GAMEPAD_Z_AXIS.positiveVersion(); const IOCode GAMEPAD_Z_NEGATIVE = GAMEPAD_Z_AXIS.negativeVersion(); const IOCode GAMEPAD_ROTATION_Z_POSITIVE = GAMEPAD_ROTATION_Z_AXIS.positiveVersion(); const IOCode GAMEPAD_ROTATION_Z_NEGATIVE = GAMEPAD_ROTATION_Z_AXIS.negativeVersion(); const IOCode GAMEPAD_VIBRATION_LEFT_FORCE = IOCode(DT_GAMEPAD, IO_VIBRATION, 0); const IOCode GAMEPAD_VIBRATION_LEFT_DURATION = IOCode(DT_GAMEPAD, IO_VIBRATION, 2); const IOCode GAMEPAD_VIBRATION_RIGHT_FORCE = IOCode(DT_GAMEPAD, IO_VIBRATION, 3); const IOCode GAMEPAD_VIBRATION_RIGHT_DURATION = IOCode(DT_GAMEPAD, IO_VIBRATION, 5); } #endif
38.803571
91
0.804878
[ "vector" ]
672269af1df7c331d941150795e896a6e716bff3
547
h
C
src/parsers/bitparser.h
fanghaocong/GitlHEVCAnalyzer
1dbf3adca4822b0a55af03c7a7f49c92798c91d6
[ "Apache-2.0" ]
394
2015-01-08T01:26:39.000Z
2022-03-16T03:07:30.000Z
src/parsers/bitparser.h
fanghaocong/GitlHEVCAnalyzer
1dbf3adca4822b0a55af03c7a7f49c92798c91d6
[ "Apache-2.0" ]
14
2016-11-30T08:24:39.000Z
2021-11-06T14:12:58.000Z
src/parsers/bitparser.h
fanghaocong/GitlHEVCAnalyzer
1dbf3adca4822b0a55af03c7a7f49c92798c91d6
[ "Apache-2.0" ]
151
2015-01-17T01:07:00.000Z
2022-03-20T08:11:07.000Z
#ifndef BITPARSER_H #define BITPARSER_H #include <QObject> #include <QTextStream> #include "model/common/comsequence.h" class BitParser : public QObject { Q_OBJECT public: explicit BitParser(QObject *parent = 0); bool parseLCUBitFile(QTextStream* pcInputStream, ComSequence* pcSequence); bool parseSCUBitFile(QTextStream* pcInputStream, ComSequence* pcSequence); protected: bool xParseSCUBitFile(QTextStream* pcSCUBitInfoStream, ComCU* pcCU); signals: public slots: }; #endif // BITPARSER_H
22.791667
79
0.725777
[ "model" ]
6727d67a667e1b325e97d4d26aa326a6de47bf5e
1,652
h
C
ThirdParty/bullet-2.75/Extras/ExtraSolid35/Solid3EpaPenetrationDepth.h
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
32
2016-05-22T23:09:19.000Z
2022-03-13T03:32:27.000Z
ThirdParty/bullet-2.75/Extras/ExtraSolid35/Solid3EpaPenetrationDepth.h
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
2
2016-05-30T19:45:58.000Z
2018-01-24T22:29:51.000Z
ThirdParty/bullet-2.75/Extras/ExtraSolid35/Solid3EpaPenetrationDepth.h
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
17
2016-05-27T11:01:42.000Z
2022-03-13T03:32:30.000Z
/* * SOLID - Software Library for Interference Detection * * Copyright (C) 2001-2003 Dtecta. All rights reserved. * * This library may be distributed under the terms of the Q Public License * (QPL) as defined by Trolltech AS of Norway and appearing in the file * LICENSE.QPL included in the packaging of this file. * * This library may be distributed and/or modified under the terms of the * GNU bteral Public License (GPL) version 2 as published by the Free Software * Foundation and appearing in the file LICENSE.GPL included in the * packaging of this file. * * This library is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Commercial use or any other use of this library not covered by either * the QPL or the GPL requires an additional license from Dtecta. * Please contact info@dtecta.com for enquiries about the terms of commercial * use of this library. */ #ifndef SOLID3_EPA_PENETRATION_DEPTH_H #define SOLID3_EPA_PENETRATION_DEPTH_H #include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h" /// Solid3EpaPenetrationDepth contains the 'Expanding Polytope Algorithm' from Solid 3.5 class Solid3EpaPenetrationDepth : public btConvexPenetrationDepthSolver { public: virtual bool calcPenDepth( btSimplexSolverInterface& simplexSolver, btConvexShape* convexA,btConvexShape* convexB, const btTransform& transA,const btTransform& transB, btVector3& v, btPoint3& pa, btPoint3& pb, class btIDebugDraw* debugDraw,btStackAlloc* stackAlloc ); }; #endif //SOLID3_EPA_PENETRATION_DEPTH_H
37.545455
88
0.779661
[ "solid" ]
6729a826cbf9c75ff46ab46168321deaf59151b1
147
h
C
interpreter/Utils.h
Zaphyk/ice-lang
e51687329058f70b3d3f6ce1bf1e90fdf39dda46
[ "MIT" ]
null
null
null
interpreter/Utils.h
Zaphyk/ice-lang
e51687329058f70b3d3f6ce1bf1e90fdf39dda46
[ "MIT" ]
2
2017-09-26T01:45:59.000Z
2017-09-26T21:56:47.000Z
interpreter/Utils.h
Zaphyk/ice-lang
e51687329058f70b3d3f6ce1bf1e90fdf39dda46
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include <algorithm> int split(const std::string &txt, std::vector<std::string> &strs, char ch);
21
75
0.714286
[ "vector" ]
672f909f83b9551352d766f3ee30a90987c23d47
209,175
c
C
Extensions/Object/Object.c
CealedLion/Triangle-Engine-X
cdfcaead0f536b3e1be606c717056a8495f72251
[ "MIT" ]
1
2021-04-09T08:45:41.000Z
2021-04-09T08:45:41.000Z
Extensions/Object/Object.c
CealedLion/Triangle-Engine-X
cdfcaead0f536b3e1be606c717056a8495f72251
[ "MIT" ]
null
null
null
Extensions/Object/Object.c
CealedLion/Triangle-Engine-X
cdfcaead0f536b3e1be606c717056a8495f72251
[ "MIT" ]
null
null
null
#pragma once //C #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdbool.h> //Third-Party #include <atomic\atomic.h> //Ours #include "Common.h" #include "Extension.h" #define TEX_EXPOSE_OBJECTS #include "Object.h" volatile ObjectUtils Utils; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Arena Allocater Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Creates a object arena allocater. * @param pArenaAllocater pointer to the allocater to create. * @param StartPtr offset from the start of the gpu buffer to reserve for this arena, arena size = (EndPtr - StartPtr) * @param EndPtr offset from the start of the gpu buffer to reserve for this arena, arena size = (EndPtr - StartPtr) * @note Always Thread safe. * @note Externally Synchronized. */ TEXRESULT Create_ArenaAllocater(ArenaAllocater* pArenaAllocater, uint64_t StartPtr, uint64_t EndPtr) { #ifndef NDEBUG if (pArenaAllocater == NULL) { Engine_Ref_ArgsError("Create_ArenaAllocater()", "pArenaAllocater == NULLPTR"); return (Invalid_Parameter | Failure); } #endif memset(pArenaAllocater, 0, sizeof(*pArenaAllocater)); Engine_Ref_Create_Mutex(&pArenaAllocater->Mutex, MutexType_Plain); pArenaAllocater->StartPtr = StartPtr; pArenaAllocater->EndPtr = EndPtr; return (Success); } /* * Added in 1.0.0 * Destroys a object arena allocater. * @param pArenaAllocater pointer to the allocater to destroy. * @note Always Thread safe. * @note Externally Synchronized. */ void Destroy_ArenaAllocater(ArenaAllocater* pArenaAllocater) { #ifndef NDEBUG if (pArenaAllocater == NULL) { Engine_Ref_ArgsError("Destroy_ArenaAllocater()", "pArenaAllocater == NULLPTR"); return; } #endif if (TestNULL(&pArenaAllocater->Mutex, sizeof(pArenaAllocater->Mutex))) Engine_Ref_Destroy_Mutex(&pArenaAllocater->Mutex); pArenaAllocater->StartPtr = 0; pArenaAllocater->EndPtr = 0; memset(pArenaAllocater, 0, sizeof(*pArenaAllocater)); return; } /* * Added in 1.0.0 * ReCreates a object arena allocater, destroys previous and then creates again. * @param pArenaAllocater pointer to the allocater to recreate. * @param StartPtr offset from the start of the gpu buffer to reserve for this arena, arena size = (EndPtr - StartPtr) * @param EndPtr offset from the start of the gpu buffer to reserve for this arena, arena size = (EndPtr - StartPtr) * @note Always Thread safe. * @note Externally Synchronized. */ TEXRESULT ReCreate_ArenaAllocater(ArenaAllocater* pArenaAllocater, uint64_t StartPtr, uint64_t EndPtr) { #ifndef NDEBUG if (pArenaAllocater == NULL) { Engine_Ref_ArgsError("ReCreate_ArenaAllocater()", "pArenaAllocater == NULLPTR"); return (Invalid_Parameter | Failure); } #endif Destroy_ArenaAllocater(pArenaAllocater); Create_ArenaAllocater(pArenaAllocater, StartPtr, EndPtr); return (Success); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Allocate Allocation //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEXRESULT Allocate_ObjectAllocationData(ObjectSignature* pSignature, uint32_t Identifier, ObjectAllocation* pAllocation, uint32_t ThreadIndex) { ArenaAllocater* pArenaAllocater = NULL; uint64_t Pointer = 0; uint64_t SizeOfBlock = 0; uint64_t ResetCount = 0; uint64_t i = 0; while (true) { if (ResetCount < EngineRes.pUtils->CPU.MaxThreads) { if (Engine_Ref_TryLock_Mutex(&Utils.InternalObjectBuffer.AllocationDatas.ArenaAllocaters[Utils.InternalObjectBuffer.AllocationDatas.Indexes[ThreadIndex]].Mutex) == Success) { pArenaAllocater = &Utils.InternalObjectBuffer.AllocationDatas.ArenaAllocaters[Utils.InternalObjectBuffer.AllocationDatas.Indexes[ThreadIndex]]; //if (pArenaAllocater->Size == 0) // ReCreate_GPU_ArenaAllocater(pLogicalDevice, pArenaAllocater, (TargetBuffer->Size > AlignedSize) ? (TargetBuffer->Size) : (TargetBuffer->Size + AlignedSize), TargetMemory); //if (pArenaAllocater->Size == 0) // ReCreate_ArenaAllocater(pArenaAllocater, TargetBuffer->Size, TargetMemory); uint64_t prevendindex = pArenaAllocater->StartPtr; for (i = pArenaAllocater->StartPtr; i < pArenaAllocater->EndPtr;) { SizeOfBlock = i - prevendindex; Pointer = prevendindex; if (!(SizeOfBlock < 1)) //if is large enough break out of loop break; if (Utils.InternalObjectBuffer.AllocationDatas.Buffer[i].Allocation.Object.Identifier != 0) { i++; prevendindex = i; } else { i++; } } if (!(SizeOfBlock < 1)) //if is large enough break out of loop break; else Engine_Ref_Unlock_Mutex(&pArenaAllocater->Mutex); } Utils.InternalObjectBuffer.AllocationDatas.Indexes[ThreadIndex] = (Utils.InternalObjectBuffer.AllocationDatas.Indexes[ThreadIndex] + 1) % EngineRes.pUtils->CPU.MaxThreads; ResetCount++; } else { if (Utils.Config.ActiveMemoryResizing == true) { Engine_Ref_FunctionError("Allocate_ObjectAllocationData()", "AAAAAAAAAAAAAA resizing main", SizeOfBlock); //ReCreate_GPU_ArenaAllocater(pLogicalDevice, pArenaAllocater, pArenaAllocater->Size + AlignedSize, TargetMemory); //ResetCount = 0; } else { Engine_Ref_FunctionError("Allocate_ObjectAllocationData()", "Not Enough Space In Allocation Memory!, Resize buffer!, Blocksize == ", SizeOfBlock); return (Failure); } } } //Engine_Ref_FunctionError("Allocate_ObjectAllocationData()", "PTR == ", Pointer); AllocationData* pAllocationData = &Utils.InternalObjectBuffer.AllocationDatas.Buffer[Pointer]; memset(pAllocationData, 0, sizeof(*pAllocationData)); //set all internal data to invalid number for (size_t i = 0; i < maxthreads; i++) { c89atomic_store_32(&pAllocationData->Threads[i].Pointer, UINT32_MAX); c89atomic_store_32(&pAllocationData->Threads[i].Count, 0); } c89atomic_store_32(&pAllocationData->LatestPointer, UINT32_MAX); //setting values to make allocation valid. c89atomic_fetch_add_32(&Utils.InternalObjectBuffer.AllocationDatas.AllocationsCount, 1); c89atomic_fetch_add_32(&pSignature->AllocationsCount, 1); c89atomic_store_32(&pAllocationData->Allocation.Object.Pointer, Pointer); c89atomic_store_32(&pAllocationData->Allocation.Object.Identifier, Identifier); Engine_Ref_Unlock_Mutex(&pArenaAllocater->Mutex); pAllocation->Pointer = Pointer; pAllocation->Identifier = Identifier; return (Success); } TEXRESULT Allocate_ResourceHeaderAllocationData(ResourceHeaderSignature* pSignature, uint32_t Identifier, ResourceHeaderAllocation* pAllocation, uint32_t ThreadIndex) { ArenaAllocater* pArenaAllocater = NULL; uint64_t Pointer = 0; uint64_t SizeOfBlock = 0; uint64_t ResetCount = 0; uint64_t i = 0; while (true) { if (ResetCount < EngineRes.pUtils->CPU.MaxThreads) { if (Engine_Ref_TryLock_Mutex(&Utils.InternalResourceHeaderBuffer.AllocationDatas.ArenaAllocaters[Utils.InternalResourceHeaderBuffer.AllocationDatas.Indexes[ThreadIndex]].Mutex) == Success) { pArenaAllocater = &Utils.InternalResourceHeaderBuffer.AllocationDatas.ArenaAllocaters[Utils.InternalResourceHeaderBuffer.AllocationDatas.Indexes[ThreadIndex]]; //if (pArenaAllocater->Size == 0) // ReCreate_GPU_ArenaAllocater(pLogicalDevice, pArenaAllocater, (TargetBuffer->Size > AlignedSize) ? (TargetBuffer->Size) : (TargetBuffer->Size + AlignedSize), TargetMemory); //if (pArenaAllocater->Size == 0) // ReCreate_ArenaAllocater(pArenaAllocater, TargetBuffer->Size, TargetMemory); uint64_t prevendindex = pArenaAllocater->StartPtr; for (i = pArenaAllocater->StartPtr; i < pArenaAllocater->EndPtr;) { SizeOfBlock = i - prevendindex; Pointer = prevendindex; if (!(SizeOfBlock < 1)) //if is large enough break out of loop break; if (Utils.InternalResourceHeaderBuffer.AllocationDatas.Buffer[i].Allocation.ResourceHeader.Identifier != 0) { i++; prevendindex = i; } else { i++; } } if (!(SizeOfBlock < 1)) //if is large enough break out of loop break; else Engine_Ref_Unlock_Mutex(&pArenaAllocater->Mutex); } Utils.InternalResourceHeaderBuffer.AllocationDatas.Indexes[ThreadIndex] = (Utils.InternalResourceHeaderBuffer.AllocationDatas.Indexes[ThreadIndex] + 1) % EngineRes.pUtils->CPU.MaxThreads; ResetCount++; } else { if (Utils.Config.ActiveMemoryResizing == true) { Engine_Ref_FunctionError("Allocate_ResourceHeaderAllocationData()", "AAAAAAAAAAAAAA resizing main", SizeOfBlock); //ReCreate_GPU_ArenaAllocater(pLogicalDevice, pArenaAllocater, pArenaAllocater->Size + AlignedSize, TargetMemory); //ResetCount = 0; } else { Engine_Ref_FunctionError("Allocate_ResourceHeaderAllocationData()", "Not Enough Space In Allocation Memory!, Resize buffer!, Blocksize == ", SizeOfBlock); return (Failure); } } } //Engine_Ref_FunctionError("Allocate_ResourceHeaderAllocationData()", "PTR == ", Pointer); AllocationData* pAllocationData = &Utils.InternalResourceHeaderBuffer.AllocationDatas.Buffer[Pointer]; memset(pAllocationData, 0, sizeof(*pAllocationData)); //set all internal data to invalid number for (size_t i = 0; i < maxthreads; i++) { c89atomic_store_32(&pAllocationData->Threads[i].Pointer, UINT32_MAX); c89atomic_store_32(&pAllocationData->Threads[i].Count, 0); } c89atomic_store_32(&pAllocationData->LatestPointer, UINT32_MAX); //setting values to make allocation valid. c89atomic_fetch_add_32(&Utils.InternalResourceHeaderBuffer.AllocationDatas.AllocationsCount, 1); c89atomic_fetch_add_32(&pSignature->AllocationsCount, 1); c89atomic_store_32(&pAllocationData->Allocation.ResourceHeader.Pointer, Pointer); c89atomic_store_32(&pAllocationData->Allocation.ResourceHeader.Identifier, Identifier); Engine_Ref_Unlock_Mutex(&pArenaAllocater->Mutex); pAllocation->Pointer = Pointer; pAllocation->Identifier = Identifier; return (Success); } TEXRESULT Allocate_ElementAllocationData(ElementSignature* pSignature, uint32_t Identifier, ElementAllocation* pAllocation, uint32_t ThreadIndex) { ArenaAllocater* pArenaAllocater = NULL; uint64_t Pointer = 0; uint64_t SizeOfBlock = 0; uint64_t ResetCount = 0; uint64_t i = 0; while (true) { if (ResetCount < EngineRes.pUtils->CPU.MaxThreads) { if (Engine_Ref_TryLock_Mutex(&Utils.InternalElementBuffer.AllocationDatas.ArenaAllocaters[Utils.InternalElementBuffer.AllocationDatas.Indexes[ThreadIndex]].Mutex) == Success) { pArenaAllocater = &Utils.InternalElementBuffer.AllocationDatas.ArenaAllocaters[Utils.InternalElementBuffer.AllocationDatas.Indexes[ThreadIndex]]; //if (pArenaAllocater->Size == 0) // ReCreate_GPU_ArenaAllocater(pLogicalDevice, pArenaAllocater, (TargetBuffer->Size > AlignedSize) ? (TargetBuffer->Size) : (TargetBuffer->Size + AlignedSize), TargetMemory); //if (pArenaAllocater->Size == 0) // ReCreate_ArenaAllocater(pArenaAllocater, TargetBuffer->Size, TargetMemory); uint64_t prevendindex = pArenaAllocater->StartPtr; for (i = pArenaAllocater->StartPtr; i < pArenaAllocater->EndPtr;) { SizeOfBlock = i - prevendindex; Pointer = prevendindex; if (!(SizeOfBlock < 1)) //if is large enough break out of loop break; if (Utils.InternalElementBuffer.AllocationDatas.Buffer[i].Allocation.Element.Identifier != 0) { i++; prevendindex = i; } else { i++; } } if (!(SizeOfBlock < 1)) //if is large enough break out of loop break; else Engine_Ref_Unlock_Mutex(&pArenaAllocater->Mutex); } Utils.InternalElementBuffer.AllocationDatas.Indexes[ThreadIndex] = (Utils.InternalElementBuffer.AllocationDatas.Indexes[ThreadIndex] + 1) % EngineRes.pUtils->CPU.MaxThreads; ResetCount++; } else { if (Utils.Config.ActiveMemoryResizing == true) { Engine_Ref_FunctionError("Allocate_ElementAllocationData()", "AAAAAAAAAAAAAA resizing main", SizeOfBlock); //ReCreate_GPU_ArenaAllocater(pLogicalDevice, pArenaAllocater, pArenaAllocater->Size + AlignedSize, TargetMemory); //ResetCount = 0; } else { Engine_Ref_FunctionError("Allocate_ElementAllocationData()", "Not Enough Space In Allocation Memory!, Resize buffer!, Blocksize == ", SizeOfBlock); return (Failure); } } } //Engine_Ref_FunctionError("Allocate_ElementAllocationData()", "PTR == ", Pointer); AllocationData* pAllocationData = &Utils.InternalElementBuffer.AllocationDatas.Buffer[Pointer]; memset(pAllocationData, 0, sizeof(*pAllocationData)); //set all internal data to invalid number for (size_t i = 0; i < maxthreads; i++) { c89atomic_store_32(&pAllocationData->Threads[i].Pointer, UINT32_MAX); c89atomic_store_32(&pAllocationData->Threads[i].Count, 0); } c89atomic_store_32(&pAllocationData->LatestPointer, UINT32_MAX); //setting values to make allocation valid. c89atomic_fetch_add_32(&Utils.InternalElementBuffer.AllocationDatas.AllocationsCount, 1); c89atomic_fetch_add_32(&pSignature->AllocationsCount, 1); c89atomic_store_32(&pAllocationData->Allocation.Element.Pointer, Pointer); c89atomic_store_32(&pAllocationData->Allocation.Element.Identifier, Identifier); Engine_Ref_Unlock_Mutex(&pArenaAllocater->Mutex); pAllocation->Pointer = Pointer; pAllocation->Identifier = Identifier; return (Success); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //DeAllocate Allocation //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DeAllocate_ObjectAllocationData(ObjectSignature* pSignature, ObjectAllocation Allocation) { /*ArenaAllocater* pArenaAllocater = NULL; for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { pArenaAllocater = &pBuffer->ArenaAllocaters[i]; if (Pointer >= pArenaAllocater->StartPtr && Pointer < pArenaAllocater->EndPtr) { break; } } if (pArenaAllocater == NULL) { Engine_Ref_FunctionError("DeAllocate_ObjectAllocationData()", "ArenaAllocater Not Found. == ", NULL); return; } Engine_Ref_Lock_Mutex(pArenaAllocater->Mutex);*/ //set the allocation validaters to null atomically so no mutex is needed. c89atomic_store_32(&Utils.InternalObjectBuffer.AllocationDatas.Buffer[Allocation.Pointer].Allocation.Object.Identifier, 0); c89atomic_store_32(&Utils.InternalObjectBuffer.AllocationDatas.Buffer[Allocation.Pointer].Allocation.Object.Pointer, 0); memset(&Utils.InternalObjectBuffer.AllocationDatas.Buffer[Allocation.Pointer], 0, sizeof(*Utils.InternalObjectBuffer.AllocationDatas.Buffer)); c89atomic_fetch_sub_32(&Utils.InternalObjectBuffer.AllocationDatas.AllocationsCount, 1); c89atomic_fetch_sub_32(&pSignature->AllocationsCount, 1); //Engine_Ref_Unlock_Mutex(pArenaAllocater->Mutex); } void DeAllocate_ResourceHeaderAllocationData(ResourceHeaderSignature* pSignature, ResourceHeaderAllocation Allocation) { /*ArenaAllocater* pArenaAllocater = NULL; for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { pArenaAllocater = &pBuffer->ArenaAllocaters[i]; if (Pointer >= pArenaAllocater->StartPtr && Pointer < pArenaAllocater->EndPtr) { break; } } if (pArenaAllocater == NULL) { Engine_Ref_FunctionError("DeAllocate_ResourceHeaderAllocationData()", "ArenaAllocater Not Found. == ", NULL); return; } Engine_Ref_Lock_Mutex(pArenaAllocater->Mutex);*/ //set the allocation validaters to null atomically so no mutex is needed. c89atomic_store_32(&Utils.InternalResourceHeaderBuffer.AllocationDatas.Buffer[Allocation.Pointer].Allocation.ResourceHeader.Identifier, 0); c89atomic_store_32(&Utils.InternalResourceHeaderBuffer.AllocationDatas.Buffer[Allocation.Pointer].Allocation.ResourceHeader.Pointer, 0); memset(&Utils.InternalResourceHeaderBuffer.AllocationDatas.Buffer[Allocation.Pointer], 0, sizeof(*Utils.InternalResourceHeaderBuffer.AllocationDatas.Buffer)); c89atomic_fetch_sub_32(&Utils.InternalResourceHeaderBuffer.AllocationDatas.AllocationsCount, 1); c89atomic_fetch_sub_32(&pSignature->AllocationsCount, 1); //Engine_Ref_Unlock_Mutex(pArenaAllocater->Mutex); } void DeAllocate_ElementAllocationData(ElementSignature* pSignature, ElementAllocation Allocation) { /*ArenaAllocater* pArenaAllocater = NULL; for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { pArenaAllocater = &pBuffer->ArenaAllocaters[i]; if (Pointer >= pArenaAllocater->StartPtr && Pointer < pArenaAllocater->EndPtr) { break; } } if (pArenaAllocater == NULL) { Engine_Ref_FunctionError("DeAllocate_ElementAllocationData()", "ArenaAllocater Not Found. == ", NULL); return; } Engine_Ref_Lock_Mutex(pArenaAllocater->Mutex);*/ //set the allocation validaters to null atomically so no mutex is needed. c89atomic_store_32(&Utils.InternalElementBuffer.AllocationDatas.Buffer[Allocation.Pointer].Allocation.Element.Identifier, 0); c89atomic_store_32(&Utils.InternalElementBuffer.AllocationDatas.Buffer[Allocation.Pointer].Allocation.Element.Pointer, 0); memset(&Utils.InternalElementBuffer.AllocationDatas.Buffer[Allocation.Pointer], 0, sizeof(*Utils.InternalElementBuffer.AllocationDatas.Buffer)); c89atomic_fetch_sub_32(&Utils.InternalElementBuffer.AllocationDatas.AllocationsCount, 1); c89atomic_fetch_sub_32(&pSignature->AllocationsCount, 1); //Engine_Ref_Unlock_Mutex(pArenaAllocater->Mutex); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Allocatie Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEXRESULT Allocate_Object(ObjectSignature* pSignature, uint32_t AllocationSize, uint32_t Identifier, ObjectAllocation Allocation, uint32_t* pPointer, uint32_t ThreadIndex) { ArenaAllocater* pArenaAllocater = NULL; uint64_t Pointer = 0; uint64_t SizeOfBlock = 0; uint64_t ResetCount = 0; uint64_t i = 0; while (true) { if (ResetCount < EngineRes.pUtils->CPU.MaxThreads) { if (Engine_Ref_TryLock_Mutex(&Utils.InternalObjectBuffer.ArenaAllocaters[Utils.InternalObjectBuffer.Indexes[ThreadIndex]].Mutex) == Success) { pArenaAllocater = &Utils.InternalObjectBuffer.ArenaAllocaters[Utils.InternalObjectBuffer.Indexes[ThreadIndex]]; //if (pArenaAllocater->Size == 0) // ReCreate_GPU_ArenaAllocater(pLogicalDevice, pArenaAllocater, (TargetBuffer->Size > AlignedSize) ? (TargetBuffer->Size) : (TargetBuffer->Size + AlignedSize), TargetMemory); //if (pArenaAllocater->Size == 0) // ReCreate_ArenaAllocater(pArenaAllocater, TargetBuffer->Size, TargetMemory); uint64_t prevendindex = pArenaAllocater->StartPtr; for (i = pArenaAllocater->StartPtr; i < pArenaAllocater->EndPtr;) { SizeOfBlock = i - prevendindex; Pointer = prevendindex; if (SizeOfBlock >= AllocationSize) //if is large enough break out of loop break; if (Utils.InternalObjectBuffer.Buffer[i].Header.AllocationSize != NULL) { i += Utils.InternalObjectBuffer.Buffer[i].Header.AllocationSize; prevendindex = i; } else { i++; } } if (SizeOfBlock >= AllocationSize) //if is large enough break out of loop break; else Engine_Ref_Unlock_Mutex(&pArenaAllocater->Mutex); } Utils.InternalObjectBuffer.Indexes[ThreadIndex] = (Utils.InternalObjectBuffer.Indexes[ThreadIndex] + 1) % EngineRes.pUtils->CPU.MaxThreads; ResetCount++; } else { if (Utils.Config.ActiveMemoryResizing == true) { Engine_Ref_FunctionError("Allocate_Object()", "AAAAAAAAAAAAAA resizing main", SizeOfBlock); //ReCreate_GPU_ArenaAllocater(pLogicalDevice, pArenaAllocater, pArenaAllocater->Size + AlignedSize, TargetMemory); //ResetCount = 0; } else { Engine_Ref_FunctionError("Allocate_Object()", "Not Enough Space In Allocation Memory!, Resize buffer!, Blocksize == ", SizeOfBlock); return (Failure); } } } //Engine_Ref_FunctionError("Allocate_Object()", "PTR == ", Pointer); //Engine_Ref_FunctionError("Allocate_Object()", "Size == ", AllocationSize); Object* pObject = &Utils.InternalObjectBuffer.Buffer[Pointer]; memset(pObject, 0, sizeof(*pObject) * AllocationSize); //setting values to make allocation valid. c89atomic_fetch_add_32(&Utils.InternalObjectBuffer.AllocationsCount, 1); c89atomic_fetch_add_32(&pSignature->ObjectsCount, 1); c89atomic_store_32(&pObject->Header.UseCount, 0); c89atomic_store_32(&pObject->Header.OverlayPointer, UINT32_MAX); pObject->Header.Allocation = Allocation; //c89atomic_store_32(&pObject->Header.Allocation, Allocation); c89atomic_store_32(&pObject->Header.AllocationSize, AllocationSize); Engine_Ref_Unlock_Mutex(&pArenaAllocater->Mutex); *pPointer = Pointer; return (Success); } TEXRESULT Allocate_ResourceHeader(ResourceHeaderSignature* pSignature, uint32_t AllocationSize, uint32_t Identifier, ResourceHeaderAllocation Allocation, uint32_t* pPointer, uint32_t ThreadIndex) { ArenaAllocater* pArenaAllocater = NULL; uint64_t Pointer = 0; uint64_t SizeOfBlock = 0; uint64_t ResetCount = 0; uint64_t i = 0; while (true) { if (ResetCount < EngineRes.pUtils->CPU.MaxThreads) { if (Engine_Ref_TryLock_Mutex(&Utils.InternalResourceHeaderBuffer.ArenaAllocaters[Utils.InternalResourceHeaderBuffer.Indexes[ThreadIndex]].Mutex) == Success) { pArenaAllocater = &Utils.InternalResourceHeaderBuffer.ArenaAllocaters[Utils.InternalResourceHeaderBuffer.Indexes[ThreadIndex]]; //if (pArenaAllocater->Size == 0) // ReCreate_GPU_ArenaAllocater(pLogicalDevice, pArenaAllocater, (TargetBuffer->Size > AlignedSize) ? (TargetBuffer->Size) : (TargetBuffer->Size + AlignedSize), TargetMemory); //if (pArenaAllocater->Size == 0) // ReCreate_ArenaAllocater(pArenaAllocater, TargetBuffer->Size, TargetMemory); uint64_t prevendindex = pArenaAllocater->StartPtr; for (i = pArenaAllocater->StartPtr; i < pArenaAllocater->EndPtr;) { SizeOfBlock = i - prevendindex; Pointer = prevendindex; if (SizeOfBlock >= AllocationSize) //if is large enough break out of loop break; if (Utils.InternalResourceHeaderBuffer.Buffer[i].Header.AllocationSize != NULL) { i += Utils.InternalResourceHeaderBuffer.Buffer[i].Header.AllocationSize; prevendindex = i; } else { i++; } } if (SizeOfBlock >= AllocationSize) //if is large enough break out of loop break; else Engine_Ref_Unlock_Mutex(&pArenaAllocater->Mutex); } Utils.InternalResourceHeaderBuffer.Indexes[ThreadIndex] = (Utils.InternalResourceHeaderBuffer.Indexes[ThreadIndex] + 1) % EngineRes.pUtils->CPU.MaxThreads; ResetCount++; } else { if (Utils.Config.ActiveMemoryResizing == true) { Engine_Ref_FunctionError("Allocate_ResourceHeader()", "AAAAAAAAAAAAAA resizing main", SizeOfBlock); //ReCreate_GPU_ArenaAllocater(pLogicalDevice, pArenaAllocater, pArenaAllocater->Size + AlignedSize, TargetMemory); //ResetCount = 0; } else { Engine_Ref_FunctionError("Allocate_ResourceHeader()", "Not Enough Space In Allocation Memory!, Resize buffer!, Blocksize == ", SizeOfBlock); return (Failure); } } } // Engine_Ref_FunctionError("Allocate_ResourceHeader()", "PTR == ", Pointer); //Engine_Ref_FunctionError("Allocate_ResourceHeader()", "Size == ", AllocationSize); ResourceHeader* pResourceHeader = &Utils.InternalResourceHeaderBuffer.Buffer[Pointer]; memset(pResourceHeader, 0, sizeof(*pResourceHeader) * AllocationSize); //setting values to make allocation valid. c89atomic_fetch_add_32(&Utils.InternalResourceHeaderBuffer.AllocationsCount, 1); c89atomic_fetch_add_32(&pSignature->ResourceHeadersCount, 1); c89atomic_store_32(&pResourceHeader->Header.UseCount, 0); c89atomic_store_32(&pResourceHeader->Header.OverlayPointer, UINT32_MAX); pResourceHeader->Header.Allocation = Allocation; //c89atomic_store_32(&pResourceHeader->Header.Allocation, AllocationPointer); c89atomic_store_32(&pResourceHeader->Header.AllocationSize, AllocationSize); Engine_Ref_Unlock_Mutex(&pArenaAllocater->Mutex); *pPointer = Pointer; return (Success); } TEXRESULT Allocate_Element(ElementSignature* pSignature, uint32_t AllocationSize, uint32_t Identifier, ElementAllocation Allocation, uint32_t* pPointer, uint32_t ThreadIndex) { ArenaAllocater* pArenaAllocater = NULL; uint64_t Pointer = 0; uint64_t SizeOfBlock = 0; uint64_t ResetCount = 0; uint64_t i = 0; while (true) { if (ResetCount < EngineRes.pUtils->CPU.MaxThreads) { if (Engine_Ref_TryLock_Mutex(&Utils.InternalElementBuffer.ArenaAllocaters[Utils.InternalElementBuffer.Indexes[ThreadIndex]].Mutex) == Success) { pArenaAllocater = &Utils.InternalElementBuffer.ArenaAllocaters[Utils.InternalElementBuffer.Indexes[ThreadIndex]]; //if (pArenaAllocater->Size == 0) // ReCreate_GPU_ArenaAllocater(pLogicalDevice, pArenaAllocater, (TargetBuffer->Size > AlignedSize) ? (TargetBuffer->Size) : (TargetBuffer->Size + AlignedSize), TargetMemory); //if (pArenaAllocater->Size == 0) // ReCreate_ArenaAllocater(pArenaAllocater, TargetBuffer->Size, TargetMemory); uint64_t prevendindex = pArenaAllocater->StartPtr; for (i = pArenaAllocater->StartPtr; i < pArenaAllocater->EndPtr;) { SizeOfBlock = i - prevendindex; Pointer = prevendindex; if (SizeOfBlock >= AllocationSize) //if is large enough break out of loop break; if (Utils.InternalElementBuffer.Buffer[i].Header.AllocationSize != NULL) { i += Utils.InternalElementBuffer.Buffer[i].Header.AllocationSize; prevendindex = i; } else { i++; } } if (SizeOfBlock >= AllocationSize) //if is large enough break out of loop break; else Engine_Ref_Unlock_Mutex(&pArenaAllocater->Mutex); } Utils.InternalElementBuffer.Indexes[ThreadIndex] = (Utils.InternalElementBuffer.Indexes[ThreadIndex] + 1) % EngineRes.pUtils->CPU.MaxThreads; ResetCount++; } else { if (Utils.Config.ActiveMemoryResizing == true) { Engine_Ref_FunctionError("Allocate_Element()", "AAAAAAAAAAAAAA resizing main", SizeOfBlock); //ReCreate_GPU_ArenaAllocater(pLogicalDevice, pArenaAllocater, pArenaAllocater->Size + AlignedSize, TargetMemory); //ResetCount = 0; } else { Engine_Ref_FunctionError("Allocate_Element()", "Not Enough Space In Allocation Memory!, Resize buffer!, Blocksize == ", SizeOfBlock); return (Failure); } } } //Engine_Ref_FunctionError("Allocate_Element()", "PTR == ", Pointer); //Engine_Ref_FunctionError("Allocate_Element()", "Size == ", AllocationSize); Element* pElement = &Utils.InternalElementBuffer.Buffer[Pointer]; memset(pElement, 0, sizeof(*pElement) * AllocationSize); //setting values to make allocation valid. c89atomic_fetch_add_32(&Utils.InternalElementBuffer.AllocationsCount, 1); c89atomic_fetch_add_32(&pSignature->ElementsCount, 1); c89atomic_store_32(&pElement->Header.UseCount, 0); c89atomic_store_32(&pElement->Header.OverlayPointer, UINT32_MAX); pElement->Header.Allocation = Allocation; //c89atomic_store_32(&pElement->Header.Allocation, AllocationPointer); c89atomic_store_32(&pElement->Header.AllocationSize, AllocationSize); Engine_Ref_Unlock_Mutex(&pArenaAllocater->Mutex); *pPointer = Pointer; return (Success); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Deallocate Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DeAllocate_Object(ObjectSignature* pSignature, uint32_t Pointer) { /*ArenaAllocater* pArenaAllocater = NULL; for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { pArenaAllocater = &Utils.InternalObjectBuffer.ArenaAllocaters[i]; if (Pointer >= pArenaAllocater->StartPtr && Pointer < pArenaAllocater->EndPtr) { break; } } if (pArenaAllocater == NULL) { Engine_Ref_FunctionError("DeAllocate_Object()", "ArenaAllocater Not Found. == ", NULL); return; } Engine_Ref_Lock_Mutex(pArenaAllocater->Mutex);*/ uint32_t AllocationSize = Utils.InternalObjectBuffer.Buffer[Pointer].Header.AllocationSize; c89atomic_store_32(&Utils.InternalObjectBuffer.Buffer[Pointer].Header.AllocationSize, 0); c89atomic_store_32(&Utils.InternalObjectBuffer.Buffer[Pointer].Header.UseCount, 0); memset(&Utils.InternalObjectBuffer.Buffer[Pointer], 0, sizeof(*Utils.InternalObjectBuffer.Buffer) * AllocationSize); c89atomic_fetch_sub_32(&Utils.InternalObjectBuffer.AllocationsCount, 1); c89atomic_fetch_sub_32(&pSignature->ObjectsCount, 1); //Engine_Ref_Unlock_Mutex(pArenaAllocater->Mutex); } void DeAllocate_ResourceHeader(ResourceHeaderSignature* pSignature, uint32_t Pointer) { /* ArenaAllocater* pArenaAllocater = NULL; for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { pArenaAllocater = &Utils.InternalResourceHeaderBuffer.ArenaAllocaters[i]; if (Pointer >= pArenaAllocater->StartPtr && Pointer < pArenaAllocater->EndPtr) { break; } } if (pArenaAllocater == NULL) { Engine_Ref_FunctionError("DeAllocate_ResourceHeader()", "ArenaAllocater Not Found. == ", NULL); return; } Engine_Ref_Lock_Mutex(pArenaAllocater->Mutex);*/ uint32_t AllocationSize = Utils.InternalResourceHeaderBuffer.Buffer[Pointer].Header.AllocationSize; c89atomic_store_32(&Utils.InternalResourceHeaderBuffer.Buffer[Pointer].Header.AllocationSize, 0); c89atomic_store_32(&Utils.InternalResourceHeaderBuffer.Buffer[Pointer].Header.UseCount, 0); memset(&Utils.InternalResourceHeaderBuffer.Buffer[Pointer], 0, sizeof(*Utils.InternalResourceHeaderBuffer.Buffer) * AllocationSize); c89atomic_fetch_sub_32(&Utils.InternalResourceHeaderBuffer.AllocationsCount, 1); c89atomic_fetch_sub_32(&pSignature->ResourceHeadersCount, 1); //Engine_Ref_Unlock_Mutex(pArenaAllocater->Mutex); } void DeAllocate_Element(ElementSignature* pSignature, uint32_t Pointer) { /*ArenaAllocater* pArenaAllocater = NULL; for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { pArenaAllocater = &Utils.InternalElementBuffer.ArenaAllocaters[i]; if (Pointer >= pArenaAllocater->StartPtr && Pointer < pArenaAllocater->EndPtr) { break; } } if (pArenaAllocater == NULL) { Engine_Ref_FunctionError("DeAllocate_Element()", "ArenaAllocater Not Found. == ", NULL); return; } //Engine_Ref_Lock_Mutex(pArenaAllocater->Mutex);*/ uint32_t AllocationSize = Utils.InternalElementBuffer.Buffer[Pointer].Header.AllocationSize; c89atomic_store_32(&Utils.InternalElementBuffer.Buffer[Pointer].Header.AllocationSize, 0); c89atomic_store_32(&Utils.InternalElementBuffer.Buffer[Pointer].Header.UseCount, 0); memset(&Utils.InternalElementBuffer.Buffer[Pointer], 0, sizeof(*Utils.InternalElementBuffer.Buffer) * AllocationSize); c89atomic_fetch_sub_32(&Utils.InternalElementBuffer.AllocationsCount, 1); c89atomic_fetch_sub_32(&pSignature->ElementsCount, 1); //Engine_Ref_Unlock_Mutex(pArenaAllocater->Mutex); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Compare Allocation Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Returns Success when allocations are identical. Failure otherwise. * @param Allocation0, first allocation to compare agaisnt. * @param Allocation1, second allocation to compare agaisnt. * @note Thread Safe always. * @note Externally Synchronized. */ TEXRESULT Compare_ObjectAllocation(ObjectAllocation Allocation0, ObjectAllocation Allocation1) { return (Allocation0.Pointer == Allocation1.Pointer && Allocation0.Identifier == Allocation1.Identifier) ? Success : Failure; } /* * Added in 1.0.0 * Returns Success when allocations are identical. Failure otherwise. * @param Allocation0, first allocation to compare agaisnt. * @param Allocation1, second allocation to compare agaisnt. * @note Thread Safe always. * @note Externally Synchronized. */ TEXRESULT Compare_ResourceHeaderAllocation(ResourceHeaderAllocation Allocation0, ResourceHeaderAllocation Allocation1) { return (Allocation0.Pointer == Allocation1.Pointer && Allocation0.Identifier == Allocation1.Identifier) ? Success : Failure; } /* * Added in 1.0.0 * Returns Success when allocations are identical. Failure otherwise. * @param Allocation0, first allocation to compare agaisnt. * @param Allocation1, second allocation to compare agaisnt. * @note Thread Safe always. * @note Externally Synchronized. */ TEXRESULT Compare_ElementAllocation(ElementAllocation Allocation0, ElementAllocation Allocation1) { return (Allocation0.Pointer == Allocation1.Pointer && Allocation0.Identifier == Allocation1.Identifier) ? Success : Failure; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Get AllocationData Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Returns AllocationData, also used to check if allocation is valid. * @return @ref return pointer to AllocationData if valid. @ref NULL if invalid. * @param Allocation, Allocation to get the AllocationData of. (required) * @note Thread Safe always. * @note Not Synchronized but doesnt matter. */ AllocationData* Get_ObjectAllocationData(ObjectAllocation Allocation) { return (Allocation.Identifier != NULL) ? &Utils.InternalObjectBuffer.AllocationDatas.Buffer[Allocation.Pointer] : NULL; } /* * Added in 1.0.0 * Returns AllocationData, also used to check if allocation is valid. * @return @ref return pointer to AllocationData if valid. @ref NULL if invalid. * @param Allocation, Allocation to get the AllocationData of. (required) * @note Thread Safe always. * @note Not Synchronized but doesnt matter. */ AllocationData* Get_ResourceHeaderAllocationData(ResourceHeaderAllocation Allocation) { return (Allocation.Identifier != NULL) ? &Utils.InternalResourceHeaderBuffer.AllocationDatas.Buffer[Allocation.Pointer] : NULL; } /* * Added in 1.0.0 * Returns AllocationData, also used to check if allocation is valid. * @return @ref return pointer to AllocationData if valid. @ref NULL if invalid. * @param Allocation, Allocation to get the AllocationData of. (required) * @note Thread Safe always. * @note Not Synchronized but doesnt matter. */ AllocationData* Get_ElementAllocationData(ElementAllocation Allocation) { return (Allocation.Identifier != NULL) ? &Utils.InternalElementBuffer.AllocationDatas.Buffer[Allocation.Pointer] : NULL; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Find Signature Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Uses Identifier to find the signature that the object is associated with. * @param Identifier, desired signature identifier to find. * @param ppSignature is a pointer to a pointer of a signature to return. * @param pIndex is a pointer to a signatureindex value to return, signature index being the index of the signature in the signatures buffer. * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT Find_ObjectSignature(ObjectIdentifier Identifier, ObjectSignature** ppSignature) { #ifndef NDEBUG if (Identifier == NULL) { Engine_Ref_ArgsError("Find_ObjectSignature()", "Identifier == NULL"); return (Invalid_Parameter | Failure); } #endif //why no sync; for (uint64_t i = 0; i < Utils.ObjectSignaturesSize; i++) { if (Utils.ObjectSignatures[i]->Identifier == Identifier) { if (ppSignature != NULL) *ppSignature = Utils.ObjectSignatures[i]; return (Success); } } *ppSignature = NULL; Engine_Ref_ArgsError("Find_ObjectSignature()", "Identifier Invalid"); return (Invalid_Parameter | Failure); } /* * Added in 1.0.0 * Uses Identifier to find the signature that the object is associated with. * @param Identifier, desired signature identifier to find. * @param ppSignature is a pointer to a pointer of a signature to return. * @param pIndex is a pointer to a signatureindex value to return, signature index being the index of the signature in the signatures buffer. * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT Find_ResourceHeaderSignature(ResourceHeaderIdentifier Identifier, ResourceHeaderSignature** ppSignature) { #ifndef NDEBUG if (Identifier == NULL) { Engine_Ref_ArgsError("Find_ResourceHeaderSignature()", "Identifier == NULL"); return (Invalid_Parameter | Failure); } #endif for (uint64_t i = 0; i < Utils.ResourceHeaderSignaturesSize; i++) { if (Utils.ResourceHeaderSignatures[i]->Identifier == Identifier) { if (ppSignature != NULL) *ppSignature = Utils.ResourceHeaderSignatures[i]; return (Success); } } *ppSignature = NULL; Engine_Ref_ArgsError("Find_ResourceHeaderSignature()", "Identifier Invalid"); return (Invalid_Parameter | Failure); } /* * Added in 1.0.0 * Uses Identifier to find the signature that the object is associated with. * @param Identifier, desired signature identifier to find. * @param ppSignature is a pointer to a pointer of a signature to return. * @param pIndex is a pointer to a signatureindex value to return, signature index being the index of the signature in the signatures buffer. * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT Find_ElementSignature(ElementIdentifier Identifier, ElementSignature** ppSignature) { #ifndef NDEBUG if (Identifier == NULL) { Engine_Ref_ArgsError("Find_ElementSignature()", "Identifier == NULL"); return (Invalid_Parameter | Failure); } #endif for (uint64_t i = 0; i < Utils.ElementSignaturesSize; i++) { if (Utils.ElementSignatures[i]->Identifier == Identifier) { if (ppSignature != NULL) *ppSignature = Utils.ElementSignatures[i]; return (Success); } } *ppSignature = NULL; Engine_Ref_ArgsError("Find_ElementSignature()", "Identifier Invalid"); return (Invalid_Parameter | Failure); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Get Pointer from pointer Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Gets a pointer from a pointer, useful for getting overlay pointer or a specific threadindex pointer. * @param Pointer Pointer to an object. * @note Thread Safe always. * @note Not Synchronized but doesnt matter. */ Object* Get_ObjectPointerFromPointer(uint32_t Pointer) { return &Utils.InternalObjectBuffer.Buffer[Pointer]; } /* * Added in 1.0.0 * Gets a pointer from a pointer, useful for getting overlay pointer or a specific threadindex pointer. * @param Pointer Pointer to an object. * @note Thread Safe always. * @note Not Synchronized but doesnt matter. */ ResourceHeader* Get_ResourceHeaderPointerFromPointer(uint32_t Pointer) { return &Utils.InternalResourceHeaderBuffer.Buffer[Pointer]; } /* * Added in 1.0.0 * Gets a pointer from a pointer, useful for getting overlay pointer or a specific threadindex pointer. * @param Pointer Pointer to an object. * @note Thread Safe always. * @note Not Synchronized but doesnt matter. */ Element* Get_ElementPointerFromPointer(uint32_t Pointer) { return &Utils.InternalElementBuffer.Buffer[Pointer]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Get Pointer Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Object* Get_ObjectPointer(ObjectAllocation Allocation, bool Write, bool Consistent, uint32_t ThreadIndex); ResourceHeader* Get_ResourceHeaderPointer(ResourceHeaderAllocation Allocation, bool Write, bool Consistent, uint32_t ThreadIndex); Element* Get_ElementPointer(ElementAllocation Allocation, bool Write, bool Consistent, uint32_t ThreadIndex); void End_ObjectPointer(ObjectAllocation Allocation, bool Write, bool Consistent, uint32_t ThreadIndex); void End_ResourceHeaderPointer(ResourceHeaderAllocation Allocation, bool Write, bool Consistent, uint32_t ThreadIndex); void End_ElementPointer(ElementAllocation Allocation, bool Write, bool Consistent, uint32_t ThreadIndex); TEXRESULT Destroy_ObjectInstance(uint32_t Pointer, ObjectSignature* pSignature, bool Full, uint32_t ThreadIndex) { TEXRESULT tres = Success; Object* pObject = &Utils.InternalObjectBuffer.Buffer[Pointer]; Object* pObjectOverlay = (pObject->Header.OverlayPointer != UINT32_MAX) ? &Utils.InternalObjectBuffer.Buffer[pObject->Header.OverlayPointer] : NULL; if (pSignature->Destructor != NULL) { Destroy_ObjectTemplate* func = *pSignature->Destructor; if ((tres = func(pObject, pObjectOverlay, Full, ThreadIndex)) != Success) return tres; } if (((pObjectOverlay != NULL) ? (pObject->Header.iResourceHeaders != pObjectOverlay->Header.iResourceHeaders) : true) && pObject->Header.iResourceHeaders != NULL) { free(pObject->Header.iResourceHeaders); pObject->Header.iResourceHeaders = NULL; pObject->Header.iResourceHeadersSize = NULL; } if (((pObjectOverlay != NULL) ? (pObject->Header.iChildren != pObjectOverlay->Header.iChildren) : true) && pObject->Header.iChildren != NULL) { free(pObject->Header.iChildren); pObject->Header.iChildren = NULL; pObject->Header.iChildrenSize = NULL; } if (((pObjectOverlay != NULL) ? (pObject->Header.Name != pObjectOverlay->Header.Name) : true) && pObject->Header.Name != NULL) { free(pObject->Header.Name); pObject->Header.Name = NULL; } return (Success); } TEXRESULT Destroy_ResourceHeaderInstance(uint32_t Pointer, ResourceHeaderSignature* pSignature, bool Full, uint32_t ThreadIndex) { TEXRESULT tres = Success; ResourceHeader* pResourceHeader = &Utils.InternalResourceHeaderBuffer.Buffer[Pointer]; ResourceHeader* pResourceHeaderOverlay = (pResourceHeader->Header.OverlayPointer != UINT32_MAX) ? &Utils.InternalResourceHeaderBuffer.Buffer[pResourceHeader->Header.OverlayPointer] : NULL; if (pSignature->Destructor != NULL) { Destroy_ResourceHeaderTemplate* func = *pSignature->Destructor; if ((tres = func(pResourceHeader, pResourceHeaderOverlay, Full, ThreadIndex)) != Success) return tres; } if (((pResourceHeaderOverlay != NULL) ? (pResourceHeader->Header.iObjects != pResourceHeaderOverlay->Header.iObjects) : true) && pResourceHeader->Header.iObjects != NULL) { free(pResourceHeader->Header.iObjects); pResourceHeader->Header.iObjects = NULL; pResourceHeader->Header.iObjectsSize = NULL; } if (((pResourceHeaderOverlay != NULL) ? (pResourceHeader->Header.iElements != pResourceHeaderOverlay->Header.iElements) : true) && pResourceHeader->Header.iElements != NULL) { free(pResourceHeader->Header.iElements); pResourceHeader->Header.iElements = NULL; pResourceHeader->Header.iElementsSize = NULL; } if (((pResourceHeaderOverlay != NULL) ? (pResourceHeader->Header.Name != pResourceHeaderOverlay->Header.Name) : true) && pResourceHeader->Header.Name != NULL) { free(pResourceHeader->Header.Name); pResourceHeader->Header.Name = NULL; } return (Success); } TEXRESULT Destroy_ElementInstance(uint32_t Pointer, ElementSignature* pSignature, bool Full, uint32_t ThreadIndex) { TEXRESULT tres = Success; Element* pElement = &Utils.InternalElementBuffer.Buffer[Pointer]; Element* pElementOverlay = (pElement->Header.OverlayPointer != UINT32_MAX) ? &Utils.InternalElementBuffer.Buffer[pElement->Header.OverlayPointer] : NULL; if (pSignature->Destructor != NULL) { Destroy_ElementTemplate* func = *pSignature->Destructor; if ((tres = func(pElement, pElementOverlay, Full, ThreadIndex)) != Success) return tres; } if (((pElementOverlay != NULL) ? (pElement->Header.iResourceHeaders != pElementOverlay->Header.iResourceHeaders) : true) && pElement->Header.iResourceHeaders != NULL) { free(pElement->Header.iResourceHeaders); pElement->Header.iResourceHeaders = NULL; pElement->Header.iResourceHeadersSize = NULL; } if (((pElementOverlay != NULL) ? (pElement->Header.Name != pElementOverlay->Header.Name) : true) && pElement->Header.Name != NULL) { free(pElement->Header.Name); pElement->Header.Name = NULL; } return (Success); } #define DestroyAndDeAllocate_ObjectInstance(Pointer, pSignature, Full, ThreadIndex)\ {\ Destroy_ObjectInstance(Pointer, pSignature, Full, ThreadIndex);\ DeAllocate_Object(pSignature, Pointer);\ } #define DestroyAndDeAllocate_ResourceHeaderInstance(Pointer, pSignature, Full, ThreadIndex)\ {\ Destroy_ResourceHeaderInstance(Pointer, pSignature, Full, ThreadIndex);\ DeAllocate_ResourceHeader(pSignature, Pointer);\ } #define DestroyAndDeAllocate_ElementInstance(Pointer, pSignature, Full, ThreadIndex)\ {\ Destroy_ElementInstance(Pointer, pSignature, Full, ThreadIndex);\ DeAllocate_Element(pSignature, Pointer);\ } void DestroyAndDeAllocate_Object(ObjectAllocation Allocation, uint32_t Pointer, ObjectSignature* pSignature, uint32_t ThreadIndex) { Object* pObject = &Utils.InternalObjectBuffer.Buffer[Pointer]; if (pObject->Header.OverlayPointer != UINT32_MAX) DestroyAndDeAllocate_ObjectInstance(pObject->Header.OverlayPointer, pSignature, false, ThreadIndex) c89atomic_store_32(&pObject->Header.OverlayPointer, UINT32_MAX); for (size_t i = 0; i < pObject->Header.iResourceHeadersSize; i++) { ResourceHeader* pChild = Get_ResourceHeaderPointer(pObject->Header.iResourceHeaders[i], true, false, ThreadIndex); if (pChild != NULL) { ResourceHeader* pChildOverlay = (pChild->Header.OverlayPointer != UINT32_MAX) ? Get_ResourceHeaderPointerFromPointer(pChild->Header.OverlayPointer) : NULL; if (((pChildOverlay != NULL) ? (pChild->Header.iObjects == pChildOverlay->Header.iObjects) : false)) pChild->Header.iObjects = CopyDataN(pChild->Header.iObjects, sizeof(*pChild->Header.iObjects) * pChild->Header.iObjectsSize); for (size_t i = 0; i < pChild->Header.iObjectsSize; i++) { if (Compare_ObjectAllocation(pChild->Header.iObjects[i], Allocation) == Success) { RemoveMember_Array((void**)&pChild->Header.iObjects, pChild->Header.iObjectsSize, i, sizeof(*pChild->Header.iObjects), 1); pChild->Header.iObjectsSize = pChild->Header.iObjectsSize - 1; } } End_ResourceHeaderPointer(pObject->Header.iResourceHeaders[i], true, false, ThreadIndex); } } //doesnt work bcuuuzzzzzzzzzzzzzz arena allokators are locked at the same time !? ; for (size_t i = 0; i < pObject->Header.iChildrenSize; i++) { Object* pChild = Get_ObjectPointer(pObject->Header.iChildren[i], true, false, ThreadIndex); if (pChild != NULL) { memset(&pChild->Header.iParent, 0, sizeof(pChild->Header.iParent)); End_ObjectPointer(pObject->Header.iChildren[i], true, false, ThreadIndex); } } DestroyAndDeAllocate_ObjectInstance(Pointer, pSignature, true, ThreadIndex) DeAllocate_ObjectAllocationData(pSignature, Allocation); } void DestroyAndDeAllocate_ResourceHeader(ResourceHeaderAllocation Allocation, uint32_t Pointer, ResourceHeaderSignature* pSignature, uint32_t ThreadIndex) { ResourceHeader* pResourceHeader = &Utils.InternalResourceHeaderBuffer.Buffer[Pointer]; if (pResourceHeader->Header.OverlayPointer != UINT32_MAX) DestroyAndDeAllocate_ResourceHeaderInstance(pResourceHeader->Header.OverlayPointer, pSignature, false, ThreadIndex) c89atomic_store_32(&pResourceHeader->Header.OverlayPointer, UINT32_MAX); for (size_t i = 0; i < pResourceHeader->Header.iObjectsSize; i++) { Object* pParent = Get_ObjectPointer(pResourceHeader->Header.iObjects[i], true, false, ThreadIndex); if (pParent != NULL) { Object* pParentOverlay = (pParent->Header.OverlayPointer != UINT32_MAX) ? Get_ObjectPointerFromPointer(pParent->Header.OverlayPointer) : NULL; if (((pParentOverlay != NULL) ? (pParent->Header.iResourceHeaders == pParentOverlay->Header.iResourceHeaders) : false)) pParent->Header.iResourceHeaders = CopyDataN(pParent->Header.iResourceHeaders, sizeof(*pParent->Header.iResourceHeaders) * pParent->Header.iResourceHeadersSize); for (size_t i = 0; i < pParent->Header.iResourceHeadersSize; i++) { if (Compare_ResourceHeaderAllocation(pParent->Header.iResourceHeaders[i], Allocation) == Success) { RemoveMember_Array((void**)&pParent->Header.iResourceHeaders, pParent->Header.iResourceHeadersSize, i, sizeof(*pParent->Header.iResourceHeaders), 1); pParent->Header.iResourceHeadersSize = pParent->Header.iResourceHeadersSize - 1; } } End_ObjectPointer(pResourceHeader->Header.iObjects[i], true, false, ThreadIndex); } } for (size_t i = 0; i < pResourceHeader->Header.iElementsSize; i++) { Element* pChild = Get_ElementPointer(pResourceHeader->Header.iElements[i], true, false, ThreadIndex); if (pChild != NULL) { Element* pChildOverlay = (pChild->Header.OverlayPointer != UINT32_MAX) ? Get_ElementPointerFromPointer(pChild->Header.OverlayPointer) : NULL; if (((pChildOverlay != NULL) ? (pChild->Header.iResourceHeaders == pChildOverlay->Header.iResourceHeaders) : false)) pChild->Header.iResourceHeaders = CopyDataN(pChild->Header.iResourceHeaders, sizeof(*pChild->Header.iResourceHeaders) * pChild->Header.iResourceHeadersSize); for (size_t i = 0; i < pChild->Header.iResourceHeadersSize; i++) { if (Compare_ResourceHeaderAllocation(pChild->Header.iResourceHeaders[i], Allocation) == Success) { RemoveMember_Array((void**)&pChild->Header.iResourceHeaders, pChild->Header.iResourceHeadersSize, i, sizeof(*pChild->Header.iResourceHeaders), 1); pChild->Header.iResourceHeadersSize = pChild->Header.iResourceHeadersSize - 1; } } End_ElementPointer(pResourceHeader->Header.iElements[i], true, false, ThreadIndex); } } DestroyAndDeAllocate_ResourceHeaderInstance(Pointer, pSignature, true, ThreadIndex) DeAllocate_ResourceHeaderAllocationData(pSignature, Allocation); } void DestroyAndDeAllocate_Element(ElementAllocation Allocation, uint32_t Pointer, ElementSignature* pSignature, uint32_t ThreadIndex) { Element* pElement = &Utils.InternalElementBuffer.Buffer[Pointer]; if (pElement->Header.OverlayPointer != UINT32_MAX) DestroyAndDeAllocate_ElementInstance(pElement->Header.OverlayPointer, pSignature, false, ThreadIndex) c89atomic_store_32(&pElement->Header.OverlayPointer, UINT32_MAX); for (size_t i = 0; i < pElement->Header.iResourceHeadersSize; i++) { ResourceHeader* pParent = Get_ResourceHeaderPointer(pElement->Header.iResourceHeaders[i], true, false, ThreadIndex); if (pParent != NULL) { ResourceHeader* pParentOverlay = (pParent->Header.OverlayPointer != UINT32_MAX) ? Get_ResourceHeaderPointerFromPointer(pParent->Header.OverlayPointer) : NULL; if (((pParentOverlay != NULL) ? (pParent->Header.iElements == pParentOverlay->Header.iElements) : false)) pParent->Header.iElements = CopyDataN(pParent->Header.iElements, sizeof(*pParent->Header.iElements) * pParent->Header.iElementsSize); for (size_t i = 0; i < pParent->Header.iElementsSize; i++) { if (Compare_ElementAllocation(pParent->Header.iElements[i], Allocation) == Success) { RemoveMember_Array((void**)&pParent->Header.iElements, pParent->Header.iElementsSize, i, sizeof(*pParent->Header.iElements), 1); pParent->Header.iElementsSize = pParent->Header.iElementsSize - 1; } } End_ResourceHeaderPointer(pElement->Header.iResourceHeaders[i], true, false, ThreadIndex); } } DestroyAndDeAllocate_ElementInstance(Pointer, pSignature, true, ThreadIndex) DeAllocate_ElementAllocationData(pSignature, Allocation); } #define CreateAndAllocate_ObjectInstance(Pointer)\ {\ Object* pOldObject = &Utils.InternalObjectBuffer.Buffer[LatestPointer];\ Allocate_Object(pSignature, pOldObject->Header.AllocationSize, pAllocationData->Allocation.Object.Identifier, Allocation, &Pointer, ThreadIndex);\ Object* pObject = &Utils.InternalObjectBuffer.Buffer[Pointer];\ memcpy(pObject, pOldObject, sizeof(Object) * pOldObject->Header.AllocationSize);\ c89atomic_store_32(&pObject->Header.UseCount, 0);\ pObject->Header.OverlayPointer = UINT32_MAX;\ } #define CreateAndAllocate_ResourceHeaderInstance(Pointer)\ {\ ResourceHeader* pOldResourceHeader = &Utils.InternalResourceHeaderBuffer.Buffer[LatestPointer]; \ Allocate_ResourceHeader(pSignature, pOldResourceHeader->Header.AllocationSize, pAllocationData->Allocation.ResourceHeader.Identifier, Allocation, &Pointer, ThreadIndex); \ ResourceHeader* pResourceHeader = &Utils.InternalResourceHeaderBuffer.Buffer[Pointer]; \ memcpy(pResourceHeader, pOldResourceHeader, sizeof(ResourceHeader) * pOldResourceHeader->Header.AllocationSize); \ c89atomic_store_32(&pResourceHeader->Header.UseCount, 0);\ pResourceHeader->Header.OverlayPointer = UINT32_MAX;\ } #define CreateAndAllocate_ElementInstance(Pointer)\ {\ Element* pOldElement = &Utils.InternalElementBuffer.Buffer[LatestPointer];\ Allocate_Element(pSignature, pOldElement->Header.AllocationSize, pAllocationData->Allocation.Element.Identifier, Allocation, &Pointer, ThreadIndex);\ Element* pElement = &Utils.InternalElementBuffer.Buffer[Pointer];\ memcpy(pElement, pOldElement, sizeof(Element) * pOldElement->Header.AllocationSize);\ c89atomic_store_32(&pElement->Header.UseCount, 0);\ pElement->Header.OverlayPointer = UINT32_MAX;\ } //attempts to destroy itself and then its overlay pointer. void TryDestruct_Object(AllocationData* pAllocationData, uint32_t Pointer, ObjectSignature* pSignature, uint32_t ThreadIndex) { if (c89atomic_fetch_add_32(&Utils.InternalObjectBuffer.Buffer[Pointer].Header.UseCount, UINT16_MAX) == 0 && pAllocationData->LatestPointer != Pointer) { uint32_t OverlayPointer = Utils.InternalObjectBuffer.Buffer[Pointer].Header.OverlayPointer; Object* pObject = &Utils.InternalObjectBuffer.Buffer[Pointer]; DestroyAndDeAllocate_ObjectInstance(Pointer, pSignature, false, ThreadIndex); if (OverlayPointer != UINT32_MAX) { c89atomic_fetch_sub_32(&Utils.InternalObjectBuffer.Buffer[OverlayPointer].Header.UseCount, 1); TryDestruct_Object(pAllocationData, OverlayPointer, pSignature, ThreadIndex); } } else { c89atomic_fetch_sub_32(&Utils.InternalObjectBuffer.Buffer[Pointer].Header.UseCount, UINT16_MAX); } } void TryDestruct_ResourceHeader(AllocationData* pAllocationData, uint32_t Pointer, ResourceHeaderSignature* pSignature, uint32_t ThreadIndex) { if (c89atomic_fetch_add_32(&Utils.InternalResourceHeaderBuffer.Buffer[Pointer].Header.UseCount, UINT16_MAX) == 0 && pAllocationData->LatestPointer != Pointer) { uint32_t OverlayPointer = Utils.InternalResourceHeaderBuffer.Buffer[Pointer].Header.OverlayPointer; ResourceHeader* pResourceHeader = &Utils.InternalResourceHeaderBuffer.Buffer[Pointer]; //Engine_Ref_FunctionError("freeing()", "size == ", Utils.InternalResourceHeaderBuffer.AllocationsCount); DestroyAndDeAllocate_ResourceHeaderInstance(Pointer, pSignature, false, ThreadIndex); if (OverlayPointer != UINT32_MAX) { c89atomic_fetch_sub_32(&Utils.InternalResourceHeaderBuffer.Buffer[OverlayPointer].Header.UseCount, 1); TryDestruct_ResourceHeader(pAllocationData, OverlayPointer, pSignature, ThreadIndex); } } else { c89atomic_fetch_sub_32(&Utils.InternalResourceHeaderBuffer.Buffer[Pointer].Header.UseCount, UINT16_MAX); } } void TryDestruct_Element(AllocationData* pAllocationData, uint32_t Pointer, ElementSignature* pSignature, uint32_t ThreadIndex) { if (c89atomic_fetch_add_32(&Utils.InternalElementBuffer.Buffer[Pointer].Header.UseCount, UINT16_MAX) == 0 && pAllocationData->LatestPointer != Pointer) { uint32_t OverlayPointer = Utils.InternalElementBuffer.Buffer[Pointer].Header.OverlayPointer; Element* pElement = &Utils.InternalElementBuffer.Buffer[Pointer]; DestroyAndDeAllocate_ElementInstance(Pointer, pSignature, false, ThreadIndex); if (OverlayPointer != UINT32_MAX) { c89atomic_fetch_sub_32(&Utils.InternalElementBuffer.Buffer[OverlayPointer].Header.UseCount, 1); TryDestruct_Element(pAllocationData, OverlayPointer, pSignature, ThreadIndex); } } else { c89atomic_fetch_sub_32(&Utils.InternalElementBuffer.Buffer[Pointer].Header.UseCount, UINT16_MAX); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Get Pointer Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Gets a pointer from an allocation for that threadindex that is an instance. * Always call End_ObjectPointer after done. * @param Allocation, allocation of the desired object to get pointer of. * @param Write, intended use of the instance that will be retrieved, true means its allocates a new instance so its quite slow. * @param Consistent, Consistent == true means that the pointer wont be modified since the last time get_pointer was called on this threadindex on this allocation, useful for making sure when reading allocation buffers that no new allocations will appear in second parsing, so it omits the requirement of a buffer per thread or such. * @param ThreadIndex threadindex global. * @note Thread Safe always. * @note Not Synchronized but doesnt matter. */ Object* Get_ObjectPointer(ObjectAllocation Allocation, bool Write, bool Consistent, uint32_t ThreadIndex) { TEXRESULT tres = Success; AllocationData* pAllocationData = Get_ObjectAllocationData(Allocation); if (pAllocationData == NULL) { //Engine_Ref_FunctionError("Get_ObjectPointer()", "pAllocationData == ", 0); return NULL; } //if latest instance UINT32_MAX it is invalid to read or write. if (pAllocationData->LatestPointer == UINT32_MAX) { Engine_Ref_FunctionError("Get_ObjectPointer()", "LatestPointer Invalid. ", 0); return NULL; } if (pAllocationData->Allocation.Object.Identifier == 0) { Engine_Ref_FunctionError("Get_ObjectPointer()", "Allocation Invalid. ", 0); return NULL; } if (c89atomic_fetch_add_32(&pAllocationData->Threads[ThreadIndex].Count, 1) == 0 && Consistent == false && pAllocationData->ScheduleDestruct == false) { if (Write == true) { //Engine_Ref_FunctionError("Get_ObjectPointer", "Begin Write On Pointer == ", Allocation.Pointer); //LOCK SO ONLY 1 WRITE AT A TIME OR FIX THE PROBLEMS ASSOCIATED WITH MULTIPLE WRITES CONCURRENTLY; if (c89atomic_test_and_set_8(&pAllocationData->WriteLock) == 0) { //get new data. ObjectSignature* pSignature = NULL; Find_ObjectSignature(pAllocationData->Allocation.Object.Identifier, &pSignature); uint32_t LatestPointer = pAllocationData->LatestPointer; //refresh pointer if (c89atomic_fetch_add_32(&Utils.InternalObjectBuffer.Buffer[LatestPointer].Header.UseCount, 1) >= UINT16_MAX) { c89atomic_fetch_sub_32(&Utils.InternalObjectBuffer.Buffer[LatestPointer].Header.UseCount, 1); LatestPointer = pAllocationData->LatestPointer; c89atomic_fetch_add_32(&Utils.InternalObjectBuffer.Buffer[LatestPointer].Header.UseCount, 1); } uint32_t Pointer = 0; CreateAndAllocate_ObjectInstance(Pointer); c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, Pointer); //save pointer of latest; c89atomic_store_32(&Utils.InternalObjectBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.OverlayPointer, LatestPointer); c89atomic_fetch_add_32(&Utils.InternalObjectBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.UseCount, 1); c89atomic_clear_8(&pAllocationData->WriteLock); } else { c89atomic_fetch_sub_32(&pAllocationData->Threads[ThreadIndex].Count, 1); Engine_Ref_FunctionError("Get_ObjectPointer()", "Concurrent Write. ", 0); return NULL; } } else { //Engine_Ref_FunctionError("Get_ObjectPointer", "Begin Read On Pointer == ", Allocation.Pointer); //get new pointer uint32_t LatestPointer = pAllocationData->LatestPointer; //refresh pointer if (c89atomic_fetch_add_32(&Utils.InternalObjectBuffer.Buffer[LatestPointer].Header.UseCount, 1) >= UINT16_MAX) { c89atomic_fetch_sub_32(&Utils.InternalObjectBuffer.Buffer[LatestPointer].Header.UseCount, 1); LatestPointer = pAllocationData->LatestPointer; c89atomic_fetch_add_32(&Utils.InternalObjectBuffer.Buffer[LatestPointer].Header.UseCount, 1); } c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, LatestPointer); } } if (pAllocationData->Threads[ThreadIndex].Pointer == UINT32_MAX) { c89atomic_fetch_sub_32(&pAllocationData->Threads[ThreadIndex].Count, 1); Engine_Ref_FunctionError("Get_ObjectPointer()", "Pointer Acquisition Failed. ", Allocation.Pointer); return NULL; } return &Utils.InternalObjectBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer]; } /* * Added in 1.0.0 * Gets a pointer from an allocation for that threadindex that is an instance. * Always call End_ResourceHeaderPointer after done. * @param Allocation, allocation of the desired object to g/et pointer of. * @param Write, intended use of the instance that will be retrieved, true means its allocates a new instance so its quite slow. * @param Consistent, Consistent == true means that the pointer wont be modified since the last time get_pointer was called on this threadindex on this allocation, useful for making sure when reading allocation buffers that no new allocations will appear in second parsing, so it omits the requirement of a buffer per thread or such. * @param ThreadIndex threadindex global. * @note Thread Safe always. * @note Not Synchronized but doesnt matter. */ ResourceHeader* Get_ResourceHeaderPointer(ResourceHeaderAllocation Allocation, bool Write, bool Consistent, uint32_t ThreadIndex) { TEXRESULT tres = Success; AllocationData* pAllocationData = Get_ResourceHeaderAllocationData(Allocation); if (pAllocationData == NULL) { //Engine_Ref_FunctionError("Get_ResourceHeaderPointer()", "pAllocationData == ", 0); return NULL; } //if latest instance UINT32_MAX it is invalid to read or write. if (pAllocationData->LatestPointer == UINT32_MAX) { Engine_Ref_FunctionError("Get_ResourceHeaderPointer()", "LatestPointer Invalid. ", 0); return NULL; } if (pAllocationData->Allocation.ResourceHeader.Identifier == 0) { Engine_Ref_FunctionError("Get_ResourceHeaderPointer()", "Allocation Invalid. ", 0); return NULL; } if (c89atomic_fetch_add_32(&pAllocationData->Threads[ThreadIndex].Count, 1) == 0 && Consistent == false && pAllocationData->ScheduleDestruct == false) { if (Write == true) { //Engine_Ref_FunctionError("Get_ResourceHeaderPointer", "Begin Write On Pointer == ", Allocation.Pointer); //LOCK SO ONLY 1 WRITE AT A TIME OR FIX THE PROBLEMS ASSOCIATED WITH MULTIPLE WRITES CONCURRENTLY; if (c89atomic_test_and_set_8(&pAllocationData->WriteLock) == 0) { //get new data. ResourceHeaderSignature* pSignature = NULL; Find_ResourceHeaderSignature(pAllocationData->Allocation.ResourceHeader.Identifier, &pSignature); uint32_t LatestPointer = pAllocationData->LatestPointer; //refresh pointer if (c89atomic_fetch_add_32(&Utils.InternalResourceHeaderBuffer.Buffer[LatestPointer].Header.UseCount, 1) >= UINT16_MAX) { c89atomic_fetch_sub_32(&Utils.InternalResourceHeaderBuffer.Buffer[LatestPointer].Header.UseCount, 1); LatestPointer = pAllocationData->LatestPointer; c89atomic_fetch_add_32(&Utils.InternalResourceHeaderBuffer.Buffer[LatestPointer].Header.UseCount, 1); } uint32_t Pointer = 0; CreateAndAllocate_ResourceHeaderInstance(Pointer); c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, Pointer); //save pointer of latest; c89atomic_store_32(&Utils.InternalResourceHeaderBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.OverlayPointer, LatestPointer); c89atomic_fetch_add_32(&Utils.InternalResourceHeaderBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.UseCount, 1); c89atomic_clear_8(&pAllocationData->WriteLock); } else { c89atomic_fetch_sub_32(&pAllocationData->Threads[ThreadIndex].Count, 1); Engine_Ref_FunctionError("Get_ResourceHeaderPointer()", "Concurrent Write. ", 0); return NULL; } } else { //Engine_Ref_FunctionError("Get_ResourceHeaderPointer", "Begin Read On Pointer == ", Allocation.Pointer); //get new pointer uint32_t LatestPointer = pAllocationData->LatestPointer; //refresh pointer if (c89atomic_fetch_add_32(&Utils.InternalResourceHeaderBuffer.Buffer[LatestPointer].Header.UseCount, 1) >= UINT16_MAX) { c89atomic_fetch_sub_32(&Utils.InternalResourceHeaderBuffer.Buffer[LatestPointer].Header.UseCount, 1); LatestPointer = pAllocationData->LatestPointer; c89atomic_fetch_add_32(&Utils.InternalResourceHeaderBuffer.Buffer[LatestPointer].Header.UseCount, 1); } c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, LatestPointer); } } if (pAllocationData->Threads[ThreadIndex].Pointer == UINT32_MAX) { c89atomic_fetch_sub_32(&pAllocationData->Threads[ThreadIndex].Count, 1); Engine_Ref_FunctionError("Get_ResourceHeaderPointer()", "Pointer Acquisition Failed. ", Allocation.Pointer); return NULL; } return &Utils.InternalResourceHeaderBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer]; } /* * Added in 1.0.0 * Gets a pointer from an allocation for that threadindex that is an instance. * Always call End_ElementPointer after done. * @param Allocation, allocation of the desired object to get pointer of. * @param Write, intended use of the instance that will be retrieved, true means its allocates a new instance so its quite slow. * @param Consistent, Consistent == true means that the pointer wont be modified since the last time get_pointer was called on this threadindex on this allocation, useful for making sure when reading allocation buffers that no new allocations will appear in second parsing, so it omits the requirement of a buffer per thread or such. * @param ThreadIndex threadindex global. * @note Thread Safe always. * @note Not Synchronized but doesnt matter. */ Element* Get_ElementPointer(ElementAllocation Allocation, bool Write, bool Consistent, uint32_t ThreadIndex) { TEXRESULT tres = Success; AllocationData* pAllocationData = Get_ElementAllocationData(Allocation); if (pAllocationData == NULL) { //Engine_Ref_FunctionError("Get_ElementPointer()", "pAllocationData == ", 0); return NULL; } //if latest instance UINT32_MAX it is invalid to read or write. if (pAllocationData->LatestPointer == UINT32_MAX) { Engine_Ref_FunctionError("Get_ElementPointer()", "LatestPointer Invalid. ", 0); return NULL; } if (pAllocationData->Allocation.Element.Identifier == 0) { Engine_Ref_FunctionError("Get_ElementPointer()", "Allocation Invalid. ", 0); return NULL; } if (c89atomic_fetch_add_32(&pAllocationData->Threads[ThreadIndex].Count, 1) == 0 && Consistent == false && pAllocationData->ScheduleDestruct == false) { if (Write == true) { //Engine_Ref_FunctionError("Get_ResourceHeaderPointer", "Begin Write On Pointer == ", Allocation.Pointer); //LOCK SO ONLY 1 WRITE AT A TIME OR FIX THE PROBLEMS ASSOCIATED WITH MULTIPLE WRITES CONCURRENTLY; if (c89atomic_test_and_set_8(&pAllocationData->WriteLock) == 0) { //get new data. ElementSignature* pSignature = NULL; Find_ElementSignature(pAllocationData->Allocation.Element.Identifier, &pSignature); uint32_t LatestPointer = pAllocationData->LatestPointer; //refresh pointer if (c89atomic_fetch_add_32(&Utils.InternalElementBuffer.Buffer[LatestPointer].Header.UseCount, 1) >= UINT16_MAX) { c89atomic_fetch_sub_32(&Utils.InternalElementBuffer.Buffer[LatestPointer].Header.UseCount, 1); LatestPointer = pAllocationData->LatestPointer; c89atomic_fetch_add_32(&Utils.InternalElementBuffer.Buffer[LatestPointer].Header.UseCount, 1); } uint32_t Pointer = 0; CreateAndAllocate_ElementInstance(Pointer); c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, Pointer); //save pointer of latest; c89atomic_store_32(&Utils.InternalElementBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.OverlayPointer, LatestPointer); c89atomic_fetch_add_32(&Utils.InternalElementBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.UseCount, 1); c89atomic_clear_8(&pAllocationData->WriteLock); } else { c89atomic_fetch_sub_32(&pAllocationData->Threads[ThreadIndex].Count, 1); Engine_Ref_FunctionError("Get_ElementPointer()", "Concurrent Write. ", 0); return NULL; } } else { //Engine_Ref_FunctionError("Get_ResourceHeaderPointer", "Begin Read On Pointer == ", Allocation.Pointer); //get new pointer uint32_t LatestPointer = pAllocationData->LatestPointer; //refresh pointer if (c89atomic_fetch_add_32(&Utils.InternalElementBuffer.Buffer[LatestPointer].Header.UseCount, 1) >= UINT16_MAX) { c89atomic_fetch_sub_32(&Utils.InternalElementBuffer.Buffer[LatestPointer].Header.UseCount, 1); LatestPointer = pAllocationData->LatestPointer; c89atomic_fetch_add_32(&Utils.InternalElementBuffer.Buffer[LatestPointer].Header.UseCount, 1); } c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, LatestPointer); } } if (pAllocationData->Threads[ThreadIndex].Pointer == UINT32_MAX) { c89atomic_fetch_sub_32(&pAllocationData->Threads[ThreadIndex].Count, 1); Engine_Ref_FunctionError("Get_ElementPointer()", "Pointer Acquisition Failed. ", Allocation.Pointer); return NULL; } return &Utils.InternalElementBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //End Write //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Ends a Get_Pointer function and applies the results. * Always call Get_Pointer before. * @param Allocation, allocation of the desired object to end read/write of. * @param Write, (MUST MATCH GET_POINTER THAT THIS IS PAIRED WITH) * @param Consistent, (MUST MATCH GET_POINTER THAT THIS IS PAIRED WITH) * @param ThreadIndex threadindex global. * @note Thread Safe always. * @note Not Synchronized but doesnt matter. */ void End_ObjectPointer(ObjectAllocation Allocation, bool Write, bool Consistent, uint32_t ThreadIndex) { TEXRESULT tres = Success; AllocationData* pAllocationData = Get_ObjectAllocationData(Allocation); if (pAllocationData == NULL) { //Engine_Ref_FunctionError("End_ObjectPointer()", "pAllocationData == ", 0); return; } if (pAllocationData->Threads[ThreadIndex].Pointer == UINT32_MAX) { Engine_Ref_FunctionError("End_ObjectPointer()", "Invalid Call. ", 0); return; } if (pAllocationData->LatestPointer == UINT32_MAX) { Engine_Ref_FunctionError("End_ObjectPointer()", "LatestPointer Invalid. ", 0); return; } if (pAllocationData->Threads[ThreadIndex].Count == 0) { Engine_Ref_FunctionError("End_ObjectPointer()", "Count == ", 0); return; } //Engine_Ref_FunctionError("RESOUrCEHEADER USED", "EEAF", pAllocationData->Threads[ThreadIndex].Count); if (c89atomic_fetch_sub_32(&pAllocationData->Threads[ThreadIndex].Count, 1) == 1 && Consistent == false) { if (Write == true) { //Engine_Ref_FunctionError("End_ObjectPointer", "End Write On Pointer == ", Allocation.Pointer); uint32_t LatestPointer = Utils.InternalObjectBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.OverlayPointer; c89atomic_store_32(&Utils.InternalObjectBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.OverlayPointer, UINT32_MAX); c89atomic_store_32(&Utils.InternalObjectBuffer.Buffer[LatestPointer].Header.OverlayPointer, pAllocationData->Threads[ThreadIndex].Pointer); c89atomic_store_32(&pAllocationData->LatestPointer, pAllocationData->Threads[ThreadIndex].Pointer); //lock usedcount for threadindex because its used as overlayand it might be destructed before; c89atomic_fetch_add_32(&Utils.InternalObjectBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.UseCount, 1); c89atomic_fetch_sub_32(&Utils.InternalObjectBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.UseCount, 1); c89atomic_fetch_sub_32(&Utils.InternalObjectBuffer.Buffer[LatestPointer].Header.UseCount, 1); //every decrement of use count must have oppurtunity to destruct. (in this case overlaypointer aka latestpointer at allocate time); ObjectSignature* pSignature = NULL; Find_ObjectSignature(Allocation.Identifier, &pSignature); TryDestruct_Object(pAllocationData, LatestPointer, pSignature, ThreadIndex); } else { //Engine_Ref_FunctionError("End_ObjectPointer", "End Read On Pointer == ", Allocation.Pointer); c89atomic_fetch_sub_32(&Utils.InternalObjectBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.UseCount, 1); } if (pAllocationData->Threads[ThreadIndex].Pointer != pAllocationData->LatestPointer) { ObjectSignature* pSignature = NULL; Find_ObjectSignature(Allocation.Identifier, &pSignature); TryDestruct_Object(pAllocationData, pAllocationData->Threads[ThreadIndex].Pointer, pSignature, ThreadIndex); } c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, UINT32_MAX); if (pAllocationData->ScheduleDestruct == true) { bool found = false; for (size_t i = 0; i < maxthreads; i++) if (pAllocationData->Threads[i].Pointer != UINT32_MAX) found = true; uint32_t Pointer = pAllocationData->LatestPointer; if (c89atomic_fetch_add_32(&Utils.InternalObjectBuffer.Buffer[Pointer].Header.UseCount, UINT16_MAX) == 0 && found == false) { ObjectSignature* pSignature = NULL; Find_ObjectSignature(Allocation.Identifier, &pSignature); DestroyAndDeAllocate_Object(Allocation, Pointer, pSignature, ThreadIndex); } else { c89atomic_fetch_sub_32(&Utils.InternalObjectBuffer.Buffer[Pointer].Header.UseCount, UINT16_MAX); } } } return; } /* * Added in 1.0.0 * Ends a Get_Pointer function and applies the results. * Always call Get_Pointer before. * @param Allocation, allocation of the desired object to end read/write of. * @param Write, (MUST MATCH GET_POINTER THAT THIS IS PAIRED WITH) * @param Consistent, (MUST MATCH GET_POINTER THAT THIS IS PAIRED WITH) * @param ThreadIndex threadindex global. * @note Thread Safe always. * @note Not Synchronized but doesnt matter. */ void End_ResourceHeaderPointer(ResourceHeaderAllocation Allocation, bool Write, bool Consistent, uint32_t ThreadIndex) { TEXRESULT tres = Success; AllocationData* pAllocationData = Get_ResourceHeaderAllocationData(Allocation); if (pAllocationData == NULL) { //Engine_Ref_FunctionError("End_ResourceHeaderPointer()", "pAllocationData == ", 0); return; } if (pAllocationData->Threads[ThreadIndex].Pointer == UINT32_MAX) { Engine_Ref_FunctionError("End_ResourceHeaderPointer()", "Invalid Call. ", 0); return; } if (pAllocationData->LatestPointer == UINT32_MAX) { Engine_Ref_FunctionError("End_ResourceHeaderPointer()", "LatestPointer Invalid. ", 0); return; } if (pAllocationData->Threads[ThreadIndex].Count == 0) { Engine_Ref_FunctionError("End_ResourceHeaderPointer()", "Count == ", 0); return; } //Engine_Ref_FunctionError("RESOUrCEHEADER USED", "EEAF", pAllocationData->Threads[ThreadIndex].Count); if (c89atomic_fetch_sub_32(&pAllocationData->Threads[ThreadIndex].Count, 1) == 1 && Consistent == false) { if (Write == true) { //Engine_Ref_FunctionError("End_ResourceHeaderPointer", "End Write On Pointer == ", Allocation.Pointer); uint32_t LatestPointer = Utils.InternalResourceHeaderBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.OverlayPointer; c89atomic_store_32(&Utils.InternalResourceHeaderBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.OverlayPointer, UINT32_MAX); c89atomic_store_32(&Utils.InternalResourceHeaderBuffer.Buffer[LatestPointer].Header.OverlayPointer, pAllocationData->Threads[ThreadIndex].Pointer); c89atomic_store_32(&pAllocationData->LatestPointer, pAllocationData->Threads[ThreadIndex].Pointer); //lock usedcount for threadindex because its used as overlayand it might be destructed before; c89atomic_fetch_add_32(&Utils.InternalResourceHeaderBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.UseCount, 1); c89atomic_fetch_sub_32(&Utils.InternalResourceHeaderBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.UseCount, 1); c89atomic_fetch_sub_32(&Utils.InternalResourceHeaderBuffer.Buffer[LatestPointer].Header.UseCount, 1); //every decrement of use count must have oppurtunity to destruct. (in this case overlaypointer aka latestpointer at allocate time); ResourceHeaderSignature* pSignature = NULL; Find_ResourceHeaderSignature(Allocation.Identifier, &pSignature); TryDestruct_ResourceHeader(pAllocationData, LatestPointer, pSignature, ThreadIndex); } else { //Engine_Ref_FunctionError("End_ResourceHeaderPointer", "End Read On Pointer == ", Allocation.Pointer); c89atomic_fetch_sub_32(&Utils.InternalResourceHeaderBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.UseCount, 1); } if (pAllocationData->Threads[ThreadIndex].Pointer != pAllocationData->LatestPointer) { ResourceHeaderSignature* pSignature = NULL; Find_ResourceHeaderSignature(Allocation.Identifier, &pSignature); TryDestruct_ResourceHeader(pAllocationData, pAllocationData->Threads[ThreadIndex].Pointer, pSignature, ThreadIndex); } c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, UINT32_MAX); if (pAllocationData->ScheduleDestruct == true) { bool found = false; for (size_t i = 0; i < maxthreads; i++) if (pAllocationData->Threads[i].Pointer != UINT32_MAX) found = true; uint32_t Pointer = pAllocationData->LatestPointer; if (c89atomic_fetch_add_32(&Utils.InternalResourceHeaderBuffer.Buffer[Pointer].Header.UseCount, UINT16_MAX) == 0 && found == false) { ResourceHeaderSignature* pSignature = NULL; Find_ResourceHeaderSignature(Allocation.Identifier, &pSignature); DestroyAndDeAllocate_ResourceHeader(Allocation, Pointer, pSignature, ThreadIndex); } else { c89atomic_fetch_sub_32(&Utils.InternalResourceHeaderBuffer.Buffer[Pointer].Header.UseCount, UINT16_MAX); } } } return; } /* * Added in 1.0.0 * Ends a Get_Pointer function and applies the results. * Always call Get_Pointer before. * @param Allocation, allocation of the desired object to end read/write of. * @param Write, (MUST MATCH GET_POINTER THAT THIS IS PAIRED WITH) * @param Consistent, (MUST MATCH GET_POINTER THAT THIS IS PAIRED WITH) * @param ThreadIndex threadindex global. * @note Thread Safe always. * @note Not Synchronized but doesnt matter. */ void End_ElementPointer(ElementAllocation Allocation, bool Write, bool Consistent, uint32_t ThreadIndex) { TEXRESULT tres = Success; AllocationData* pAllocationData = Get_ElementAllocationData(Allocation); if (pAllocationData == NULL) { //Engine_Ref_FunctionError("End_ElementPointer()", "pAllocationData == ", 0); return; } if (pAllocationData->Threads[ThreadIndex].Pointer == UINT32_MAX) { Engine_Ref_FunctionError("End_ElementPointer()", "Invalid Call. ", 0); return; } if (pAllocationData->LatestPointer == UINT32_MAX) { Engine_Ref_FunctionError("End_ElementPointer()", "LatestPointer Invalid. ", 0); return; } if (pAllocationData->Threads[ThreadIndex].Count == 0) { Engine_Ref_FunctionError("End_ElementPointer()", "Count == ", 0); return; } if (c89atomic_fetch_sub_32(&pAllocationData->Threads[ThreadIndex].Count, 1) == 1 && Consistent == false) { if (Write == true) { //Engine_Ref_FunctionError("End_ElementPointer", "End Write On Pointer == ", Allocation.Pointer); uint32_t LatestPointer = Utils.InternalElementBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.OverlayPointer; c89atomic_store_32(&Utils.InternalElementBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.OverlayPointer, UINT32_MAX); c89atomic_store_32(&Utils.InternalElementBuffer.Buffer[LatestPointer].Header.OverlayPointer, pAllocationData->Threads[ThreadIndex].Pointer); //lock usedcount for threadindex because its used as overlayand it might be destructed before; c89atomic_fetch_add_32(&Utils.InternalElementBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.UseCount, 1); c89atomic_fetch_sub_32(&Utils.InternalElementBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.UseCount, 1); c89atomic_fetch_sub_32(&Utils.InternalElementBuffer.Buffer[LatestPointer].Header.UseCount, 1); c89atomic_store_32(&pAllocationData->LatestPointer, pAllocationData->Threads[ThreadIndex].Pointer); //every decrement of use count must have oppurtunity to destruct. (in this case overlaypointer aka latestpointer at allocate time); ElementSignature* pSignature = NULL; Find_ElementSignature(Allocation.Identifier, &pSignature); TryDestruct_Element(pAllocationData, LatestPointer, pSignature, ThreadIndex); } else { //Engine_Ref_FunctionError("End_ElementPointer", "End Read On Pointer == ", Allocation.Pointer); c89atomic_fetch_sub_32(&Utils.InternalElementBuffer.Buffer[pAllocationData->Threads[ThreadIndex].Pointer].Header.UseCount, 1); } if (pAllocationData->Threads[ThreadIndex].Pointer != pAllocationData->LatestPointer) { ElementSignature* pSignature = NULL; Find_ElementSignature(Allocation.Identifier, &pSignature); TryDestruct_Element(pAllocationData, pAllocationData->Threads[ThreadIndex].Pointer, pSignature, ThreadIndex); } c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, UINT32_MAX); if (pAllocationData->ScheduleDestruct == true) { bool found = false; for (size_t i = 0; i < maxthreads; i++) if (pAllocationData->Threads[i].Pointer != UINT32_MAX) found = true; uint32_t Pointer = pAllocationData->LatestPointer; if (c89atomic_fetch_add_32(&Utils.InternalElementBuffer.Buffer[Pointer].Header.UseCount, UINT16_MAX) == 0 && found == false) { ElementSignature* pSignature = NULL; Find_ElementSignature(Allocation.Identifier, &pSignature); DestroyAndDeAllocate_Element(Allocation, Pointer, pSignature, ThreadIndex); } else { c89atomic_fetch_sub_32(&Utils.InternalElementBuffer.Buffer[Pointer].Header.UseCount, UINT16_MAX); } } } return; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Construct Buffer Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define Create_Buffer(name)\ {\ pBuffer->BufferSize = InitialSize;\ pBuffer->Buffer = calloc(pBuffer->BufferSize, sizeof(*pBuffer->Buffer));\ pBuffer->ArenaAllocaters = calloc(EngineRes.pUtils->CPU.MaxThreads, sizeof(*pBuffer->ArenaAllocaters));\ pBuffer->Indexes = calloc(EngineRes.pUtils->CPU.MaxThreads, sizeof(*pBuffer->Indexes));\ if (pBuffer->ArenaAllocaters == NULL || pBuffer->Indexes == NULL || pBuffer->Buffer == NULL) {\ Engine_Ref_FunctionError(name, "Out Of Memory.", 0);\ return (Out_Of_Memory_Result | Failure);\ }\ for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++)\ Create_ArenaAllocater(&pBuffer->ArenaAllocaters[i], (i)*InitialSize, (i + 1) * InitialSize);\ } #define Create_AllocationDataBuffer(name)\ {\ pBuffer->AllocationDatas.BufferSize = InitialSize;\ pBuffer->AllocationDatas.Buffer = calloc(pBuffer->AllocationDatas.BufferSize, sizeof(*pBuffer->AllocationDatas.Buffer));\ pBuffer->AllocationDatas.ArenaAllocaters = calloc(EngineRes.pUtils->CPU.MaxThreads, sizeof(*pBuffer->AllocationDatas.ArenaAllocaters));\ pBuffer->AllocationDatas.Indexes = calloc(EngineRes.pUtils->CPU.MaxThreads, sizeof(*pBuffer->AllocationDatas.Indexes));\ if (pBuffer->AllocationDatas.ArenaAllocaters == NULL || pBuffer->AllocationDatas.Indexes == NULL || pBuffer->AllocationDatas.Buffer == NULL) {\ Engine_Ref_FunctionError(name, "Out Of Memory.", 0);\ return (Out_Of_Memory_Result | Failure);\ }\ for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++)\ Create_ArenaAllocater(&pBuffer->AllocationDatas.ArenaAllocaters[i], (i)*InitialSize, (i + 1) * InitialSize);\ } /* * Added in 1.0.0 * Creates a buffer for objects to be stored, to be used in a signature. * @param pBuffer pointer to a buffer object to initialize. * @param Size is in allocation chunks. (1 Object == 1 chunk). * @note Thread Safe always. * @note Externally Synchronized. */ TEXRESULT Create_ObjectBuffer(ObjectBuffer* pBuffer, uint64_t InitialSize) { #ifndef NDEBUG if (pBuffer == NULL) { Engine_Ref_ArgsError("Create_ObjectBuffer()", "pBuffer == NULLPTR"); return (Invalid_Parameter | Failure); } if (InitialSize == NULL) { Engine_Ref_ArgsError("Create_ObjectBuffer()", "InitialSize == NULL"); return (Invalid_Parameter | Failure); } #endif memset(pBuffer, 0, sizeof(*pBuffer)); Create_Buffer("Create_ObjectBuffer()"); Create_AllocationDataBuffer("Create_ObjectBuffer()"); return (Success); } /* * Added in 1.0.0 * Creates a buffer for objects to be stored, to be used in a signature. * @param pBuffer pointer to a buffer object to initialize. * @param Size is in allocation chunks. (1 Object == 1 chunk). * @note Thread Safe always. * @note Externally Synchronized. */ TEXRESULT Create_ResourceHeaderBuffer(ResourceHeaderBuffer* pBuffer, uint64_t InitialSize) { #ifndef NDEBUG if (pBuffer == NULL) { Engine_Ref_ArgsError("Create_ResourceHeaderBuffer()", "pBuffer == NULLPTR"); return (Invalid_Parameter | Failure); } if (InitialSize == NULL) { Engine_Ref_ArgsError("Create_ResourceHeaderBuffer()", "InitialSize == NULL"); return (Invalid_Parameter | Failure); } #endif memset(pBuffer, 0, sizeof(*pBuffer)); Create_Buffer("Create_ResourceHeaderBuffer()"); Create_AllocationDataBuffer("Create_ResourceHeaderBuffer()"); return (Success); } /* * Added in 1.0.0 * Creates a buffer for objects to be stored, to be used in a signature. * @param pBuffer pointer to a buffer object to initialize. * @param Size is in allocation chunks. (1 Object == 1 chunk). * @note Thread Safe always. * @note Externally Synchronized. */ TEXRESULT Create_ElementBuffer(ElementBuffer* pBuffer, uint64_t InitialSize) { #ifndef NDEBUG if (pBuffer == NULL) { Engine_Ref_ArgsError("Create_ElementBuffer()", "pBuffer == NULLPTR"); return (Invalid_Parameter | Failure); } if (InitialSize == NULL) { Engine_Ref_ArgsError("Create_ElementBuffer()", "InitialSize == NULL"); return (Invalid_Parameter | Failure); } #endif memset(pBuffer, 0, sizeof(*pBuffer)); Create_Buffer("Create_ElementBuffer()"); Create_AllocationDataBuffer("Create_ElementBuffer()"); return (Success); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Construct Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Allocates and calls construct on an object from CreateInfo.Identifier Signature. * if CreateInfo.name = null it will be defaulted. * @param pAllocation pointer to allocation to return. * @param CreateInfo of the object. * @param pCreateInfo is specialized createinfo for the signature. * @note Thread safe. * @note Internally Synchronized. */ TEXRESULT Create_Object(ObjectAllocation* pAllocation, ObjectCreateInfo CreateInfo, void* pCreateInfo, uint32_t ThreadIndex) { ObjectSignature* pSignature = NULL; Find_ObjectSignature(CreateInfo.Identifier, &pSignature); #ifndef NDEBUG if (pAllocation == NULL) { Engine_Ref_ArgsError("Create_Object()", "pAllocation == NULL"); return (Invalid_Parameter | Failure); } if (CreateInfo.Identifier == NULL) { Engine_Ref_ArgsError("Create_Object()", "CreateInfo.Identifier == NULL"); return (Invalid_Parameter | Failure); } if (pSignature == NULL) { Engine_Ref_ArgsError("Create_Object()", "pSignature == NULL, No Associated Signature Was Found For The Identifier"); return (Invalid_Parameter | Failure); } if (pSignature->ByteLength == NULL) { Engine_Ref_ObjectError("Create_Object()", "pSignature", &pSignature, "pSignature.ByteLength == NULL"); return (Invalid_Parameter | Failure); } if (pSignature->Identifier == NULL) { Engine_Ref_ObjectError("Create_Object()", "pSignature", &pSignature, "pSignature.Identifer == NULL"); return (Invalid_Parameter | Failure); } #endif TEXRESULT tres = Success; uint64_t RequiredSizeBytes = NULL; if (pSignature->Constructor != NULL) { Create_ObjectTemplate* pFunction = *pSignature->Constructor; if ((tres = pFunction(NULL, pCreateInfo, &RequiredSizeBytes, ThreadIndex)) != Success) return tres; } uint64_t RequiredSizeChunks = (RequiredSizeBytes != NULL) ? RequiredSizeBytes / sizeof(Object) + ((RequiredSizeBytes % sizeof(Object)) != 0) : pSignature->ByteLength / sizeof(Object) + ((pSignature->ByteLength % sizeof(Object)) != 0); ObjectAllocation Allocation = {sizeof(Allocation)}; uint32_t Pointer = 0; if ((tres = Allocate_ObjectAllocationData(pSignature, CreateInfo.Identifier, &Allocation, ThreadIndex)) != Success) return tres; if ((tres = Allocate_Object(pSignature, RequiredSizeChunks, CreateInfo.Identifier, Allocation, &Pointer, ThreadIndex)) != Success) return tres; Object* pObject = &Utils.InternalObjectBuffer.Buffer[Pointer]; if (CreateInfo.Name != NULL) pObject->Header.Name = (UTF8*)CopyData((void*)CreateInfo.Name); else { UTF8 TempBuffer[20 + 65 + 65 + 1]; memset(TempBuffer, 0, 20 + 65 + 65 + 1); sprintf((char*)TempBuffer, "Object_%i_%llu", CreateInfo.Identifier, RequiredSizeChunks); pObject->Header.Name = (UTF8*)CopyData((void*)TempBuffer); } if (pSignature->Constructor != NULL) { Create_ObjectTemplate* pFunction = *pSignature->Constructor; if ((tres = pFunction(pObject, pCreateInfo, &RequiredSizeBytes, ThreadIndex)) != Success) return tres; } AllocationData* pAllocationData = Get_ObjectAllocationData(Allocation); c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, Pointer); c89atomic_store_32(&pAllocationData->LatestPointer, Pointer); *pAllocation = Allocation; return (Success); } /* * Added in 1.0.0 * Allocates and calls construct on an object from CreateInfo.Identifier Signature. * if CreateInfo.name = null it will be defaulted. * @param pAllocation pointer to allocation to return. * @param CreateInfo of the object. * @param pCreateInfo is specialized createinfo for the signature. * @note Thread safe. * @note Internally Synchronized. */ TEXRESULT Create_ResourceHeader(ResourceHeaderAllocation* pAllocation, ResourceHeaderCreateInfo CreateInfo, void* pCreateInfo, uint32_t ThreadIndex) { ResourceHeaderSignature* pSignature = NULL; Find_ResourceHeaderSignature(CreateInfo.Identifier, &pSignature); #ifndef NDEBUG if (pAllocation == NULL) { Engine_Ref_ArgsError("Create_ResourceHeader()", "pAllocation == NULL"); return (Invalid_Parameter | Failure); } if (CreateInfo.Identifier == NULL) { Engine_Ref_ArgsError("Create_ResourceHeader()", "CreateInfo.Identifier == NULL"); return (Invalid_Parameter | Failure); } if (pSignature == NULL) { Engine_Ref_ArgsError("Create_ResourceHeader()", "pSignature == NULL, No Associated Signature Was Found For The Identifier"); return (Invalid_Parameter | Failure); } if (pSignature->ByteLength == NULL) { Engine_Ref_ObjectError("Create_ResourceHeader()", "pSignature", &pSignature, "pSignature.ByteLength == NULL"); return (Invalid_Parameter | Failure); } if (pSignature->Identifier == NULL) { Engine_Ref_ObjectError("Create_ResourceHeader()", "pSignature", &pSignature, "pSignature.Identifer == NULL"); return (Invalid_Parameter | Failure); } #endif TEXRESULT tres = Success; uint64_t RequiredSizeBytes = NULL; if (pSignature->Constructor != NULL) { Create_ResourceHeaderTemplate* pFunction = *pSignature->Constructor; if ((tres = pFunction(NULL, pCreateInfo, &RequiredSizeBytes, ThreadIndex)) != Success) return tres; } uint64_t RequiredSizeChunks = (RequiredSizeBytes != NULL) ? RequiredSizeBytes / sizeof(ResourceHeader) + ((RequiredSizeBytes % sizeof(ResourceHeader)) != 0) : pSignature->ByteLength / sizeof(ResourceHeader) + ((pSignature->ByteLength % sizeof(ResourceHeader)) != 0); ResourceHeaderAllocation Allocation = { sizeof(Allocation) }; uint32_t Pointer = 0; if ((tres = Allocate_ResourceHeaderAllocationData(pSignature, CreateInfo.Identifier, &Allocation, ThreadIndex)) != Success) return tres; if ((tres = Allocate_ResourceHeader(pSignature, RequiredSizeChunks, CreateInfo.Identifier, Allocation, &Pointer, ThreadIndex)) != Success) return tres; ResourceHeader* pResourceHeader = &Utils.InternalResourceHeaderBuffer.Buffer[Pointer]; if (CreateInfo.Name != NULL) pResourceHeader->Header.Name = (UTF8*)CopyData((void*)CreateInfo.Name); else { UTF8 TempBuffer[20 + 65 + 65 + 1]; memset(TempBuffer, 0, 20 + 65 + 65 + 1); sprintf((char*)TempBuffer, "ResourceHeader_%i_%llu", CreateInfo.Identifier, RequiredSizeChunks); pResourceHeader->Header.Name = (UTF8*)CopyData((void*)TempBuffer); } if (pSignature->Constructor != NULL) { Create_ResourceHeaderTemplate* pFunction = *pSignature->Constructor; if ((tres = pFunction(pResourceHeader, pCreateInfo, &RequiredSizeBytes, ThreadIndex)) != Success) return tres; } AllocationData* pAllocationData = Get_ResourceHeaderAllocationData(Allocation); c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, Pointer); c89atomic_store_32(&pAllocationData->LatestPointer, Pointer); *pAllocation = Allocation; return (Success); } /* * Added in 1.0.0 * Allocates and calls construct on an object from CreateInfo.Identifier Signature. * if CreateInfo.name = null it will be defaulted. * @param pAllocation pointer to allocation to return. * @param CreateInfo of the object. * @param pCreateInfo is specialized createinfo for the signature. * @note Thread safe. * @note Internally Synchronized. */ TEXRESULT Create_Element(ElementAllocation* pAllocation, ElementCreateInfo CreateInfo, void* pCreateInfo, uint32_t ThreadIndex) { ElementSignature* pSignature = NULL; Find_ElementSignature(CreateInfo.Identifier, &pSignature); #ifndef NDEBUG if (pAllocation == NULL) { Engine_Ref_ArgsError("Create_Element()", "pAllocation == NULL"); return (Invalid_Parameter | Failure); } if (CreateInfo.Identifier == NULL) { Engine_Ref_ArgsError("Create_Element()", "CreateInfo.Identifier == NULL"); return (Invalid_Parameter | Failure); } if (pSignature == NULL) { Engine_Ref_ArgsError("Create_Element()", "pSignature == NULL, No Associated Signature Was Found For The Identifier"); return (Invalid_Parameter | Failure); } if (pSignature->ByteLength == NULL) { Engine_Ref_ObjectError("Create_Element()", "pSignature", &pSignature, "pSignature.ByteLength == NULL"); return (Invalid_Parameter | Failure); } if (pSignature->Identifier == NULL) { Engine_Ref_ObjectError("Create_Element()", "pSignature", &pSignature, "pSignature.Identifer == NULL"); return (Invalid_Parameter | Failure); } #endif TEXRESULT tres = Success; uint64_t RequiredSizeBytes = NULL; if (pSignature->Constructor != NULL) { Create_ElementTemplate* pFunction = *pSignature->Constructor; if ((tres = pFunction(NULL, pCreateInfo, &RequiredSizeBytes, ThreadIndex)) != Success) return tres; } uint64_t RequiredSizeChunks = (RequiredSizeBytes != NULL) ? RequiredSizeBytes / sizeof(Element) + ((RequiredSizeBytes % sizeof(Element)) != 0) : pSignature->ByteLength / sizeof(Element) + ((pSignature->ByteLength % sizeof(Element)) != 0); ElementAllocation Allocation = { sizeof(Allocation) }; uint32_t Pointer = 0; if ((tres = Allocate_ElementAllocationData(pSignature, CreateInfo.Identifier, &Allocation, ThreadIndex)) != Success) return tres; if ((tres = Allocate_Element(pSignature, RequiredSizeChunks, CreateInfo.Identifier, Allocation, &Pointer, ThreadIndex)) != Success) return tres; Element* pElement = &Utils.InternalElementBuffer.Buffer[Pointer]; if (CreateInfo.Name != NULL) pElement->Header.Name = (UTF8*)CopyData((void*)CreateInfo.Name); else { UTF8 TempBuffer[20 + 65 + 65 + 1]; memset(TempBuffer, 0, 20 + 65 + 65 + 1); sprintf((char*)TempBuffer, "Element_%i_%llu", CreateInfo.Identifier, RequiredSizeChunks); pElement->Header.Name = (UTF8*)CopyData((void*)TempBuffer); } if (pSignature->Constructor != NULL) { Create_ElementTemplate* pFunction = *pSignature->Constructor; if ((tres = pFunction(pElement, pCreateInfo, &RequiredSizeBytes, ThreadIndex)) != Success) return tres; } AllocationData* pAllocationData = Get_ElementAllocationData(Allocation); c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, Pointer); c89atomic_store_32(&pAllocationData->LatestPointer, Pointer); *pAllocation = Allocation; return (Success); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Destruct Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Does not destroy child objects only itself, although it removes refrences of itself from all child/parent objects. * all allocations of the object to be deleted will be invalid and you have to deal with them. * will destroy all values that it owns. * @param Allocation refrencing the desired object to destruct. * @param Full means full destruct, as in everything is destroyed, non full destruct is for recreation mainly. * @param ThreadIndex Index of the thread that is calling this. * @note Multithread safe when threadindex is unique on each thread calling. * @note Externally Synchronized. */ TEXRESULT Destroy_Object(ObjectAllocation Allocation, bool Full, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ObjectAllocationData(Allocation); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Destroy_Object()", "Allocation Invalid."); return (Invalid_Parameter | Failure); } #endif //destroy should destroy anything it can via overlay pointer (which is the previous latest pointer for it?), and then set rest to NULL ? ; //if overlay == UINT32_MAX then it has full ownerhsip otherwise usual destruct regime; //overlay pointer is just the latest pointer during this stage; //if pointer is uint32_t max it means that it hasnt been aquirred yet, otherwise make consistent. TEXRESULT tres = Success; //if it is already aquired then it must be writing. if (pAllocationData->Threads[ThreadIndex].Pointer != UINT32_MAX) { Object* pObject = Get_ObjectPointer(Allocation, true, false, ThreadIndex); if (pObject == NULL) return (Failure); ObjectSignature* pSignature = NULL; Find_ObjectSignature(pObject->Header.Allocation.Identifier, &pSignature); if ((tres = Destroy_ObjectInstance(pAllocationData->Threads[ThreadIndex].Pointer, pSignature, false, ThreadIndex)) != Success) return tres; if (Full == true) { pAllocationData->ScheduleDestruct = true; } End_ObjectPointer(Allocation, true, false, ThreadIndex); } //if it is not aquired then calling destroy does nothing. else { Object* pObject = Get_ObjectPointer(Allocation, false, false, ThreadIndex); if (pObject == NULL) return (Failure); if (Full == true) { pAllocationData->ScheduleDestruct = true; } End_ObjectPointer(Allocation, false, false, ThreadIndex); } return (Success); } /* * Added in 1.0.0 * Does not destroy child objects only itself, although it removes refrences of itself from all child/parent objects. * all allocations of the object to be deleted will be invalid and you have to deal with them. * will destroy all values that it owns. * @param Allocation refrencing the desired object to destruct. * @param Full means full destruct, as in everything is destroyed, non full destruct is for recreation mainly. * @param ThreadIndex Index of the thread that is calling this. * @note Multithread safe when threadindex is unique on each thread calling. * @note Externally Synchronized. */ TEXRESULT Destroy_ResourceHeader(ResourceHeaderAllocation Allocation, bool Full, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ResourceHeaderAllocationData(Allocation); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Destroy_ResourceHeader()", "Allocation Invalid."); return (Invalid_Parameter | Failure); } #endif //destroy should destroy anything it can via overlay pointer (which is the previous latest pointer for it?), and then set rest to NULL ? ; //if overlay == UINT32_MAX then it has full ownerhsip otherwise usual destruct regime; //overlay pointer is just the latest pointer during this stage; //if pointer is uint32_t max it means that it hasnt been aquirred yet, otherwise make consistent. TEXRESULT tres = Success; //if it is already aquired then it must be writing. if (pAllocationData->Threads[ThreadIndex].Pointer != UINT32_MAX) { ResourceHeader* pResourceHeader = Get_ResourceHeaderPointer(Allocation, true, false, ThreadIndex); if (pResourceHeader == NULL) return (Failure); ResourceHeaderSignature* pSignature = NULL; Find_ResourceHeaderSignature(pResourceHeader->Header.Allocation.Identifier, &pSignature); if ((tres = Destroy_ResourceHeaderInstance(pAllocationData->Threads[ThreadIndex].Pointer, pSignature, false, ThreadIndex)) != Success) return tres; if (Full == true) { pAllocationData->ScheduleDestruct = true; } End_ResourceHeaderPointer(Allocation, true, false, ThreadIndex); } //if it is not aquired then calling destroy does nothing. else { ResourceHeader* pResourceHeader = Get_ResourceHeaderPointer(Allocation, false, false, ThreadIndex); if (pResourceHeader == NULL) return (Failure); if (Full == true) { pAllocationData->ScheduleDestruct = true; } End_ResourceHeaderPointer(Allocation, false, false, ThreadIndex); } return (Success); } /* * Added in 1.0.0 * Does not destroy child objects only itself, although it removes refrences of itself from all child/parent objects. * all allocations of the object to be deleted will be invalid and you have to deal with them. * will destroy all values that it owns. * @param Allocation refrencing the desired object to destruct. * @param Full means full destruct, as in everything is destroyed, non full destruct is for recreation mainly, when Full destruct and is used on other threads it will block until fully destructed as well. * @param ThreadIndex Index of the thread that is calling this. * @note Multithread safe when threadindex is unique on each thread calling. * @note Externally Synchronized. */ TEXRESULT Destroy_Element(ElementAllocation Allocation, bool Full, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ElementAllocationData(Allocation); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Destroy_Element()", "Allocation Invalid."); return (Invalid_Parameter | Failure); } #endif //destroy should destroy anything it can via overlay pointer (which is the previous latest pointer for it?), and then set rest to NULL ? ; //if overlay == UINT32_MAX then it has full ownerhsip otherwise usual destruct regime; //overlay pointer is just the latest pointer during this stage; //if pointer is uint32_t max it means that it hasnt been aquirred yet, otherwise make consistent. TEXRESULT tres = Success; //if it is already aquired then it must be writing. if (pAllocationData->Threads[ThreadIndex].Pointer != UINT32_MAX) { Element* pElement = Get_ElementPointer(Allocation, true, false, ThreadIndex); if (pElement == NULL) return (Failure); ElementSignature* pSignature = NULL; Find_ElementSignature(pElement->Header.Allocation.Identifier, &pSignature); if ((tres = Destroy_ElementInstance(pAllocationData->Threads[ThreadIndex].Pointer, pSignature, false, ThreadIndex)) != Success) return tres; if (Full == true) { pAllocationData->ScheduleDestruct = true; } End_ElementPointer(Allocation, true, false, ThreadIndex); } //if it is not aquired then calling destroy does nothing. else { Element* pElement = Get_ElementPointer(Allocation, false, false, ThreadIndex); if (pElement == NULL) return (Failure); if (Full == true) { pAllocationData->ScheduleDestruct = true; } End_ElementPointer(Allocation, false, false, ThreadIndex); } return (Success); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Recreate Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Recreate Object with new data. (basicially just calls that signature's recreate function on this item. * @param Allocation refrencing the desired Object to update. * @param pInstance pointer to Object created by CreateInstance_Object(), if its null recreate will be not multithreaded safe. * @param ThreadIndex Index of the thread that is calling this. * @note Externally Synchronized. */ TEXRESULT ReCreate_Object(ObjectAllocation Allocation, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ObjectAllocationData(Allocation); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("ReCreate_Object()", "Allocation Invalid."); return (Invalid_Parameter | Failure); } #endif TEXRESULT tres = Success; Object* pObject = Get_ObjectPointer(Allocation, true, false, ThreadIndex); if (pObject == NULL) return (Failure); ObjectSignature* pSignature = NULL; Find_ObjectSignature(pObject->Header.Allocation.Identifier, &pSignature); if (pSignature->ReConstructor != NULL) { ReCreate_ObjectTemplate* pFunction = *pSignature->ReConstructor; if ((tres = pFunction(pObject, ThreadIndex)) != Success) return tres; } End_ObjectPointer(Allocation, true, false, ThreadIndex); return (Success); } /* * Added in 1.0.0 * Recreate ResourceHeader with new data. (basicially just calls that signature's recreate function on this item. * @param Allocation refrencing the desired ResourceHeader to update. * @param pInstance pointer to ResourceHeader created by CreateInstance_ResourceHeader(), if its null recreate will be not multithreaded safe. * @param ThreadIndex Index of the thread that is calling this. * @note Externally Synchronized. */ TEXRESULT ReCreate_ResourceHeader(ResourceHeaderAllocation Allocation, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ResourceHeaderAllocationData(Allocation); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("ReCreate_ResourceHeader()", "Allocation Invalid."); return (Invalid_Parameter | Failure); } #endif TEXRESULT tres = Success; ResourceHeader* pResourceHeader = Get_ResourceHeaderPointer(Allocation, true, false, ThreadIndex); if (pResourceHeader == NULL) return (Failure); ResourceHeaderSignature* pSignature = NULL; Find_ResourceHeaderSignature(pResourceHeader->Header.Allocation.Identifier, &pSignature); if (pSignature->ReConstructor != NULL) { ReCreate_ResourceHeaderTemplate* pFunction = *pSignature->ReConstructor; if ((tres = pFunction(pResourceHeader, ThreadIndex)) != Success) return tres; } End_ResourceHeaderPointer(Allocation, true, false, ThreadIndex); return (Success); } /* * Added in 1.0.0 * Recreate Element with new data. (basicially just calls that signature's recreate function on this item. * @param Allocation refrencing the desired Element to update. * @param pInstance pointer to Element created by CreateInstance_Element(), if its null recreate will be not multithreaded safe. * @param ThreadIndex Index of the thread that is calling this. * @note Externally Synchronized. */ TEXRESULT ReCreate_Element(ElementAllocation Allocation, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ElementAllocationData(Allocation); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("ReCreate_Element()", "Allocation Invalid."); return (Invalid_Parameter | Failure); } #endif TEXRESULT tres = Success; Element* pElement = Get_ElementPointer(Allocation, true, false, ThreadIndex); if (pElement == NULL) return (Failure); ElementSignature* pSignature = NULL; Find_ElementSignature(pElement->Header.Allocation.Identifier, &pSignature); if (pSignature->ReConstructor != NULL) { ReCreate_ElementTemplate* pFunction = *pSignature->ReConstructor; if ((tres = pFunction(pElement, ThreadIndex)) != Success) return tres; } End_ElementPointer(Allocation, true, false, ThreadIndex); return (Success); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Resizes Buffer Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define Resize_Buffer(name)\ {\ Resize_Array((void**)&pBuffer->Buffer, pBuffer->BufferSize, NewSize, sizeof(*pBuffer->Buffer));\ pBuffer->BufferSize = NewSize;\ Resize_Array((void**)&pBuffer->AllocationDatas.Buffer, pBuffer->AllocationDatas.BufferSize, NewSize, sizeof(*pBuffer->AllocationDatas.Buffer));\ pBuffer->AllocationDatas.BufferSize = NewSize;\ for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) {\ pBuffer->ArenaAllocaters[i].StartPtr = (i)*NewSize;\ pBuffer->ArenaAllocaters[i].EndPtr = (i + 1) * NewSize;\ pBuffer->AllocationDatas.ArenaAllocaters[i].StartPtr = (i)*NewSize;\ pBuffer->AllocationDatas.ArenaAllocaters[i].EndPtr = (i + 1) * NewSize;\ }\ } /* * Added in 1.0.0 * Resizes specified buffer to newsize. * doesnt compact, there will be excess space in the array. * resize functions are super expensive and shouldnt be done often. * destroys all objects that are no longer in range. * @param pBuffer pointer to a buffer object to resize. * @param NewSize is in allocation chunks. (1 Object == 1 chunk). * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT Resize_ObjectBuffer(ObjectBuffer* pBuffer, uint64_t NewSize, uint32_t ThreadIndex) { #ifndef NDEBUG if (pBuffer == NULL) { Engine_Ref_ArgsError("Resize_ObjectBuffer()", "pBuffer == NULLPTR"); return (Invalid_Parameter | Failure); } if (NewSize == NULL) { Engine_Ref_ArgsError("Resize_ObjectBuffer()", "NewSize == NULL"); return (Invalid_Parameter | Failure); } #endif for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Lock_Mutex(&pBuffer->ArenaAllocaters[i].Mutex); Engine_Ref_Lock_Mutex(&pBuffer->AllocationDatas.ArenaAllocaters[i].Mutex); } uint32_t AllocationsToCut = 0; uint32_t AllocationsCount = pBuffer->AllocationDatas.AllocationsCount; if (NewSize < pBuffer->AllocationDatas.BufferSize) { //set all allocations that are out of range to destruct. for (size_t i = NewSize; i < pBuffer->AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &pBuffer->AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.Object.Identifier != 0) { Destroy_Object(pAllocationData->Allocation.Object, true, ThreadIndex); AllocationsToCut++; } } } if (NewSize < pBuffer->BufferSize) { //set all items that are out of range to destruct. //the problem is you arent supposed to destruct allocation instances like this; for (size_t i = NewSize; i < pBuffer->BufferSize;) { Object* pObject = &pBuffer->Buffer[i]; if (pObject->Header.AllocationSize != NULL) { //if it is under newsize then we can assure that it hasnt been counted yet, otherwise it has. if ((pObject->Header.Allocation.Pointer < NewSize)) { Destroy_Object(pObject->Header.Allocation, true, ThreadIndex); AllocationsToCut++; } i += pObject->Header.AllocationSize; } else { i++; } } } //wait for them to destruct while (pBuffer->AllocationDatas.AllocationsCount > (AllocationsCount - AllocationsToCut)) { } Resize_Buffer("Resize_ObjectBuffer()"); for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Unlock_Mutex(&pBuffer->ArenaAllocaters[i].Mutex); Engine_Ref_Unlock_Mutex(&pBuffer->AllocationDatas.ArenaAllocaters[i].Mutex); } return (Success); } /* * Added in 1.0.0 * Resizes specified buffer to newsize. * doesnt compact, there will be excess space in the array. * resize functions are super expensive and shouldnt be done often. * destroys all objects that are no longer in range. * @param pBuffer pointer to a buffer object to resize. * @param NewSize is in allocation chunks. (1 Object == 1 chunk). * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT Resize_ResourceHeaderBuffer(ResourceHeaderBuffer* pBuffer, uint64_t NewSize, uint32_t ThreadIndex) { #ifndef NDEBUG if (pBuffer == NULL) { Engine_Ref_ArgsError("Resize_ResourceHeaderBuffer()", "pBuffer == NULLPTR"); return (Invalid_Parameter | Failure); } if (NewSize == NULL) { Engine_Ref_ArgsError("Resize_ResourceHeaderBuffer()", "NewSize == NULL"); return (Invalid_Parameter | Failure); } #endif for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Lock_Mutex(&pBuffer->ArenaAllocaters[i].Mutex); Engine_Ref_Lock_Mutex(&pBuffer->AllocationDatas.ArenaAllocaters[i].Mutex); } uint32_t AllocationsToCut = 0; uint32_t AllocationsCount = pBuffer->AllocationDatas.AllocationsCount; if (NewSize < pBuffer->AllocationDatas.BufferSize) { //set all allocations that are out of range to destruct. for (size_t i = NewSize; i < pBuffer->AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &pBuffer->AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.ResourceHeader.Identifier != 0) { Destroy_ResourceHeader(pAllocationData->Allocation.ResourceHeader, true, ThreadIndex); AllocationsToCut++; } } } if (NewSize < pBuffer->BufferSize) { //set all items that are out of range to destruct. //the problem is you arent supposed to destruct allocation instances like this; for (size_t i = NewSize; i < pBuffer->BufferSize;) { ResourceHeader* pResourceHeader = &pBuffer->Buffer[i]; if (pResourceHeader->Header.AllocationSize != NULL) { //if it is under newsize then we can assure that it hasnt been counted yet, otherwise it has. if ((pResourceHeader->Header.Allocation.Pointer < NewSize)) { Destroy_ResourceHeader(pResourceHeader->Header.Allocation, true, ThreadIndex); AllocationsToCut++; } i += pResourceHeader->Header.AllocationSize; } else { i++; } } } //wait for them to destruct while (pBuffer->AllocationDatas.AllocationsCount > (AllocationsCount - AllocationsToCut)) { } Resize_Buffer("Resize_ResourceHeaderBuffer()"); for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Unlock_Mutex(&pBuffer->ArenaAllocaters[i].Mutex); Engine_Ref_Unlock_Mutex(&pBuffer->AllocationDatas.ArenaAllocaters[i].Mutex); } return (Success); } /* * Added in 1.0.0 * Resizes specified buffer to newsize. * doesnt compact, there will be excess space in the array. * resize functions are super expensive and shouldnt be done often. * destroys all objects that are no longer in range. * @param pBuffer pointer to a buffer object to resize. * @param NewSize is in allocation chunks. (1 Object == 1 chunk). * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT Resize_ElementBuffer(ElementBuffer* pBuffer, uint64_t NewSize, uint32_t ThreadIndex) { #ifndef NDEBUG if (pBuffer == NULL) { Engine_Ref_ArgsError("Resize_ElementBuffer()", "pBuffer == NULLPTR"); return (Invalid_Parameter | Failure); } if (NewSize == NULL) { Engine_Ref_ArgsError("Resize_ElementBuffer()", "NewSize == NULL"); return (Invalid_Parameter | Failure); } #endif for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Lock_Mutex(&pBuffer->ArenaAllocaters[i].Mutex); Engine_Ref_Lock_Mutex(&pBuffer->AllocationDatas.ArenaAllocaters[i].Mutex); } uint32_t AllocationsToCut = 0; uint32_t AllocationsCount = pBuffer->AllocationDatas.AllocationsCount; if (NewSize < pBuffer->AllocationDatas.BufferSize) { //set all allocations that are out of range to destruct. for (size_t i = NewSize; i < pBuffer->AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &pBuffer->AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.Element.Identifier != 0) { Destroy_Element(pAllocationData->Allocation.Element, true, ThreadIndex); AllocationsToCut++; } } } if (NewSize < pBuffer->BufferSize) { //set all items that are out of range to destruct. //the problem is you arent supposed to destruct allocation instances like this; for (size_t i = NewSize; i < pBuffer->BufferSize;) { Element* pElement = &pBuffer->Buffer[i]; if (pElement->Header.AllocationSize != NULL) { //if it is under newsize then we can assure that it hasnt been counted yet, otherwise it has. if ((pElement->Header.Allocation.Pointer < NewSize)) { Destroy_Element(pElement->Header.Allocation, true, ThreadIndex); AllocationsToCut++; } i += pElement->Header.AllocationSize; } else { i++; } } } //wait for them to destruct while (pBuffer->AllocationDatas.AllocationsCount > (AllocationsCount - AllocationsToCut)) { } Resize_Buffer("Resize_ElementBuffer()"); for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Unlock_Mutex(&pBuffer->ArenaAllocaters[i].Mutex); Engine_Ref_Unlock_Mutex(&pBuffer->AllocationDatas.ArenaAllocaters[i].Mutex); } return (Success); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Destruct Buffers Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define Destroy_Buffer()\ {\ if (pBuffer->Indexes != NULL)\ free(pBuffer->Indexes);\ pBuffer->Indexes = NULL;\ pBuffer->BufferSize = 0;\ if (pBuffer->Buffer != NULL)\ free(pBuffer->Buffer);\ if (pBuffer->ArenaAllocaters != NULL) {\ for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++)\ Destroy_ArenaAllocater(&pBuffer->ArenaAllocaters[i]);\ free(pBuffer->ArenaAllocaters);\ }\ pBuffer->ArenaAllocaters = NULL;\ \ if (pBuffer->AllocationDatas.Indexes != NULL)\ free(pBuffer->AllocationDatas.Indexes);\ pBuffer->AllocationDatas.Indexes = NULL;\ pBuffer->AllocationDatas.BufferSize = 0;\ if (pBuffer->AllocationDatas.Buffer != NULL)\ free(pBuffer->AllocationDatas.Buffer);\ if (pBuffer->AllocationDatas.ArenaAllocaters != NULL) {\ for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++)\ Destroy_ArenaAllocater(&pBuffer->AllocationDatas.ArenaAllocaters[i]);\ free(pBuffer->AllocationDatas.ArenaAllocaters);\ }\ pBuffer->AllocationDatas.ArenaAllocaters = NULL;\ \ memset(pBuffer, 0, sizeof(*pBuffer));\ } /* * Added in 1.0.0 * When a buffer is destroyed all objects within it are also destroyed, you can circumvent this by moving the object. * @param pBuffer refrencing the desired buffer to destroy. * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT Destroy_ObjectBuffer(ObjectBuffer* pBuffer, uint32_t ThreadIndex) { #ifndef NDEBUG if (pBuffer == NULL) { Engine_Ref_ArgsError("Destroy_ObjectBuffer", "pBuffer == NULLPTR"); return (Invalid_Parameter | Failure); } #endif for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Lock_Mutex(&pBuffer->ArenaAllocaters[i].Mutex); Engine_Ref_Lock_Mutex(&pBuffer->AllocationDatas.ArenaAllocaters[i].Mutex); } //set all items in buffer to destruct. for (size_t i = 0; i < pBuffer->AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &pBuffer->AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.Object.Identifier != 0) { Destroy_Object(pAllocationData->Allocation.Object, true, ThreadIndex); } } //wait for all in the buffer to destruct. while (pBuffer->AllocationDatas.AllocationsCount > 0) { } for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Unlock_Mutex(&pBuffer->ArenaAllocaters[i].Mutex); Engine_Ref_Unlock_Mutex(&pBuffer->AllocationDatas.ArenaAllocaters[i].Mutex); } //period between unlock and destruct that is unsafe; //mayby fix it by adding checks in the allocaters; //cleanup. Destroy_Buffer(); return (Success); } /* * Added in 1.0.0 * When a buffer is destroyed all objects within it are also destroyed, you can circumvent this by moving the object. * @param pBuffer refrencing the desired buffer to destroy. * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT Destroy_ResourceHeaderBuffer(ResourceHeaderBuffer* pBuffer, uint32_t ThreadIndex) { #ifndef NDEBUG if (pBuffer == NULL) { Engine_Ref_ArgsError("Destroy_ResourceHeaderBuffer", "pBuffer == NULLPTR"); return (Invalid_Parameter | Failure); } #endif for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Lock_Mutex(&pBuffer->ArenaAllocaters[i].Mutex); Engine_Ref_Lock_Mutex(&pBuffer->AllocationDatas.ArenaAllocaters[i].Mutex); } //set all items in buffer to destruct. for (size_t i = 0; i < pBuffer->AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &pBuffer->AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.ResourceHeader.Identifier != 0) { Destroy_ResourceHeader(pAllocationData->Allocation.ResourceHeader, true, ThreadIndex); } } //wait for all in the buffer to destruct. while (pBuffer->AllocationDatas.AllocationsCount > 0) { } for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Unlock_Mutex(&pBuffer->ArenaAllocaters[i].Mutex); Engine_Ref_Unlock_Mutex(&pBuffer->AllocationDatas.ArenaAllocaters[i].Mutex); } //cleanup. Destroy_Buffer(); return (Success); } /* * Added in 1.0.0 * When a buffer is destroyed all objects within it are also destroyed, you can circumvent this by moving the object. * @param pBuffer refrencing the desired buffer to destroy. * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT Destroy_ElementBuffer(ElementBuffer* pBuffer, uint32_t ThreadIndex) { #ifndef NDEBUG if (pBuffer == NULL) { Engine_Ref_ArgsError("Destroy_ElementBuffer", "pBuffer == NULLPTR"); return (Invalid_Parameter | Failure); } #endif for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Lock_Mutex(&pBuffer->ArenaAllocaters[i].Mutex); Engine_Ref_Lock_Mutex(&pBuffer->AllocationDatas.ArenaAllocaters[i].Mutex); } //set all items in buffer to destruct. for (size_t i = 0; i < pBuffer->AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &pBuffer->AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.Element.Identifier != 0) { Destroy_Element(pAllocationData->Allocation.Element, true, ThreadIndex); } } //wait for all in the buffer to destruct. while (pBuffer->AllocationDatas.AllocationsCount > 0) { } for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Unlock_Mutex(&pBuffer->ArenaAllocaters[i].Mutex); Engine_Ref_Unlock_Mutex(&pBuffer->AllocationDatas.ArenaAllocaters[i].Mutex); } //cleanup. Destroy_Buffer(); return (Success); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Add New Children Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Macro for adding childs to objects. * @param Allocation refrencing the desired object to make child of. * @param Parent refrencing the desired object to make parent of Allocation. * @note Externally Synchronized. */ void Add_ObjectChild(ObjectAllocation Allocation, ObjectAllocation Parent, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ObjectAllocationData(Allocation); AllocationData* pParentAllocationData = Get_ObjectAllocationData(Parent); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Add_ObjectChild()", "Allocation Invalid"); return; } if (pParentAllocationData == NULL) { Engine_Ref_ArgsError("Add_ObjectChild()", "Parent Invalid."); return; } #endif { Object* pParent = Get_ObjectPointer(Parent, true, false, ThreadIndex); if (pParent == NULL) return (Failure); Object* pParentOverlay = (pParent->Header.OverlayPointer != UINT32_MAX) ? Get_ObjectPointerFromPointer(pParent->Header.OverlayPointer) : NULL; if (((pParentOverlay != NULL) ? (pParent->Header.iChildren == pParentOverlay->Header.iChildren) : false)) { //copy new pParent->Header.iChildren = CopyDataN(pParent->Header.iChildren, sizeof(*pParent->Header.iChildren) * pParent->Header.iChildrenSize); } Resize_Array((void**)&pParent->Header.iChildren, pParent->Header.iChildrenSize, pParent->Header.iChildrenSize + 1, sizeof(*pParent->Header.iChildren)); pParent->Header.iChildrenSize = pParent->Header.iChildrenSize + 1; pParent->Header.iChildren[pParent->Header.iChildrenSize - 1] = Allocation; End_ObjectPointer(Parent, true, false, ThreadIndex); } { Object* pChild = Get_ObjectPointer(Allocation, true, false, ThreadIndex); if (pChild == NULL) return (Failure); pChild->Header.iParent = Parent; End_ObjectPointer(Allocation, true, false, ThreadIndex); } } /* * Added in 1.0.0 * Macro for adding childs to objects. * @param Allocation refrencing the desired resourceheader to make child of. * @param Parent refrencing the desired object to make parent of Allocation. * @note Externally Synchronized. */ void Add_Object_ResourceHeaderChild(ResourceHeaderAllocation Allocation, ObjectAllocation Parent, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ResourceHeaderAllocationData(Allocation); AllocationData* pParentAllocationData = Get_ObjectAllocationData(Parent); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Add_Object_ResourceHeaderChild()", "Allocation Invalid"); return; } if (pParentAllocationData == NULL) { Engine_Ref_ArgsError("Add_Object_ResourceHeaderChild()", "Parent Invalid."); return; } #endif { Object* pParent = Get_ObjectPointer(Parent, true, false, ThreadIndex); if (pParent == NULL) return (Failure); Object* pParentOverlay = (pParent->Header.OverlayPointer != UINT32_MAX) ? Get_ObjectPointerFromPointer(pParent->Header.OverlayPointer) : NULL; if (((pParentOverlay != NULL) ? (pParent->Header.iResourceHeaders == pParentOverlay->Header.iResourceHeaders) : false)) { //copy new pParent->Header.iResourceHeaders = CopyDataN(pParent->Header.iResourceHeaders, sizeof(*pParent->Header.iResourceHeaders) * pParent->Header.iResourceHeadersSize); } Resize_Array((void**)&pParent->Header.iResourceHeaders, pParent->Header.iResourceHeadersSize, pParent->Header.iResourceHeadersSize + 1, sizeof(*pParent->Header.iResourceHeaders)); pParent->Header.iResourceHeadersSize = pParent->Header.iResourceHeadersSize + 1; pParent->Header.iResourceHeaders[pParent->Header.iResourceHeadersSize - 1] = Allocation; End_ObjectPointer(Parent, true, false, ThreadIndex); } { ResourceHeader* pResourceHeader = Get_ResourceHeaderPointer(Allocation, true, false, ThreadIndex); if (pResourceHeader == NULL) return (Failure); ResourceHeader* pResourceHeaderOverlay = (pResourceHeader->Header.OverlayPointer != UINT32_MAX) ? Get_ResourceHeaderPointerFromPointer(pResourceHeader->Header.OverlayPointer) : NULL; if (((pResourceHeaderOverlay != NULL) ? (pResourceHeader->Header.iObjects == pResourceHeaderOverlay->Header.iObjects) : false)) { //copy new pResourceHeader->Header.iObjects = CopyDataN(pResourceHeader->Header.iObjects, sizeof(*pResourceHeader->Header.iObjects) * pResourceHeader->Header.iObjectsSize); } Resize_Array((void**)&pResourceHeader->Header.iObjects, pResourceHeader->Header.iObjectsSize, pResourceHeader->Header.iObjectsSize + 1, sizeof(*pResourceHeader->Header.iObjects)); pResourceHeader->Header.iObjectsSize = pResourceHeader->Header.iObjectsSize + 1; pResourceHeader->Header.iObjects[pResourceHeader->Header.iObjectsSize - 1] = Parent; End_ResourceHeaderPointer(Allocation, true, false, ThreadIndex); } } /* * Added in 1.0.0 * Macro for adding childs to objects. * @param Allocation refrencing the desired element to make child of. * @param Parent refrencing the desired resourceheader to make parent of Allocation. * @note Externally Synchronized. */ void Add_ResourceHeader_ElementChild(ElementAllocation Allocation, ResourceHeaderAllocation Parent, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ElementAllocationData(Allocation); AllocationData* pParentAllocationData = Get_ResourceHeaderAllocationData(Parent); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Add_ResourceHeader_ElementChild()", "Allocation Invalid"); return; } if (pParentAllocationData == NULL) { Engine_Ref_ArgsError("Add_ResourceHeader_ElementChild()", "Parent Invalid."); return; } #endif { ResourceHeader* pParent = Get_ResourceHeaderPointer(Parent, true, false, ThreadIndex); if (pParent == NULL) return (Failure); ResourceHeader* pParentOverlay = (pParent->Header.OverlayPointer != UINT32_MAX) ? Get_ResourceHeaderPointerFromPointer(pParent->Header.OverlayPointer) : NULL; if (((pParentOverlay != NULL) ? (pParent->Header.iElements == pParentOverlay->Header.iElements) : false)) { //copy new pParent->Header.iElements = CopyDataN(pParent->Header.iElements, sizeof(*pParent->Header.iElements) * pParent->Header.iElementsSize); } Resize_Array((void**)&pParent->Header.iElements, pParent->Header.iElementsSize, pParent->Header.iElementsSize + 1, sizeof(*pParent->Header.iElements)); pParent->Header.iElementsSize = pParent->Header.iElementsSize + 1; pParent->Header.iElements[pParent->Header.iElementsSize - 1] = Allocation; End_ResourceHeaderPointer(Parent, true, false, ThreadIndex); } { Element* pElement = Get_ElementPointer(Allocation, true, false, ThreadIndex); if (pElement == NULL) return (Failure); Element* pElementOverlay = (pElement->Header.OverlayPointer != UINT32_MAX) ? Get_ElementPointerFromPointer(pElement->Header.OverlayPointer) : NULL; if (((pElementOverlay != NULL) ? (pElement->Header.iResourceHeaders == pElementOverlay->Header.iResourceHeaders) : false)) { //copy new pElement->Header.iResourceHeaders = CopyDataN(pElement->Header.iResourceHeaders, sizeof(*pElement->Header.iResourceHeaders) * pElement->Header.iResourceHeadersSize); } Resize_Array((void**)&pElement->Header.iResourceHeaders, pElement->Header.iResourceHeadersSize, pElement->Header.iResourceHeadersSize + 1, sizeof(*pElement->Header.iResourceHeaders)); pElement->Header.iResourceHeadersSize = pElement->Header.iResourceHeadersSize + 1; pElement->Header.iResourceHeaders[pElement->Header.iResourceHeadersSize - 1] = Parent; End_ElementPointer(Allocation, true, false, ThreadIndex); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Remove Children Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Macro for removing childs from objects. * @param Allocation refrencing the desired object to remove child of. * @param Parent refrencing the desired object to remove parent of Allocation. * @note Externally Synchronized. */ void Remove_ObjectChild(ObjectAllocation Allocation, ObjectAllocation Parent, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ObjectAllocationData(Allocation); AllocationData* pParentAllocationData = Get_ObjectAllocationData(Parent); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Remove_ObjectChild()", "Allocation Invalid"); return; } if (pParentAllocationData == NULL) { Engine_Ref_ArgsError("Remove_ObjectChild", "Parent Invalid."); return; } #endif { Object* pParent = Get_ObjectPointer(Parent, true, false, ThreadIndex); if (pParent == NULL) return (Failure); Object* pParentOverlay = (pParent->Header.OverlayPointer != UINT32_MAX) ? Get_ObjectPointerFromPointer(pParent->Header.OverlayPointer) : NULL; if (((pParentOverlay != NULL) ? (pParent->Header.iChildren == pParentOverlay->Header.iChildren) : false)) { //copy new pParent->Header.iChildren = CopyDataN(pParent->Header.iChildren, sizeof(*pParent->Header.iChildren) * pParent->Header.iChildrenSize); } for (size_t i = 0; i < pParent->Header.iChildrenSize; i++) { if (Compare_ObjectAllocation(pParent->Header.iChildren[i], Allocation) == Success) { RemoveMember_Array((void**)&pParent->Header.iChildren, pParent->Header.iChildrenSize, i, sizeof(*pParent->Header.iChildren), 1); pParent->Header.iChildrenSize = pParent->Header.iChildrenSize - 1; } } End_ObjectPointer(Parent, true, false, ThreadIndex); } { Object* pChild = Get_ObjectPointer(Allocation, true, false, ThreadIndex); if (pChild == NULL) return (Failure); memset(&pChild->Header.iParent, 0, sizeof(pChild->Header.iParent)); End_ObjectPointer(Allocation, true, false, ThreadIndex); } } /* * Added in 1.0.0 * Macro for removing childs from objects. * @param Allocation refrencing the desired resourceheader to remove child of. * @param Parent refrencing the desired object to remove parent of Allocation. * @note Externally Synchronized. */ void Remove_Object_ResourceHeaderChild(ResourceHeaderAllocation Allocation, ObjectAllocation Parent, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ResourceHeaderAllocationData(Allocation); AllocationData* pParentAllocationData = Get_ObjectAllocationData(Parent); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Remove_ResourceHeader_ElementChild()", "Allocation Invalid"); return; } if (pParentAllocationData == NULL) { Engine_Ref_ArgsError("Remove_Object_ResourceHeaderChild", "Parent Invalid."); return; } #endif { Object* pParent = Get_ObjectPointer(Parent, true, false, ThreadIndex); if (pParent == NULL) return (Failure); Object* pParentOverlay = (pParent->Header.OverlayPointer != UINT32_MAX) ? Get_ObjectPointerFromPointer(pParent->Header.OverlayPointer) : NULL; if (((pParentOverlay != NULL) ? (pParent->Header.iResourceHeaders == pParentOverlay->Header.iResourceHeaders) : false)) { //copy new pParent->Header.iResourceHeaders = CopyDataN(pParent->Header.iResourceHeaders, sizeof(*pParent->Header.iResourceHeaders) * pParent->Header.iResourceHeadersSize); } for (size_t i = 0; i < pParent->Header.iResourceHeadersSize; i++) { if (Compare_ResourceHeaderAllocation(pParent->Header.iResourceHeaders[i], Allocation) == Success) { RemoveMember_Array((void**)&pParent->Header.iResourceHeaders, pParent->Header.iResourceHeadersSize, i, sizeof(*pParent->Header.iResourceHeaders), 1); pParent->Header.iResourceHeadersSize = pParent->Header.iResourceHeadersSize - 1; } } End_ObjectPointer(Parent, true, false, ThreadIndex); } { ResourceHeader* pResourceHeader = Get_ResourceHeaderPointer(Allocation, true, false, ThreadIndex); if (pResourceHeader == NULL) return (Failure); ResourceHeader* pResourceHeaderOverlay = (pResourceHeader->Header.OverlayPointer != UINT32_MAX) ? Get_ResourceHeaderPointerFromPointer(pResourceHeader->Header.OverlayPointer) : NULL; if (((pResourceHeaderOverlay != NULL) ? (pResourceHeader->Header.iObjects == pResourceHeaderOverlay->Header.iObjects) : false)) { //copy new pResourceHeader->Header.iObjects = CopyDataN(pResourceHeader->Header.iObjects, sizeof(*pResourceHeader->Header.iObjects) * pResourceHeader->Header.iObjectsSize); } for (size_t i = 0; i < pResourceHeader->Header.iObjectsSize; i++) { if (Compare_ObjectAllocation(pResourceHeader->Header.iObjects[i], Parent) == Success) { RemoveMember_Array((void**)&pResourceHeader->Header.iObjects, pResourceHeader->Header.iObjectsSize, i, sizeof(*pResourceHeader->Header.iObjects), 1); pResourceHeader->Header.iObjectsSize = pResourceHeader->Header.iObjectsSize - 1; } } End_ResourceHeaderPointer(Allocation, true, false, ThreadIndex); } } /* * Added in 1.0.0 * Macro for removing childs from objects. * @param Allocation refrencing the desired element to remove child of. * @param Parent refrencing the desired resourceheader to remove parent of Allocation. * @note Externally Synchronized. */ void Remove_ResourceHeader_ElementChild(ElementAllocation Allocation, ResourceHeaderAllocation Parent, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ElementAllocationData(Allocation); AllocationData* pParentAllocationData = Get_ResourceHeaderAllocationData(Parent); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Remove_ResourceHeader_ElementChild()", "Allocation Invalid"); return; } if (pParentAllocationData == NULL) { Engine_Ref_ArgsError("Remove_ResourceHeader_ElementChild", "Parent Invalid."); return; } #endif { ResourceHeader* pParent = Get_ResourceHeaderPointer(Parent, true, false, ThreadIndex); if (pParent == NULL) return (Failure); ResourceHeader* pParentOverlay = (pParent->Header.OverlayPointer != UINT32_MAX) ? Get_ResourceHeaderPointerFromPointer(pParent->Header.OverlayPointer) : NULL; if (((pParentOverlay != NULL) ? (pParent->Header.iElements == pParentOverlay->Header.iElements) : false)) { //copy new pParent->Header.iElements = CopyDataN(pParent->Header.iElements, sizeof(*pParent->Header.iElements) * pParent->Header.iElementsSize); } for (size_t i = 0; i < pParent->Header.iElementsSize; i++) { if (Compare_ElementAllocation(pParent->Header.iElements[i], Allocation) == Success) { RemoveMember_Array((void**)&pParent->Header.iElements, pParent->Header.iElementsSize, i, sizeof(*pParent->Header.iElements), 1); pParent->Header.iElementsSize = pParent->Header.iElementsSize - 1; } } End_ResourceHeaderPointer(Parent, true, false, ThreadIndex); } { Element* pElement = Get_ElementPointer(Allocation, true, false, ThreadIndex); if (pElement == NULL) return (Failure); Element* pElementOverlay = (pElement->Header.OverlayPointer != UINT32_MAX) ? Get_ElementPointerFromPointer(pElement->Header.OverlayPointer) : NULL; if (((pElementOverlay != NULL) ? (pElement->Header.iResourceHeaders == pElementOverlay->Header.iResourceHeaders) : false)) { //copy new pElement->Header.iResourceHeaders = CopyDataN(pElement->Header.iResourceHeaders, sizeof(*pElement->Header.iResourceHeaders) * pElement->Header.iResourceHeadersSize); } for (size_t i = 0; i < pElement->Header.iResourceHeadersSize; i++) { if (Compare_ResourceHeaderAllocation(pElement->Header.iResourceHeaders[i], Parent) == Success) { RemoveMember_Array((void**)&pElement->Header.iResourceHeaders, pElement->Header.iResourceHeadersSize, i, sizeof(*pElement->Header.iResourceHeaders), 1); pElement->Header.iResourceHeadersSize = pElement->Header.iResourceHeadersSize - 1; } } End_ElementPointer(Allocation, true, false, ThreadIndex); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Scan Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Macro for scanning all childs of an object including childs of their childs. * @param pChilds is a pointer to an array of allocations to return. * @param pChildsSize is a pointer to size of the array to return. * @note Externally Synchronized. */ void Scan_ObjectChilds(ObjectAllocation Allocation, ObjectAllocation** pChilds, uint64_t* pChildsSize, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ObjectAllocationData(Allocation); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Scan_ObjectChilds", "Allocation Invalid."); return; } if (pChilds == NULL) { Engine_Ref_ArgsError("Scan_ObjectChilds()", "pChilds == NULLPTR"); return; } if (pChildsSize == NULL) { Engine_Ref_ArgsError("Scan_ObjectChilds()", "pChildsSize == NULLPTR"); return; } #endif Object* pObject = Get_ObjectPointer(Allocation, false, false, ThreadIndex); if (pObject == NULL) return; for (size_t i = 0; i < pObject->Header.iChildrenSize; i++) { uint64_t ChildsSize = *pChildsSize; Resize_Array((void**)pChilds, ChildsSize, ChildsSize + 1, sizeof(ObjectAllocation)); ObjectAllocation* Childs = *pChilds; Childs[ChildsSize] = pObject->Header.iChildren[i]; *pChildsSize += 1; Scan_ObjectChilds(Allocation, pChilds, pChildsSize, ThreadIndex); } End_ObjectPointer(Allocation, false, false, ThreadIndex); } /* * Added in 1.0.0 * Macro for scanning all parents of an object including parents of their parents * @param pParents is a pointer to an array of allocations to return. * @param pParentsSize is a pointer to size of the array to return. * @note Externally Synchronized. */ void Scan_ObjectParents(ObjectAllocation Allocation, ObjectAllocation** pParents, uint64_t* pParentsSize, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ObjectAllocationData(Allocation); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Scan_ObjectParents", "Allocation Invalid."); return; } if (pParents == NULL) { Engine_Ref_ArgsError("Scan_ObjectParents()", "pParents == NULLPTR"); return; } if (pParentsSize == NULL) { Engine_Ref_ArgsError("Scan_ObjectParents()", "pParentsSize == NULLPTR"); return; } #endif Object* pObject = Get_ObjectPointer(Allocation, false, false, ThreadIndex); if (pObject == NULL) return; if (Get_ObjectAllocationData(pObject->Header.iParent) != NULL) { uint64_t ParentsSize = *pParentsSize; Resize_Array((void**)pParents, ParentsSize, ParentsSize + 1, sizeof(ObjectAllocation)); ObjectAllocation* Parents = *pParents; Parents[ParentsSize] = pObject->Header.iParent; *pParentsSize += 1; Scan_ObjectParents(pObject->Header.iParent, pParents, pParentsSize, ThreadIndex); } End_ObjectPointer(Allocation, false, false, ThreadIndex); } /* * Added in 1.0.0 * Macro for scanning all resourceheader childs of specified identifier of a object. * @param Allocation Allocation to scan from. * @param Identifier desired Identifier to find. * @param pResourceHeaders is a pointer to an array of allocations to return. * @param pResourceHeadersSize is a pointer to size of the array to return. * @note Externally Synchronized. */ void Scan_ObjectResourceHeaders(ObjectAllocation Allocation, ResourceHeaderIdentifier Identifier, ResourceHeaderAllocation** pResourceHeaders, uint64_t* pResourceHeadersSize, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ObjectAllocationData(Allocation); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Scan_ObjectResourceHeaders", "Allocation Invalid."); return; } if (Identifier == NULL) { Engine_Ref_ArgsError("Scan_ObjectResourceHeaders", "Identifier Invalid."); return; } if (pResourceHeaders == NULL) { Engine_Ref_ArgsError("Scan_ObjectResourceHeaders()", "pResourceHeaders == NULLPTR"); return; } if (pResourceHeadersSize == NULL) { Engine_Ref_ArgsError("Scan_ObjectResourceHeaders()", "pResourceHeadersSize == NULLPTR"); return; } #endif Object* pObject = Get_ObjectPointer(Allocation, false, false, ThreadIndex); if (pObject == NULL) return; for (size_t i = 0; i < pObject->Header.iResourceHeadersSize; i++) { if (pObject->Header.iResourceHeaders[i].Identifier == Identifier) { uint64_t ResourceHeadersSize = *pResourceHeadersSize; Resize_Array((void**)pResourceHeaders, ResourceHeadersSize, ResourceHeadersSize + 1, sizeof(ResourceHeaderAllocation)); ResourceHeaderAllocation* ResourceHeaders = *pResourceHeaders; ResourceHeaders[ResourceHeadersSize] = pObject->Header.iResourceHeaders[i]; *pResourceHeadersSize += 1; } } End_ObjectPointer(Allocation, false, false, ThreadIndex); } /* * Added in 1.0.0 * Macro for scanning all element childs of specified identifier of a resourceheader. * @param Allocation Allocation to scan from. * @param Identifier desired Identifier to find. * @param pElements is a pointer to an array of allocations to return. * @param pElementsSize is a pointer to size of the array to return. * @note Externally Synchronized. */ void Scan_ResourceHeaderElements(ResourceHeaderAllocation Allocation, ElementIdentifier Identifier, ElementAllocation** pElements, uint64_t* pElementsSize, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ResourceHeaderAllocationData(Allocation); #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Scan_ResourceHeaderElements", "Allocation Invalid."); return; } if (Identifier == NULL) { Engine_Ref_ArgsError("Scan_ResourceHeaderElements", "Identifier Invalid."); return; } if (pElements == NULL) { Engine_Ref_ArgsError("Scan_ResourceHeaderElements()", "pElements == NULLPTR"); return; } if (pElementsSize == NULL) { Engine_Ref_ArgsError("Scan_ResourceHeaderElements()", "pElementsSize == NULLPTR"); return; } #endif ResourceHeader* pResourceHeader = Get_ResourceHeaderPointer(Allocation, false, false, ThreadIndex); if (pResourceHeader == NULL) return; for (size_t i = 0; i < pResourceHeader->Header.iElementsSize; i++) { if (pResourceHeader->Header.iElements[i].Identifier == Identifier) { uint64_t ElementsSize = *pElementsSize; Resize_Array((void**)pElements, ElementsSize, ElementsSize + 1, sizeof(ElementAllocation)); ElementAllocation* Elements = *pElements; Elements[ElementsSize] = pResourceHeader->Header.iElements[i]; *pElementsSize += 1; } } End_ResourceHeaderPointer(Allocation, false, false, ThreadIndex); } /* * Added in 1.0.0 * Macro for scanning all resourceheader childs of specified identifier of a object, * except unlike Scan_ObjectHeaders() it only returns the first found of specified identifier. * @param Allocation Allocation to scan from. * @param Identifier desired Identifier to find. * @note Externally Synchronized. */ ResourceHeaderAllocation Scan_ObjectResourceHeadersSingle(ObjectAllocation Allocation, ResourceHeaderIdentifier Identifier, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ObjectAllocationData(Allocation); ResourceHeaderAllocation Return = { sizeof(Return) }; #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Scan_ObjectResourceHeadersSingle", "Allocation Invalid."); return Return; } if (Identifier == NULL) { Engine_Ref_ArgsError("Scan_ObjectResourceHeadersSingle", "Identifier Invalid."); return Return; } #endif Object* pObject = Get_ObjectPointer(Allocation, false, false, ThreadIndex); if (pObject == NULL) return; for (size_t i = 0; i < pObject->Header.iResourceHeadersSize; i++) { if (pObject->Header.iResourceHeaders[i].Identifier == Identifier) { Return = pObject->Header.iResourceHeaders[i]; break; } } End_ObjectPointer(Allocation, false, false, ThreadIndex); return Return; } /* * Added in 1.0.0 * Macro for scanning all element childs of specified identifier of a resourceheader. * except unlike Scan_ResourceHeaderElements() it only returns the first found of specified identifier. * @param Allocation Allocation to scan from. * @param Identifier desired Identifier to find. * @note Externally Synchronized. */ ElementAllocation Scan_ResourceHeaderElementsSingle(ResourceHeaderAllocation Allocation, ElementIdentifier Identifier, uint32_t ThreadIndex) { AllocationData* pAllocationData = Get_ResourceHeaderAllocationData(Allocation); ElementAllocation Return = { sizeof(Return) }; #ifndef NDEBUG if (pAllocationData == NULL) { Engine_Ref_ArgsError("Scan_ResourceHeaderElementsSingle", "Allocation Invalid."); return Return; } if (Identifier == NULL) { Engine_Ref_ArgsError("Scan_ResourceHeaderElementsSingle", "Identifier Invalid."); return Return; } #endif ResourceHeader* pResourceHeader = Get_ResourceHeaderPointer(Allocation, false, false, ThreadIndex); if (pResourceHeader == NULL) return; for (size_t i = 0; i < pResourceHeader->Header.iElementsSize; i++) { if (pResourceHeader->Header.iElements[i].Identifier == Identifier) { Return = pResourceHeader->Header.iElements[i]; break; } } End_ResourceHeaderPointer(Allocation, false, false, ThreadIndex); return Return; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Registration Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Registers a Signature struct with the API so you can create objects of that type, This creates an internal refrence to the signature in the API, so do not modify! * @param pSignature is a pointer to the signature to register. * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT Register_ObjectSignature(ObjectSignature* pSignature, uint32_t ThreadIndex) { #ifndef NDEBUG if (pSignature == NULL) { Engine_Ref_ArgsError("Register_ObjectSignature()", "pSignature == NULLPTR"); return (Invalid_Parameter | Failure); } if (pSignature->Identifier == NULL) { Engine_Ref_ArgsError("Register_ObjectSignature()", "pSignature->Identifier == NULL, This is invalid."); return (Invalid_Parameter | Failure); } #endif Engine_Ref_Lock_Mutex(&Utils.ObjectSignaturesMutex); for (size_t i = 0; i < Utils.ObjectSignaturesSize; i++) { if (Utils.ObjectSignatures[i]->Identifier == pSignature->Identifier) { Engine_Ref_ArgsError("Register_ObjectSignature()", "pSignature->Identifier Already Used."); Engine_Ref_Unlock_Mutex(&Utils.ObjectSignaturesMutex); return (Invalid_Parameter | Failure); } } Resize_Array((void**)&Utils.ObjectSignatures, Utils.ObjectSignaturesSize, Utils.ObjectSignaturesSize + 1, sizeof(*Utils.ObjectSignatures)); Utils.ObjectSignatures[Utils.ObjectSignaturesSize] = pSignature; Utils.ObjectSignaturesSize++; Engine_Ref_Unlock_Mutex(&Utils.ObjectSignaturesMutex); return (Success); } /* * Added in 1.0.0 * Registers a Signature struct with the API so you can create objects of that type, This creates an internal refrence to the signature in the API, so do not modify! * @param pSignature is a pointer to the signature to register. * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT Register_ResourceHeaderSignature(ResourceHeaderSignature* pSignature, uint32_t ThreadIndex) { #ifndef NDEBUG if (pSignature == NULL) { Engine_Ref_ArgsError("Register_ResourceHeaderSignature()", "pSignature == NULLPTR"); return (Invalid_Parameter | Failure); } if (pSignature->Identifier == NULL) { Engine_Ref_ArgsError("Register_ResourceHeaderSignature()", "pSignature->Identifier == NULL, This is invalid."); return (Invalid_Parameter | Failure); } #endif Engine_Ref_Lock_Mutex(&Utils.ResourceHeaderSignaturesMutex); for (size_t i = 0; i < Utils.ResourceHeaderSignaturesSize; i++) { if (Utils.ResourceHeaderSignatures[i]->Identifier == pSignature->Identifier) { Engine_Ref_ArgsError("Register_ResourceHeaderSignature()", "pSignature->Identifier Already Used."); Engine_Ref_Unlock_Mutex(&Utils.ResourceHeaderSignaturesMutex); return (Invalid_Parameter | Failure); } } Resize_Array((void**)&Utils.ResourceHeaderSignatures, Utils.ResourceHeaderSignaturesSize, Utils.ResourceHeaderSignaturesSize + 1, sizeof(*Utils.ResourceHeaderSignatures)); Utils.ResourceHeaderSignatures[Utils.ResourceHeaderSignaturesSize] = pSignature; Utils.ResourceHeaderSignaturesSize++; Engine_Ref_Unlock_Mutex(&Utils.ResourceHeaderSignaturesMutex); return (Success); } /* * Added in 1.0.0 * Registers a Signature struct with the API so you can create objects of that type, This creates an internal refrence to the signature in the API, so do not modify! * @param pSignature is a pointer to the signature to register. * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT Register_ElementSignature(ElementSignature* pSignature, uint32_t ThreadIndex) { #ifndef NDEBUG if (pSignature == NULL) { Engine_Ref_ArgsError("Register_ElementSignature()", "pSignature == NULLPTR"); return (Invalid_Parameter | Failure); } if (pSignature->Identifier == NULL) { Engine_Ref_ArgsError("Register_ElementSignature()", "pSignature->Identifier == NULL, This is invalid."); return (Invalid_Parameter | Failure); } #endif Engine_Ref_Lock_Mutex(&Utils.ElementSignaturesMutex); for (size_t i = 0; i < Utils.ElementSignaturesSize; i++) { if (Utils.ElementSignatures[i]->Identifier == pSignature->Identifier) { Engine_Ref_ArgsError("Register_ElementSignature()", "pSignature->Identifier Already Used."); Engine_Ref_Unlock_Mutex(&Utils.ElementSignaturesMutex); return (Invalid_Parameter | Failure); } } Resize_Array((void**)&Utils.ElementSignatures, Utils.ElementSignaturesSize, Utils.ElementSignaturesSize + 1, sizeof(*Utils.ElementSignatures)); Utils.ElementSignatures[Utils.ElementSignaturesSize] = pSignature; Utils.ElementSignaturesSize++; Engine_Ref_Unlock_Mutex(&Utils.ElementSignaturesMutex); return (Success); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //De-Registration Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * Removes the internal refrence to the signature in the API. * @param pSignature is a pointer to the signature to deregister. * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT DeRegister_ObjectSignature(ObjectSignature* pSignature, uint32_t ThreadIndex) { #ifndef NDEBUG if (pSignature == NULL) { Engine_Ref_ArgsError("DeRegister_ObjectSignature()", "pSignature == NULLPTR"); return (Invalid_Parameter | Failure); } /*if (pSignature->AllocationsCount != NULL) { Engine_Ref_ArgsError("DeRegister_ObjectSignature()", "pSignature still has allocations, this is invalid."); return (Invalid_Parameter | Failure); } if (pSignature->ObjectsCount != NULL) { Engine_Ref_ArgsError("DeRegister_ObjectSignature()", "pSignature still has objects, this is invalid."); return (Invalid_Parameter | Failure); }*/ #endif for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Lock_Mutex(&Utils.InternalObjectBuffer.ArenaAllocaters[i].Mutex); Engine_Ref_Lock_Mutex(&Utils.InternalObjectBuffer.AllocationDatas.ArenaAllocaters[i].Mutex); } uint32_t AllocationsToCut = 0; uint32_t AllocationsCount = Utils.InternalObjectBuffer.AllocationDatas.AllocationsCount; //set all allocations that are out of range to destruct. for (size_t i = 0; i < Utils.InternalObjectBuffer.AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &Utils.InternalObjectBuffer.AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.Object.Identifier == pSignature->Identifier) { Destroy_Object(pAllocationData->Allocation.Object, true, ThreadIndex); AllocationsToCut++; } } //wait for them to destruct while (Utils.InternalObjectBuffer.AllocationDatas.AllocationsCount > (AllocationsCount - AllocationsToCut)) { //Engine_Ref_FunctionError("DeRegister_ObjectSignature()", "Waiting", Utils.InternalObjectBuffer.AllocationDatas.AllocationsCount); } for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Unlock_Mutex(&Utils.InternalObjectBuffer.ArenaAllocaters[i].Mutex); Engine_Ref_Unlock_Mutex(&Utils.InternalObjectBuffer.AllocationDatas.ArenaAllocaters[i].Mutex); } Engine_Ref_Lock_Mutex(&Utils.ObjectSignaturesMutex); for (size_t i = 0; i < Utils.ObjectSignaturesSize; i++) { if (Utils.ObjectSignatures[i] == pSignature) { RemoveMember_Array((void**)&Utils.ObjectSignatures, Utils.ObjectSignaturesSize, i, sizeof(*Utils.ObjectSignatures), 1); Utils.ObjectSignaturesSize--; Engine_Ref_Unlock_Mutex(&Utils.ObjectSignaturesMutex); return (Success); } } Engine_Ref_ArgsError("DeRegister_ObjectSignature()", "pSignature Not Found."); Engine_Ref_Unlock_Mutex(&Utils.ObjectSignaturesMutex); return (Invalid_Parameter | Failure); } /* * Added in 1.0.0 * Removes the internal refrence to the signature in the API. * @param pSignature is a pointer to the signature to deregister. * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT DeRegister_ResourceHeaderSignature(ResourceHeaderSignature* pSignature, uint32_t ThreadIndex) { #ifndef NDEBUG if (pSignature == NULL) { Engine_Ref_ArgsError("DeRegister_ResourceHeaderSignature()", "pSignature == NULLPTR"); return (Invalid_Parameter | Failure); } /*if (pSignature->AllocationsCount != NULL) { Engine_Ref_ArgsError("DeRegister_ResourceHeaderSignature()", "pSignature still has allocations, this is invalid."); return (Invalid_Parameter | Failure); } if (pSignature->ResourceHeadersCount != NULL) { Engine_Ref_ArgsError("DeRegister_ResourceHeaderSignature()", "pSignature still has resourceheaders, this is invalid."); return (Invalid_Parameter | Failure); }*/ #endif for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Lock_Mutex(&Utils.InternalResourceHeaderBuffer.ArenaAllocaters[i].Mutex); Engine_Ref_Lock_Mutex(&Utils.InternalResourceHeaderBuffer.AllocationDatas.ArenaAllocaters[i].Mutex); } uint32_t AllocationsToCut = 0; uint32_t AllocationsCount = Utils.InternalResourceHeaderBuffer.AllocationDatas.AllocationsCount; //set all allocations that are out of range to destruct. for (size_t i = 0; i < Utils.InternalResourceHeaderBuffer.AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &Utils.InternalResourceHeaderBuffer.AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.ResourceHeader.Identifier == pSignature->Identifier) { Destroy_ResourceHeader(pAllocationData->Allocation.ResourceHeader, true, ThreadIndex); AllocationsToCut++; } } //wait for them to destruct while (Utils.InternalResourceHeaderBuffer.AllocationDatas.AllocationsCount > (AllocationsCount - AllocationsToCut)) { // Engine_Ref_FunctionError("DeRegister_ResourceHeaderSignature()", "Waiting", Utils.InternalResourceHeaderBuffer.AllocationDatas.AllocationsCount); } for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Unlock_Mutex(&Utils.InternalResourceHeaderBuffer.ArenaAllocaters[i].Mutex); Engine_Ref_Unlock_Mutex(&Utils.InternalResourceHeaderBuffer.AllocationDatas.ArenaAllocaters[i].Mutex); } Engine_Ref_Lock_Mutex(&Utils.ResourceHeaderSignaturesMutex); for (size_t i = 0; i < Utils.ResourceHeaderSignaturesSize; i++) { if (Utils.ResourceHeaderSignatures[i] == pSignature) { RemoveMember_Array((void**)&Utils.ResourceHeaderSignatures, Utils.ResourceHeaderSignaturesSize, i, sizeof(*Utils.ResourceHeaderSignatures), 1); Utils.ResourceHeaderSignaturesSize--; Engine_Ref_Unlock_Mutex(&Utils.ResourceHeaderSignaturesMutex); return (Success); } } Engine_Ref_ArgsError("DeRegister_ResourceHeaderSignature()", "pSignature Not Found."); Engine_Ref_Unlock_Mutex(&Utils.ResourceHeaderSignaturesMutex); return (Invalid_Parameter | Failure); } /* * Added in 1.0.0 * Removes the internal refrence to the signature in the API. * @param pSignature is a pointer to the signature to deregister. * @note Thread Safe. * @note Internally Synchronized. */ TEXRESULT DeRegister_ElementSignature(ElementSignature* pSignature, uint32_t ThreadIndex) { #ifndef NDEBUG if (pSignature == NULL) { Engine_Ref_ArgsError("DeRegister_ElementSignature()", "pSignature == NULLPTR"); return (Invalid_Parameter | Failure); } /* if (pSignature->AllocationsCount != NULL) { Engine_Ref_ArgsError("DeRegister_ElementSignature()", "pSignature still has allocations, this is invalid."); return (Invalid_Parameter | Failure); } if (pSignature->ElementsCount != NULL) { Engine_Ref_ArgsError("DeRegister_ElementSignature()", "pSignature still has elements, this is invalid."); return (Invalid_Parameter | Failure); }*/ #endif for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Lock_Mutex(&Utils.InternalElementBuffer.ArenaAllocaters[i].Mutex); Engine_Ref_Lock_Mutex(&Utils.InternalElementBuffer.AllocationDatas.ArenaAllocaters[i].Mutex); } uint32_t AllocationsToCut = 0; uint32_t AllocationsCount = Utils.InternalElementBuffer.AllocationDatas.AllocationsCount; //set all allocations that are out of range to destruct. for (size_t i = 0; i < Utils.InternalElementBuffer.AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &Utils.InternalElementBuffer.AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.Element.Identifier == pSignature->Identifier) { Destroy_Element(pAllocationData->Allocation.Element, true, ThreadIndex); AllocationsToCut++; } } //wait for them to destruct while (Utils.InternalElementBuffer.AllocationDatas.AllocationsCount > (AllocationsCount - AllocationsToCut)) { //Engine_Ref_FunctionError("DeRegister_ElementSignature()", "Waiting", Utils.InternalElementBuffer.AllocationDatas.AllocationsCount); } for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { //Engine_Ref_Unlock_Mutex(&Utils.InternalElementBuffer.ArenaAllocaters[i].Mutex); Engine_Ref_Unlock_Mutex(&Utils.InternalElementBuffer.AllocationDatas.ArenaAllocaters[i].Mutex); } Engine_Ref_Lock_Mutex(&Utils.ElementSignaturesMutex); for (size_t i = 0; i < Utils.ElementSignaturesSize; i++) { if (Utils.ElementSignatures[i] == pSignature) { RemoveMember_Array((void**)&Utils.ElementSignatures, Utils.ElementSignaturesSize, i, sizeof(*Utils.ElementSignatures), 1); Utils.ElementSignaturesSize--; Engine_Ref_Unlock_Mutex(&Utils.ElementSignaturesMutex); return (Success); } } Engine_Ref_ArgsError("DeRegister_ElementSignature()", "pSignature Not Found."); Engine_Ref_Unlock_Mutex(&Utils.ElementSignaturesMutex); return (Invalid_Parameter | Failure); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Binary Export/Import Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Added in 1.0.0 * writes all objects into file, regardless of anything. * @param Path file path to save to, C format. * @note Thread Safe. */ TEXRESULT Write_TEIF(const UTF8* Path, uint32_t ThreadIndex) { #ifndef NDEBUG if (Path == NULL) { Engine_Ref_ArgsError("Read_TEIF()", "Path == NULLPTR"); return (Invalid_Parameter | Failure); } #endif FILE* file = fopen((char*)Path, "wb"); //open file if (file == NULL) { Engine_Ref_ArgsError("Write_TEIF()", "Failed to open file."); return (Invalid_Parameter | Failure); } uint64_t FinalObjectSize = 0; uint64_t FinalResourceHeaderSize = 0; uint64_t FinalElementSize = 0; uint64_t FinalBufferSize = 0; for (size_t i = 0; i < Utils.InternalObjectBuffer.AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &Utils.InternalObjectBuffer.AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.Object.Identifier != 0) { Object* pObject = Get_ObjectPointer(pAllocationData->Allocation.Object, false, false, ThreadIndex); if (pObject != NULL) { ObjectSignature* pSignature = NULL; Find_ObjectSignature(pObject->Header.Allocation.Identifier, &pSignature); if (pSignature->Packer != NULL) { Pack_ObjectTemplate* func = *pSignature->Packer; func(pObject, NULL, &FinalBufferSize, NULL, ThreadIndex); } FinalBufferSize += sizeof(*pObject->Header.iResourceHeaders) * pObject->Header.iResourceHeadersSize; FinalBufferSize += sizeof(*pObject->Header.iChildren) * pObject->Header.iChildrenSize; if (pObject->Header.Name != NULL) FinalBufferSize += strlen((const char*)pObject->Header.Name) + 1; FinalObjectSize += pObject->Header.AllocationSize; //End_ObjectPointer(i, false, ThreadIndex); } } } for (size_t i = 0; i < Utils.InternalResourceHeaderBuffer.AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &Utils.InternalResourceHeaderBuffer.AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.ResourceHeader.Identifier != 0) { ResourceHeader* pResourceHeader = Get_ResourceHeaderPointer(pAllocationData->Allocation.ResourceHeader, false, false, ThreadIndex); if (pResourceHeader != NULL) { ResourceHeaderSignature* pSignature = NULL; Find_ResourceHeaderSignature(pResourceHeader->Header.Allocation.Identifier, &pSignature); if (pSignature->Packer != NULL) { Pack_ResourceHeaderTemplate* func = *pSignature->Packer; func(pResourceHeader, NULL, &FinalBufferSize, NULL, ThreadIndex); } FinalBufferSize += sizeof(*pResourceHeader->Header.iElements) * pResourceHeader->Header.iElementsSize; FinalBufferSize += sizeof(*pResourceHeader->Header.iObjects) * pResourceHeader->Header.iObjectsSize; if (pResourceHeader->Header.Name != NULL) FinalBufferSize += strlen((const char*)pResourceHeader->Header.Name) + 1; FinalResourceHeaderSize += pResourceHeader->Header.AllocationSize; //End_ResourceHeaderPointer(i, false, ThreadIndex); } } } for (size_t i = 0; i < Utils.InternalElementBuffer.AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &Utils.InternalElementBuffer.AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.Element.Identifier != 0) { Element* pElement = Get_ElementPointer(pAllocationData->Allocation.Element, false, false, ThreadIndex); if (pElement != NULL) { ElementSignature* pSignature = NULL; Find_ElementSignature(pElement->Header.Allocation.Identifier, &pSignature); if (pSignature->Packer != NULL) { Pack_ElementTemplate* func = *pSignature->Packer; func(pElement, NULL, &FinalBufferSize, NULL, ThreadIndex); } FinalBufferSize += sizeof(*pElement->Header.iResourceHeaders) * pElement->Header.iResourceHeadersSize; if (pElement->Header.Name != NULL) FinalBufferSize += strlen((const char*)pElement->Header.Name) + 1; FinalElementSize += pElement->Header.AllocationSize; //End_ElementPointer(i, false, ThreadIndex); } } } TEIF_HEADER header; memset(&header, 0, sizeof(header)); header.filecode[0] = 'T'; header.filecode[1] = 'E'; header.filecode[2] = 'I'; header.filecode[3] = 'F'; Object* ObjectsData = NULL; uint64_t FinalObjectPointer = 0; if (FinalObjectSize != NULL) { ObjectsData = (Object*)malloc(FinalObjectSize * sizeof(Object)); if (ObjectsData == NULL) { Engine_Ref_ArgsError("Write_TEIF()", "Out Of Memory."); return (Out_Of_Memory_Result | Failure); } } ResourceHeader* ResourceHeadersData = NULL; uint64_t FinalResourceHeaderPointer = 0; if (FinalResourceHeaderSize != NULL) { ResourceHeadersData = (ResourceHeader*)malloc(FinalResourceHeaderSize * sizeof(ResourceHeader)); if (ResourceHeadersData == NULL) { Engine_Ref_ArgsError("Write_TEIF()", "Out Of Memory."); return (Out_Of_Memory_Result | Failure); } } Element* ElementsData = NULL; uint64_t FinalElementPointer = 0; if (FinalElementSize != NULL) { ElementsData = (Element*)malloc(FinalElementSize * sizeof(Element)); if (ElementsData == NULL) { Engine_Ref_ArgsError("Write_TEIF()", "Out Of Memory."); return (Out_Of_Memory_Result | Failure); } } uint8_t* MiscDataBuffer = NULL; uint64_t FinalBufferPointer = 0; if (FinalBufferSize != NULL) { MiscDataBuffer = (uint8_t*)malloc(FinalBufferSize); if (MiscDataBuffer == NULL) { Engine_Ref_ArgsError("Write_TEIF()", "Out Of Memory."); return (Out_Of_Memory_Result | Failure); } } for (size_t i = 0; i < Utils.InternalObjectBuffer.AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &Utils.InternalObjectBuffer.AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.Object.Identifier != 0) { Object* pObject = Get_ObjectPointer(pAllocationData->Allocation.Object, false, true, ThreadIndex); if (pObject != NULL) { memcpy(&ObjectsData[FinalObjectPointer], pObject, pObject->Header.AllocationSize * sizeof(Object)); Object* pCopiedObject = &ObjectsData[FinalObjectPointer]; ObjectSignature* pSignature = NULL; Find_ObjectSignature(pObject->Header.Allocation.Identifier, &pSignature); if (pSignature->Packer != NULL) { Pack_ObjectTemplate* func = *pSignature->Packer; func(pObject, pCopiedObject, &FinalBufferPointer, MiscDataBuffer, ThreadIndex); } if (pObject->Header.iResourceHeadersSize != NULL) { memcpy((void*)((uint64_t)MiscDataBuffer + FinalBufferPointer), pObject->Header.iResourceHeaders, sizeof(*pObject->Header.iResourceHeaders) * pObject->Header.iResourceHeadersSize); pCopiedObject->Header.iResourceHeaders = (ResourceHeaderAllocation*)FinalBufferPointer; FinalBufferPointer += sizeof(*pObject->Header.iResourceHeaders) * pObject->Header.iResourceHeadersSize; } if (pObject->Header.iChildrenSize != NULL) { memcpy((void*)((uint64_t)MiscDataBuffer + FinalBufferPointer), pObject->Header.iChildren, sizeof(*pObject->Header.iChildren) * pObject->Header.iChildrenSize); pCopiedObject->Header.iChildren = (ObjectAllocation*)FinalBufferPointer; FinalBufferPointer += sizeof(*pObject->Header.iChildren) * pObject->Header.iChildrenSize; } if (pObject->Header.Name != NULL) { memcpy((void*)((uint64_t)MiscDataBuffer + FinalBufferPointer), pObject->Header.Name, strlen((char*)pObject->Header.Name) + 1); pCopiedObject->Header.Name = (UTF8*)FinalBufferPointer; FinalBufferPointer += strlen((char*)pObject->Header.Name) + 1; } FinalObjectPointer += pObject->Header.AllocationSize; End_ObjectPointer(pAllocationData->Allocation.Object, false, true, ThreadIndex); End_ObjectPointer(pAllocationData->Allocation.Object, false, false, ThreadIndex); } } } for (size_t i = 0; i < Utils.InternalResourceHeaderBuffer.AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &Utils.InternalResourceHeaderBuffer.AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.ResourceHeader.Identifier != 0) { ResourceHeader* pResourceHeader = Get_ResourceHeaderPointer(pAllocationData->Allocation.ResourceHeader, false, true, ThreadIndex); if (pResourceHeader != NULL) { memcpy(&ResourceHeadersData[FinalResourceHeaderPointer], pResourceHeader, pResourceHeader->Header.AllocationSize * sizeof(ResourceHeader)); ResourceHeader* pCopiedResourceHeader = &ResourceHeadersData[FinalResourceHeaderPointer]; ResourceHeaderSignature* pSignature = NULL; Find_ResourceHeaderSignature(pResourceHeader->Header.Allocation.Identifier, &pSignature); if (pSignature->Packer != NULL) { Pack_ResourceHeaderTemplate* func = *pSignature->Packer; func(pResourceHeader, pCopiedResourceHeader, &FinalBufferPointer, MiscDataBuffer, ThreadIndex); } if (pResourceHeader->Header.iElementsSize != NULL) { memcpy((void*)((uint64_t)MiscDataBuffer + FinalBufferPointer), pResourceHeader->Header.iElements, sizeof(*pResourceHeader->Header.iElements) * pResourceHeader->Header.iElementsSize); pCopiedResourceHeader->Header.iElements = (ElementAllocation*)FinalBufferPointer; FinalBufferPointer += sizeof(*pResourceHeader->Header.iElements) * pResourceHeader->Header.iElementsSize; } if (pResourceHeader->Header.iObjectsSize != NULL) { memcpy((void*)((uint64_t)MiscDataBuffer + FinalBufferPointer), pResourceHeader->Header.iObjects, sizeof(*pResourceHeader->Header.iObjects) * pResourceHeader->Header.iObjectsSize); pCopiedResourceHeader->Header.iObjects = (ObjectAllocation*)FinalBufferPointer; FinalBufferPointer += sizeof(*pResourceHeader->Header.iObjects) * pResourceHeader->Header.iObjectsSize; } if (pResourceHeader->Header.Name != NULL) { memcpy((void*)((uint64_t)MiscDataBuffer + FinalBufferPointer), pResourceHeader->Header.Name, strlen((char*)pResourceHeader->Header.Name) + 1); pCopiedResourceHeader->Header.Name = (UTF8*)FinalBufferPointer; FinalBufferPointer += strlen((char*)pResourceHeader->Header.Name) + 1; } FinalResourceHeaderPointer += pResourceHeader->Header.AllocationSize; End_ResourceHeaderPointer(pAllocationData->Allocation.ResourceHeader, false, true, ThreadIndex); End_ResourceHeaderPointer(pAllocationData->Allocation.ResourceHeader, false, false, ThreadIndex); } } } for (size_t i = 0; i < Utils.InternalElementBuffer.AllocationDatas.BufferSize; i++) { AllocationData* pAllocationData = &Utils.InternalElementBuffer.AllocationDatas.Buffer[i]; if (pAllocationData->Allocation.Element.Identifier != 0) { Element* pElement = Get_ElementPointer(pAllocationData->Allocation.Element, false, true, ThreadIndex); if (pElement != NULL) { memcpy(&ElementsData[FinalElementPointer], pElement, pElement->Header.AllocationSize * sizeof(Element)); Element* pCopiedElement = &ElementsData[FinalElementPointer]; ElementSignature* pSignature = NULL; Find_ElementSignature(pElement->Header.Allocation.Identifier, &pSignature); if (pSignature->Packer != NULL) { Pack_ElementTemplate* func = *pSignature->Packer; func(pElement, pCopiedElement, &FinalBufferPointer, MiscDataBuffer, ThreadIndex); } if (pElement->Header.iResourceHeadersSize != NULL) { memcpy((void*)((uint64_t)MiscDataBuffer + FinalBufferPointer), pElement->Header.iResourceHeaders, sizeof(*pElement->Header.iResourceHeaders) * pElement->Header.iResourceHeadersSize); pCopiedElement->Header.iResourceHeaders = (ResourceHeaderAllocation*)FinalBufferPointer; FinalBufferPointer += sizeof(*pElement->Header.iResourceHeaders) * pElement->Header.iResourceHeadersSize; } if (pElement->Header.Name != NULL) { memcpy((void*)((uint64_t)MiscDataBuffer + FinalBufferPointer), pElement->Header.Name, strlen((char*)pElement->Header.Name) + 1); pCopiedElement->Header.Name = (UTF8*)FinalBufferPointer; FinalBufferPointer += strlen((char*)pElement->Header.Name) + 1; } FinalElementPointer += pElement->Header.AllocationSize; End_ElementPointer(pAllocationData->Allocation.Element, false, true, ThreadIndex); End_ElementPointer(pAllocationData->Allocation.Element, false, false, ThreadIndex); } } } header.DataBufferOffset = sizeof(TEIF_HEADER); header.DataBufferSize = FinalBufferSize; header.ObjectsOffset = sizeof(TEIF_HEADER) + (FinalBufferSize); header.ObjectsSize = FinalObjectSize; header.ResourceHeadersOffset = sizeof(TEIF_HEADER) + (FinalBufferSize + (FinalObjectSize * sizeof(Object))); header.ResourceHeadersSize = FinalResourceHeaderSize; header.ElementsOffset = sizeof(TEIF_HEADER) + (FinalBufferSize + (FinalObjectSize * sizeof(Object)) + (FinalResourceHeaderSize * sizeof(ResourceHeader))); header.ElementsSize = FinalElementSize; fwrite(&header, sizeof(TEIF_HEADER), 1, file); if (FinalBufferSize != NULL) fwrite(MiscDataBuffer, sizeof(uint8_t), FinalBufferSize, file); if (FinalObjectSize != NULL) fwrite(ObjectsData, sizeof(Object), FinalObjectSize, file); if (FinalResourceHeaderSize != NULL) fwrite(ResourceHeadersData, sizeof(ResourceHeader), FinalResourceHeaderSize, file); if (FinalElementSize != NULL) fwrite(ElementsData, sizeof(Element), FinalElementSize, file); if (FinalBufferSize != NULL) free(MiscDataBuffer); if (FinalObjectSize != NULL) free(ObjectsData); if (FinalResourceHeaderSize != NULL) free(ResourceHeadersData); if (FinalElementSize != NULL) free(ElementsData); fclose(file); return Success; } /* * Added in 1.0.0 * reads objects from file and imparts them * cant do partial load (Yet), whole system will be overwrriten. * @param Path file path to load from, C format. * @note Thread Safe. */ TEXRESULT Read_TEIF(const UTF8* Path, uint32_t ThreadIndex) { TEXRESULT tres = Success; #ifndef NDEBUG if (Path == NULL) { Engine_Ref_ArgsError("Read_TEIF()", "Path == NULLPTR"); return (Invalid_Parameter | Failure); } #endif FileData data = { 0, 0 }; Open_Data(&data, Path); if (data.pData == NULL) { Engine_Ref_ArgsError("Read_TEIF()", "Failed to open file."); return (Invalid_Parameter | Failure); } TEIF_HEADER* pHeader = (TEIF_HEADER*)data.pData; if (strncmp(pHeader->filecode, "TEIF", 4) != 0) { Engine_Ref_ArgsError("Read_TEIF()", "Filecode Not Equal To TEIF, Invalid File Format!"); return (Invalid_Format | Failure); } Object* pObjects = (Object*)((void*)((uint64_t)data.pData + (uint64_t)pHeader->ObjectsOffset)); uint64_t ObjectsSize = pHeader->ObjectsSize; ResourceHeader* pResourceHeaders = (ResourceHeader*)((void*)((uint64_t)data.pData + (uint64_t)pHeader->ResourceHeadersOffset)); uint64_t ResourceHeadersSize = pHeader->ResourceHeadersSize; Element* pElements = (Element*)((void*)((uint64_t)data.pData + (uint64_t)pHeader->ElementsOffset)); uint64_t ElementsSize = pHeader->ElementsSize; uint8_t* pDataBuffer = (uint8_t*)((void*)((uint64_t)data.pData + (uint64_t)pHeader->DataBufferOffset)); for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { Engine_Ref_Lock_Mutex(&Utils.InternalObjectBuffer.AllocationDatas.ArenaAllocaters[i].Mutex); Engine_Ref_Lock_Mutex(&Utils.InternalResourceHeaderBuffer.AllocationDatas.ArenaAllocaters[i].Mutex); Engine_Ref_Lock_Mutex(&Utils.InternalElementBuffer.AllocationDatas.ArenaAllocaters[i].Mutex); } Engine_Ref_FunctionError("TESETTES", "T", 0); //place items in the buffers and unpack them for (size_t i = 0; i < ObjectsSize;) { Object* pObject = &pObjects[i]; ObjectSignature* pSignature = NULL; Find_ObjectSignature(pObject->Header.Allocation.Identifier, &pSignature); AllocationData* pAllocationData = &Utils.InternalObjectBuffer.AllocationDatas.Buffer[pObject->Header.Allocation.Pointer]; //check if that pointer is already used. if (pAllocationData->Allocation.Object.Identifier != 0) { //figure out what to do if pointer is used.; Engine_Ref_FunctionError("Read_TEIF()", "Object Pointer Conflict, Can't Read TEIF file if its gonna overwrite existing allocations. Pointer == ", pObject->Header.Allocation.Pointer); } memset(pAllocationData, 0, sizeof(*pAllocationData)); //set all internal data to invalid number for (size_t i = 0; i < maxthreads; i++) c89atomic_store_32(&pAllocationData->Threads[i].Pointer, UINT32_MAX); c89atomic_store_32(&pAllocationData->LatestPointer, UINT32_MAX); //setting values to make allocation valid. c89atomic_fetch_add_32(&Utils.InternalObjectBuffer.AllocationsCount, 1); c89atomic_store_32(&pAllocationData->Allocation.Object.Identifier, pObject->Header.Allocation.Identifier); c89atomic_store_32(&pAllocationData->Allocation.Object.Pointer, pObject->Header.Allocation.Pointer); uint32_t Pointer = 0; if ((tres = Allocate_Object(pSignature, pObject->Header.AllocationSize, pObject->Header.Allocation.Identifier, pObject->Header.Allocation, &Pointer, ThreadIndex)) != Success) return tres; Object* pCopiedObject = &Utils.InternalObjectBuffer.Buffer[Pointer]; memcpy(pCopiedObject, pObject, pObject->Header.AllocationSize * sizeof(*pObject)); if (pObject->Header.iResourceHeadersSize != NULL) { pCopiedObject->Header.iResourceHeaders = (ResourceHeaderAllocation*)malloc(sizeof(*pCopiedObject->Header.iResourceHeaders) * pObject->Header.iResourceHeadersSize); memcpy(pCopiedObject->Header.iResourceHeaders, (void*)((uint64_t)pDataBuffer + (uint64_t)pObject->Header.iResourceHeaders), sizeof(*pCopiedObject->Header.iResourceHeaders) * pObject->Header.iResourceHeadersSize); } if (pObject->Header.iChildrenSize != NULL) { pCopiedObject->Header.iChildren = (ObjectAllocation*)malloc(sizeof(*pCopiedObject->Header.iChildren) * pObject->Header.iChildrenSize); memcpy(pCopiedObject->Header.iChildren, (void*)((uint64_t)pDataBuffer + (uint64_t)pObject->Header.iChildren), sizeof(*pCopiedObject->Header.iChildren) * pObject->Header.iChildrenSize); } if (pObject->Header.Name != NULL) { const UTF8* pName = (UTF8*)((void*)((uint64_t)pDataBuffer + (uint64_t)pObject->Header.Name)); pCopiedObject->Header.Name = (UTF8*)malloc(strlen((char*)pName) + 1); memcpy((void*)pCopiedObject->Header.Name, pName, strlen((char*)pName) + 1); } if (pSignature->UnPacker != NULL) { UnPack_ObjectTemplate* func = *pSignature->UnPacker; func(pObject, pCopiedObject, pDataBuffer, ThreadIndex); } c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, Pointer); c89atomic_store_32(&pAllocationData->LatestPointer, Pointer); ReCreate_Object(pAllocationData->Allocation.Object, ThreadIndex); i += pObject->Header.AllocationSize; } for (size_t i = 0; i < ResourceHeadersSize;) { ResourceHeader* pResourceHeader = &pResourceHeaders[i]; ResourceHeaderSignature* pSignature = NULL; Find_ResourceHeaderSignature(pResourceHeader->Header.Allocation.Identifier, &pSignature); AllocationData* pAllocationData = &Utils.InternalResourceHeaderBuffer.AllocationDatas.Buffer[pResourceHeader->Header.Allocation.Pointer]; //check if that pointer is already used. if (pAllocationData->Allocation.ResourceHeader.Identifier != 0) { //figure out what to do if pointer is used.; Engine_Ref_FunctionError("Read_TEIF()", "ResourceHeader Pointer Conflict, Can't Read TEIF file if its gonna overwrite existing allocations. Pointer == ", pResourceHeader->Header.Allocation.Pointer); } memset(pAllocationData, 0, sizeof(*pAllocationData)); //set all internal data to invalid number for (size_t i = 0; i < maxthreads; i++) c89atomic_store_32(&pAllocationData->Threads[i].Pointer, UINT32_MAX); c89atomic_store_32(&pAllocationData->LatestPointer, UINT32_MAX); //setting values to make allocation valid. c89atomic_fetch_add_32(&Utils.InternalResourceHeaderBuffer.AllocationsCount, 1); c89atomic_store_32(&pAllocationData->Allocation.ResourceHeader.Identifier, pResourceHeader->Header.Allocation.Identifier); c89atomic_store_32(&pAllocationData->Allocation.ResourceHeader.Pointer, pResourceHeader->Header.Allocation.Pointer); uint32_t Pointer = 0; if ((tres = Allocate_ResourceHeader(pSignature, pResourceHeader->Header.AllocationSize, pResourceHeader->Header.Allocation.Identifier, pResourceHeader->Header.Allocation, &Pointer, ThreadIndex)) != Success) return tres; ResourceHeader* pCopiedResourceHeader = &Utils.InternalResourceHeaderBuffer.Buffer[Pointer]; memcpy(pCopiedResourceHeader, pResourceHeader, pResourceHeader->Header.AllocationSize * sizeof(*pResourceHeader)); if (pResourceHeader->Header.iElementsSize != NULL) { pCopiedResourceHeader->Header.iElements = (ElementAllocation*)malloc(sizeof(*pResourceHeader->Header.iElements) * pResourceHeader->Header.iElementsSize); memcpy(pCopiedResourceHeader->Header.iElements, (void*)((uint64_t)pDataBuffer + (uint64_t)pResourceHeader->Header.iElements), sizeof(*pResourceHeader->Header.iElements) * pResourceHeader->Header.iElementsSize); } if (pResourceHeader->Header.iObjectsSize != NULL) { pCopiedResourceHeader->Header.iObjects = (ObjectAllocation*)malloc(sizeof(*pResourceHeader->Header.iObjects) * pResourceHeader->Header.iObjectsSize); memcpy(pCopiedResourceHeader->Header.iObjects, (void*)((uint64_t)pDataBuffer + (uint64_t)pResourceHeader->Header.iObjects), sizeof(*pResourceHeader->Header.iObjects) * pResourceHeader->Header.iObjectsSize); } if (pResourceHeader->Header.Name != NULL) { const UTF8* pName = (UTF8*)((void*)((uint64_t)pDataBuffer + (uint64_t)pResourceHeader->Header.Name)); pCopiedResourceHeader->Header.Name = (UTF8*)malloc(strlen((char*)pName) + 1); memcpy((void*)pCopiedResourceHeader->Header.Name, pName, strlen((char*)pName) + 1); } if (pSignature->UnPacker != NULL) { UnPack_ResourceHeaderTemplate* func = *pSignature->UnPacker; func(pResourceHeader, pCopiedResourceHeader, pDataBuffer, ThreadIndex); } c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, Pointer); c89atomic_store_32(&pAllocationData->LatestPointer, Pointer); ReCreate_ResourceHeader(pAllocationData->Allocation.ResourceHeader, ThreadIndex); i += pResourceHeader->Header.AllocationSize; } for (size_t i = 0; i < ElementsSize;) { Element* pElement = &pElements[i]; ElementSignature* pSignature = NULL; Find_ElementSignature(pElement->Header.Allocation.Identifier, &pSignature); AllocationData* pAllocationData = &Utils.InternalElementBuffer.AllocationDatas.Buffer[pElement->Header.Allocation.Pointer]; //check if that pointer is already used. if (pAllocationData->Allocation.Element.Identifier != 0) { //figure out what to do if pointer is used.; Engine_Ref_FunctionError("Read_TEIF()", "Element Pointer Conflict, Can't Read TEIF file if its gonna overwrite existing allocations. Pointer == ", pElement->Header.Allocation.Pointer); } memset(pAllocationData, 0, sizeof(*pAllocationData)); //set all internal data to invalid number for (size_t i = 0; i < maxthreads; i++) c89atomic_store_32(&pAllocationData->Threads[i].Pointer, UINT32_MAX); c89atomic_store_32(&pAllocationData->LatestPointer, UINT32_MAX); //setting values to make allocation valid. c89atomic_fetch_add_32(&Utils.InternalElementBuffer.AllocationsCount, 1); c89atomic_store_32(&pAllocationData->Allocation.Element.Identifier, pElement->Header.Allocation.Identifier); c89atomic_store_32(&pAllocationData->Allocation.Element.Pointer, pElement->Header.Allocation.Pointer); uint32_t Pointer = 0; if ((tres = Allocate_Element(pSignature, pElement->Header.AllocationSize, pElement->Header.Allocation.Identifier, pElement->Header.Allocation, &Pointer, ThreadIndex)) != Success) return tres; Element* pCopiedElement = &Utils.InternalElementBuffer.Buffer[Pointer]; memcpy(pCopiedElement, pElement, pElement->Header.AllocationSize * sizeof(*pElement)); if (pElement->Header.iResourceHeadersSize != NULL) { pCopiedElement->Header.iResourceHeaders = (ResourceHeaderAllocation*)malloc(sizeof(*pElement->Header.iResourceHeaders) * pElement->Header.iResourceHeadersSize); memcpy(pCopiedElement->Header.iResourceHeaders, (void*)((uint64_t)pDataBuffer + (uint64_t)pElement->Header.iResourceHeaders), sizeof(*pElement->Header.iResourceHeaders) * pElement->Header.iResourceHeadersSize); } if (pElement->Header.Name != NULL) { const UTF8* pName = (UTF8*)((void*)((uint64_t)pDataBuffer + (uint64_t)pElement->Header.Name)); pCopiedElement->Header.Name = (UTF8*)malloc(strlen((char*)pName) + 1); memcpy((void*)pCopiedElement->Header.Name, pName, strlen((char*)pName) + 1); } if (pSignature->UnPacker != NULL) { UnPack_ElementTemplate* func = *pSignature->UnPacker; func(pElement, pCopiedElement, pDataBuffer, ThreadIndex); } c89atomic_store_32(&pAllocationData->Threads[ThreadIndex].Pointer, Pointer); c89atomic_store_32(&pAllocationData->LatestPointer, Pointer); ReCreate_Element(pAllocationData->Allocation.Element, ThreadIndex); i += pElement->Header.AllocationSize; } for (size_t i = 0; i < EngineRes.pUtils->CPU.MaxThreads; i++) { Engine_Ref_Unlock_Mutex(&Utils.InternalObjectBuffer.AllocationDatas.ArenaAllocaters[i].Mutex); Engine_Ref_Unlock_Mutex(&Utils.InternalResourceHeaderBuffer.AllocationDatas.ArenaAllocaters[i].Mutex); Engine_Ref_Unlock_Mutex(&Utils.InternalElementBuffer.AllocationDatas.ArenaAllocaters[i].Mutex); } free(data.pData); Engine_Ref_FunctionError("TESETTES1", "T", 0); return Success; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //ResourceHeaders //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEXRESULT Destroy_SceneHeader(RHeaderScene* pResourceHeader, bool Full, uint32_t ThreadIndex) { if (Full == true) { } return (Success); } TEXRESULT Pack_SceneHeader(const RHeaderScene* pResourceHeader, RHeaderScene* pCopiedResourceHeader, uint64_t* pBufferPointer, void* pData, uint32_t ThreadIndex) { if (pData != NULL) { } else { } return (Success); } TEXRESULT UnPack_SceneHeader(const RHeaderScene* pResourceHeader, RHeaderScene* pCopiedResourceHeader, void* pData, uint32_t ThreadIndex) { return (Success); } TEXRESULT Create_SceneHeader(RHeaderScene* pResourceHeader, RHeaderSceneCreateInfo* pCreateInfo, uint64_t* pAllocationSize, uint32_t ThreadIndex) { if (pResourceHeader == NULL) { } else { #ifndef NDEBUG if (pCreateInfo == NULL) { Engine_Ref_ArgsError("Create_SceneHeader()", "pCreateInfo == NULLPTR"); return (Invalid_Parameter | Failure); } #endif pResourceHeader->Active = pCreateInfo->InitialActive; } *pAllocationSize = sizeof(RHeaderScene); return (Success); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Main Functions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEXRESULT Initialise_Objects() { memset(&Utils, 0, sizeof(Utils)); //config Utils.Config.InitialItemsMax = 1024; Utils.Config.ActiveMemoryResizing = true; /////////////////////////////////////////////////////////////////////////////////////////////// //Signatures /////////////////////////////////////////////////////////////////////////////////////////////// uint32_t ThreadIndex = 0; Engine_Ref_Create_Mutex(&Utils.ObjectSignaturesMutex, MutexType_Plain); Engine_Ref_Create_Mutex(&Utils.ResourceHeaderSignaturesMutex, MutexType_Plain); Engine_Ref_Create_Mutex(&Utils.ElementSignaturesMutex, MutexType_Plain); Create_ElementBuffer(&Utils.InternalElementBuffer, Utils.Config.InitialItemsMax); Create_ResourceHeaderBuffer(&Utils.InternalResourceHeaderBuffer, Utils.Config.InitialItemsMax); Create_ObjectBuffer(&Utils.InternalObjectBuffer, Utils.Config.InitialItemsMax); Utils.GenericElementSig.Identifier = (uint32_t)Element_Generic; Utils.GenericResourceHeaderSig.Identifier = (uint32_t)ResourceHeader_Generic; Utils.GenericObjectSig.Identifier = (uint32_t)Object_Generic; Utils.GenericElementSig.ByteLength = sizeof(Element); Utils.GenericResourceHeaderSig.ByteLength = sizeof(ResourceHeader); Utils.GenericObjectSig.ByteLength = sizeof(Object); Register_ElementSignature(&Utils.GenericElementSig, ThreadIndex); Register_ResourceHeaderSignature(&Utils.GenericResourceHeaderSig, ThreadIndex); Register_ObjectSignature(&Utils.GenericObjectSig, ThreadIndex); Utils.RHeaderSceneSig.ByteLength = sizeof(RHeaderScene); Utils.RHeaderSceneSig.Identifier = (uint32_t)ResourceHeader_Scene; Utils.RHeaderSceneSig.Destructor = (Destroy_ResourceHeaderTemplate*)&Destroy_SceneHeader; Utils.RHeaderSceneSig.Constructor = (Create_ResourceHeaderTemplate*)&Create_SceneHeader; //Utils.RHeaderSceneSig.ReConstructor = (ReCreate_ResourceHeaderTemplate*)&ReCreate_SceneHeader; Utils.RHeaderSceneSig.Packer = (Pack_ResourceHeaderTemplate*)&Pack_SceneHeader; Utils.RHeaderSceneSig.UnPacker = (UnPack_ResourceHeaderTemplate*)&UnPack_SceneHeader; Register_ResourceHeaderSignature(&Utils.RHeaderSceneSig, ThreadIndex); return Success; } TEXRESULT Destroy_Objects() { uint32_t ThreadIndex = 0; DeRegister_ResourceHeaderSignature(&Utils.RHeaderSceneSig, ThreadIndex); DeRegister_ElementSignature(&Utils.GenericElementSig, ThreadIndex); DeRegister_ResourceHeaderSignature(&Utils.GenericResourceHeaderSig, ThreadIndex); DeRegister_ObjectSignature(&Utils.GenericObjectSig, ThreadIndex); Destroy_ElementBuffer(&Utils.InternalElementBuffer, 0); Destroy_ResourceHeaderBuffer(&Utils.InternalResourceHeaderBuffer, 0); Destroy_ObjectBuffer(&Utils.InternalObjectBuffer, 0); if (Utils.ObjectSignatures != NULL && Utils.ObjectSignaturesSize != NULL) free(Utils.ObjectSignatures); Utils.ObjectSignatures = NULL; Utils.ObjectSignaturesSize = NULL; if (Utils.ResourceHeaderSignatures != NULL && Utils.ResourceHeaderSignaturesSize != NULL) free(Utils.ResourceHeaderSignatures); Utils.ResourceHeaderSignatures = NULL; Utils.ResourceHeaderSignaturesSize = NULL; if (Utils.ElementSignatures != NULL && Utils.ElementSignaturesSize != NULL) free(Utils.ElementSignatures); Utils.ElementSignatures = NULL; Utils.ElementSignaturesSize = NULL; Engine_Ref_Destroy_Mutex(&Utils.ObjectSignaturesMutex); Engine_Ref_Destroy_Mutex(&Utils.ResourceHeaderSignaturesMutex); Engine_Ref_Destroy_Mutex(&Utils.ElementSignaturesMutex); memset(&Utils, 0, sizeof(Utils)); return Success; } //entry point to the extension //this functions purpose is to register everything with the application. One time only. __declspec(dllexport) void Initialise_Resources(ExtensionCreateInfo* ReturnInfo) { #ifdef NDEBUG ReturnInfo->BinType = Release; #else ReturnInfo->BinType = Debug; #endif MakeVersion(ReturnInfo->ExtensionVersion, 1, 0, 0); MakeVersion(ReturnInfo->MinRequiredVersion, 1, 0, 0); MakeVersion(ReturnInfo->MaxRequiredVersion, UINT32_MAX, UINT32_MAX, UINT32_MAX); Engine_Initialise_Resources(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, &ReturnInfo->pResources, &ReturnInfo->pResourcesSize); //Config ConfigParameterExport(&ReturnInfo->ConfigParameters, &ReturnInfo->ConfigParametersSize, (const UTF8*)CopyData("Object::InitialItemsMax"), &Utils.Config.InitialItemsMax, 1, sizeof(Utils.Config.InitialItemsMax)); ConfigParameterExport(&ReturnInfo->ConfigParameters, &ReturnInfo->ConfigParametersSize, (const UTF8*)CopyData((void*)"Object::ActiveMemoryResizing"), &Utils.Config.ActiveMemoryResizing, 1, sizeof(Utils.Config.ActiveMemoryResizing)); //Resources ResourceExport(&ReturnInfo->pResources, &ReturnInfo->pResourcesSize, (const UTF8*)CopyData("Object::Utils"), &ObjectsRes.pUtils, &Utils); //Functions FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Initialise_Objects"), &ObjectsRes.pInitialise_Objects, &Initialise_Objects, Construct, 0.001f, 0, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Destroy_Objects"), &ObjectsRes.pDestroy_Objects, &Destroy_Objects, Destruct, 10000.0f, 0, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Compare_ObjectAllocation"), &ObjectsRes.pCompare_ObjectAllocation, &Compare_ObjectAllocation, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Compare_ResourceHeaderAllocation"), &ObjectsRes.pCompare_ResourceHeaderAllocation, &Compare_ResourceHeaderAllocation, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Compare_ElementAllocation"), &ObjectsRes.pCompare_ElementAllocation, &Compare_ElementAllocation, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Get_ObjectAllocationData"), &ObjectsRes.pGet_ObjectAllocationData, &Get_ObjectAllocationData, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Get_ResourceHeaderAllocationData"), &ObjectsRes.pGet_ResourceHeaderAllocationData, &Get_ResourceHeaderAllocationData, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Get_ElementAllocationData"), &ObjectsRes.pGet_ElementAllocationData, &Get_ElementAllocationData, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Get_ObjectPointerFromPointer"), &ObjectsRes.pGet_ObjectPointerFromPointer, &Get_ObjectPointerFromPointer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Get_ResourceHeaderPointerFromPointer"), &ObjectsRes.pGet_ResourceHeaderPointerFromPointer, &Get_ResourceHeaderPointerFromPointer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Get_ElementPointerFromPointer"), &ObjectsRes.pGet_ElementPointerFromPointer, &Get_ElementPointerFromPointer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Get_ObjectPointer"), &ObjectsRes.pGet_ObjectPointer, &Get_ObjectPointer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Get_ResourceHeaderPointer"), &ObjectsRes.pGet_ResourceHeaderPointer, &Get_ResourceHeaderPointer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Get_ElementPointer"), &ObjectsRes.pGet_ElementPointer, &Get_ElementPointer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::End_ObjectPointer"), &ObjectsRes.pEnd_ObjectPointer, &End_ObjectPointer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::End_ResourceHeaderPointer"), &ObjectsRes.pEnd_ResourceHeaderPointer, &End_ResourceHeaderPointer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::End_ElementPointer"), &ObjectsRes.pEnd_ElementPointer, &End_ElementPointer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Find_ObjectSignature"), &ObjectsRes.pFind_ObjectSignature, &Find_ObjectSignature, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Find_ResourceHeaderSignature"), &ObjectsRes.pFind_ResourceHeaderSignature, &Find_ResourceHeaderSignature, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Find_ElementSignature"), &ObjectsRes.pFind_ElementSignature, &Find_ElementSignature, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Create_ObjectBuffer"), &ObjectsRes.pCreate_ObjectBuffer, &Create_ObjectBuffer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Create_ResourceHeaderBuffer"), &ObjectsRes.pCreate_ResourceHeaderBuffer, &Create_ResourceHeaderBuffer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Create_ElementBuffer"), &ObjectsRes.pCreate_ElementBuffer, &Create_ElementBuffer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Resize_ObjectBuffer"), &ObjectsRes.pResize_ObjectBuffer, &Resize_ObjectBuffer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Resize_ResourceHeaderBuffer"), &ObjectsRes.pResize_ResourceHeaderBuffer, &Resize_ResourceHeaderBuffer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Resize_ElementBuffer"), &ObjectsRes.pResize_ElementBuffer, &Resize_ElementBuffer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Destroy_ObjectBuffer"), &ObjectsRes.pDestroy_ObjectBuffer, &Destroy_ObjectBuffer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Destroy_ResourceHeaderBuffer"), &ObjectsRes.pDestroy_ResourceHeaderBuffer, &Destroy_ResourceHeaderBuffer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Destroy_ElementBuffer"), &ObjectsRes.pDestroy_ElementBuffer, &Destroy_ElementBuffer, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Create_Object"), &ObjectsRes.pCreate_Object, &Create_Object, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Create_ResourceHeader"), &ObjectsRes.pCreate_ResourceHeader, &Create_ResourceHeader, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Create_Element"), &ObjectsRes.pCreate_Element, &Create_Element, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Destroy_Object"), &ObjectsRes.pDestroy_Object, &Destroy_Object, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Destroy_ResourceHeader"), &ObjectsRes.pDestroy_ResourceHeader, &Destroy_ResourceHeader, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Destroy_Element"), &ObjectsRes.pDestroy_Element, &Destroy_Element, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::ReCreate_Object"), &ObjectsRes.pReCreate_Object, &ReCreate_Object, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::ReCreate_ResourceHeader"), &ObjectsRes.pReCreate_ResourceHeader, &ReCreate_ResourceHeader, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::ReCreate_Element"), &ObjectsRes.pReCreate_Element, &ReCreate_Element, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Add_ObjectChild"), &ObjectsRes.pAdd_ObjectChild, &Add_ObjectChild, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Add_Object_ResourceHeaderChild"), &ObjectsRes.pAdd_Object_ResourceHeaderChild, &Add_Object_ResourceHeaderChild, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Add_ResourceHeader_ElementChild"), &ObjectsRes.pAdd_ResourceHeader_ElementChild, &Add_ResourceHeader_ElementChild, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Remove_ObjectChild"), &ObjectsRes.pRemove_ObjectChild, &Remove_ObjectChild, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Remove_Object_ResourceHeaderChild"), &ObjectsRes.pRemove_Object_ResourceHeaderChild, &Remove_Object_ResourceHeaderChild, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Remove_ResourceHeader_ElementChild"), &ObjectsRes.pRemove_ResourceHeader_ElementChild, &Remove_ResourceHeader_ElementChild, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Register_ObjectSignature"), &ObjectsRes.pRegister_ObjectSignature, &Register_ObjectSignature, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Register_ResourceHeaderSignature"), &ObjectsRes.pRegister_ResourceHeaderSignature, &Register_ResourceHeaderSignature, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Register_ElementSignature"), &ObjectsRes.pRegister_ElementSignature, &Register_ElementSignature, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::DeRegister_ObjectSignature"), &ObjectsRes.pDeRegister_ObjectSignature, &DeRegister_ObjectSignature, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::DeRegister_ResourceHeaderSignature"), &ObjectsRes.pDeRegister_ResourceHeaderSignature, &DeRegister_ResourceHeaderSignature, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::DeRegister_ElementSignature"), &ObjectsRes.pDeRegister_ElementSignature, &DeRegister_ElementSignature, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Scan_ObjectChilds"), &ObjectsRes.pScan_ObjectChilds, &Scan_ObjectChilds, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Scan_ObjectParents"), &ObjectsRes.pScan_ObjectParents, &Scan_ObjectParents, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Scan_ObjectResourceHeaders"), &ObjectsRes.pScan_ObjectResourceHeaders, &Scan_ObjectResourceHeaders, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Scan_ResourceHeaderElements"), &ObjectsRes.pScan_ResourceHeaderElements, &Scan_ResourceHeaderElements, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Scan_ObjectResourceHeadersSingle"), &ObjectsRes.pScan_ObjectResourceHeadersSingle, &Scan_ObjectResourceHeadersSingle, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Scan_ResourceHeaderElementsSingle"), &ObjectsRes.pScan_ResourceHeaderElementsSingle, &Scan_ResourceHeaderElementsSingle, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Write_TEIF"), &ObjectsRes.pWrite_TEIF, &Write_TEIF, (CallFlagBits)NULL, 0.0f, NULL, NULL); FunctionExport(&ReturnInfo->pFunctions, &ReturnInfo->pFunctionsSize, (const UTF8*)CopyData("Object::Read_TEIF"), &ObjectsRes.pRead_TEIF, &Read_TEIF, (CallFlagBits)NULL, 0.0f, NULL, NULL); }
46.711702
269
0.73852
[ "object" ]
67318bd3df4c7a27b0119f92770a71843002cd3b
3,316
h
C
TestPlugIn/AudioUnit/TestAudioUnit.h
Celemony/ARA_Examples
24239cf5176b9b230ddd7aa2b9053b6e582cdb2a
[ "Apache-2.0" ]
2
2021-04-27T07:08:07.000Z
2021-05-20T16:08:51.000Z
TestPlugIn/AudioUnit/TestAudioUnit.h
Celemony/ARA_Examples
24239cf5176b9b230ddd7aa2b9053b6e582cdb2a
[ "Apache-2.0" ]
null
null
null
TestPlugIn/AudioUnit/TestAudioUnit.h
Celemony/ARA_Examples
24239cf5176b9b230ddd7aa2b9053b6e582cdb2a
[ "Apache-2.0" ]
null
null
null
//------------------------------------------------------------------------------ //! \file TestAudioUnit.h //! Audio Unit effect class for the ARA test plug-in, //! created via the Xcode 3 project template for Audio Unit effects. //! \project ARA SDK Examples //! \copyright Copyright (c) 2012-2021, Celemony Software GmbH, All Rights Reserved. //! \license 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 __TestAudioUnit_h__ #define __TestAudioUnit_h__ #include "AUEffectBase.h" #if AU_DEBUG_DISPATCHER #include "AUDebugDispatcher.h" #endif #if !CA_USE_AUDIO_PLUGIN_ONLY #error "Audio Unit v1 is no longer supported." #endif #include "ARA_Library/PlugIn/ARAPlug.h" class TestAudioUnit : public AUEffectBase { public: TestAudioUnit(AudioUnit component); #if AU_DEBUG_DISPATCHER virtual ~TestAudioUnit () { delete mDebugDispatcher; } #endif virtual OSStatus Initialize(); virtual void Cleanup(); virtual UInt32 SupportedNumChannels(const AUChannelInfo** outInfo); virtual CFURLRef CopyIconLocation (); virtual OSStatus GetPropertyInfo(AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, UInt32 & outDataSize, Boolean & outWritable ); virtual OSStatus GetProperty(AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, void * outData); virtual OSStatus ProcessBufferLists( AudioUnitRenderActionFlags & ioActionFlags, const AudioBufferList & inBuffer, AudioBufferList & outBuffer, UInt32 inFramesToProcess ); virtual OSStatus Render(AudioUnitRenderActionFlags & ioActionFlags, const AudioTimeStamp & inTimeStamp, UInt32 inNumberFrames); private: ARA::PlugIn::PlugInExtension _araPlugInExtension; }; #endif
46.704225
98
0.501206
[ "render" ]
673367cb9adf07eb52750a539da277ce5538cf5a
7,758
h
C
cxx/quickstore/quickstore.h
hanhanW/iree-mako
e0fddf0b96b4c46dfbd179d3cf290458ed20aab4
[ "Apache-2.0" ]
60
2019-08-01T21:26:36.000Z
2021-11-06T06:08:29.000Z
cxx/quickstore/quickstore.h
google/mako
2ce9ad2e45cec6d3a91292b4ef1bddb3c9743463
[ "Apache-2.0" ]
16
2019-08-06T15:39:04.000Z
2022-03-15T22:26:03.000Z
cxx/quickstore/quickstore.h
hanhanW/iree-mako
e0fddf0b96b4c46dfbd179d3cf290458ed20aab4
[ "Apache-2.0" ]
12
2019-08-08T23:44:36.000Z
2021-07-22T03:35:12.000Z
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // see the license for the specific language governing permissions and // limitations under the license. #ifndef CXX_QUICKSTORE_QUICKSTORE_H_ #define CXX_QUICKSTORE_QUICKSTORE_H_ #include <list> #include <map> #include <string> #include "cxx/spec/storage.h" #include "proto/clients/analyzers/threshold_analyzer.pb.h" #include "proto/clients/analyzers/utest_analyzer.pb.h" #include "proto/clients/analyzers/window_deviation.pb.h" #include "proto/quickstore/quickstore.pb.h" #include "spec/proto/mako.pb.h" namespace mako { namespace quickstore { // Quickstore offers a way to utilize Mako storage, downsampling, // aggregation and analyzers in a simple way. This is most helpful when you have // a pre-existing benchmarking tool which exports data that you would like to // save in Mako. // // Basic usage: // // Store data, metric and run aggregates will be calculated automatically. // Quickstore q(kBenchmarkKey); // for (int data : {1, 2, 3, 4, 5, 6}) { // q.AddSamplePoint(time_ms, {{"y", data}}); // } // QuickstoreOutput output = q.Store(); // if(!IsOK(output)) { // LOG(ERROR) << "Failed to store: " << output.summary_output(); // } // // More information about quickstore: go/mako-quickstore // // Class is not thread-safe per go/thread-safe. // Convenience function checking Store() was successful. inline bool IsOK( const mako::quickstore::QuickstoreOutput& output) { return output.status() == mako::quickstore::QuickstoreOutput::SUCCESS; } class Quickstore { public: // Will create a new Mako Run under this benchmark key in the default // Mako storage system. explicit Quickstore(const std::string& benchmark_key); // Will create a new Mako Run under this benchmark key in the storage // provided. // It does not take ownership of the Storage client object. Quickstore(const std::string& benchmark_key, Storage* storage); // Provide extra metadata about the Run (eg. such as a description). // See QuickstoreInput for more information. explicit Quickstore( const mako::quickstore::QuickstoreInput& input) : input_(input), storage_(nullptr) {} // Provide extra metadata about the Run (eg. such as a description). // See QuickstoreInput for more information. // Takes a pointer to a mako::Storage client implementation. // It does not take ownership of the Storage client object. Quickstore(const mako::quickstore::QuickstoreInput& input, Storage* storage) : input_(input), storage_(storage) {} virtual ~Quickstore() {} // Add a sample at the specified xval. // // The map represents a mapping from metric to value. // It is more efficient for Mako to store multiple metrics collected at // the same xval together, but it is optional. // // When adding data via this function, calling the Add*Aggregate() functions // is optional, as the aggregates will get computed by this class. // // A std::string is returned with an error if the operation was unsucessful. virtual std::string AddSamplePoint( double xval, const std::map<std::string, double>& yvals); virtual std::string AddSamplePoint(const mako::SamplePoint& point); // Add an error at the specified xval. // // When adding errors via this function, the aggregate error count will be set // automatically. // // A std::string is returned with an error if the operation was unsucessful. virtual std::string AddError(double xval, const std::string& error_msg); virtual std::string AddError(const mako::SampleError& error); // Add an aggregate value over the entire run. // If value_key is: // * "~ignore_sample_count" // * "~usable_sample_count" // * "~error_sample_count" // * "~benchmark_score" // The corresponding value will be overwritten by the Mako aggregator. If // none of these values are provided, they will be calculated automatically // by the framework based on SamplePoints/Errors provided before Store() is // called. // // Otherwise the value_key will be set to a custom aggregate (see // RunAggregate.custom_aggregate_list in mako.proto). // // If no run aggregates are manully set with this method, values are // automatically calculated. // // A std::string is returned with an error if the operation was unsucessful. virtual std::string AddRunAggregate(const std::string& value_key, double value); // Add an aggregate for a specific metric. // If value_key is: // * "min" // * "max" // * "mean" // * "median" // * "standard_deviation" // * "median_absolute_deviation" // * "count" // The corresponding value inside the MetricAggregate (defined in // mako.proto) will be set. // // The value_key can also represent a percentile in // MetricAggregate.percentile_list (defined in mako.proto). // // For example "p98000" would be interpreted as the 98th percentile. These // need to correspond to the percentiles that your benchmark has set. // It is an error to supply an percentile that is not part of your benchmark. // If any percentiles are provided, the automatically calculated percentiles // will be cleared to 0. // // If any aggregate_types (eg. "min") are set for a value_key it will // overwrite the entire MetricAggregate for that value_key. If no // aggregate_types are provided for a value_key metric aggregates (including // percentiles) will be calculated automatically based on data provided via // calls to AddSamplePoint. // // A std::string is returned with an error if the operation was unsucessful. virtual std::string AddMetricAggregate(const std::string& value_key, const std::string& aggregate_type, double value); // Add an analyzer input for the appropriate analyzer. // // A std::string is returned with an error if the operation was unsucessful. virtual std::string AddThresholdAnalyzer( mako::analyzers::threshold_analyzer::ThresholdAnalyzerInput input); virtual std::string AddWindowDeviationAnalyzer( mako::window_deviation::WindowDeviationInput input); virtual std::string AddUTestAnalyzer( mako::utest_analyzer::UTestAnalyzerInput input); // Store all the values that you have added. You cannot save if no Add*() // functions have been called. // // Each call to Store() will create a new unique Mako Run and store all // Aggregate and SamplePoint data registered using the Add* methods since the // last call to Store() as a part of that new Run. // // Data and analyzers can be added via Add* calls in any order. // // After a call to Store() all data added via Add* will be cleared, but // analyzers will persist. virtual mako::quickstore::QuickstoreOutput Store(); private: mako::quickstore::QuickstoreInput input_; Storage* storage_; std::list<mako::SamplePoint> points_; std::list<mako::SampleError> errors_; std::list<mako::KeyedValue> run_aggregates_; std::list<std::string> metric_aggregate_value_keys_; std::list<std::string> metric_aggregate_types_; std::list<double> metric_aggregate_values_; }; } // namespace quickstore } // namespace mako #endif // CXX_QUICKSTORE_QUICKSTORE_H_
38.79
80
0.711008
[ "object" ]
67400bf9e763382827de67fdd00b0263fe59ba6e
2,282
h
C
GUI/Spectrum/SpectrographWidget.h
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
GUI/Spectrum/SpectrographWidget.h
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
GUI/Spectrum/SpectrographWidget.h
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
#ifndef SIDECAR_GUI_SPECTRUM_SPECTROGRAPHWIDGET_H // -*- C++ -*- #define SIDECAR_GUI_SPECTRUM_SPECTROGRAPHWIDGET_H #include "QtCore/QBasicTimer" #include "QtOpenGL/QGLWidget" #include "GUI/Texture.h" #include "GUI/Utils.h" #include "GUI/VertexColorArray.h" class QGLFramebufferObject; namespace Logger { class Log; } namespace SideCar { namespace GUI { class VertexColorArray; namespace Spectrum { class Configuration; class FFTSettings; class SpectrographImaging; class SpectrographWidget : public QGLWidget { Q_OBJECT using Super = QGLWidget; public: static Logger::Log& Log(); /** Obtain the OpenGL configuration we want to use. \return OpenGL format */ static QGLFormat GetGLFormat(); /** Constructor. \param parent parent object */ SpectrographWidget(QWidget* parent = 0); ~SpectrographWidget(); signals: void currentCursorPosition(const QPointF& pos); public slots: void clear(); void processBins(const QVector<QPointF>& bins); void needUpdate(); void setFrozen(bool state); private slots: void sizeChanged(); private: enum ListIndex { kBeginUpdate = 0, kBeginPaint, kCopyPrevious0, kCopyPrevious1, kPaintTexture0, kPaintTexture1, kNumLists }; GLuint getDisplayList(int index) const { return displayLists_ + index; } /** Initialize the OpenGL environment. */ void initializeGL(); void resizeGL(int width, int height); void makeOffscreenBuffer(); void deleteOffscreenBuffer(); void makeDisplayLists(); /** Update the GL display with the lates PPI information. */ void paintGL(); void timerEvent(QTimerEvent* event); void showEvent(QShowEvent* event); void closeEvent(QCloseEvent* event); SpectrographImaging* imaging_; FFTSettings* fftSettings_; QGLFramebufferObject* fbo_; QSize size_; Texture textures_[2]; int readTexture_; int writeTexture_; VertexColorArray points_; QBasicTimer updateTimer_; QPoint mouse_; GLuint displayLists_; bool needUpdate_; bool doClear_; bool frozen_; }; } // namespace Spectrum } // end namespace GUI } // end namespace SideCar /** \file */ #endif
18.111111
76
0.683173
[ "object" ]
674cd41c083b9c8a2af74ee1d059453d34e36368
19,610
h
C
include/evm.h
walden01/evmjit
ae5046967c5a3eec5c18a708d77a98402537ac57
[ "MIT" ]
null
null
null
include/evm.h
walden01/evmjit
ae5046967c5a3eec5c18a708d77a98402537ac57
[ "MIT" ]
null
null
null
include/evm.h
walden01/evmjit
ae5046967c5a3eec5c18a708d77a98402537ac57
[ "MIT" ]
null
null
null
/// EVM-C -- C interface to Ethereum Virtual Machine /// /// ## High level design rules /// /// 1. Pass function arguments and results by value. /// This rule comes from modern C++ and tries to avoid costly alias analysis /// needed for optimization. As the result we have a lots of complex structs /// and unions. And variable sized arrays of bytes cannot be passed by copy. /// 2. The EVM operates on integers so it prefers values to be host-endian. /// On the other hand, LLVM can generate good code for byte swaping. /// The interface also tries to match host application "natural" endianess. /// I would like to know what endianess you use and where. /// /// ## Terms /// /// 1. EVM -- an Ethereum Virtual Machine instance/implementation. /// 2. Host -- an entity controlling the EVM. The Host requests code execution /// and responses to EVM queries by callback functions. /// /// @defgroup EVMC EVM-C /// @{ #ifndef EVM_H #define EVM_H #include <stdint.h> // Definition of int64_t, uint64_t. #include <stddef.h> // Definition of size_t. #if __cplusplus extern "C" { #endif // BEGIN Python CFFI declarations enum { /// The EVM-C ABI version number of the interface declared in this file. EVM_ABI_VERSION = 0 }; /// Big-endian 256-bit integer. /// /// 32 bytes of data representing big-endian 256-bit integer. I.e. bytes[0] is /// the most significant byte, bytes[31] is the least significant byte. /// This type is used to transfer to/from the VM values interpreted by the user /// as both 256-bit integers and 256-bit hashes. struct evm_uint256be { /// The 32 bytes of the big-endian integer or hash. uint8_t bytes[32]; }; /// Big-endian 160-bit hash suitable for keeping an Ethereum address. struct evm_address { /// The 20 bytes of the hash. uint8_t bytes[20]; }; /// The kind of call-like instruction. enum evm_call_kind { EVM_CALL = 0, ///< Request CALL. EVM_DELEGATECALL = 1, ///< Request DELEGATECALL. The value param ignored. EVM_CALLCODE = 2, ///< Request CALLCODE. EVM_CREATE = 3, ///< Request CREATE. Semantic of some params changes. }; enum evm_flags { EVM_STATIC = 1 }; struct evm_message { struct evm_address address; struct evm_address sender; struct evm_uint256be value; const uint8_t* input; size_t input_size; struct evm_uint256be code_hash; int64_t gas; int32_t depth; enum evm_call_kind kind; uint32_t flags; }; struct evm_tx_context { struct evm_uint256be tx_gas_price; struct evm_address tx_origin; struct evm_address block_coinbase; int64_t block_number; int64_t block_timestamp; int64_t block_gas_limit; struct evm_uint256be block_difficulty; }; struct evm_context; typedef void (*evm_get_tx_context_fn)(struct evm_tx_context* result, struct evm_context* context); typedef void (*evm_get_block_hash_fn)(struct evm_uint256be* result, struct evm_context* context, int64_t number); /// The execution status code. enum evm_status_code { EVM_SUCCESS = 0, ///< Execution finished with success. EVM_FAILURE = 1, ///< Generic execution failure. EVM_OUT_OF_GAS = 2, EVM_BAD_INSTRUCTION = 3, EVM_BAD_JUMP_DESTINATION = 4, EVM_STACK_OVERFLOW = 5, EVM_STACK_UNDERFLOW = 6, EVM_REVERT = 7, ///< Execution terminated with REVERT opcode. /// EVM implementation internal error. /// /// @todo We should rethink reporting internal errors. One of the options /// it to allow using any negative value to represent internal errors. EVM_INTERNAL_ERROR = -1, }; struct evm_result; ///< Forward declaration. /// Releases resources assigned to an execution result. /// /// This function releases memory (and other resources, if any) assigned to the /// specified execution result making the result object invalid. /// /// @param result The execution result which resource are to be released. The /// result itself it not modified by this function, but becomes /// invalid and user should discard it as well. typedef void (*evm_release_result_fn)(const struct evm_result* result); /// The EVM code execution result. struct evm_result { /// The execution status code. enum evm_status_code status_code; /// The amount of gas left after the execution. /// /// If evm_result::code is not ::EVM_SUCCESS nor ::EVM_REVERT /// the value MUST be 0. int64_t gas_left; /// The reference to output data. /// /// The output contains data coming from RETURN opcode (iff evm_result::code /// field is ::EVM_SUCCESS) or from REVERT opcode. /// /// The memory containing the output data is owned by EVM and has to be /// freed with evm_result::release(). uint8_t const* output_data; /// The size of the output data. size_t output_size; /// The pointer to a function releasing all resources associated with /// the result object. /// /// This function pointer is optional (MAY be NULL) and MAY be set by /// the EVM implementation. If set it MUST be used by the user to /// release memory and other resources associated with the result object. /// After the result resources are released the result object /// MUST NOT be used any more. /// /// The suggested code pattern for releasing EVM results: /// @code /// struct evm_result result = ...; /// if (result.release) /// result.release(&result); /// @endcode /// /// @note /// It works similarly to C++ virtual destructor. Attaching the release /// function to the result itself allows EVM composition. evm_release_result_fn release; /// The address of the contract created by CREATE opcode. /// /// This field has valid value only if the result describes successful /// CREATE (evm_result::status_code is ::EVM_SUCCESS). struct evm_address create_address; /// Reserved data that MAY be used by a evm_result object creator. /// /// This reserved 4 bytes together with 20 bytes from create_address form /// 24 bytes of memory called "optional data" within evm_result struct /// to be optionally used by the evm_result object creator. /// /// @see evm_result_optional_data, evm_get_optional_data(). /// /// Also extends the size of the evm_result to 64 bytes (full cache line). uint8_t padding[4]; }; /// The union representing evm_result "optional data". /// /// The evm_result struct contains 24 bytes of optional data that can be /// reused by the obejct creator if the object does not contain /// evm_result::create_address. /// /// An EVM implementation MAY use this memory to keep additional data /// when returning result from ::evm_execute_fn. /// The host application MAY use this memory to keep additional data /// when returning result of performed calls from ::evm_call_fn. /// /// @see evm_get_optional_data(), evm_get_const_optional_data(). union evm_result_optional_data { uint8_t bytes[24]; void* pointer; }; /// Provides read-write access to evm_result "optional data". static inline union evm_result_optional_data* evm_get_optional_data( struct evm_result* result) { return (union evm_result_optional_data*) &result->create_address; } /// Provides read-only access to evm_result "optional data". static inline const union evm_result_optional_data* evm_get_const_optional_data( const struct evm_result* result) { return (const union evm_result_optional_data*) &result->create_address; } /// Check account existence callback function /// /// This callback function is used by the EVM to check if /// there exists an account at given address. /// @param context The pointer to the Host execution context. /// @see ::evm_context. /// @param address The address of the account the query is about. /// @return 1 if exists, 0 otherwise. typedef int (*evm_account_exists_fn)(struct evm_context* context, const struct evm_address* address); /// Get storage callback function. /// /// This callback function is used by an EVM to query the given contract /// storage entry. /// @param[out] result The returned storage value. /// @param context The pointer to the Host execution context. /// @see ::evm_context. /// @param address The address of the contract. /// @param key The index of the storage entry. typedef void (*evm_get_storage_fn)(struct evm_uint256be* result, struct evm_context* context, const struct evm_address* address, const struct evm_uint256be* key); /// Set storage callback function. /// /// This callback function is used by an EVM to update the given contract /// storage entry. /// @param context The pointer to the Host execution context. /// @see ::evm_context. /// @param address The address of the contract. /// @param key The index of the storage entry. /// @param value The value to be stored. typedef void (*evm_set_storage_fn)(struct evm_context* context, const struct evm_address* address, const struct evm_uint256be* key, const struct evm_uint256be* value); /// Get balance callback function. /// /// This callback function is used by an EVM to query the balance of the given /// address. /// @param[out] result The returned balance value. /// @param context The pointer to the Host execution context. /// @see ::evm_context. /// @param address The address. typedef void (*evm_get_balance_fn)(struct evm_uint256be* result, struct evm_context* context, const struct evm_address* address); /// Get code callback function. /// /// This callback function is used by an EVM to get the code of a contract of /// given address. /// @param[out] result_code The pointer to the contract code. This argument is /// optional. If NULL is provided, the host MUST only /// return the code size. /// @param context The pointer to the Host execution context. /// @see ::evm_context. /// @param address The address of the contract. /// @return The size of the code. typedef size_t (*evm_get_code_fn)(const uint8_t** result_code, struct evm_context* context, const struct evm_address* address); /// Selfdestruct callback function. /// /// This callback function is used by an EVM to SELFDESTRUCT given contract. /// @param context The pointer to the Host execution context. /// @see ::evm_context. /// @param address The address of the contract to be selfdestructed. /// @param beneficiary The address where the remaining ETH is going to be /// transferred. typedef void (*evm_selfdestruct_fn)(struct evm_context* context, const struct evm_address* address, const struct evm_address* beneficiary); /// Log callback function. /// /// This callback function is used by an EVM to inform about a LOG that happened /// during an EVM bytecode execution. /// @param context The pointer to the Host execution context. /// @see ::evm_context. /// @param address The address of the contract that generated the log. /// @param data The pointer to unindexed data attached to the log. /// @param data_size The length of the data. /// @param topics The pointer to the array of topics attached to the log. /// @param topics_count The number of the topics. Valid values are between /// 0 and 4 inclusively. typedef void (*evm_log_fn)(struct evm_context* context, const struct evm_address* address, const uint8_t* data, size_t data_size, const struct evm_uint256be topics[], size_t topics_count); /// Pointer to the callback function supporting EVM calls. /// /// @param[out] result The result of the call. The result object is not /// initialized by the EVM, the Client MUST correctly /// initialize all expected fields of the structure. /// @param context The pointer to the Host execution context. /// @see ::evm_context. /// @param msg Call parameters. typedef void (*evm_call_fn)(struct evm_result* result, struct evm_context* context, const struct evm_message* msg); /// The context interface. /// /// The set of all callback functions expected by EVM instances. This is C /// realisation of vtable for OOP interface (only virtual methods, no data). /// Host implementations SHOULD create constant singletons of this (similarly /// to vtables) to lower the maintenance and memory management cost. struct evm_context_fn_table { evm_account_exists_fn account_exists; evm_get_storage_fn get_storage; evm_set_storage_fn set_storage; evm_get_balance_fn get_balance; evm_get_code_fn get_code; evm_selfdestruct_fn selfdestruct; evm_call_fn call; evm_get_tx_context_fn get_tx_context; evm_get_block_hash_fn get_block_hash; evm_log_fn log; }; /// Execution context managed by the Host. /// /// The Host MUST pass the pointer to the execution context to /// ::evm_execute_fn. The EVM MUST pass the same pointer back to the Host in /// every callback function. /// The context MUST contain at least the function table defining the context /// callback interface. /// Optionally, The Host MAY include in the context additional data. struct evm_context { /// Function table defining the context interface (vtable). const struct evm_context_fn_table* fn_table; }; struct evm_instance; ///< Forward declaration. /// Destroys the EVM instance. /// /// @param evm The EVM instance to be destroyed. typedef void (*evm_destroy_fn)(struct evm_instance* evm); /// Configures the EVM instance. /// /// Allows modifying options of the EVM instance. /// Options: /// - code cache behavior: on, off, read-only, ... /// - optimizations, /// /// @param evm The EVM instance to be configured. /// @param name The option name. NULL-terminated string. Cannot be NULL. /// @param value The new option value. NULL-terminated string. Cannot be NULL. /// @return 1 if the option set successfully, 0 otherwise. typedef int (*evm_set_option_fn)(struct evm_instance* evm, char const* name, char const* value); /// EVM revision. /// /// The revision of the EVM specification based on the Ethereum /// upgrade / hard fork codenames. enum evm_revision { EVM_FRONTIER = 0, EVM_HOMESTEAD = 1, EVM_TANGERINE_WHISTLE = 2, EVM_SPURIOUS_DRAGON = 3, EVM_BYZANTIUM = 4, EVM_CONSTANTINOPLE = 5, }; /// Generates and executes machine code for given EVM bytecode. /// /// All the fun is here. This function actually does something useful. /// /// @param instance A EVM instance. /// @param context The pointer to the Host execution context to be passed /// to callback functions. @see ::evm_context. /// @param rev Requested EVM specification revision. /// @param code_hash A hash of the bytecode, usually Keccak. The EVM uses it /// as the code identifier. A EVM implementation is able to /// hash the code itself if it requires it, but the host /// application usually has the hash already. /// @param code Reference to the bytecode to be executed. /// @param code_size The length of the bytecode. /// @param gas Gas for execution. Min 0, max 2^63-1. /// @param input Reference to the input data. /// @param input_size The size of the input data. /// @param value Call value. /// @return All execution results. typedef struct evm_result (*evm_execute_fn)(struct evm_instance* instance, struct evm_context* context, enum evm_revision rev, const struct evm_message* msg, uint8_t const* code, size_t code_size); /// Status of a code in VM. Useful for JIT-like implementations. enum evm_code_status { /// The code is uknown to the VM. EVM_UNKNOWN, /// The code has been compiled and is available in memory. EVM_READY, /// The compiled version of the code is available in on-disk cache. EVM_CACHED, }; /// Get information the status of the code in the VM. typedef enum evm_code_status (*evm_get_code_status_fn)(struct evm_instance* instance, enum evm_revision rev, uint32_t flags, struct evm_uint256be code_hash); /// Request preparation of the code for faster execution. It is not required /// to execute the code but allows compilation of the code ahead of time in /// JIT-like VMs. typedef void (*evm_prepare_code_fn)(struct evm_instance* instance, enum evm_revision rev, uint32_t flags, struct evm_uint256be code_hash, uint8_t const* code, size_t code_size); /// The EVM instance. /// /// Defines the base struct of the EVM implementation. struct evm_instance { /// EVM-C ABI version implemented by the EVM instance. /// /// For future use to detect ABI incompatibilities. The EVM-C ABI version /// represented by this file is in ::EVM_ABI_VERSION. /// /// @todo Consider removing this field. const int abi_version; /// Pointer to function destroying the EVM instance. evm_destroy_fn destroy; /// Pointer to function executing a code by the EVM instance. evm_execute_fn execute; /// Optional pointer to function returning a status of a code. /// /// If the VM does not support this feature the pointer can be NULL. evm_get_code_status_fn get_code_status; /// Optional pointer to function compiling a code. /// /// If the VM does not support this feature the pointer can be NULL. evm_prepare_code_fn prepare_code; /// Optional pointer to function modifying VM's options. /// /// If the VM does not support this feature the pointer can be NULL. evm_set_option_fn set_option; }; // END Python CFFI declarations /// Example of a function creating an instance of an example EVM implementation. /// /// Each EVM implementation MUST provide a function returning an EVM instance. /// The function SHOULD be named `<vm-name>_create(void)`. /// /// @return EVM instance or NULL indicating instance creation failure. struct evm_instance* examplevm_create(void); #if __cplusplus } #endif #endif // EVM_H /// @}
37.930368
80
0.649057
[ "object" ]
6761333d3b8a39b5ca2f4ce00c287ddc89681cc1
380
h
C
src/Commands/PWD.h
tbaust/ESP-FTP-Server-Lib
dbc98e66a4a6deccd0d50ac94c8503abf64befff
[ "MIT" ]
3
2020-09-11T01:34:31.000Z
2021-07-08T06:02:37.000Z
src/Commands/PWD.h
tbaust/ESP-FTP-Server-Lib
dbc98e66a4a6deccd0d50ac94c8503abf64befff
[ "MIT" ]
7
2020-09-11T01:37:37.000Z
2021-11-25T17:00:43.000Z
src/Commands/PWD.h
tbaust/ESP-FTP-Server-Lib
dbc98e66a4a6deccd0d50ac94c8503abf64befff
[ "MIT" ]
3
2021-02-27T12:08:01.000Z
2021-11-06T17:26:56.000Z
#ifndef PWD_H_ #define PWD_H_ #include <WiFiClient.h> #include "../FTPCommand.h" class PWD : public FTPCommand { public: explicit PWD(WiFiClient * const Client) : FTPCommand("PWD", 0, Client) {} void run(FTPPath & WorkDirectory, const std::vector<String> & Line) override { SendResponse(257, "\"" + WorkDirectory.getPath() + "\" is your current directory"); } }; #endif
20
85
0.692105
[ "vector" ]
678e0531dbae9da7373b11b7f96fab2a2a27693c
516
h
C
ds4wizard-cpp/JsonData.h
SonicFreak94/ds4wizard
4d2ddc15b7db7cc5618c8676c91cf81614921c3c
[ "MIT" ]
7
2019-02-27T19:23:34.000Z
2021-11-13T08:35:31.000Z
ds4wizard-cpp/JsonData.h
SonicFreak94/ds4wizard
4d2ddc15b7db7cc5618c8676c91cf81614921c3c
[ "MIT" ]
1
2020-01-29T20:34:26.000Z
2020-06-30T04:00:38.000Z
ds4wizard-cpp/JsonData.h
SonicFreak94/ds4wizard
4d2ddc15b7db7cc5618c8676c91cf81614921c3c
[ "MIT" ]
null
null
null
#pragma once #include <nlohmann/json.hpp> /** * \brief A simple interface for de/serializable JSON objects. */ struct JsonData { virtual ~JsonData() = default; virtual void readJson(const nlohmann::json& json) = 0; virtual void writeJson(nlohmann::json& json) const = 0; nlohmann::json toJson() const { nlohmann::json object; writeJson(object); return object; } template <typename T> static T fromJson(const nlohmann::json& json) { T result {}; result.readJson(json); return result; } };
17.793103
62
0.693798
[ "object" ]
6799fcd1dca9fb2c27fda05988cd6f99776cd31e
30,017
h
C
example-output/cpp.h
sonder-joker/witx-codegen
525bdea6f08faa6e94daab643efb0dfc92feec9c
[ "MIT" ]
null
null
null
example-output/cpp.h
sonder-joker/witx-codegen
525bdea6f08faa6e94daab643efb0dfc92feec9c
[ "MIT" ]
null
null
null
example-output/cpp.h
sonder-joker/witx-codegen
525bdea6f08faa6e94daab643efb0dfc92feec9c
[ "MIT" ]
null
null
null
/* * This file was automatically generated by witx-codegen - Do not edit manually. */ #include <cstdint> #include <cstring> #include <tuple> #include <cstddef> #include <variant> // namespace WitxCodegenHeader { using WasiHandle = int32_t; template <typename T> using WasiPtr = T *const; template <typename T> using WasiMutPtr = T *; using WasiStringBytesPtr = WasiPtr<unsigned char>; template <typename R, typename E> using Expected = std::variant<R, E>; using WasiStringBytesPtr = WasiPtr<unsigned char>; struct WasiString { WasiStringBytesPtr ptr; size_t length; }; template<typename T> struct WasiSlice { WasiPtr<T> ptr; size_t length; }; template<typename T> struct WasiMutSlice { WasiMutPtr<T> ptr; size_t length; }; // } // ---------------------- Module: [wasi_ephemeral_crypto_symmetric] ---------------------- /** * Error codes. **/ enum class CryptoErrno : uint16_t { SUCCESS = 0, GUEST_ERROR = 1, NOT_IMPLEMENTED = 2, UNSUPPORTED_FEATURE = 3, PROHIBITED_OPERATION = 4, UNSUPPORTED_ENCODING = 5, UNSUPPORTED_ALGORITHM = 6, UNSUPPORTED_OPTION = 7, INVALID_KEY = 8, INVALID_LENGTH = 9, VERIFICATION_FAILED = 10, RNG_ERROR = 11, ALGORITHM_FAILURE = 12, INVALID_SIGNATURE = 13, CLOSED = 14, INVALID_HANDLE = 15, OVERFLOW = 16, INTERNAL_ERROR = 17, TOO_MANY_HANDLES = 18, KEY_NOT_SUPPORTED = 19, KEY_REQUIRED = 20, INVALID_TAG = 21, INVALID_OPERATION = 22, NONCE_REQUIRED = 23, INVALID_NONCE = 24, OPTION_NOT_SET = 25, NOT_FOUND = 26, PARAMETERS_MISSING = 27, IN_PROGRESS = 28, INCOMPATIBLE_KEYS = 29, EXPIRED = 30, }; /** * Encoding to use for importing or exporting a key pair. **/ enum class KeypairEncoding : uint16_t { RAW = 0, PKCS_8 = 1, PEM = 2, LOCAL = 3, }; /** * Encoding to use for importing or exporting a public key. **/ enum class PublickeyEncoding : uint16_t { RAW = 0, PKCS_8 = 1, PEM = 2, SEC = 3, COMPRESSED_SEC = 4, LOCAL = 5, }; /** * Encoding to use for importing or exporting a secret key. **/ enum class SecretkeyEncoding : uint16_t { RAW = 0, PKCS_8 = 1, PEM = 2, SEC = 3, COMPRESSED_SEC = 4, LOCAL = 5, }; /** * Encoding to use for importing or exporting a signature. **/ enum class SignatureEncoding : uint16_t { RAW = 0, DER = 1, }; /** * An algorithm category. **/ enum class AlgorithmType : uint16_t { SIGNATURES = 0, SYMMETRIC = 1, KEY_EXCHANGE = 2, }; /** * Version of a managed key. * * A version can be an arbitrary `u64` integer, with the expection of some reserved values. **/ using Version = uint64_t; /** * Size of a value. **/ using Size = size_t; /** * A UNIX timestamp, in seconds since 01/01/1970. **/ using Timestamp = uint64_t; /** * A 64-bit value **/ using U64 = uint64_t; /** * Handle for functions returning output whose size may be large or not known in advance. * * An `array_output` object contains a host-allocated byte array. * * A guest can get the size of that array after a function returns in order to then allocate a buffer of the correct size. * In addition, the content of such an object can be consumed by a guest in a streaming fashion. * * An `array_output` handle is automatically closed after its full content has been consumed. **/ using ArrayOutput = WasiHandle; /** * A set of options. * * This type is used to set non-default parameters. * * The exact set of allowed options depends on the algorithm being used. **/ using Options = WasiHandle; /** * A handle to the optional secrets management facilities offered by a host. * * This is used to generate, retrieve and invalidate managed keys. **/ using SecretsManager = WasiHandle; /** * A key pair. **/ using Keypair = WasiHandle; /** * A state to absorb data to be signed. * * After a signature has been computed or verified, the state remains valid for further operations. * * A subsequent signature would sign all the data accumulated since the creation of the state object. **/ using SignatureState = WasiHandle; /** * A signature. **/ using Signature = WasiHandle; /** * A public key, for key exchange and signature verification. **/ using Publickey = WasiHandle; /** * A secret key, for key exchange mechanisms. **/ using Secretkey = WasiHandle; /** * A state to absorb signed data to be verified. **/ using SignatureVerificationState = WasiHandle; /** * A state to perform symmetric operations. * * The state is not reset nor invalidated after an option has been performed. * Incremental updates and sessions are thus supported. **/ using SymmetricState = WasiHandle; /** * A symmetric key. * * The key can be imported from raw bytes, or can be a reference to a managed key. * * If it was imported, the host will wipe it from memory as soon as the handle is closed. **/ using SymmetricKey = WasiHandle; /** * An authentication tag. * * This is an object returned by functions computing authentication tags. * * A tag can be compared against another tag (directly supplied as raw bytes) in constant time with the `symmetric_tag_verify()` function. * * This object type can't be directly created from raw bytes. They are only returned by functions computing MACs. * * The host is reponsible for securely wiping them from memory on close. **/ using SymmetricTag = WasiHandle; /** * Options index, only required by the Interface Types translation layer. **/ enum class OptOptionsU : uint8_t { SOME = 0, NONE = 1, }; /** * An optional options set. * * This union simulates an `Option<Options>` type to make the `options` parameter of some functions optional. **/ union OptOptionsMember { Options some; // if tag=0 // none: (no associated content) if tag=1 }; struct __attribute__((packed)) OptOptions { uint8_t tag; uint8_t __pad8_0; uint16_t __pad16_0; uint32_t __pad32_0; OptOptionsMember member; }; /** * Symmetric key index, only required by the Interface Types translation layer. **/ enum class OptSymmetricKeyU : uint8_t { SOME = 0, NONE = 1, }; /** * An optional symmetric key. * * This union simulates an `Option<SymmetricKey>` type to make the `symmetric_key` parameter of some functions optional. **/ union OptSymmetricKeyMember { SymmetricKey some; // if tag=0 // none: (no associated content) if tag=1 }; struct __attribute__((packed)) OptSymmetricKey { uint8_t tag; uint8_t __pad8_0; uint16_t __pad16_0; uint32_t __pad32_0; OptSymmetricKeyMember member; }; /** * Generate a new symmetric key for a given algorithm. * * `options` can be `None` to use the default parameters, or an algoritm-specific set of parameters to override. * * This function may return `unsupported_feature` if key generation is not supported by the host for the chosen algorithm, or `unsupported_algorithm` if the algorithm is not supported by the host. **/ Expected<SymmetricKey, CryptoErrno> symmetric_key_generate( WasiPtr<unsigned char> algorithm_ptr, size_t algorithm_len, OptOptions options ); /** * Create a symmetric key from raw material. * * The algorithm is internally stored along with the key, and trying to use the key with an operation expecting a different algorithm will return `invalid_key`. * * The function may also return `unsupported_algorithm` if the algorithm is not supported by the host. **/ Expected<SymmetricKey, CryptoErrno> symmetric_key_import( WasiPtr<unsigned char> algorithm_ptr, size_t algorithm_len, WasiPtr<uint8_t> raw, Size raw_len ); /** * Export a symmetric key as raw material. * * This is mainly useful to export a managed key. * * May return `prohibited_operation` if this operation is denied. **/ Expected<ArrayOutput, CryptoErrno> symmetric_key_export( SymmetricKey symmetric_key ); /** * Destroy a symmetric key. * * Objects are reference counted. It is safe to close an object immediately after the last function needing it is called. **/ Expected<std::monostate, CryptoErrno> symmetric_key_close( SymmetricKey symmetric_key ); /** * __(optional)__ * Generate a new managed symmetric key. * * The key is generated and stored by the secrets management facilities. * * It may be used through its identifier, but the host may not allow it to be exported. * * The function returns the `unsupported_feature` error code if secrets management facilities are not supported by the host, * or `unsupported_algorithm` if a key cannot be created for the chosen algorithm. * * The function may also return `unsupported_algorithm` if the algorithm is not supported by the host. * * This is also an optional import, meaning that the function may not even exist. **/ Expected<SymmetricKey, CryptoErrno> symmetric_key_generate_managed( SecretsManager secrets_manager, WasiPtr<unsigned char> algorithm_ptr, size_t algorithm_len, OptOptions options ); /** * __(optional)__ * Store a symmetric key into the secrets manager. * * On success, the function stores the key identifier into `$symmetric_key_id`, * into which up to `$symmetric_key_id_max_len` can be written. * * The function returns `overflow` if the supplied buffer is too small. **/ Expected<std::monostate, CryptoErrno> symmetric_key_store_managed( SecretsManager secrets_manager, SymmetricKey symmetric_key, WasiMutPtr<uint8_t> symmetric_key_id, Size symmetric_key_id_max_len ); /** * __(optional)__ * Replace a managed symmetric key. * * This function crates a new version of a managed symmetric key, by replacing `$kp_old` with `$kp_new`. * * It does several things: * * - The key identifier for `$symmetric_key_new` is set to the one of `$symmetric_key_old`. * - A new, unique version identifier is assigned to `$kp_new`. This version will be equivalent to using `$version_latest` until the key is replaced. * - The `$symmetric_key_old` handle is closed. * * Both keys must share the same algorithm and have compatible parameters. If this is not the case, `incompatible_keys` is returned. * * The function may also return the `unsupported_feature` error code if secrets management facilities are not supported by the host, * or if keys cannot be rotated. * * Finally, `prohibited_operation` can be returned if `$symmetric_key_new` wasn't created by the secrets manager, and the secrets manager prohibits imported keys. * * If the operation succeeded, the new version is returned. * * This is an optional import, meaning that the function may not even exist. **/ Expected<Version, CryptoErrno> symmetric_key_replace_managed( SecretsManager secrets_manager, SymmetricKey symmetric_key_old, SymmetricKey symmetric_key_new ); /** * __(optional)__ * Return the key identifier and version of a managed symmetric key. * * If the key is not managed, `unsupported_feature` is returned instead. * * This is an optional import, meaning that the function may not even exist. **/ Expected<std::tuple<Size, Version>, CryptoErrno> symmetric_key_id( SymmetricKey symmetric_key, WasiMutPtr<uint8_t> symmetric_key_id, Size symmetric_key_id_max_len ); /** * __(optional)__ * Return a managed symmetric key from a key identifier. * * `kp_version` can be set to `version_latest` to retrieve the most recent version of a symmetric key. * * If no key matching the provided information is found, `not_found` is returned instead. * * This is an optional import, meaning that the function may not even exist. **/ Expected<SymmetricKey, CryptoErrno> symmetric_key_from_id( SecretsManager secrets_manager, WasiPtr<uint8_t> symmetric_key_id, Size symmetric_key_id_len, Version symmetric_key_version ); /** * Create a new state to aborb and produce data using symmetric operations. * * The state remains valid after every operation in order to support incremental updates. * * The function has two optional parameters: a key and an options set. * * It will fail with a `key_not_supported` error code if a key was provided but the chosen algorithm doesn't natively support keying. * * On the other hand, if a key is required, but was not provided, a `key_required` error will be thrown. * * Some algorithms may require additional parameters. They have to be supplied as an options set: * * ```rust * let options_handle = ctx.options_open()?; * ctx.options_set("context", b"My application")?; * ctx.options_set_u64("fanout", 16)?; * let state_handle = ctx.symmetric_state_open("BLAKE2b-512", None, Some(options_handle))?; * ``` * * If some parameters are mandatory but were not set, the `parameters_missing` error code will be returned. * * A notable exception is the `nonce` parameter, that is common to most AEAD constructions. * * If a nonce is required but was not supplied: * * - If it is safe to do so, the host will automatically generate a nonce. This is true for nonces that are large enough to be randomly generated, or if the host is able to maintain a global counter. * - If not, the function will fail and return the dedicated `nonce_required` error code. * * A nonce that was automatically generated can be retrieved after the function returns with `symmetric_state_get(state_handle, "nonce")`. * * **Sample usage patterns:** * * - **Hashing** * * ```rust * let mut out = [0u8; 64]; * let state_handle = ctx.symmetric_state_open("SHAKE-128", None, None)?; * ctx.symmetric_state_absorb(state_handle, b"data")?; * ctx.symmetric_state_absorb(state_handle, b"more_data")?; * ctx.symmetric_state_squeeze(state_handle, &mut out)?; * ``` * * - **MAC** * * ```rust * let mut raw_tag = [0u8; 64]; * let key_handle = ctx.symmetric_key_import("HMAC/SHA-512", b"key")?; * let state_handle = ctx.symmetric_state_open("HMAC/SHA-512", Some(key_handle), None)?; * ctx.symmetric_state_absorb(state_handle, b"data")?; * ctx.symmetric_state_absorb(state_handle, b"more_data")?; * let computed_tag_handle = ctx.symmetric_state_squeeze_tag(state_handle)?; * ctx.symmetric_tag_pull(computed_tag_handle, &mut raw_tag)?; * ``` * * Verification: * * ```rust * let state_handle = ctx.symmetric_state_open("HMAC/SHA-512", Some(key_handle), None)?; * ctx.symmetric_state_absorb(state_handle, b"data")?; * ctx.symmetric_state_absorb(state_handle, b"more_data")?; * let computed_tag_handle = ctx.symmetric_state_squeeze_tag(state_handle)?; * ctx.symmetric_tag_verify(computed_tag_handle, expected_raw_tag)?; * ``` * * - **Tuple hashing** * * ```rust * let mut out = [0u8; 64]; * let state_handle = ctx.symmetric_state_open("TupleHashXOF256", None, None)?; * ctx.symmetric_state_absorb(state_handle, b"value 1")?; * ctx.symmetric_state_absorb(state_handle, b"value 2")?; * ctx.symmetric_state_absorb(state_handle, b"value 3")?; * ctx.symmetric_state_squeeze(state_handle, &mut out)?; * ``` * Unlike MACs and regular hash functions, inputs are domain separated instead of being concatenated. * * - **Key derivation using extract-and-expand** * * Extract: * * ```rust * let mut prk = vec![0u8; 64]; * let key_handle = ctx.symmetric_key_import("HKDF-EXTRACT/SHA-512", b"key")?; * let state_handle = ctx.symmetric_state_open("HKDF-EXTRACT/SHA-512", Some(key_handle), None)?; * ctx.symmetric_state_absorb(state_handle, b"salt")?; * let prk_handle = ctx.symmetric_state_squeeze_key(state_handle, "HKDF-EXPAND/SHA-512")?; * ``` * * Expand: * * ```rust * let mut subkey = vec![0u8; 32]; * let state_handle = ctx.symmetric_state_open("HKDF-EXPAND/SHA-512", Some(prk_handle), None)?; * ctx.symmetric_state_absorb(state_handle, b"info")?; * ctx.symmetric_state_squeeze(state_handle, &mut subkey)?; * ``` * * - **Key derivation using a XOF** * * ```rust * let mut subkey1 = vec![0u8; 32]; * let mut subkey2 = vec![0u8; 32]; * let key_handle = ctx.symmetric_key_import("BLAKE3", b"key")?; * let state_handle = ctx.symmetric_state_open("BLAKE3", Some(key_handle), None)?; * ctx.symmetric_absorb(state_handle, b"context")?; * ctx.squeeze(state_handle, &mut subkey1)?; * ctx.squeeze(state_handle, &mut subkey2)?; * ``` * * - **Password hashing** * * ```rust * let mut memory = vec![0u8; 1_000_000_000]; * let options_handle = ctx.symmetric_options_open()?; * ctx.symmetric_options_set_guest_buffer(options_handle, "memory", &mut memory)?; * ctx.symmetric_options_set_u64(options_handle, "opslimit", 5)?; * ctx.symmetric_options_set_u64(options_handle, "parallelism", 8)?; * * let state_handle = ctx.symmetric_state_open("ARGON2-ID-13", None, Some(options))?; * ctx.symmtric_state_absorb(state_handle, b"password")?; * * let pw_str_handle = ctx.symmetric_state_squeeze_tag(state_handle)?; * let mut pw_str = vec![0u8; ctx.symmetric_tag_len(pw_str_handle)?]; * ctx.symmetric_tag_pull(pw_str_handle, &mut pw_str)?; * ``` * * - **AEAD encryption with an explicit nonce** * * ```rust * let key_handle = ctx.symmetric_key_generate("AES-256-GCM", None)?; * let message = b"test"; * * let options_handle = ctx.symmetric_options_open()?; * ctx.symmetric_options_set(options_handle, "nonce", nonce)?; * * let state_handle = ctx.symmetric_state_open("AES-256-GCM", Some(key_handle), Some(options_handle))?; * let mut ciphertext = vec![0u8; message.len() + ctx.symmetric_state_max_tag_len(state_handle)?]; * ctx.symmetric_state_absorb(state_handle, "additional data")?; * ctx.symmetric_state_encrypt(state_handle, &mut ciphertext, message)?; * ``` * * - **AEAD encryption with automatic nonce generation** * * ```rust * let key_handle = ctx.symmetric_key_generate("AES-256-GCM-SIV", None)?; * let message = b"test"; * let mut nonce = [0u8; 24]; * * let state_handle = ctx.symmetric_state_open("AES-256-GCM-SIV", Some(key_handle), None)?; * * let nonce_handle = ctx.symmetric_state_options_get(state_handle, "nonce")?; * ctx.array_output_pull(nonce_handle, &mut nonce)?; * * let mut ciphertext = vec![0u8; message.len() + ctx.symmetric_state_max_tag_len(state_handle)?]; * ctx.symmetric_state_absorb(state_handle, "additional data")?; * ctx.symmetric_state_encrypt(state_handle, &mut ciphertext, message)?; * ``` * * - **Session authenticated modes** * * ```rust * let mut out = [0u8; 16]; * let mut out2 = [0u8; 16]; * let mut ciphertext = [0u8; 20]; * let key_handle = ctx.symmetric_key_generate("Xoodyak-128", None)?; * let state_handle = ctx.symmetric_state_open("Xoodyak-128", Some(key_handle), None)?; * ctx.symmetric_state_absorb(state_handle, b"data")?; * ctx.symmetric_state_encrypt(state_handle, &mut ciphertext, b"abcd")?; * ctx.symmetric_state_absorb(state_handle, b"more data")?; * ctx.symmetric_state_squeeze(state_handle, &mut out)?; * ctx.symmetric_state_squeeze(state_handle, &mut out2)?; * ctx.symmetric_state_ratchet(state_handle)?; * ctx.symmetric_state_absorb(state_handle, b"more data")?; * let next_key_handle = ctx.symmetric_state_squeeze_key(state_handle, "Xoodyak-128")?; * // ... * ``` **/ Expected<SymmetricState, CryptoErrno> symmetric_state_open( WasiPtr<unsigned char> algorithm_ptr, size_t algorithm_len, OptSymmetricKey key, OptOptions options ); /** * Retrieve a parameter from the current state. * * In particular, `symmetric_state_options_get("nonce")` can be used to get a nonce that as automatically generated. * * The function may return `options_not_set` if an option was not set, which is different from an empty value. * * It may also return `unsupported_option` if the option doesn't exist for the chosen algorithm. **/ Expected<Size, CryptoErrno> symmetric_state_options_get( SymmetricState handle, WasiPtr<unsigned char> name_ptr, size_t name_len, WasiMutPtr<uint8_t> value, Size value_max_len ); /** * Retrieve an integer parameter from the current state. * * In particular, `symmetric_state_options_get("nonce")` can be used to get a nonce that as automatically generated. * * The function may return `options_not_set` if an option was not set. * * It may also return `unsupported_option` if the option doesn't exist for the chosen algorithm. **/ Expected<U64, CryptoErrno> symmetric_state_options_get_u_64( SymmetricState handle, WasiPtr<unsigned char> name_ptr, size_t name_len ); /** * Destroy a symmetric state. * * Objects are reference counted. It is safe to close an object immediately after the last function needing it is called. **/ Expected<std::monostate, CryptoErrno> symmetric_state_close( SymmetricState handle ); /** * Absorb data into the state. * * - **Hash functions:** adds data to be hashed. * - **MAC functions:** adds data to be authenticated. * - **Tuplehash-like constructions:** adds a new tuple to the state. * - **Key derivation functions:** adds to the IKM or to the subkey information. * - **AEAD constructions:** adds additional data to be authenticated. * - **Stateful hash objects, permutation-based constructions:** absorbs. * * If the chosen algorithm doesn't accept input data, the `invalid_operation` error code is returned. * * If too much data has been fed for the algorithm, `overflow` may be thrown. **/ Expected<std::monostate, CryptoErrno> symmetric_state_absorb( SymmetricState handle, WasiPtr<uint8_t> data, Size data_len ); /** * Squeeze bytes from the state. * * - **Hash functions:** this tries to output an `out_len` bytes digest from the absorbed data. The hash function output will be truncated if necessary. If the requested size is too large, the `invalid_len` error code is returned. * - **Key derivation functions:** : outputs an arbitrary-long derived key. * - **RNGs, DRBGs, stream ciphers:**: outputs arbitrary-long data. * - **Stateful hash objects, permutation-based constructions:** squeeze. * * Other kinds of algorithms may return `invalid_operation` instead. * * For password-stretching functions, the function may return `in_progress`. * In that case, the guest should retry with the same parameters until the function completes. **/ Expected<std::monostate, CryptoErrno> symmetric_state_squeeze( SymmetricState handle, WasiMutPtr<uint8_t> out, Size out_len ); /** * Compute and return a tag for all the data injected into the state so far. * * - **MAC functions**: returns a tag authenticating the absorbed data. * - **Tuplehash-like constructions:** returns a tag authenticating all the absorbed tuples. * - **Password-hashing functions:** returns a standard string containing all the required parameters for password verification. * * Other kinds of algorithms may return `invalid_operation` instead. * * For password-stretching functions, the function may return `in_progress`. * In that case, the guest should retry with the same parameters until the function completes. **/ Expected<SymmetricTag, CryptoErrno> symmetric_state_squeeze_tag( SymmetricState handle ); /** * Use the current state to produce a key for a target algorithm. * * For extract-then-expand constructions, this returns the PRK. * For session-base authentication encryption, this returns a key that can be used to resume a session without storing a nonce. * * `invalid_operation` is returned for algorithms not supporting this operation. **/ Expected<SymmetricKey, CryptoErrno> symmetric_state_squeeze_key( SymmetricState handle, WasiPtr<unsigned char> alg_str_ptr, size_t alg_str_len ); /** * Return the maximum length of an authentication tag for the current algorithm. * * This allows guests to compute the size required to store a ciphertext along with its authentication tag. * * The returned length may include the encryption mode's padding requirements in addition to the actual tag. * * For an encryption operation, the size of the output buffer should be `input_len + symmetric_state_max_tag_len()`. * * For a decryption operation, the size of the buffer that will store the decrypted data must be `ciphertext_len - symmetric_state_max_tag_len()`. **/ Expected<Size, CryptoErrno> symmetric_state_max_tag_len( SymmetricState handle ); /** * Encrypt data with an attached tag. * * - **Stream cipher:** adds the input to the stream cipher output. `out_len` and `data_len` can be equal, as no authentication tags will be added. * - **AEAD:** encrypts `data` into `out`, including the authentication tag to the output. Additional data must have been previously absorbed using `symmetric_state_absorb()`. The `symmetric_state_max_tag_len()` function can be used to retrieve the overhead of adding the tag, as well as padding if necessary. * - **SHOE, Xoodyak, Strobe:** encrypts data, squeezes a tag and appends it to the output. * * If `out` and `data` are the same address, encryption may happen in-place. * * The function returns the actual size of the ciphertext along with the tag. * * `invalid_operation` is returned for algorithms not supporting encryption. **/ Expected<Size, CryptoErrno> symmetric_state_encrypt( SymmetricState handle, WasiMutPtr<uint8_t> out, Size out_len, WasiPtr<uint8_t> data, Size data_len ); /** * Encrypt data, with a detached tag. * * - **Stream cipher:** returns `invalid_operation` since stream ciphers do not include authentication tags. * - **AEAD:** encrypts `data` into `out` and returns the tag separately. Additional data must have been previously absorbed using `symmetric_state_absorb()`. The output and input buffers must be of the same length. * - **SHOE, Xoodyak, Strobe:** encrypts data and squeezes a tag. * * If `out` and `data` are the same address, encryption may happen in-place. * * The function returns the tag. * * `invalid_operation` is returned for algorithms not supporting encryption. **/ Expected<SymmetricTag, CryptoErrno> symmetric_state_encrypt_detached( SymmetricState handle, WasiMutPtr<uint8_t> out, Size out_len, WasiPtr<uint8_t> data, Size data_len ); /** * - **Stream cipher:** adds the input to the stream cipher output. `out_len` and `data_len` can be equal, as no authentication tags will be added. * - **AEAD:** decrypts `data` into `out`. Additional data must have been previously absorbed using `symmetric_state_absorb()`. * - **SHOE, Xoodyak, Strobe:** decrypts data, squeezes a tag and verify that it matches the one that was appended to the ciphertext. * * If `out` and `data` are the same address, decryption may happen in-place. * * `out_len` must be exactly `data_len` + `max_tag_len` bytes. * * The function returns the actual size of the decrypted message, which can be smaller than `out_len` for modes that requires padding. * * `invalid_tag` is returned if the tag didn't verify. * * `invalid_operation` is returned for algorithms not supporting encryption. **/ Expected<Size, CryptoErrno> symmetric_state_decrypt( SymmetricState handle, WasiMutPtr<uint8_t> out, Size out_len, WasiPtr<uint8_t> data, Size data_len ); /** * - **Stream cipher:** returns `invalid_operation` since stream ciphers do not include authentication tags. * - **AEAD:** decrypts `data` into `out`. Additional data must have been previously absorbed using `symmetric_state_absorb()`. * - **SHOE, Xoodyak, Strobe:** decrypts data, squeezes a tag and verify that it matches the expected one. * * `raw_tag` is the expected tag, as raw bytes. * * `out` and `data` be must have the same length. * If they also share the same address, decryption may happen in-place. * * The function returns the actual size of the decrypted message. * * `invalid_tag` is returned if the tag verification failed. * * `invalid_operation` is returned for algorithms not supporting encryption. **/ Expected<Size, CryptoErrno> symmetric_state_decrypt_detached( SymmetricState handle, WasiMutPtr<uint8_t> out, Size out_len, WasiPtr<uint8_t> data, Size data_len, WasiPtr<uint8_t> raw_tag, Size raw_tag_len ); /** * Make it impossible to recover the previous state. * * This operation is supported by some systems keeping a rolling state over an entire session, for forward security. * * `invalid_operation` is returned for algorithms not supporting ratcheting. **/ Expected<std::monostate, CryptoErrno> symmetric_state_ratchet( SymmetricState handle ); /** * Return the length of an authentication tag. * * This function can be used by a guest to allocate the correct buffer size to copy a computed authentication tag. **/ Expected<Size, CryptoErrno> symmetric_tag_len( SymmetricTag symmetric_tag ); /** * Copy an authentication tag into a guest-allocated buffer. * * The handle automatically becomes invalid after this operation. Manually closing it is not required. * * Example usage: * * ```rust * let mut raw_tag = [0u8; 16]; * ctx.symmetric_tag_pull(raw_tag_handle, &mut raw_tag)?; * ``` * * The function returns `overflow` if the supplied buffer is too small to copy the tag. * * Otherwise, it returns the number of bytes that have been copied. **/ Expected<Size, CryptoErrno> symmetric_tag_pull( SymmetricTag symmetric_tag, WasiMutPtr<uint8_t> buf, Size buf_len ); /** * Verify that a computed authentication tag matches the expected value, in constant-time. * * The expected tag must be provided as a raw byte string. * * The function returns `invalid_tag` if the tags don't match. * * Example usage: * * ```rust * let key_handle = ctx.symmetric_key_import("HMAC/SHA-256", b"key")?; * let state_handle = ctx.symmetric_state_open("HMAC/SHA-256", Some(key_handle), None)?; * ctx.symmetric_state_absorb(state_handle, b"data")?; * let computed_tag_handle = ctx.symmetric_state_squeeze_tag(state_handle)?; * ctx.symmetric_tag_verify(computed_tag_handle, expected_raw_tag)?; * ``` **/ Expected<std::monostate, CryptoErrno> symmetric_tag_verify( SymmetricTag symmetric_tag, WasiPtr<uint8_t> expected_raw_tag_ptr, Size expected_raw_tag_len ); /** * Explicitly destroy an unused authentication tag. * * This is usually not necessary, as `symmetric_tag_pull()` automatically closes a tag after it has been copied. * * Objects are reference counted. It is safe to close an object immediately after the last function needing it is called. **/ Expected<std::monostate, CryptoErrno> symmetric_tag_close( SymmetricTag symmetric_tag );
32.662677
308
0.732818
[ "object" ]
7cc9b31f9e0845354f970df0a0ddfdfb3c05d6e4
3,957
h
C
Plugins/org.commontk.dah.core/ctkDicomAbstractExchangeCache.h
kraehlit/CTK
6557c5779d20b78f501f1fd6ce1063d0f219cca6
[ "Apache-2.0" ]
515
2015-01-13T05:42:10.000Z
2022-03-29T03:10:01.000Z
Plugins/org.commontk.dah.core/ctkDicomAbstractExchangeCache.h
kraehlit/CTK
6557c5779d20b78f501f1fd6ce1063d0f219cca6
[ "Apache-2.0" ]
425
2015-01-06T05:28:38.000Z
2022-03-08T19:42:18.000Z
Plugins/org.commontk.dah.core/ctkDicomAbstractExchangeCache.h
kraehlit/CTK
6557c5779d20b78f501f1fd6ce1063d0f219cca6
[ "Apache-2.0" ]
341
2015-01-08T06:18:17.000Z
2022-03-29T21:47:49.000Z
/*============================================================================= Library: CTK Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics 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 CTKDICOMABSTRACTEXCHANGECACHE_H #define CTKDICOMABSTRACTEXCHANGECACHE_H #include <ctkDicomExchangeInterface.h> #include <QScopedPointer> #include <org_commontk_dah_core_Export.h> class ctkDicomAbstractExchangeCachePrivate; class ctkDicomObjectLocatorCache; /** * @brief Provides a basic convenience methods for the data exchange. * * The implementation is based on the ctkDicomObjectLocatorCache. */ class org_commontk_dah_core_EXPORT ctkDicomAbstractExchangeCache : public QObject, public virtual ctkDicomExchangeInterface { Q_OBJECT Q_INTERFACES(ctkDicomExchangeInterface) public: /** * @brief Construct object. * * @param exchangeService the ctkDicomExchangeService of the other side. */ ctkDicomAbstractExchangeCache(); /** * @brief Destructor * */ virtual ~ctkDicomAbstractExchangeCache(); /** * @brief Gets the exchange service of the other side. * * If we are a host, this must return the exchange service * of the hosted app and vice versa. * * @return ctkDicomExchangeService * of the other side */ virtual ctkDicomExchangeInterface* getOtherSideExchangeService() const = 0; /** * @brief Provide ctkDicomAppHosting::ObjectLocators to the other side. * * If we are a host, the other side is the hosted app and vice versa. * * @param objectUUIDs * @param acceptableTransferSyntaxUIDs * @param includeBulkData * @return QList<ctkDicomAppHosting::ObjectLocator> */ virtual QList<ctkDicomAppHosting::ObjectLocator> getData( const QList<QUuid>& objectUUIDs, const QList<QString>& acceptableTransferSyntaxUIDs, bool includeBulkData); void releaseData(const QList<QUuid>& objectUUIDs); /** * @brief Return the cache for outgoing data. * * @return ctkDicomObjectLocatorCache * */ ctkDicomObjectLocatorCache* objectLocatorCache() const; /** * @brief Publish data to other side * * @param availableData * @param lastData * @return bool */ bool publishData(const ctkDicomAppHosting::AvailableData& availableData, bool lastData); // Methods to support receiving data /** * @brief Return the incoming available data. * * @return AvailableData * */ const ctkDicomAppHosting::AvailableData& getIncomingAvailableData() const; /** * @brief Return whether the incoming data was marked as @a lastData. * * @return bool value of @a lastData in incoming notifyDataAvailable call */ bool lastIncomingData() const; /** * @brief Receive notification from other side. * */ bool notifyDataAvailable(const ctkDicomAppHosting::AvailableData& data, bool lastData); /** * @brief Clean internal data stucture that keeps the incoming data. * * Called when other side is gone (i.e., usually the other side is a hosted app). * */ void cleanIncomingData(); Q_SIGNALS: void dataAvailable(); private: Q_SIGNALS: void internalDataAvailable(); private: Q_DECLARE_PRIVATE(ctkDicomAbstractExchangeCache) const QScopedPointer<ctkDicomAbstractExchangeCachePrivate> d_ptr; /**< TODO */ }; #endif // CTKDICOMABSTRACTEXCHANGECACHE_H
26.736486
123
0.707859
[ "object" ]
7cd64625cd77910cf14810134f6b74902454ccd5
4,074
h
C
DefineStructure/utilityClusteringFunctions.h
ReetBarik/Grappolo
c9aed34ade92021fc7983eb21bc7b2933a3e43de
[ "BSD-3-Clause" ]
12
2020-04-28T04:30:07.000Z
2022-03-21T21:52:51.000Z
DefineStructure/utilityClusteringFunctions.h
ReetBarik/Grappolo
c9aed34ade92021fc7983eb21bc7b2933a3e43de
[ "BSD-3-Clause" ]
1
2021-06-07T13:49:08.000Z
2021-06-07T13:49:08.000Z
DefineStructure/utilityClusteringFunctions.h
ReetBarik/Grappolo
c9aed34ade92021fc7983eb21bc7b2933a3e43de
[ "BSD-3-Clause" ]
3
2020-06-01T14:30:22.000Z
2021-12-03T12:57:05.000Z
// *********************************************************************** // // Grappolo: A C++ library for graph clustering // Mahantesh Halappanavar (hala@pnnl.gov) // Pacific Northwest National Laboratory // // *********************************************************************** // // Copyright (2014) Battelle Memorial Institute // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED 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. // // ************************************************************************ #ifndef __CLUSTERING__FUNCTIONS__ #define __CLUSTERING__FUNCTIONS__ #include "defs.h" using namespace std; void sumVertexDegree(edge* vtxInd, long* vtxPtr, double* vDegree, long NV, Comm* cInfo); double calConstantForSecondTerm(double* vDegree, long NV); void initCommAss(long* pastCommAss, long* currCommAss, long NV); void initCommAssOpt(long* pastCommAss, long* currCommAss, long NV, mapElement* clusterLocalMap, long* vtxPtr, edge* vtxInd, Comm* cInfo, double constant, double* vDegree ); double buildLocalMapCounter(long adj1, long adj2, map<long, long> &clusterLocalMap, vector<double> &Counter, edge* vtxInd, long* currCommAss, long me); double buildLocalMapCounterNoMap(long v, mapElement* clusterLocalMap, long* vtxPtr, edge* vtxInd, long* currCommAss, long &numUniqueClusters); long max(map<long, long> &clusterLocalMap, vector<double> &Counter, double selfLoop, Comm* cInfo, double degree, long sc, double constant ) ; long maxNoMap(long v, mapElement* clusterLocalMap, long* vtxPtr, double selfLoop, Comm* cInfo, double degree, long sc, double constant, long numUniqueClusters ); void computeCommunityComparisons(vector<long>& C1, long N1, vector<long>& C2, long N2); double computeGiniCoefficient(long *colorSize, int numColors); double computeMerkinMetric(long* C1, long N1, long* C2, long N2); double computeVanDongenMetric(long* C1, long N1, long* C2, long N2); //Sorting functions: void merge(long* arr, long l, long m, long r); void mergeSort(long* arr, long l, long r); void SortNeighborListUsingInsertionAndMergeSort(graph *G); long removeEdges(long NV, long NE, edge *edgeList); void SortEdgesUndirected(long NV, long NE, edge *list1, edge *list2, long *ptrs); void SortNodeEdgesByIndex(long NV, edge *list1, edge *list2, long *ptrs); double* computeEdgeSimilarityMetrics(graph *G); graph* buildSparifiedGraph(graph *Gin, double alpha); void buildOld2NewMap(long N, long *C, long *commIndex); //Build the reordering map #endif
44.769231
109
0.698576
[ "vector" ]
7cdaf4955efa0fe2d71856c87274fdc7fbec0485
6,233
h
C
src/game/client/c_effects.h
Joshua-Ashton/Source-
4056819cea889d73626a1cbc09518b2f8ba5dda4
[ "MIT" ]
75
2017-12-06T09:06:47.000Z
2022-03-29T12:01:44.000Z
src/game/client/c_effects.h
Joshua-Ashton/Source-
4056819cea889d73626a1cbc09518b2f8ba5dda4
[ "MIT" ]
65
2017-12-08T21:46:33.000Z
2019-11-25T08:07:59.000Z
src/game/client/c_effects.h
Joshua-Ashton/Source-
4056819cea889d73626a1cbc09518b2f8ba5dda4
[ "MIT" ]
37
2017-12-03T22:58:09.000Z
2022-03-02T11:20:38.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #ifndef C_EFFECTS_H #define C_EFFECTS_H #ifdef _WIN32 #pragma once #endif #include "env_wind_shared.h" #include "precipitation_shared.h" class CPrecipitationParticle { public: Vector m_Pos; Vector m_Velocity; float m_SpawnTime; // Note: Tweak with this to change lifetime float m_Mass; float m_Ramp; float m_flMaxLifetime; int m_nSplitScreenPlayerSlot; }; class AshDebrisEffect : public CSimpleEmitter { public: AshDebrisEffect( const char *pDebugName ) : CSimpleEmitter( pDebugName ) {} static CSmartPtr<AshDebrisEffect> Create( const char *pDebugName ); virtual float UpdateAlpha( const SimpleParticle *pParticle ); virtual float UpdateRoll( SimpleParticle *pParticle, float timeDelta ); private: AshDebrisEffect( const AshDebrisEffect & ); }; //----------------------------------------------------------------------------- // Precipitation blocker entity //----------------------------------------------------------------------------- class C_PrecipitationBlocker : public C_BaseEntity { public: DECLARE_CLASS( C_PrecipitationBlocker, C_BaseEntity ); DECLARE_CLIENTCLASS(); C_PrecipitationBlocker(); virtual ~C_PrecipitationBlocker(); }; //----------------------------------------------------------------------------- // Precipitation base entity //----------------------------------------------------------------------------- class CClient_Precipitation : public C_BaseEntity { class CPrecipitationEffect; friend class CClient_Precipitation::CPrecipitationEffect; public: DECLARE_CLASS( CClient_Precipitation, C_BaseEntity ); DECLARE_CLIENTCLASS(); CClient_Precipitation(); virtual ~CClient_Precipitation(); // Inherited from C_BaseEntity virtual void Precache(); virtual bool IsTransparent() { return true; } virtual bool IsTwoPass() { return true; } void Render(); // Computes where we're gonna emit bool ComputeEmissionArea( Vector& origin, Vector2D& size, C_BaseCombatCharacter *pCharacter ) const; private: // Creates a single particle CPrecipitationParticle* CreateParticle(); virtual void OnDataChanged( DataUpdateType_t updateType ); virtual void ClientThink(); void Simulate( float dt ); // Renders the particle void RenderParticle( CPrecipitationParticle* pParticle, CMeshBuilder &mb ) const; void CreateWaterSplashes(); // Emits the actual particles void EmitParticles( float fTimeDelta ); // Gets the tracer width and speed float GetWidth() const; float GetLength() const; float GetSpeed() const; // Gets the remaining lifetime of the particle float GetRemainingLifetime( CPrecipitationParticle* pParticle ) const; // Computes the wind vector static void ComputeWindVector( ); // simulation methods bool SimulateRain( CPrecipitationParticle* pParticle, float dt ); bool SimulateSnow( CPrecipitationParticle* pParticle, float dt ) const; void CreateParticlePrecip( void ); void InitializeParticlePrecip( void ); void DispatchOuterParticlePrecip( C_BasePlayer *pPlayer, const Vector& vForward ); void DispatchInnerParticlePrecip( C_BasePlayer *pPlayer, const Vector& vForward ); void DestroyOuterParticlePrecip(); void DestroyInnerParticlePrecip(); void UpdateParticlePrecip( C_BasePlayer *pPlayer ); float GetDensity() const { return m_flDensity; } private: void CreateAshParticle( void ); void CreateRainOrSnowParticle( const Vector &vSpawnPosition, const Vector &vEndPosition, const Vector &vVelocity ); // TERROR: adding end pos for lifetime calcs // Information helpful in creating and rendering particles IMaterial *m_MatHandle; // material used float m_Color[4]; // precip color float m_Lifetime; // Precip lifetime float m_InitialRamp; // Initial ramp value float m_Speed; // Precip speed float m_Width; // Tracer width float m_Remainder; // particles we should render next time PrecipitationType_t m_nPrecipType; // Precip type float m_flHalfScreenWidth; // Precalculated each frame. float m_flDensity; #ifdef INFESTED_DLL int m_nSnowDustAmount; #endif // Some state used in rendering and simulation // Used to modify the rain density and wind from the console static ConVar s_raindensity; static ConVar s_rainwidth; static ConVar s_rainlength; static ConVar s_rainspeed; static Vector s_WindVector; // Stores the wind speed vector CUtlLinkedList<CPrecipitationParticle> m_Particles; CUtlVector<Vector> m_Splashes; protected: CSmartPtr<AshDebrisEffect> m_pAshEmitter; TimedEvent m_tAshParticleTimer; TimedEvent m_tAshParticleTraceTimer; bool m_bActiveAshEmitter; Vector m_vAshSpawnOrigin; int m_iAshCount; float m_flParticleInnerDist; //The distance at which to start drawing the inner system const char *m_pParticleInnerNearDef; //Name of the first inner system const char *m_pParticleInnerFarDef; //Name of the second inner system const char *m_pParticleOuterDef; //Name of the outer system HPARTICLEFFECT m_pParticlePrecipInnerNear; HPARTICLEFFECT m_pParticlePrecipInnerFar; HPARTICLEFFECT m_pParticlePrecipOuter; TimedEvent m_tParticlePrecipTraceTimer; bool m_bActiveParticlePrecipEmitter; bool m_bParticlePrecipInitialized; private: CClient_Precipitation( const CClient_Precipitation & ); // not defined, not accessible }; extern CUtlVector<CClient_Precipitation*> g_Precipitations; //----------------------------------------------------------------------------- // EnvWind - global wind info //----------------------------------------------------------------------------- class C_EnvWind : public C_BaseEntity { public: C_EnvWind(); DECLARE_CLIENTCLASS(); DECLARE_CLASS( C_EnvWind, C_BaseEntity ); virtual void OnDataChanged( DataUpdateType_t updateType ); virtual bool ShouldDraw( void ) { return false; } virtual void ClientThink( ); const CEnvWindShared& WindShared() const { return m_EnvWindShared; } private: C_EnvWind( const C_EnvWind & ); CEnvWindShared m_EnvWindShared; }; // Draw rain effects. void DrawPrecipitation(); #endif // C_EFFECTS_H
29.126168
161
0.700144
[ "render", "vector" ]
7ce11e0bda16f617bf233d9d51bf8acb9c28aa35
3,936
h
C
usr/src/uts/common/sys/sunpm.h
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/uts/common/sys/sunpm.h
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/uts/common/sys/sunpm.h
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
1
2020-12-30T00:04:16.000Z
2020-12-30T00:04:16.000Z
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2014 Garrett D'Amore <garrett@damore.org> * * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SYS_SUNPM_H #define _SYS_SUNPM_H /* * Sun Specific Power Management definitions */ #include <sys/isa_defs.h> #include <sys/dditypes.h> #include <sys/ddipropdefs.h> #include <sys/devops.h> #include <sys/time.h> #include <sys/cmn_err.h> #include <sys/ddidevmap.h> #include <sys/ddi_implfuncs.h> #include <sys/ddi_isa.h> #include <sys/model.h> #include <sys/devctl.h> #ifdef __cplusplus extern "C" { #endif #ifdef _KERNEL /* * Power cycle transition check is supported for SCSI and SATA devices. */ #define DC_SCSI_FORMAT 0x1 /* SCSI */ #define DC_SMART_FORMAT 0x2 /* SMART */ #define DC_SCSI_MFR_LEN 6 /* YYYYWW */ struct pm_scsi_cycles { int lifemax; /* lifetime max power cycles */ int ncycles; /* number of cycles so far */ char svc_date[DC_SCSI_MFR_LEN]; /* service date YYYYWW */ int flag; /* reserved for future */ }; struct pm_smart_count { int allowed; /* normalized max cycles allowed */ int consumed; /* normalized consumed cycles */ int flag; /* type of cycles */ }; struct pm_trans_data { int format; /* data format */ union { struct pm_scsi_cycles scsi_cycles; struct pm_smart_count smart_count; } un; }; /* * Power levels for devices supporting ACPI based D0, D1, D2, D3 states. * * Note that 0 is off in Solaris PM framework but D0 is full power * for these devices. */ #define PM_LEVEL_D3 0 /* D3 state - off */ #define PM_LEVEL_D2 1 /* D2 state */ #define PM_LEVEL_D1 2 /* D1 state */ #define PM_LEVEL_D0 3 /* D0 state - fully on */ /* * Useful strings for creating pm-components property for these devices. * If a device driver wishes to provide more specific description of power * levels (highly recommended), it should NOT use following generic defines. */ #define PM_LEVEL_D3_STR "0=Device D3 State" #define PM_LEVEL_D2_STR "1=Device D2 State" #define PM_LEVEL_D1_STR "2=Device D1 State" #define PM_LEVEL_D0_STR "3=Device D0 State" /* * Generic Sun PM definitions. */ /* * These are obsolete power management interfaces, they will be removed from * a subsequent release. */ int pm_create_components(dev_info_t *dip, int num_components); void pm_destroy_components(dev_info_t *dip); void pm_set_normal_power(dev_info_t *dip, int component_number, int level); int pm_get_normal_power(dev_info_t *dip, int component_number); /* * These are power management interfaces. */ int pm_busy_component(dev_info_t *dip, int component_number); int pm_idle_component(dev_info_t *dip, int component_number); int pm_get_current_power(dev_info_t *dip, int component, int *levelp); int pm_power_has_changed(dev_info_t *, int, int); int pm_trans_check(struct pm_trans_data *datap, time_t *intervalp); int pm_lower_power(dev_info_t *dip, int comp, int level); int pm_raise_power(dev_info_t *dip, int comp, int level); int pm_update_maxpower(dev_info_t *dip, int comp, int level); #endif /* _KERNEL */ #ifdef __cplusplus } #endif #endif /* _SYS_SUNPM_H */
26.958904
76
0.73501
[ "model" ]
7cecafaf4e3fe968300c29311c0cc8e3ea03e2a4
617
h
C
BTE/Classes/SelectVC/View/BTECoinTableViewCell.h
sophiemarceau/bte_iOS
3e44be16be9559709e5dfbe24855f929e68832b1
[ "MIT" ]
1
2022-02-08T06:42:11.000Z
2022-02-08T06:42:11.000Z
BTE/Classes/SelectVC/View/BTECoinTableViewCell.h
sophiemarceau/bte_iOS
3e44be16be9559709e5dfbe24855f929e68832b1
[ "MIT" ]
1
2021-11-12T02:04:11.000Z
2021-11-12T02:04:11.000Z
BTE/Classes/SelectVC/View/BTECoinTableViewCell.h
sophiemarceau/bte_iOS
3e44be16be9559709e5dfbe24855f929e68832b1
[ "MIT" ]
null
null
null
// // BTECoinTableViewCell.h // BTE // // Created by wanmeizty on 24/10/18. // Copyright © 2018年 wangli. All rights reserved. // #import <UIKit/UIKit.h> #import "CurrencyModel.h" NS_ASSUME_NONNULL_BEGIN @interface BTECoinTableViewCell : UITableViewCell //@property (copy,nonatomic) void(^selectblock)(CurrencyModel * model); @property (copy,nonatomic) void(^selectblock)(BOOL selected); - (void)configwidth:(NSDictionary *)dict; - (void)configwidthModel:(CurrencyModel *)model; - (void)configwidthModel:(CurrencyModel *)model optionList:(NSArray *)optionList; + (CGFloat)cellHeight; @end NS_ASSUME_NONNULL_END
26.826087
81
0.758509
[ "model" ]
7cefc109437dde1e068e2fea2cdb2899579b94aa
1,187
h
C
DataCollector/mozilla/xulrunner-sdk/include/GMPProcessChild.h
andrasigneczi/TravelOptimiser
b08805f97f0823fd28975a36db67193386aceb22
[ "Apache-2.0" ]
1
2016-04-20T08:35:44.000Z
2016-04-20T08:35:44.000Z
DataCollector/mozilla/xulrunner-sdk/include/GMPProcessChild.h
andrasigneczi/TravelOptimiser
b08805f97f0823fd28975a36db67193386aceb22
[ "Apache-2.0" ]
null
null
null
DataCollector/mozilla/xulrunner-sdk/include/GMPProcessChild.h
andrasigneczi/TravelOptimiser
b08805f97f0823fd28975a36db67193386aceb22
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef GMPProcessChild_h_ #define GMPProcessChild_h_ #include "mozilla/ipc/ProcessChild.h" #include "GMPChild.h" namespace mozilla { namespace gmp { class GMPLoader; class GMPProcessChild final : public mozilla::ipc::ProcessChild { protected: typedef mozilla::ipc::ProcessChild ProcessChild; public: explicit GMPProcessChild(ProcessId aParentPid); ~GMPProcessChild(); virtual bool Init() override; virtual void CleanUp() override; // Set/get the GMPLoader singleton for this child process. // Note: The GMPLoader is not deleted by this object, the caller of // SetGMPLoader() must manage the GMPLoader's lifecycle. static void SetGMPLoader(GMPLoader* aHost); static GMPLoader* GetGMPLoader(); private: GMPChild mPlugin; static GMPLoader* mLoader; DISALLOW_COPY_AND_ASSIGN(GMPProcessChild); }; } // namespace gmp } // namespace mozilla #endif // GMPProcessChild_h_
26.977273
79
0.73968
[ "object" ]
7cf399fc49f47197982d1659d5f548698d9f9a81
1,731
h
C
DataConfig/Source/DataConfigCore/Public/DataConfig/Deserialize/DcDeserializeTypes.h
slowburn-dev/DataConfig
cd4a494b5d83fae40cad094cf33fda0c7c11fde0
[ "MIT" ]
45
2021-04-03T03:49:31.000Z
2022-03-17T07:52:06.000Z
DataConfig/Source/DataConfigCore/Public/DataConfig/Deserialize/DcDeserializeTypes.h
slowburn-dev/DataConfig
cd4a494b5d83fae40cad094cf33fda0c7c11fde0
[ "MIT" ]
null
null
null
DataConfig/Source/DataConfigCore/Public/DataConfig/Deserialize/DcDeserializeTypes.h
slowburn-dev/DataConfig
cd4a494b5d83fae40cad094cf33fda0c7c11fde0
[ "MIT" ]
11
2021-04-14T20:37:01.000Z
2022-03-21T01:09:01.000Z
#pragma once #include "CoreMinimal.h" #include "DataConfig/DcTypes.h" #include "DataConfig/Property/DcPropertyDatum.h" struct FDcReader; struct FDcPropertyWriter; struct FDcDeserializer; struct DATACONFIGCORE_API FDcDeserializeContext { enum class EState { Uninitialized, Ready, DeserializeInProgress, DeserializeEnded, }; EState State = EState::Uninitialized; FString Name; TArray<UObject*, TInlineAllocator<4>> Objects; TArray<FFieldVariant, TInlineAllocator<8>> Properties; FDcDeserializer* Deserializer; FDcReader* Reader; FDcPropertyWriter* Writer; FORCEINLINE FFieldVariant& TopProperty() { checkf(Properties.Num(), TEXT("Expect TopProperty found none.")); return Properties.Top(); } FORCEINLINE UObject* TopObject() { checkf(Objects.Num(), TEXT("Expect TopObject found none.")); return Objects.Top(); } FDcResult Prepare(); }; using FDcDeserializeDelegateSignature = FDcResult(*)(FDcDeserializeContext& Ctx); DECLARE_DELEGATE_RetVal_OneParam(FDcResult, FDcDeserializeDelegate, FDcDeserializeContext&); enum class EDcDeserializePredicateResult { Pass, Process, }; using FDcDeserializePredicateSignature = EDcDeserializePredicateResult(*)(FDcDeserializeContext& Ctx); DECLARE_DELEGATE_RetVal_OneParam(EDcDeserializePredicateResult, FDcDeserializePredicate, FDcDeserializeContext&); struct DATACONFIGCORE_API FDcScopedProperty { FDcScopedProperty(FDcDeserializeContext& InCtx); ~FDcScopedProperty(); FDcResult PushProperty(); FFieldVariant Property; FDcDeserializeContext& Ctx; }; struct DATACONFIGCORE_API FDcScopedObject { FDcScopedObject(FDcDeserializeContext& InCtx, UObject* InObject); ~FDcScopedObject(); UObject* Object; FDcDeserializeContext& Ctx; };
21.109756
113
0.794339
[ "object" ]
6b0eb7947b6bb178708eba6a28d835ba3195dfb9
5,146
h
C
devel/include/ur_msgs/Analog.h
Orwatronic/MAS_513
d6c2ffd4ef604fe814b32ee08335da5ea718dad9
[ "Apache-2.0", "BSD-3-Clause" ]
2
2022-03-14T16:01:53.000Z
2022-03-25T09:14:21.000Z
devel/include/ur_msgs/Analog.h
Orwatronic/MAS_513
d6c2ffd4ef604fe814b32ee08335da5ea718dad9
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-09-30T03:58:47.000Z
2020-09-30T03:58:47.000Z
devel/include/ur_msgs/Analog.h
Orwatronic/MAS_513
d6c2ffd4ef604fe814b32ee08335da5ea718dad9
[ "Apache-2.0", "BSD-3-Clause" ]
1
2022-03-25T07:16:57.000Z
2022-03-25T07:16:57.000Z
// Generated by gencpp from file ur_msgs/Analog.msg // DO NOT EDIT! #ifndef UR_MSGS_MESSAGE_ANALOG_H #define UR_MSGS_MESSAGE_ANALOG_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace ur_msgs { template <class ContainerAllocator> struct Analog_ { typedef Analog_<ContainerAllocator> Type; Analog_() : pin(0) , domain(0) , state(0.0) { } Analog_(const ContainerAllocator& _alloc) : pin(0) , domain(0) , state(0.0) { (void)_alloc; } typedef uint8_t _pin_type; _pin_type pin; typedef uint8_t _domain_type; _domain_type domain; typedef float _state_type; _state_type state; // reducing the odds to have name collisions with Windows.h #if defined(_WIN32) && defined(VOLTAGE) #undef VOLTAGE #endif #if defined(_WIN32) && defined(CURRENT) #undef CURRENT #endif enum { VOLTAGE = 0u, CURRENT = 1u, }; typedef boost::shared_ptr< ::ur_msgs::Analog_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::ur_msgs::Analog_<ContainerAllocator> const> ConstPtr; }; // struct Analog_ typedef ::ur_msgs::Analog_<std::allocator<void> > Analog; typedef boost::shared_ptr< ::ur_msgs::Analog > AnalogPtr; typedef boost::shared_ptr< ::ur_msgs::Analog const> AnalogConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::ur_msgs::Analog_<ContainerAllocator> & v) { ros::message_operations::Printer< ::ur_msgs::Analog_<ContainerAllocator> >::stream(s, "", v); return s; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator==(const ::ur_msgs::Analog_<ContainerAllocator1> & lhs, const ::ur_msgs::Analog_<ContainerAllocator2> & rhs) { return lhs.pin == rhs.pin && lhs.domain == rhs.domain && lhs.state == rhs.state; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator!=(const ::ur_msgs::Analog_<ContainerAllocator1> & lhs, const ::ur_msgs::Analog_<ContainerAllocator2> & rhs) { return !(lhs == rhs); } } // namespace ur_msgs namespace ros { namespace message_traits { template <class ContainerAllocator> struct IsFixedSize< ::ur_msgs::Analog_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::ur_msgs::Analog_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::ur_msgs::Analog_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::ur_msgs::Analog_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::ur_msgs::Analog_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::ur_msgs::Analog_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::ur_msgs::Analog_<ContainerAllocator> > { static const char* value() { return "f41c08a810adf63713aec88712cd553d"; } static const char* value(const ::ur_msgs::Analog_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xf41c08a810adf637ULL; static const uint64_t static_value2 = 0x13aec88712cd553dULL; }; template<class ContainerAllocator> struct DataType< ::ur_msgs::Analog_<ContainerAllocator> > { static const char* value() { return "ur_msgs/Analog"; } static const char* value(const ::ur_msgs::Analog_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::ur_msgs::Analog_<ContainerAllocator> > { static const char* value() { return "uint8 VOLTAGE=0\n" "uint8 CURRENT=1\n" "\n" "uint8 pin\n" "uint8 domain # can be VOLTAGE or CURRENT\n" "float32 state\n" ; } static const char* value(const ::ur_msgs::Analog_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::ur_msgs::Analog_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.pin); stream.next(m.domain); stream.next(m.state); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct Analog_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::ur_msgs::Analog_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::ur_msgs::Analog_<ContainerAllocator>& v) { s << indent << "pin: "; Printer<uint8_t>::stream(s, indent + " ", v.pin); s << indent << "domain: "; Printer<uint8_t>::stream(s, indent + " ", v.domain); s << indent << "state: "; Printer<float>::stream(s, indent + " ", v.state); } }; } // namespace message_operations } // namespace ros #endif // UR_MSGS_MESSAGE_ANALOG_H
21.897872
133
0.713953
[ "vector" ]
6b1919ca2ce42433fe77ac4dd2f3f00fdf929271
22,522
h
C
NpyArray.h
wme7/NpyArray
5dda2f7d69e8f285ddb88786c1f65791900bd07c
[ "MIT" ]
null
null
null
NpyArray.h
wme7/NpyArray
5dda2f7d69e8f285ddb88786c1f65791900bd07c
[ "MIT" ]
null
null
null
NpyArray.h
wme7/NpyArray
5dda2f7d69e8f285ddb88786c1f65791900bd07c
[ "MIT" ]
null
null
null
// Copyright (C) 2011 Carl Rogers // Minor modifications by Manuel A. Diaz (2020) // Released under MIT License // license available in LICENSE file, or at http://www.opensource.org/licenses/mit-license.php #ifndef LIBCNPY_H_ #define LIBCNPY_H_ #include<string> #include<stdexcept> #include<sstream> #include<vector> #include<cstdio> #include<typeinfo> #include<iostream> #include<cassert> #include<zlib.h> // <--flag -lz #include<map> #include<memory> #include<stdint.h> #include<numeric> #include<complex> #include<cstdlib> #include<algorithm> #include<cstring> #include<iomanip> #include<regex> // Define the cnpy namespace: namespace cnpy { struct NpyArray { NpyArray(const std::vector<size_t>& _shape, size_t _word_size, bool _fortran_order) : shape(_shape), word_size(_word_size), fortran_order(_fortran_order) { num_vals = 1; for(size_t i = 0;i < shape.size();i++) num_vals *= shape[i]; data_holder = std::shared_ptr<std::vector<char>>( new std::vector<char>(num_vals * word_size)); } NpyArray() : shape(0), word_size(0), fortran_order(0), num_vals(0) { } template<typename T> T* data() { return reinterpret_cast<T*>(&(*data_holder)[0]); } template<typename T> const T* data() const { return reinterpret_cast<T*>(&(*data_holder)[0]); } template<typename T> std::vector<T> as_vec() const { const T* p = data<T>(); return std::vector<T>(p, p+num_vals); } size_t num_bytes() const { return data_holder->size(); } std::shared_ptr<std::vector<char>> data_holder; std::vector<size_t> shape; size_t word_size; bool fortran_order; size_t num_vals; }; using npz_t = std::map<std::string, NpyArray>; char BigEndianTest() { int x = 1; return (((char *)&x)[0]) ? '<' : '>'; } char map_type(const std::type_info& t) { if(t == typeid(float) ) return 'f'; if(t == typeid(double) ) return 'f'; if(t == typeid(long double) ) return 'f'; if(t == typeid(int) ) return 'i'; if(t == typeid(char) ) return 'i'; if(t == typeid(short) ) return 'i'; if(t == typeid(long) ) return 'i'; if(t == typeid(long long) ) return 'i'; if(t == typeid(unsigned char) ) return 'u'; if(t == typeid(unsigned short) ) return 'u'; if(t == typeid(unsigned long) ) return 'u'; if(t == typeid(unsigned long long) ) return 'u'; if(t == typeid(unsigned int) ) return 'u'; if(t == typeid(bool) ) return 'b'; if(t == typeid(std::complex<float>) ) return 'c'; if(t == typeid(std::complex<double>) ) return 'c'; if(t == typeid(std::complex<long double>) ) return 'c'; else return '?'; } template<typename T> std::vector<char> create_npy_header(const std::vector<size_t>& shape); void parse_npy_header(FILE* fp,size_t& word_size, std::vector<size_t>& shape, bool& fortran_order) { char buffer[256]; size_t res = fread(buffer,sizeof(char),11,fp); if(res != 11) throw std::runtime_error("parse_npy_header: failed fread"); std::string header = fgets(buffer,256,fp); assert(header[header.size()-1] == '\n'); size_t loc1, loc2; //fortran order loc1 = header.find("fortran_order"); if (loc1 == std::string::npos) throw std::runtime_error("parse_npy_header: failed to find header keyword: 'fortran_order'"); loc1 += 16; fortran_order = (header.substr(loc1,4) == "True" ? true : false); //shape loc1 = header.find("("); loc2 = header.find(")"); if (loc1 == std::string::npos || loc2 == std::string::npos) throw std::runtime_error("parse_npy_header: failed to find header keyword: '(' or ')'"); std::regex num_regex("[0-9][0-9]*"); std::smatch sm; shape.clear(); std::string str_shape = header.substr(loc1+1,loc2-loc1-1); while(std::regex_search(str_shape, sm, num_regex)) { shape.push_back(std::stoi(sm[0].str())); str_shape = sm.suffix().str(); } //endian, word size, data type //byte order code | stands for not applicable. //not sure when this applies except for byte array loc1 = header.find("descr"); if (loc1 == std::string::npos) throw std::runtime_error("parse_npy_header: failed to find header keyword: 'descr'"); loc1 += 9; bool littleEndian = (header[loc1] == '<' || header[loc1] == '|' ? true : false); assert(littleEndian); //char type = header[loc1+1]; //assert(type == map_type(T)); std::string str_ws = header.substr(loc1+2); loc2 = str_ws.find("'"); word_size = atoi(str_ws.substr(0,loc2).c_str()); } void parse_npy_header(unsigned char* buffer,size_t& word_size, std::vector<size_t>& shape, bool& fortran_order) { //std::string magic_string(buffer,6); uint8_t major_version = *reinterpret_cast<uint8_t*>(buffer+6); uint8_t minor_version = *reinterpret_cast<uint8_t*>(buffer+7); uint16_t header_len = *reinterpret_cast<uint16_t*>(buffer+8); std::string header(reinterpret_cast<char*>(buffer+9),header_len); size_t loc1, loc2; //fortran order loc1 = header.find("fortran_order")+16; fortran_order = (header.substr(loc1,4) == "True" ? true : false); //shape loc1 = header.find("("); loc2 = header.find(")"); std::regex num_regex("[0-9][0-9]*"); std::smatch sm; shape.clear(); std::string str_shape = header.substr(loc1+1,loc2-loc1-1); while(std::regex_search(str_shape, sm, num_regex)) { shape.push_back(std::stoi(sm[0].str())); str_shape = sm.suffix().str(); } //endian, word size, data type //byte order code | stands for not applicable. //not sure when this applies except for byte array loc1 = header.find("descr")+9; bool littleEndian = (header[loc1] == '<' || header[loc1] == '|' ? true : false); assert(littleEndian); //char type = header[loc1+1]; //assert(type == map_type(T)); std::string str_ws = header.substr(loc1+2); loc2 = str_ws.find("'"); word_size = atoi(str_ws.substr(0,loc2).c_str()); } void parse_zip_footer(FILE* fp, uint16_t& nrecs, size_t& global_header_size, size_t& global_header_offset) { std::vector<char> footer(22); fseek(fp,-22,SEEK_END); size_t res = fread(&footer[0],sizeof(char),22,fp); if(res != 22) throw std::runtime_error("parse_zip_footer: failed fread"); uint16_t disk_no, disk_start, nrecs_on_disk, comment_len; disk_no = *(uint16_t*) &footer[4]; disk_start = *(uint16_t*) &footer[6]; nrecs_on_disk = *(uint16_t*) &footer[8]; nrecs = *(uint16_t*) &footer[10]; global_header_size = *(uint32_t*) &footer[12]; global_header_offset = *(uint32_t*) &footer[16]; comment_len = *(uint16_t*) &footer[20]; assert(disk_no == 0); assert(disk_start == 0); assert(nrecs_on_disk == nrecs); assert(comment_len == 0); } NpyArray load_the_npy_file(FILE* fp) { std::vector<size_t> shape; size_t word_size; bool fortran_order; cnpy::parse_npy_header(fp,word_size,shape,fortran_order); cnpy::NpyArray arr(shape, word_size, fortran_order); size_t nread = fread(arr.data<char>(),1,arr.num_bytes(),fp); if(nread != arr.num_bytes()) throw std::runtime_error("load_the_npy_file: failed fread"); return arr; } NpyArray load_the_npz_array(FILE* fp, uint32_t compr_bytes, uint32_t uncompr_bytes) { std::vector<unsigned char> buffer_compr(compr_bytes); std::vector<unsigned char> buffer_uncompr(uncompr_bytes); size_t nread = fread(&buffer_compr[0],1,compr_bytes,fp); if(nread != compr_bytes) throw std::runtime_error("load_the_npy_file: failed fread"); int err; z_stream d_stream; d_stream.zalloc = Z_NULL; d_stream.zfree = Z_NULL; d_stream.opaque = Z_NULL; d_stream.avail_in = 0; d_stream.next_in = Z_NULL; err = inflateInit2(&d_stream, -MAX_WBITS); d_stream.avail_in = compr_bytes; d_stream.next_in = &buffer_compr[0]; d_stream.avail_out = uncompr_bytes; d_stream.next_out = &buffer_uncompr[0]; err = inflate(&d_stream, Z_FINISH); err = inflateEnd(&d_stream); std::vector<size_t> shape; size_t word_size; bool fortran_order; cnpy::parse_npy_header(&buffer_uncompr[0],word_size,shape,fortran_order); cnpy::NpyArray array(shape, word_size, fortran_order); size_t offset = uncompr_bytes - array.num_bytes(); memcpy(array.data<unsigned char>(),&buffer_uncompr[0]+offset,array.num_bytes()); return array; } npz_t npz_load(std::string fname) { FILE* fp = fopen(fname.c_str(),"rb"); if(!fp) { throw std::runtime_error("npz_load: Error! Unable to open file "+fname+"!"); } cnpy::npz_t arrays; while(1) { std::vector<char> local_header(30); size_t headerres = fread(&local_header[0],sizeof(char),30,fp); if(headerres != 30) throw std::runtime_error("npz_load: failed fread"); //if we've reached the global header, stop reading if(local_header[2] != 0x03 || local_header[3] != 0x04) break; //read in the variable name uint16_t name_len = *(uint16_t*) &local_header[26]; std::string varname(name_len,' '); size_t vname_res = fread(&varname[0],sizeof(char),name_len,fp); if(vname_res != name_len) throw std::runtime_error("npz_load: failed fread"); //erase the lagging .npy varname.erase(varname.end()-4,varname.end()); //read in the extra field uint16_t extra_field_len = *(uint16_t*) &local_header[28]; if(extra_field_len > 0) { std::vector<char> buff(extra_field_len); size_t efield_res = fread(&buff[0],sizeof(char),extra_field_len,fp); if(efield_res != extra_field_len) throw std::runtime_error("npz_load: failed fread"); } uint16_t compr_method = *reinterpret_cast<uint16_t*>(&local_header[0]+8); uint32_t compr_bytes = *reinterpret_cast<uint32_t*>(&local_header[0]+18); uint32_t uncompr_bytes = *reinterpret_cast<uint32_t*>(&local_header[0]+22); if(compr_method == 0) {arrays[varname] = load_the_npy_file(fp);} else {arrays[varname] = load_the_npz_array(fp,compr_bytes,uncompr_bytes);} } fclose(fp); return arrays; } NpyArray npz_load(std::string fname, std::string varname) { FILE* fp = fopen(fname.c_str(),"rb"); if(!fp) throw std::runtime_error("npz_load: Unable to open file "+fname); while(1) { std::vector<char> local_header(30); size_t header_res = fread(&local_header[0],sizeof(char),30,fp); if(header_res != 30) throw std::runtime_error("npz_load: failed fread"); //if we've reached the global header, stop reading if(local_header[2] != 0x03 || local_header[3] != 0x04) break; //read in the variable name uint16_t name_len = *(uint16_t*) &local_header[26]; std::string vname(name_len,' '); size_t vname_res = fread(&vname[0],sizeof(char),name_len,fp); if(vname_res != name_len) throw std::runtime_error("npz_load: failed fread"); vname.erase(vname.end()-4,vname.end()); //erase the lagging .npy //read in the extra field uint16_t extra_field_len = *(uint16_t*) &local_header[28]; fseek(fp,extra_field_len,SEEK_CUR); //skip past the extra field uint16_t compr_method = *reinterpret_cast<uint16_t*>(&local_header[0]+8); uint32_t compr_bytes = *reinterpret_cast<uint32_t*>(&local_header[0]+18); uint32_t uncompr_bytes = *reinterpret_cast<uint32_t*>(&local_header[0]+22); if(vname == varname) { NpyArray array = (compr_method == 0) ? load_the_npy_file(fp) : load_the_npz_array(fp,compr_bytes,uncompr_bytes); fclose(fp); return array; } else { //skip past the data uint32_t size = *(uint32_t*) &local_header[22]; fseek(fp,size,SEEK_CUR); } } fclose(fp); //if we get here, we haven't found the variable in the file throw std::runtime_error("npz_load: Variable name "+varname+" not found in "+fname); } NpyArray npy_load(std::string fname) { FILE* fp = fopen(fname.c_str(), "rb"); if(!fp) throw std::runtime_error("npy_load: Unable to open file "+fname); NpyArray arr = load_the_npy_file(fp); fclose(fp); return arr; } template<typename T> std::vector<char>& operator+=(std::vector<char>& lhs, const T rhs) { //write in little endian for(size_t byte = 0; byte < sizeof(T); byte++) { char val = *((char*)&rhs+byte); lhs.push_back(val); } return lhs; } template<> std::vector<char>& operator+=(std::vector<char>& lhs, const std::string rhs) { lhs.insert(lhs.end(),rhs.begin(),rhs.end()); return lhs; } template<> std::vector<char>& operator+=(std::vector<char>& lhs, const char* rhs) { //write in little endian size_t len = strlen(rhs); lhs.reserve(len); for(size_t byte = 0; byte < len; byte++) { lhs.push_back(rhs[byte]); } return lhs; } template<typename T> void npy_save(std::string fname, const T* data, const std::vector<size_t> shape, std::string mode = "w") { FILE* fp = NULL; std::vector<size_t> true_data_shape; //if appending, the shape of existing + new data if(mode == "a") fp = fopen(fname.c_str(),"r+b"); if(fp) { //file exists. we need to append to it. read the header, modify the array size size_t word_size; bool fortran_order; parse_npy_header(fp,word_size,true_data_shape,fortran_order); assert(!fortran_order); if(word_size != sizeof(T)) { std::cout<<"libnpy error: "<<fname<<" has word size "<<word_size<<" but npy_save appending data sized "<<sizeof(T)<<"\n"; assert( word_size == sizeof(T) ); } if(true_data_shape.size() != shape.size()) { std::cout<<"libnpy error: npy_save attempting to append misdimensioned data to "<<fname<<"\n"; assert(true_data_shape.size() != shape.size()); } for(size_t i = 1; i < shape.size(); i++) { if(shape[i] != true_data_shape[i]) { std::cout<<"libnpy error: npy_save attempting to append misshaped data to "<<fname<<"\n"; assert(shape[i] == true_data_shape[i]); } } true_data_shape[0] += shape[0]; } else { fp = fopen(fname.c_str(),"wb"); true_data_shape = shape; } std::vector<char> header = create_npy_header<T>(true_data_shape); size_t nels = std::accumulate(shape.begin(),shape.end(),1,std::multiplies<size_t>()); fseek(fp,0,SEEK_SET); fwrite(&header[0],sizeof(char),header.size(),fp); fseek(fp,0,SEEK_END); fwrite(data,sizeof(T),nels,fp); fclose(fp); } template<typename T> void npz_save(std::string zipname, std::string fname, const T* data, const std::vector<size_t>& shape, std::string mode = "w") { //first, append a .npy to the fname fname += ".npy"; //now, on with the show FILE* fp = NULL; uint16_t nrecs = 0; size_t global_header_offset = 0; std::vector<char> global_header; if(mode == "a") fp = fopen(zipname.c_str(),"r+b"); if(fp) { //zip file exists. we need to add a new npy file to it. //first read the footer. this gives us the offset and size of the global header //then read and store the global header. //below, we will write the the new data at the start of the global header then append the global header and footer below it size_t global_header_size; parse_zip_footer(fp,nrecs,global_header_size,global_header_offset); fseek(fp,global_header_offset,SEEK_SET); global_header.resize(global_header_size); size_t res = fread(&global_header[0],sizeof(char),global_header_size,fp); if(res != global_header_size){ throw std::runtime_error("npz_save: header read error while adding to existing zip"); } fseek(fp,global_header_offset,SEEK_SET); } else { fp = fopen(zipname.c_str(),"wb"); } std::vector<char> npy_header = create_npy_header<T>(shape); size_t nels = std::accumulate(shape.begin(),shape.end(),1,std::multiplies<size_t>()); size_t nbytes = nels*sizeof(T) + npy_header.size(); //get the CRC of the data to be added uint32_t crc = crc32(0L,(uint8_t*)&npy_header[0],npy_header.size()); crc = crc32(crc,(uint8_t*)data,nels*sizeof(T)); //build the local header std::vector<char> local_header; local_header += "PK"; //first part of sig local_header += (uint16_t) 0x0403; //second part of sig local_header += (uint16_t) 20; //min version to extract local_header += (uint16_t) 0; //general purpose bit flag local_header += (uint16_t) 0; //compression method local_header += (uint16_t) 0; //file last mod time local_header += (uint16_t) 0; //file last mod date local_header += (uint32_t) crc; //crc local_header += (uint32_t) nbytes; //compressed size local_header += (uint32_t) nbytes; //uncompressed size local_header += (uint16_t) fname.size(); //fname length local_header += (uint16_t) 0; //extra field length local_header += fname; //build global header global_header += "PK"; //first part of sig global_header += (uint16_t) 0x0201; //second part of sig global_header += (uint16_t) 20; //version made by global_header.insert(global_header.end(),local_header.begin()+4,local_header.begin()+30); global_header += (uint16_t) 0; //file comment length global_header += (uint16_t) 0; //disk number where file starts global_header += (uint16_t) 0; //internal file attributes global_header += (uint32_t) 0; //external file attributes global_header += (uint32_t) global_header_offset; //relative offset of local file header, since it begins where the global header used to begin global_header += fname; //build footer std::vector<char> footer; footer += "PK"; //first part of sig footer += (uint16_t) 0x0605; //second part of sig footer += (uint16_t) 0; //number of this disk footer += (uint16_t) 0; //disk where footer starts footer += (uint16_t) (nrecs+1); //number of records on this disk footer += (uint16_t) (nrecs+1); //total number of records footer += (uint32_t) global_header.size(); //nbytes of global headers footer += (uint32_t) (global_header_offset + nbytes + local_header.size()); //offset of start of global headers, since global header now starts after newly written array footer += (uint16_t) 0; //zip file comment length //write everything fwrite(&local_header[0],sizeof(char),local_header.size(),fp); fwrite(&npy_header[0],sizeof(char),npy_header.size(),fp); fwrite(data,sizeof(T),nels,fp); fwrite(&global_header[0],sizeof(char),global_header.size(),fp); fwrite(&footer[0],sizeof(char),footer.size(),fp); fclose(fp); } template<typename T> void npy_save(std::string fname, const std::vector<T> data, std::string mode = "w") { std::vector<size_t> shape; shape.push_back(data.size()); npy_save(fname, &data[0], shape, mode); } template<typename T> void npz_save(std::string zipname, std::string fname, const std::vector<T> data, std::string mode = "w") { std::vector<size_t> shape; shape.push_back(data.size()); npz_save(zipname, fname, &data[0], shape, mode); } template<typename T> std::vector<char> create_npy_header(const std::vector<size_t>& shape) { std::vector<char> dict; dict += "{'descr': '"; dict += BigEndianTest(); dict += map_type(typeid(T)); dict += std::to_string(sizeof(T)); dict += "', 'fortran_order': False, 'shape': ("; dict += std::to_string(shape[0]); for(size_t i = 1;i < shape.size();i++) { dict += ", "; dict += std::to_string(shape[i]); } if(shape.size() == 1) dict += ","; dict += "), }"; //pad with spaces so that preamble+dict is modulo 16 bytes. preamble is 10 bytes. dict needs to end with \n int remainder = 16 - (10 + dict.size()) % 16; dict.insert(dict.end(),remainder,' '); dict.back() = '\n'; std::vector<char> header; header += (char) 0x93; header += "NUMPY"; header += (char) 0x01; //major version of numpy format header += (char) 0x00; //minor version of numpy format header += (uint16_t) dict.size(); header.insert(header.end(),dict.begin(),dict.end()); return header; } } #endif // LIBCNPY_H_
37.915825
177
0.581964
[ "shape", "vector" ]
6b1e8dc755e69d4b6242e9b73bc04ffee6a75a64
2,403
h
C
src/record_batch_handlers/stateful_handlers/derivative_handler.h
QratorLabs/stream-data-processor
10be5b5d7c9ffa2f481218f6bf7c3c1ee12a0752
[ "MIT" ]
null
null
null
src/record_batch_handlers/stateful_handlers/derivative_handler.h
QratorLabs/stream-data-processor
10be5b5d7c9ffa2f481218f6bf7c3c1ee12a0752
[ "MIT" ]
null
null
null
src/record_batch_handlers/stateful_handlers/derivative_handler.h
QratorLabs/stream-data-processor
10be5b5d7c9ffa2f481218f6bf7c3c1ee12a0752
[ "MIT" ]
1
2021-03-11T15:32:34.000Z
2021-03-11T15:32:34.000Z
#pragma once #include <chrono> #include <deque> #include <map> #include <memory> #include <string> #include <unordered_map> #include <vector> #include <arrow/api.h> #include "handler_factory.h" #include "record_batch_handlers/record_batch_handler.h" #include "utils/compute_utils.h" namespace stream_data_processor { using compute_utils::DerivativeCalculator; class DerivativeHandler : public RecordBatchHandler { public: struct DerivativeCase { std::string values_column_name; size_t order; }; struct DerivativeOptions { std::chrono::nanoseconds unit_time_segment; std::chrono::nanoseconds derivative_neighbourhood; std::unordered_map<std::string, DerivativeCase> derivative_cases; bool no_wait_future{false}; }; public: template <typename DerivativeCalculatorType, typename OptionsType> DerivativeHandler(DerivativeCalculatorType&& derivative_calculator, OptionsType&& options) : derivative_calculator_( std::forward<DerivativeCalculatorType>(derivative_calculator)), options_(std::forward<OptionsType>(options)) {} arrow::Result<arrow::RecordBatchVector> handle( const std::shared_ptr<arrow::RecordBatch>& record_batch) override; private: struct BufferedValues { std::deque<double> times; std::deque<double> values; }; private: arrow::Result<double> getScaledPositionTime( int64_t row_id, const arrow::Array& time_column) const; private: std::shared_ptr<DerivativeCalculator> derivative_calculator_; DerivativeOptions options_; std::deque<double> all_buffered_times_; std::unordered_map<std::string, BufferedValues> buffered_values_; std::shared_ptr<arrow::RecordBatch> buffered_batch_{nullptr}; }; class DerivativeHandlerFactory : public HandlerFactory { public: template <typename DerivativeCalculatorType, typename OptionsType> DerivativeHandlerFactory(DerivativeCalculatorType&& derivative_calculator, OptionsType&& options) : derivative_calculator_( std::forward<DerivativeCalculatorType>(derivative_calculator)), options_(std::forward<OptionsType>(options)) {} std::shared_ptr<RecordBatchHandler> createHandler() const override; private: std::shared_ptr<DerivativeCalculator> derivative_calculator_; DerivativeHandler::DerivativeOptions options_; }; } // namespace stream_data_processor
29.666667
76
0.755306
[ "vector" ]
6b1f12d72d93d70e530330c3ce87198eebc72393
2,553
h
C
src/bringup/bin/bootsvc/util.h
Prajwal-Koirala/fuchsia
ca7ae6c143cd4c10bad9aa1869ffcc24c3e4b795
[ "BSD-2-Clause" ]
2
2021-12-29T10:11:08.000Z
2022-01-04T15:37:09.000Z
src/bringup/bin/bootsvc/util.h
PlugFox/fuchsia
39afe5230d41628b3c736a6e384393df954968c8
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
src/bringup/bin/bootsvc/util.h
PlugFox/fuchsia
39afe5230d41628b3c736a6e384393df954968c8
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia 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 SRC_BRINGUP_BIN_BOOTSVC_UTIL_H_ #define SRC_BRINGUP_BIN_BOOTSVC_UTIL_H_ #include <lib/zx/channel.h> #include <lib/zx/vmo.h> #include <map> #include <optional> #include <string> #include <string_view> #include <vector> #include "src/lib/storage/vfs/cpp/fuchsia_vfs.h" #include "src/lib/storage/vfs/cpp/vfs_types.h" namespace bootsvc { // Identifier of a boot item. struct ItemKey { uint32_t type; uint32_t extra; bool operator<(const ItemKey& ik) const { uint64_t a = (static_cast<uint64_t>(type) << 32) | extra; uint64_t b = (static_cast<uint64_t>(ik.type) << 32) | ik.extra; return a < b; } }; // Location of a boot item within a boot image. struct ItemValue { uint32_t offset; uint32_t length; }; struct FactoryItemValue { zx::vmo vmo; uint32_t length; }; // Map for boot items. using FactoryItemMap = std::map<uint32_t, FactoryItemValue>; using ItemMap = std::map<ItemKey, std::vector<ItemValue>>; using BootloaderFileMap = std::map<std::string, ItemValue>; // Retrieve boot image |vmo| from the startup handle table, and add boot items // to |out_map| and factory boot items to |out_factory_map|. zx_status_t RetrieveBootImage(zx::vmo* out_vmo, ItemMap* out_map, FactoryItemMap* out_factory_map, BootloaderFileMap* out_bootloader_file_map); // Parses ' '-separated boot arguments in |str|, and adds them to |buf|. |buf| // is a series of NUL-separated "key" or "key=value" pairs. Furthermore, if // `bootsvc.next` is present among the given arguments, its value will be // returned. std::optional<std::string> ParseBootArgs(std::string_view str, std::vector<char>* buf); // Parses boot arguments in |str| as a ZBI_TYPE_IMAGE_ARGS payload (see // <zircon/boot/image.h> for more information), and adds them to |buf|. |buf| // is a series of NUL-separated "key" or "key=value" pairs. zx_status_t ParseLegacyBootArgs(std::string_view str, std::vector<char>* buf); // Create a connection to a |vnode| in a |vfs|. zx_status_t CreateVnodeConnection(fs::FuchsiaVfs* vfs, fbl::RefPtr<fs::Vnode> vnode, fs::Rights rights, zx::channel* out); // Path relative to /boot used for crashlogs. extern const char* const kLastPanicFilePath; std::vector<std::string> SplitString(std::string_view input, char delimiter); } // namespace bootsvc #endif // SRC_BRINGUP_BIN_BOOTSVC_UTIL_H_
32.730769
98
0.718762
[ "vector" ]